repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
documentcloud/cloud-crowd
lib/cloud_crowd/worker.rb
5368
require 'benchmark' module CloudCrowd # The Worker, forked off from the Node when a new WorkUnit is received, # launches an Action for processing. Workers will only ever receive WorkUnits # that they are able to handle (for which they have a corresponding action in # their actions directory). If communication with the central server is # interrupted, the Worker will repeatedly attempt to complete its unit -- # every Worker::RETRY_WAIT seconds. Any exceptions that take place during # the course of the Action will cause the Worker to mark the WorkUnit as # having failed. When finished, the Worker's process exits, minimizing the # potential for memory leaks. class Worker # Wait five seconds to retry, after internal communcication errors. RETRY_WAIT = 5 attr_reader :pid, :node, :unit, :status # A new Worker customizes itself to its WorkUnit at instantiation. def initialize(node, unit) @start_time = Time.now @pid = $$ @node = node @unit = unit @status = @unit['status'] @retry_wait = RETRY_WAIT $0 = "#{unit['action']} (#{unit['id']}) [cloud-crowd-worker]" end # Return output to the central server, marking the WorkUnit done. def complete_work_unit(result) keep_trying_to "complete work unit" do data = base_params.merge({:status => 'succeeded', :output => result}) @node.central["/work/#{data[:id]}"].put(data) log "finished #{display_work_unit} in #{data[:time]} seconds" end end # Mark the WorkUnit failed, returning the exception to central. def fail_work_unit(exception) keep_trying_to "mark work unit as failed" do data = base_params.merge({:status => 'failed', :output => {'output' => exception.message}.to_json}) @node.central["/work/#{data[:id]}"].put(data) log "failed #{display_work_unit} in #{data[:time]} seconds\n#{exception.message}\n#{exception.backtrace}" end end # We expect and require internal communication between the central server # and the workers to succeed. If it fails for any reason, log it, and then # keep trying the same request. def keep_trying_to(title) begin yield rescue RestClient::ResourceNotFound => e log "work unit ##{@unit['id']} doesn't exist. discarding..." rescue Exception => e log "failed to #{title} -- retry in #{@retry_wait} seconds" log e.message log e.backtrace sleep @retry_wait retry end end # Loggable details describing what the Worker is up to. def display_work_unit "unit ##{@unit['id']} (#{@unit['action']}/#{CloudCrowd.display_status(@status)})" end # Executes the WorkUnit by running the Action, catching all exceptions as # failures. We capture the thread so that we can kill it from the outside, # when exiting. def run_work_unit begin result = nil action_class = CloudCrowd.actions[@unit['action']] action = action_class.new(@status, @unit['input'], enhanced_unit_options, @node.asset_store) Dir.chdir(action.work_directory) do result = case @status when PROCESSING then action.process when SPLITTING then action.split when MERGING then action.merge else raise Error::StatusUnspecified, "work units must specify their status" end end action.cleanup_work_directory if action complete_work_unit({'output' => result}.to_json) rescue Exception => e action.cleanup_work_directory if action fail_work_unit(e) end @node.resolve_work(@unit['id']) end # Run this worker inside of a fork. Attempts to exit cleanly. # Wraps run_work_unit to benchmark the execution time, if requested. def run trap_signals log "starting #{display_work_unit}" if @unit['options']['benchmark'] log("ran #{display_work_unit} in " + Benchmark.measure { run_work_unit }.to_s) else run_work_unit end Process.exit! end # There are some potentially important attributes of the WorkUnit that we'd # like to pass into the Action -- in case it needs to know them. They will # always be made available in the options hash. def enhanced_unit_options @unit['options'].merge({ 'job_id' => @unit['job_id'], 'work_unit_id' => @unit['id'], 'attempts' => @unit['attempts'] }) end # How long has this worker been running for? def time_taken Time.now - @start_time end private # Common parameters to send back to central upon unit completion, # regardless of success or failure. def base_params { :pid => @pid, :id => @unit['id'], :time => time_taken } end # Log a message to the daemon log. Includes PID for identification. def log(message) puts "Worker ##{@pid}: #{message}" unless ENV['RACK_ENV'] == 'test' end # When signaled to exit, make sure that the Worker shuts down without firing # the Node's at_exit callbacks. def trap_signals Signal.trap('QUIT') { Process.exit! } Signal.trap('INT') { Process.exit! } Signal.trap('TERM') { Process.exit! } end end end
mit
AshwinKumarVijay/ECS-Development
ECS/Project/Project/Renderers/RendererResourceManagers/RendererMaterialManager/RendererMaterialManager.cpp
4995
#include "RendererMaterialManager.h" #include "../Resources/ResourceData/MaterialData/MaterialData.h" // Default RendererMaterialManager Constructor. RendererMaterialManager::RendererMaterialManager() { } // Default RendererMaterialManager Destructor. RendererMaterialManager::~RendererMaterialManager() { } // Add a new Material from provided MaterialData and the Material Name. void RendererMaterialManager::addMaterial(std::string newMaterialName, std::shared_ptr<const MaterialData> newMaterialData) { // Find the Material to see if the Material exists. auto materialIterator = mapNameToMaterialData.find(newMaterialName); // Check if the Material Already Exists. if (materialIterator != mapNameToMaterialData.end()) { // TO DO // Throw Already Exists Error. } else { // Create the New Material Values and Material Albedo Maps. std::shared_ptr<std::pair<RendererMaterialValues, RendererMaterialMaps>> newRendererMaterialData; newRendererMaterialData = std::make_shared<std::pair<RendererMaterialValues, RendererMaterialMaps>>(); // Copy over the Diffuse Albedo and the Metallic, Roughness, Fresnel and Opactiy. newRendererMaterialData->first.diffuseAlbedo = newMaterialData->viewMaterialValues().diffuseAlbdeo; newRendererMaterialData->first.specularAlbedo = newMaterialData->viewMaterialValues().specularAlbedo; newRendererMaterialData->first.metallicRoughnessFresnelOpacity = newMaterialData->viewMaterialValues().metallicRoughnessFresnelOpacity; // Copy over the Diffuse and Specular Albedo Maps. newRendererMaterialData->second.DiffuseAlbedoMap = newMaterialData->viewMaterialMaps().DiffuseAlbedoMap; newRendererMaterialData->second.SpecularAlbedoMap = newMaterialData->viewMaterialMaps().SpecularAlbedoMap; // Copy over the MRFO, Normal and Occlusion Maps. newRendererMaterialData->second.MRFOMap = newMaterialData->viewMaterialMaps().MRFOMap; newRendererMaterialData->second.NormalMap = newMaterialData->viewMaterialMaps().NormalMap; newRendererMaterialData->second.OcclusionMap = newMaterialData->viewMaterialMaps().OcclusionMap; // Associated the Material Name with the new Material Data. mapNameToMaterialData[newMaterialName] = newRendererMaterialData; } } // Update the Material of the Material Name and the specified Material Data. void RendererMaterialManager::updateMaterial(std::string requestedMaterialName, std::shared_ptr<const MaterialData> newMaterialData) { // Find the Material to see if the Material exists. auto materialIterator = mapNameToMaterialData.find(requestedMaterialName); // Check if the Material Already Exists. if (materialIterator != mapNameToMaterialData.end()) { // Copy over the Diffuse Albedo and the Metallic, Roughness, Fresnel and Opactiy. mapNameToMaterialData[requestedMaterialName]->first.diffuseAlbedo = newMaterialData->viewMaterialValues().diffuseAlbdeo; mapNameToMaterialData[requestedMaterialName]->first.specularAlbedo = newMaterialData->viewMaterialValues().specularAlbedo; mapNameToMaterialData[requestedMaterialName]->first.metallicRoughnessFresnelOpacity = newMaterialData->viewMaterialValues().metallicRoughnessFresnelOpacity; // Copy over the Diffuse and Specular Albedo Maps. mapNameToMaterialData[requestedMaterialName]->second.DiffuseAlbedoMap = newMaterialData->viewMaterialMaps().DiffuseAlbedoMap; mapNameToMaterialData[requestedMaterialName]->second.SpecularAlbedoMap = newMaterialData->viewMaterialMaps().SpecularAlbedoMap; // Copy over the MRFO, Normal and Occlusion Maps. mapNameToMaterialData[requestedMaterialName]->second.MRFOMap = newMaterialData->viewMaterialMaps().MRFOMap; mapNameToMaterialData[requestedMaterialName]->second.NormalMap = newMaterialData->viewMaterialMaps().NormalMap; mapNameToMaterialData[requestedMaterialName]->second.OcclusionMap = newMaterialData->viewMaterialMaps().OcclusionMap; } else { // TO DO // Throw does not exist error. } } // View the Material of the specified Name. std::shared_ptr<const std::pair<RendererMaterialValues, RendererMaterialMaps>> RendererMaterialManager::viewMaterial(const std::string & requestedMaterialName) const { // Find the Material to see if the Material exists. auto materialIterator = mapNameToMaterialData.find(requestedMaterialName); // Check if the Material Already Exists. if (materialIterator != mapNameToMaterialData.end()) { // Return the Material return materialIterator->second; } else { // TO DO // Throw does not exist error. return NULL; } } // Delete the Material of the specified Name. void RendererMaterialManager::deleteMaterial(std::string deadMaterialName) { // Find the Material to see if the Material exists. auto materialIterator = mapNameToMaterialData.find(deadMaterialName); // Check if the Material Already Exists. if (materialIterator != mapNameToMaterialData.end()) { // Erase the Material. mapNameToMaterialData.erase(materialIterator); } else { // TO DO // Throw does not exist error. } }
mit
palkan/anyway_config
spec/support/print_warning_matcher.rb
690
# frozen_string_literal: true RSpec::Matchers.define :print_warning do |message| def supports_block_expectations? true end match do |block| stderr = fake_stderr(&block) message ? stderr.include?(message) : !stderr.empty? end description do "write #{message && "\"#{message}\"" || "anything"} to standard error" end failure_message do "expected to #{description}" end failure_message_when_negated do "expected not to #{description}" end # Fake STDERR and return a string written to it. def fake_stderr original_stderr = $stderr $stderr = StringIO.new yield $stderr.string ensure $stderr = original_stderr end end
mit
moimikey/react-boilerplate
src/app/modules/Counter/reducers.js
305
import { handleAction, combineActions } from 'redux-actions' import { increment } from './actions' export default handleAction(combineActions(increment), { next: (state, { payload: { amount } }) => ({ ...state, count: state.count + amount }), throw: state => ({ ...state, count: 0 }) }, { count: 0 })
mit
jucimarjr/posueagames
felipepb/breakup/src/GameFramework/Game.js
3439
// Namespace GameFramework encapsulates class Game to detach it from the wild world of the deepweb!GameFramework var GameFramework = { }; GameFramework.KeyCode = { LeftArrow: 37, UpArrow: 38, RightArrow: 39, DownArrow: 40, SpaceBar: 32, EnterKey: 13 }; GameFramework.removeObjectFromArray = function (array, object) { var index = array.indexOf(object); if (index !== -1) { var removedObjects = array.splice(index, 1); removedObjects[0] = null; } }; GameFramework.clearArray = function (array) { var length = array.length; for (var i = 0; i < length; i++) array[i].dispose(); array.splice(0, length + 1); }; GameFramework.isInternetExplorer = function () { var userAgent = window.navigator.userAgent; var msie = userAgent.indexOf('MSIE'); return msie > 0; }; GameFramework.random = function (from, to) { return Math.floor(Math.random() * (to - from + 1) + from); }; // Constructor for the Game class. GameFramework.Game = function (canvas, backgroundColor, debugDraw) { // Reference to the canvas html5 object. this.targetFPS; this.backgroundColor = backgroundColor; this._debugDraw = debugDraw; this._canvas = canvas; this._context2D = canvas.getContext("2d"); this._gameObjects = new Array(); this._mainIntervalID; this._time = { startTime: 0, elapsedTime: 0, deltaTime: 0, _lastUpdateTime: 0 }; if (!GameFramework.Game.Instance) { GameFramework.Game.Instance = this; } else { console.error("Trying to instantiate Breakout.Game again. It should be a singleton."); } return this; }; GameFramework.Game.Instance; GameFramework.Game.prototype = { startGame: function (targetFPS) { var self = this; self.targetFPS = targetFPS; self._time.startTime = +new Date(); self._time._lastUpdateTime = self._time.startTime; self._mainIntervalID = setInterval(function() { self.update(self); } , 1000 / self.targetFPS); }, update: function () { var self = this; var millisecondsNow = +new Date(); self._time.deltaTime = millisecondsNow - self._time._lastUpdateTime; self._time.elapsedTime += self._time.deltaTime; for (var i = 0; i < self._gameObjects.length; i++) { self._gameObjects[i].update(self._time); } self._context2D.fillStyle = self.backgroundColor; self._context2D.fillRect(0, 0, self._canvas.width, self._canvas.height); for (var i = 0; i < self._gameObjects.length; i++) { self._gameObjects[i].render(self._time, self._context2D, self._debugDraw); } self._time._lastUpdateTime = millisecondsNow; }, addGameObject: function (newGameObject) { var self = this; newGameObject.init(); self._gameObjects.push(newGameObject); self._gameObjects.sort(self._compareGameObjects); }, removeGameObject: function (gameObject) { var index = this._gameObjects.indexOf(gameObject); if (index !== -1) { var removedObjects = this._gameObjects.splice(index, 1); removedObjects[0].dispose(); removedObjects[0] = null; } }, clearGameObjects: function () { var self = this; var gameObjects = self._gameObjects; var length = gameObjects.length; for (var i = 0; i < length; i++) gameObjects[i].dispose(); gameObjects.splice(0, length + 1); }, _compareGameObjects: function (a, b) { if (a.zOrder === undefined || b.zOrder === undefined) { return 1; } else { return a.zOrder - b.zOrder; } } };
mit
xnnyygn/report8
config/initializers/redis.rb
91
# uncomment me to enable PV support $redis = Redis.new(:host => 'localhost', :port => 6379)
mit
SaintGimp/BeagleBoneHardware
bbio-test/watch_test.py
377
import gimpbbio.gpio as gpio import time import datetime count = 0 data_file = open("/var/tmp/test_data.txt", "w+") def callback(pin): data_file.write(str(datetime.datetime.now()) + '\n') global count count += 1 input_pin = gpio.pins.p8_8 input_pin.open_for_input() input_pin.watch(gpio.RISING, callback) while True: count = 0 time.sleep(1) print(str(count) + " hz")
mit
okoskimi/Xfolite
source/com/nokia/xfolite/client/ui/XF_ChoiceItem.java
1489
/* * This file is part of: Xfolite (J2ME XForms client) * * Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Oskari Koskimies <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser * General Public License along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package com.nokia.xfolite.client.ui; import javax.microedition.lcdui.Image; import javax.microedition.lcdui.Graphics; import de.enough.polish.ui.*; import com.nokia.xfolite.client.PolishWidgetFactory; import com.nokia.xfolite.xforms.dom.XFormsElement; import com.nokia.xfolite.xml.dom.events.DOMEvent; public class XF_ChoiceItem extends ChoiceItem { public XF_ChoiceItem(String arg0, Image arg1, int arg2) { super(arg0, arg1, arg2); } public XF_ChoiceItem(String arg0, Image arg1, int arg2, Style arg3) { super(arg0, arg1, arg2, arg3); } //#include ${dir.include}/XFormsItemImpl.java }
mit
SArnab/JHU-605.401.82-SupaFly
client/src/components/controls.tsx
7692
import * as React from "react" import * as Commands from "../commands" import Network from "../network" import { showModal } from "./modal" import SuggestionModal from "./suggestion-modal" import AccusationModal from "./accusation-modal" interface Props { game: ClueLess.Game, player: ClueLess.Player } interface State { did_just_move: boolean selected_refute_suggestion_card_name: ClueLess.CardName | null } export default class Controls extends React.Component<Props,State> { constructor(props: Props) { super(props) this.state = { did_just_move: false, selected_refute_suggestion_card_name: null } } componentWillMount() { // Listeners Network.addOperationListener(ClueLess.Operation.ERROR, (message) => { // Did a move command fail? if (message.data.message.indexOf("Hallway is blocked") > -1 && this.state.did_just_move) { this.setState({ did_just_move: false }) } }) } componentWillReceiveProps(nextProps: Props) { if (!this.isActiveTurn() && nextProps.game.active_turn == this.props.player.id) { // Reset state, we are entering a new turn. this.setState({ did_just_move: false }) } } isActiveTurn(): boolean { return this.props.game.active_turn == this.props.player.id } isActiveSuggestionTurn(): boolean { return ( this.props.game.active_suggestion != null && this.props.game.active_suggestion_turn == this.props.player.id ) } suggestionInProgress(): boolean { return this.props.game.active_turn_state == "suggesting" } canMakeSuggestion(): boolean { return this.isActiveTurn() && !this.didFailAccusation() && this.props.player.location.type === "room" && ( this.props.game.active_turn_state === "waiting_to_move" || this.props.game.active_turn_state === "waiting_to_suggest" ) } canMakeAccusation(): boolean { return this.isActiveTurn() && !this.didFailAccusation() } didFailAccusation(): boolean { return this.props.player.did_fail_accusation } canMove(): boolean { return (!this.state.did_just_move) && !this.didFailAccusation() && this.isActiveTurn() && this.props.game.active_turn_state === "waiting_to_move" } canMoveLeft(): boolean { return this.canMove() && this.props.player.location.move_left } canMoveRight(): boolean { return this.canMove() && this.props.player.location.move_right } canMoveUp(): boolean { return this.canMove() && this.props.player.location.move_up } canMoveDown(): boolean { return this.canMove() && this.props.player.location.move_down } canMoveUpLeft(): boolean { return this.canMove() && this.props.player.location.move_up_left } canMoveUpRight(): boolean { return this.canMove() && this.props.player.location.move_up_right } canMoveDownLeft(): boolean { return this.canMove() && this.props.player.location.move_down_left } canMoveDownRight(): boolean { return this.canMove() && this.props.player.location.move_down_right } didClickMakeSuggestion(): void { showModal(<SuggestionModal game={this.props.game} player={this.props.player} />) } didClickMakeAccusation(): void { showModal(<AccusationModal game={this.props.game} player={this.props.player} />) } didClickMoveButton = (direction: "up" | "down" | "left" | "right" | "up_left" | "up_right" | "down_left" | "down_right"): void => { this.setState({ did_just_move: true }) switch (direction) { case "up": Commands.move_up() break case "up_left": Commands.move_up_left() break case "up_right": Commands.move_up_right() break case "down": Commands.move_down() break case "down_left": Commands.move_down_left() break case "down_right": Commands.move_down_right() break case "left": Commands.move_left() break case "right": Commands.move_right() break } } renderActiveTurn() { return ( <div> <h2>Your Turn</h2> { this.canMakeSuggestion() && <button onClick={ () => { this.didClickMakeSuggestion() }}>Make Suggestion</button> } { this.canMoveLeft() && <button onClick={() => { this.didClickMoveButton("left") }}>Move Left</button> } { this.canMoveRight() && <button onClick={() => { this.didClickMoveButton("right") }}>Move Right</button> } { this.canMoveUp() && <button onClick={() => { this.didClickMoveButton("up") }}>Move Up</button> } { this.canMoveDown() && <button onClick={() => { this.didClickMoveButton("down") }}>Move Down</button> } { this.canMoveUpRight() && <button onClick={() => { this.didClickMoveButton("up_right") }}>Take Secret Passage</button> } { this.canMoveUpLeft() && <button onClick={() => { this.didClickMoveButton("up_left") }} >Take Secret Passage</button> } { this.canMoveDownRight() && <button onClick={() => { this.didClickMoveButton("down_right") }}>Take Secret Passage</button> } { this.canMoveDownLeft() && <button onClick={() => { this.didClickMoveButton("down_left") }}>Take Secret Passage</button> } { this.canMakeAccusation() && <button onClick={ () => { this.didClickMakeAccusation() }}>Make Accusation</button> } <button onClick={ Commands.nextTurn }>End Turn</button> </div> ) } renderRefuteSuggestionChoices() { const suggestion = this.props.game.active_suggestion as ClueLess.Suggestion const suggesting_player = this.props.game.players.find(p => p.id == suggestion.player) as ClueLess.Player // What cards are applicable to refuting this suggestion? const matchingCards = this.props.player.cards.filter((card) => { return card.name == suggestion.weapon || card.name == suggestion.location || card.name == suggestion.suspect }) return ( <div> <h2>Refute Suggestion</h2> { matchingCards.length == 0 && <p> <b>No Matching Cards</b> <button onClick={ Commands.passSuggestion }>Pass</button> </p> } { matchingCards.length > 0 && <p> <b>Select a card to show</b> <br /> <select name="refute_suggestion" value={ this.state.selected_refute_suggestion_card_name || matchingCards[0].name } onChange={ (e) => { this.setState({ selected_refute_suggestion_card_name: e.target.value as ClueLess.CardName }) }}> { matchingCards.map((card) => { return <option key={card.name} value={card.name}>{card.name}</option> })} </select> <button onClick={() => { Commands.refuteSuggestion(this.state.selected_refute_suggestion_card_name || matchingCards[0].name) }}> Show To { suggesting_player.character } </button> </p> } </div> ) } renderSuggestionInProgress() { if (!this.props.game.active_suggestion) { return } const suggesting_player = this.props.game.players.find(p => p.id == (this.props.game.active_suggestion as ClueLess.Suggestion).player) as ClueLess.Player return ( <div> <h2>Suggestion Made By { suggesting_player.character }</h2> <ul> <li key="suspect">Suspect: { this.props.game.active_suggestion.suspect }</li> <li key="location">Location: { this.props.game.active_suggestion.location }</li> <li key="weapon">Weapon: { this.props.game.active_suggestion.weapon }</li> </ul> { this.isActiveSuggestionTurn() && this.renderRefuteSuggestionChoices() } </div> ) } render() { return ( <div className="controls"> { !this.suggestionInProgress() && this.isActiveTurn() && this.renderActiveTurn() } { !this.suggestionInProgress() && !this.isActiveTurn() && !this.didFailAccusation() && <h2>Not Your Turn</h2> } { this.didFailAccusation() && <h2>Accusation Failed - You Are Out</h2> } { this.suggestionInProgress() && this.renderSuggestionInProgress() } </div> ) } }
mit
rightscale/global_session
lib/global_session/session/v4.rb
7093
require 'securerandom' module GlobalSession::Session # Version 4 is based on JSON Web Token; in fact, if there is no insecure # state, then a V4 session _is_ a JWT. Otherwise, it's a JWT with a # nonstandard fourth component containing the insecure state. class V4 < Abstract EXPIRED_AT = 'exp'.freeze ID = 'id'.freeze ISSUED_AT = 'iat'.freeze ISSUER = 'iss'.freeze NOT_BEFORE = 'nbf'.freeze KEY_ID = 'kid'.freeze # Pattern that matches possible Flexera Okta issuers ISSUER_REGEXP = /^https:\/\/secure.flexeratest.com|^https:\/\/secure.flexera.com|^https:\/\/secure.flexera.eu/ # Pattern that matches strings that are probably a V4 session cookie. HEADER = /^eyJ/ def self.decode_cookie(cookie) header, payload, sig, insec = cookie.split('.') header, payload, insec = [header, payload, insec]. map { |c| c && RightSupport::Data::Base64URL.decode(c) }. map { |j| j && GlobalSession::Encoding::JSON.load(j) } sig = sig && RightSupport::Data::Base64URL.decode(sig) insec ||= {} unless Hash === header raise GlobalSession::MalformedCookie, "JWT header unexpected format" end # typ header is optional, so only check if present if header['typ'] != nil && header['typ'] != 'JWT' raise GlobalSession::MalformedCookie, "Token type is not JWT" end unless Hash === payload raise GlobalSession::MalformedCookie, "JWT payload not present" end [header, payload, sig, insec] rescue JSON::ParserError => e raise GlobalSession::MalformedCookie, e.message end # Serialize the session. If any secure attributes have changed since the # session was instantiated, compute a fresh RSA signature. # # @return [String] def to_s if @cookie && !dirty? # nothing has changed; just return cached cookie return @cookie end unless @insecure.nil? || @insecure.empty? insec = GlobalSession::Encoding::JSON.dump(@insecure) insec = RightSupport::Data::Base64URL.encode(insec) end if @signature && !(@dirty_timestamps || @dirty_secure) # secure state hasn't changed; reuse JWT piece of cookie jwt = @cookie.split('.')[0..2].join('.') else # secure state has changed; recompute signature & make new JWT authority_check payload = @signed.dup payload[ID] = id payload[EXPIRED_AT] = @expired_at.to_i payload[ISSUED_AT] = @created_at.to_i payload[ISSUER] = @directory.local_authority_name sh = RightSupport::Crypto::SignedHash.new(payload, @directory.private_key, envelope: :jwt) jwt = sh.to_jwt(@expired_at) end if insec && !insec.empty? return "#{jwt}.#{insec}" else return jwt end end private def load_from_cookie(cookie) # Get the basic facts header, payload, sig, insec = self.class.decode_cookie(cookie) id = payload[ID] created_at = payload[ISSUED_AT] issuer = payload[ISSUER] expired_at = payload[EXPIRED_AT] not_before = payload[NOT_BEFORE] raise GlobalSession::InvalidSignature, "JWT iat claim missing/wrong" unless Integer === created_at raise GlobalSession::InvalidSignature, "JWT iat claim missing/wrong" unless Integer === expired_at created_at = Time.at(created_at) expired_at = Time.at(expired_at) if Numeric === not_before not_before = Time.at(not_before) raise GlobalSession::PrematureSession, "Session not valid before #{not_before}" unless Time.now >= not_before end # if this token was issued by Flexera IAM, we will use the "kid" header as the issuer if header[KEY_ID] && issuer =~ ISSUER_REGEXP issuer = header[KEY_ID] end # Check trust in signing authority if @directory.trusted_authority?(issuer) # Verify the signature key = @directory.authorities[issuer] digest_klass = digest_for_key(key) plaintext = cookie.split('.')[0..1].join('.') if key.respond_to?(:dsa_verify_asn1) # DSA signature with JWT-compatible encoding digest = digest_klass.new.update(plaintext).digest signature = raw_to_asn1(sig, key) result = key.dsa_verify_asn1(digest, signature) raise GlobalSession::InvalidSignature, "Global session signature verification failed: Signature mismatch: DSA verify failed" unless result elsif key.respond_to?(:verify) digest = digest_klass.new result = key.verify(digest, sig, plaintext) raise GlobalSession::InvalidSignature, "Global session signature verification failed: Signature mismatch: verify failed" unless result else raise NotImplementedError, "Cannot verify JWT with #{key.class.name}" end # Check expiration raise GlobalSession::ExpiredSession, "Session expired at #{expired_at}" unless expired_at >= Time.now else raise GlobalSession::InvalidSignature, "Global sessions signed by #{authority.inspect} are not trusted" end #Check other validity (delegate to directory) unless @directory.valid_session?(id, expired_at) raise GlobalSession::InvalidSession, "Global session has been invalidated" end #If all validation stuff passed, assign our instance variables. @id = id @authority = issuer @created_at = created_at @expired_at = expired_at @signed = payload @insecure = insec @signature = sig @cookie = cookie end # Returns the digest class used for the given key type # # @param key [OpenSSL::PKey::PKey] the key used for verifying signatures # # @return [OpenSSL::Digest] the digest class to use def digest_for_key(key) case key when OpenSSL::PKey::DSA OpenSSL::Digest::SHA1 when OpenSSL::PKey::EC case key.group.degree when 256 then OpenSSL::Digest::SHA256 when 384 then OpenSSL::Digest::SHA384 when 521 then OpenSSL::Digest::SHA512 else raise ArgumentError, "Cannot guess digest" end when OpenSSL::PKey::RSA OpenSSL::Digest::SHA256 else OpenSSL::Digest::SHA1 end end # Convert raw pair of concatenated bignums into ASN1-encoded pair of integers. # This only works for OpenSSL::PKey::EC. # https://github.com/jwt/ruby-jwt/blob/master/lib/jwt.rb#L159 def raw_to_asn1(signature, public_key) # :nodoc: byte_size = (public_key.group.degree + 7) / 8 r = signature[0..(byte_size - 1)] s = signature[byte_size..-1] || '' OpenSSL::ASN1::Sequence.new([r, s].map { |int| OpenSSL::ASN1::Integer.new(OpenSSL::BN.new(int, 2)) }).to_der end def create_from_scratch @signed = {} @insecure = {} @created_at = Time.now.utc @authority = @directory.local_authority_name @id = generate_id renew! end end end
mit
JunKikuchi/raws
spec/raws/s3_spec.rb
6644
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') RAWS::S3.http = RAWS::HTTP::HT2P RAWS_S3_BUCKETS.each do |bucket_name, location, acl| location_label = location ? location : 'US' describe RAWS::S3 do describe 'class' do before(:all) do =begin response = RAWS::S3.create_bucket(bucket_name, location) response.should be_kind_of(RAWS::HTTP::Response) =end begin RAWS::S3.put_object(bucket_name, 'aaa') do |request| request.send 'AAA' end RAWS::S3.put_object(bucket_name, 'bbb') do |request| request.header['content-length'] = 3 request.send do |io| io.write 'BBB' end end RAWS::S3.put_object(bucket_name, 'ccc') do |request| request.send 'CCC' end rescue => e d e end end =begin after(:all) do response = RAWS::S3.delete_bucket(bucket_name, :force) response.should be_kind_of(RAWS::HTTP::Response) sleep 30 end =end it "owner should return a owner information of the bucket" do RAWS::S3.owner.should be_instance_of(RAWS::S3::Owner) RAWS::S3.owner.display_name.should be_instance_of(String) RAWS::S3.owner.id.should be_instance_of(String) end it "buckets should return an array of RAWS::S3" do RAWS::S3.list_buckets.should be_instance_of(Array) RAWS::S3.list_buckets.each do |bucket| bucket.should be_instance_of(RAWS::S3) end end it "self['#{bucket_name}'] should be instance of RAWS::S3" do RAWS::S3[bucket_name].should be_instance_of(RAWS::S3) RAWS::S3[bucket_name].bucket_name.should == bucket_name RAWS::S3[bucket_name].name.should == bucket_name end it "location('#{bucket_name}') should return location of the bucket" do begin RAWS::S3.location(bucket_name).should == location_label rescue => e d e.response.doc end end it "filter('#{bucket_name}')" do RAWS::S3.filter(bucket_name) do |object| object.should be_instance_of(Hash) end end it 'put_object, get_object and delete_object method should put, get and delete the object' do RAWS::S3.put_object(bucket_name, 'a') do |request| request.should be_kind_of(RAWS::HTTP::Request) response = request.send('AAA') response.should be_kind_of(RAWS::HTTP::Response) end RAWS::S3.get_object(bucket_name, 'a') do |request| request.should be_kind_of(RAWS::HTTP::Request) response = request.send response.receive.should == 'AAA' response.should be_kind_of(RAWS::HTTP::Response) end response = RAWS::S3.delete_object(bucket_name, 'a') response.should be_kind_of(RAWS::HTTP::Response) lambda do RAWS::S3.get_object(bucket_name, 'a') end.should raise_error(RAWS::HTTP::Error) end it "copy_object method should copy the object" do response = RAWS::S3.copy_object(bucket_name, 'aaa', bucket_name, 'AAA') response.should be_kind_of(RAWS::HTTP::Response) src = nil RAWS::S3.get_object(bucket_name, 'aaa') do |request| src = request.send.receive end dest = nil RAWS::S3.get_object(bucket_name, 'AAA') do |request| dest = request.send.receive end dest.should == src response = RAWS::S3.delete_object(bucket_name, 'AAA') response.should be_kind_of(RAWS::HTTP::Response) end it "head_object method should return header information of the object" do response = RAWS::S3.head_object(bucket_name, 'aaa') response.should be_kind_of(RAWS::HTTP::Response) end end describe 'object' do before(:all) do @bucket = RAWS::S3[bucket_name] #@bucket.create_bucket.should be_kind_of(RAWS::HTTP::Response) @bucket.put('aaa') do |request| request.send 'AAA' end @bucket.put('bbb') do |request| request.header['content-length'] = 3 request.send do |io| io.write 'AAA' end end @bucket.put('ccc') do |request| request.send 'CCC' end end =begin after(:all) do response = @bucket.delete_bucket(:force) response.should be_kind_of(RAWS::HTTP::Response) sleep 30 end =end it "location should return location of the bucket" do @bucket.location.should == location_label end it "filter should" do @bucket.filter do |object| object.should be_instance_of(Hash) end end it 'put, get and delete method should put, get and delete the object' do @bucket.put('a') do |request| request.should be_kind_of(RAWS::HTTP::Request) response = request.send('AAA') response.should be_kind_of(RAWS::HTTP::Response) end @bucket.get('a') do |request| request.should be_kind_of(RAWS::HTTP::Request) response = request.send response.receive.should == 'AAA' response.should be_kind_of(RAWS::HTTP::Response) end @bucket.delete('a').should be_kind_of(RAWS::HTTP::Response) lambda do @bucket.get('a') end.should raise_error(RAWS::HTTP::Error) end it "copy method should copy the object" do response = @bucket.copy('aaa', bucket_name, 'AAA') response.should be_kind_of(RAWS::HTTP::Response) src = nil @bucket.get('aaa') do |request| src = request.send.receive end dest = nil @bucket.get('AAA') do |request| dest = request.send.receive end dest.should == src @bucket.delete('AAA').should be_kind_of(RAWS::HTTP::Response) end it "head method should return header information of the object" do @bucket.head('aaa').should be_kind_of(RAWS::HTTP::Response) end end end =begin describe RAWS::S3::S3Object do class S3 < RAWS::S3::S3Object self.bucket_name = bucket_name end describe 'class' do before(:all) do # S3.create_bucket end after(:all) do # S3.delete_bucket # sleep 60 end it "location should return location of the bucket" it "filter should return an array of RAWS::S3::Object" it "create method should put the object" end describe 'object' do end end =end end
mit
cloudera/more-behaviors
Specs/more-behaviors/Forms/Behavior.FormRequest.js
700
/* --- name: Behavior.FormRequest Tests description: n/a requires: [More-Behaviors/Behavior.FormRequest, Behavior-Tests/Behavior.SpecsHelpers] provides: [Behavior.FormRequest.Tests] ... */ (function(){ var str = '<form data-filters="FormRequest" data-update-by-selector=".formRequestTest"></form><div id="formRequestTest"></div>'; Behavior.addFilterTest({ filterName: 'FormRequest', desc: 'Creates an instance of FormRequest (by selector)', content: str, returns: Form.Request }); Behavior.addFilterTest({ filterName: 'FormRequest', desc: 'Creates an instance of FormRequest (by selector) (10x)', content: str, returns: Form.Request, multiplier: 10, noSpecs: true }); })();
mit
bombomby/brofiler
gui/Profiler.Data/EventBoard.cs
4795
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; namespace Profiler.Data { [System.AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)] public class HiddenColumn : Attribute { } [System.AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)] public class ColumnWidth : Attribute { public double Width { get; private set; } public ColumnWidth(double width) { Width = width; } } public interface IBoardItem { bool Match(String text); void CollectNodeFilter(HashSet<Object> filter); void CollectDescriptionFilter(HashSet<Object> filter); } public class BoardItem<TDesciption, TNode> : IBoardItem where TDesciption : Description where TNode : TreeNode<TDesciption> { [HiddenColumn] public List<TNode> Nodes = new List<TNode>(); [HiddenColumn] public TDesciption Description { get { return Nodes[0].Description; } } public String GetFilterName() { return Description.Name; } virtual public void CollectNodeFilter(HashSet<Object> filter) { filter.UnionWith(Nodes); } virtual public void CollectDescriptionFilter(HashSet<Object> filter) { filter.Add(Description); } public virtual void Add(TNode node) { Nodes.Add(node); } public bool Match(String text) { return GetFilterName().IndexOf(text, StringComparison.OrdinalIgnoreCase) != -1; } public BoardItem() { } } public class EventBoardItem : BoardItem<EventDescription, EventNode> { [ColumnWidth(400)] public String Function { get { return Description.Name; } } [DisplayName("Self%")] public double SelfPercent { get; private set; } [DisplayName("Self(ms)")] public double SelfTime { get; private set; } //[DisplayName("Total%")] //public double TotalPercent { get; private set; } [DisplayName("Total(ms)")] public double Total { get; private set; } [DisplayName("Max(ms)")] public double MaxTime { get; set; } [HiddenColumn] public double ChildTime { get; private set; } public int Count { get; private set; } public String Path { get { return Description.Path.ShortPath; } } public override void Add(EventNode node) { base.Add(node); MaxTime = Math.Max(MaxTime, node.Entry.Duration); ChildTime += node.ChildrenDuration; SelfPercent += node.SelfPercent; SelfTime += node.SelfDuration; if (!node.ExcludeFromTotal) { Total += node.Entry.Duration; //TotalPercent += node.TotalPercent; } ++Count; } } public class SamplingBoardItem : BoardItem<SamplingDescription, SamplingNode> { [ColumnWidth(400)] public String Function { get { return !String.IsNullOrWhiteSpace(Description.Name) ? Description.Name : String.Format("[Unresolved] 0x{0:x}", Description.Address); } } [DisplayName("Self %")] public double SelfPercent { get; private set; } public uint Self { get; private set; } [DisplayName("Total %")] public double TotalPercent { get; private set; } public uint Total { get; private set; } public String Module { get { return Description.ModuleShortName; } } public String Path { get { return Description.Path.ShortPath; } } public override void CollectDescriptionFilter(HashSet<Object> filter) { foreach (var node in Nodes) filter.Add(node.Description); } public override void Add(SamplingNode node) { base.Add(node); if (!node.ExcludeFromSelf) { Self += node.Sampled; SelfPercent += node.SelfPercent; } if (!node.ExcludeFromTotal) { Total += node.Passed; TotalPercent += node.TotalPercent; } } } public class Board<TItem, TDescription, TNode> : List<TItem> where TItem : BoardItem<TDescription, TNode>, new() where TNode : TreeNode<TDescription> where TDescription : Description { public Board(TNode node) { Dictionary<Object, TItem> items = new Dictionary<Object, TItem>(); Add(items, node); AddRange(items.Values); } void AddInternal(Dictionary<Object, TItem> items, TNode node) { if (node.Description != null) { TItem item; Object key = node.Description.GetSharedKey(); if (!items.TryGetValue(key, out item)) { item = new TItem(); items.Add(key, item); } item.Add(node); } } void Add(Dictionary<Object, TItem> items, TNode node) { if (node.ShadowNodes != null) node.ShadowNodes.ForEach(shadow => AddInternal(items, shadow as TNode)); else AddInternal(items, node); node.Children?.ForEach(child => Add(items, child as TNode)); } } }
mit
quarantin/jscep
src/test/java/org/jscep/transport/response/CapabilitiesCipherTest.java
1266
package org.jscep.transport.response; import org.jscep.transport.response.Capabilities; import org.jscep.transport.response.Capability; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.ArrayList; import java.util.Collection; import java.util.List; @RunWith(Parameterized.class) public class CapabilitiesCipherTest { @Parameters public static Collection<Object[]> getParameters() { List<Object[]> params = new ArrayList<Object[]>(); Capabilities capabilities; capabilities = new Capabilities(); params.add(new Object[] { capabilities, "DES" }); capabilities = new Capabilities(Capability.TRIPLE_DES); params.add(new Object[] { capabilities, "DESede" }); return params; } private final Capabilities capabilities; private final String algorithm; public CapabilitiesCipherTest(Capabilities capabilities, String algorithm) { this.capabilities = capabilities; this.algorithm = algorithm; } @Test public void testStrongestCipher() { Assert.assertEquals(algorithm, capabilities.getStrongestCipher()); } }
mit
stopyoukid/DojoToTypescriptConverter
out/separate/dojox.dtl.tag.logic.d.ts
435
/// <reference path="Object.d.ts" /> module dojox.dtl.tag.logic{ export var IfNode : Object; export var IfEqualNode : Object; export var ForNode : Object; export function if_ (parser:any,token:any) : any; export function _ifequal (parser:any,token:any,negate:any) : any; export function ifequal (parser:any,token:any) : any; export function ifnotequal (parser:any,token:any) : any; export function for_ (parser:any,token:any) : any; }
mit
noyelling/wage_slave
spec/wage_slave/aba_spec.rb
1039
require "spec_helper" describe WageSlave::ABA do let(:details) {[ { bsb: "789-112", account_number: "12345678", name: "Jim Sanders", amount: 5000 }, { bsb: "213-213", account_number: "98765432", name: "Herc Dundall", amount: 6000 }, { bsb: "099-231", account_number: "00012312", name: "Ridgells", amount: 12421 }, { bsb: "123-444", account_number: "34432131", name: "Sam Blimpton", amount: 8753 } ]} describe "#new" do it "will create a new ABA object" do aba = WageSlave::ABA.new(details) aba.must_be_instance_of WageSlave::ABA aba.descriptive_record.must_be_instance_of WageSlave::ABA::DescriptiveRecord aba.details.must_be_instance_of WageSlave::ABA::DetailCollection aba.details.each do | d | d.must_be_instance_of WageSlave::ABA::DetailRecord end end end describe "#to_s" do it "will generate a valid ABA that is 120 characters wide" do aba = WageSlave::ABA.new(details) aba.to_s.split("\r\n").each do | str | str.length.must_equal 120 end end end end
mit
Rousscot/M1CAR_PEER2PEER
src/peer2peer/model/peers/Peer.java
2292
package peer2peer.model.peers; import java.io.File; import java.io.IOException; import java.nio.file.FileAlreadyExistsException; import java.rmi.Remote; import java.rmi.RemoteException; import java.util.Set; /** * I am an interface to define the comportment of a Peer. */ public interface Peer extends Remote { /** * I init the Peer with a Root. * @param root the root of the community. * @throws RemoteException raised if there is a remote error. */ void init(Root root) throws RemoteException; /** * I return the list of the Peers of the community. * @return The peers of the community. * @throws RemoteException raised if there is a remote error. */ Set<Peer> getPeers() throws RemoteException; /** * I register a Peer to the community. * @param peer the peer to register. * @throws RemoteException raised if there is a remote error. */ void register(Peer peer) throws RemoteException; /** * I unregister a Peer of the community. * @param peer the peer to unregister. * @throws RemoteException raised if there is a remote error. */ void unregister(Peer peer) throws RemoteException; /** * I return the list of the files I can share. * @return the files I can share. * @throws RemoteException raised if there is a remote error. */ File[] getLocalFiles() throws RemoteException; /** * I return the name of the peer. * @return the name of the peer. * @throws RemoteException raised if there is a remote error. */ String getPeerName() throws RemoteException; /** * I check that the root is still connected. * @throws RemoteException raised if the root is disconnected. */ void checkRoot() throws RemoteException; /** * I download a file of a peer of the community. * @param peer The peer containing the file. * @param file The file to download. * @throws IOException raised if there is a error during the reading/writing of the file. * @throws RemoteException raised if there is a remote error. * @throws FileAlreadyExistsException raised if I already poccess a file of this name. */ void downloadFrom(Peer peer, File file) throws IOException; }
mit
tsnorri/vcf2multialign
combine-msa-vcf/utility.cc
4849
/* * Copyright (c) 2020 Tuukka Norri * This code is licensed under MIT license (see LICENSE for details). */ #include <numeric> #include <vcf2multialign/variant_format.hh> #include "utility.hh" namespace lb = libbio; namespace rsv = ranges::view; namespace vcf = libbio::vcf; namespace v2m = vcf2multialign; namespace { inline void setup_segment(v2m::aligned_segment const &src, v2m::aligned_segment &dst, std::size_t const pos_diff, bool const is_match) { if (is_match) dst.type = v2m::segment_type::MATCH; else dst.type = v2m::segment_type::MISMATCH; dst.aligned_position = src.aligned_position + pos_diff; dst.ref.position = src.ref.position + pos_diff; dst.alt.position = src.alt.position + pos_diff; } } namespace vcf2multialign { std::pair <std::uint16_t, std::uint16_t> count_set_genotype_values(vcf::variant const &var, std::uint16_t const alt_idx) { typedef std::pair <std::uint16_t, std::uint16_t> return_type; auto const &samples(var.samples()); libbio_assert(!samples.empty()); auto const *gt_field(v2m::get_variant_format(var).gt); libbio_assert(gt_field); auto const &first_sample(samples.front()); auto const &gt((*gt_field)(first_sample)); // vector of sample_genotype // If 0 == alt_idx, count all non-zero values. Otherwise, count the instances of the given value. if (0 == alt_idx) { auto const count(std::accumulate(gt.begin(), gt.end(), std::int32_t(0), [](auto const sum, auto const &sample_gt) -> std::int32_t { return (0 == sample_gt.alt ? sum : 1 + sum); })); return return_type(count, gt.size()); } else { auto const count(std::accumulate(gt.begin(), gt.end(), std::int32_t(0), [alt_idx](auto const sum, auto const &sample_gt) -> std::int32_t { return (alt_idx == sample_gt.alt ? 1 + sum : sum); })); return return_type(count, gt.size()); } } void split_mixed_segment(aligned_segment &src, aligned_segment_vector &dst) { auto const ref_size(src.ref.string.size()); auto const alt_size(src.alt.string.size()); // OK b.c. segment_type is MIXED. auto const head_size(alt_size <= ref_size ? alt_size : ref_size - 1); libbio_assert_gt(ref_size, 0); // Split the strings into head and tail parts like so: // Ref GATTACA GCTT // Alt GCTT GATTACA // ^tail begins ^tail begins // Then create smaller segments. // Considering the case where the alt start with a gap (segment_type::MIXED_ALT_STARTS_WITH_GAP == src.type), // the alt character position needs to be adjusted by one b.c. the parser sets the segment position to that of the first // alt character (which is set to the position of the previous non-gap character). Obviously this need not be done if // there actually are no alt characters. if (segment_type::MIXED_ALT_STARTS_WITH_GAP == src.type && alt_size) ++src.alt.position; // Handle the head part. aligned_segment seg; { auto const head_range( rsv::zip(rsv::iota(std::size_t(0)), src.ref.string, src.alt.string) | rsv::take_exactly(head_size) ); segment( head_range, [](auto const &tup) -> bool { // Project auto const [i, refc, altc] = tup; return (refc == altc); }, [&src, &seg](auto const &tup, auto const is_match){ // Start a segment auto const [i, refc, altc] = tup; setup_segment(src, seg, i, is_match); }, [&src, &seg](auto const &tup, auto const is_match){ // Handle an item auto const [i, refc, altc] = tup; seg.ref.string += refc; if (!is_match) seg.alt.string += altc; }, [&dst, &seg](auto const is_match){ // Finish a segment auto &new_seg(dst.emplace_back()); check_segment(seg); // Move the strings. using std::swap; swap(new_seg, seg); } ); } // Handle the tail part. { auto &ref_str(src.ref.string); auto &alt_str(src.alt.string); if (alt_size < ref_size) { ref_str.erase(ref_str.begin(), ref_str.begin() + alt_size); alt_str.clear(); src.type = segment_type::DELETION; src.aligned_position += alt_size; src.ref.position += alt_size; src.alt.position += alt_size; check_segment(src); auto &new_seg(dst.emplace_back()); using std::swap; swap(new_seg, src); } else if (ref_size < alt_size) { ref_str.erase(ref_str.begin(), ref_str.begin() + ref_size - 1); alt_str.erase(alt_str.begin(), alt_str.begin() + ref_size - 1); if (ref_str[0] == alt_str[0]) src.type = segment_type::INSERTION; else src.type = segment_type::INSERTION_WITH_SNP; src.aligned_position += ref_size - 1; src.ref.position += ref_size - 1; src.alt.position += ref_size - 1; check_segment(src); auto &new_seg(dst.emplace_back()); using std::swap; swap(new_seg, src); } } } }
mit
fmenesesp/CursoSymfony
src/CursoSymfony/MainBundle/Entity/Producto.php
885
<?php /** * Created by PhpStorm. * User: Fernando * Date: 07/02/2016 * Time: 13:48 */ namespace CursoSymfony\MainBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * * @ORM\Entity * */ class Producto { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue */ protected $id; /** * * @ORM\Column(type="string", length=100) * */ protected $nombre; /** * * @ORM\Column(type="integer") * */ protected $precio; public function getId(){ return $this->id; } public function getNombre(){ return $this->nombre; } public function getPrecio(){ return $this->precio; } public function setNombre($nombre){ $this->nombre = $nombre; } public function setPrecio($precio){ $this->precio = $precio; } }
mit
hilgenberg/cplot
Windows/Controls/DefinitionView.cpp
2129
#include "../stdafx.h" #include "DefinitionView.h" #include "../Document.h" #include "../res/resource.h" #include "ViewUtil.h" #include "SideSectionDefs.h" #include "../MainWindow.h" #include "../MainView.h" #include "../CPlotApp.h" #ifdef _DEBUG #define new DEBUG_NEW #endif enum { ID_def = 2000 }; IMPLEMENT_DYNAMIC(DefinitionView, CWnd) BEGIN_MESSAGE_MAP(DefinitionView, CWnd) ON_WM_CREATE() ON_WM_SIZE() ON_BN_CLICKED(ID_def, OnEdit) END_MESSAGE_MAP() DefinitionView::DefinitionView(SideSectionDefs &parent, UserFunction &f) : parent(parent), f_id(f.oid()) { } BOOL DefinitionView::PreCreateWindow(CREATESTRUCT &cs) { cs.style |= WS_CHILD; cs.dwExStyle |= WS_EX_CONTROLPARENT | WS_EX_TRANSPARENT; return CWnd::PreCreateWindow(cs); } BOOL DefinitionView::Create(const RECT &rect, CWnd *parent, UINT ID) { static bool init = false; if (!init) { WNDCLASS wndcls; memset(&wndcls, 0, sizeof(WNDCLASS)); wndcls.style = CS_DBLCLKS; wndcls.lpfnWndProc = ::DefWindowProc; wndcls.hInstance = AfxGetInstanceHandle(); wndcls.hCursor = theApp.LoadStandardCursor(IDC_ARROW); wndcls.lpszMenuName = NULL; wndcls.lpszClassName = _T("DefinitionView"); wndcls.hbrBackground = NULL; if (!AfxRegisterClass(&wndcls)) throw std::runtime_error("AfxRegisterClass(DefinitionView) failed"); init = true; } return CWnd::Create(_T("DefinitionView"), NULL, WS_CHILD | WS_TABSTOP, rect, parent, ID); } int DefinitionView::OnCreate(LPCREATESTRUCT cs) { if (CWnd::OnCreate(cs) < 0) return -1; EnableScrollBarCtrl(SB_BOTH, FALSE); START_CREATE; BUTTONLABEL(def); return 0; } void DefinitionView::Update(bool full) { CRect bounds; GetClientRect(bounds); UserFunction *f = function(); if (!f) return; def.SetWindowText(Convert(f->formula())); if (!full) return; Layout layout(*this, 0, 20); SET(-1); USE(&def); } void DefinitionView::OnInitialUpdate() { Update(true); } void DefinitionView::OnSize(UINT type, int w, int h) { CWnd::OnSize(type, w, h); EnableScrollBarCtrl(SB_BOTH, FALSE); Update(true); } void DefinitionView::OnEdit() { auto *f = function(); if (!f) return; parent.OnEdit(f); }
mit
dmpe/Homeworks5
Assignment5/src/serverPart/ChatServerBind.java
1804
package serverPart; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import java.io.IOException; import java.net.URISyntaxException; import java.rmi.AlreadyBoundException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Scanner; /** * Created by jm on 10/10/2014. */ public class ChatServerBind { public static void main(String[] args) throws IOException, AlreadyBoundException, NoSuchAlgorithmException, KeyManagementException, URISyntaxException { Channel channel; Connection connection; Scanner scan = new Scanner(System.in); System.out.println("Enter your name"); String yourName = scan.next(); ChatServer chse = new ChatServer(yourName); //Create a connection factory ConnectionFactory factory = new ConnectionFactory(); //hostname of your rabbitmq server factory.setUri("amqp://test:[email protected]:5672"); //getting a connection connection = factory.newConnection(); //creating a channel channel = connection.createChannel(); //declaring a queue for this channel. If queue does not exist, //it will be created on the server. channel.queueDeclare("newQeueRMIJAVA", false, false, false, null); ChatInterface client =null; while (true) { String msg = scan.nextLine(); if ((chse.getName() != null) && (msg != null)) { client = chse.getClient(); System.out.println(msg = "[" + chse.getName() + "] " + msg); } client.postMessage(msg); } } }
mit
joshNM/webton-cleaner
front-page.php
423
<?php get_template_part('templates/partial', 'banner'); ?> <?php get_template_part('templates/page', 'home-intro'); ?> <?php get_template_part('templates/partial', 'team'); ?> <?php get_template_part('templates/partial', 'testimonial'); ?> <?php get_template_part('templates/partial', 'clients'); ?> <?php get_template_part('templates/partial', 'social'); ?> <?php get_template_part('templates/partial', 'contact'); ?>
mit
TimPietrusky/ThunderCommander
app.js
944
// Load dependencies var express = require('express'), ThunderConnector = require('thunder-connector'); // Init express var app = express(); // gzip / deflate app.use(express.compress()); // Load static files app.use(express.static(__dirname + '/app')); // Handle the default route app.get('/', function(req, res) { // Display the app if no action is given (initial state) if (!req.param('action')) { // Load the application page res.sendfile("app/app.html"); // Send a response if an action was triggered } else { // Send a command to the device var result = ThunderConnector.command(req.param('action')); // Create the result result = { 'action' : req.param('action'), 'result' : result }; // Send the result back to the client res.json(result); } }); // Listen on port for connection app.listen(1337); console.log('Server started on http://localhost:1337');
mit
treverhines/PyGeoNS
pygeons/main/gpstation.py
7668
''' Module of station Gaussian process constructors. ''' import numpy as np import rbf.basis import rbf.poly from rbf import gauss from pygeons.main.gptools import set_units @set_units([]) def const(): ''' Constant in time basis function Parameters ---------- None ''' def basis(x,diff): # use 2000-01-01 as the reference time which is 51544 in MJD t0 = np.array([51544.0]) powers = np.array([[0]]) out = rbf.poly.mvmonos(x - t0,powers,diff) return out return gauss.gpbfci(basis,dim=1) @set_units([]) def linear(): ''' Constant and linear in time basis functions Parameters ---------- None ''' def basis(x,diff): # use 2000-01-01 as the reference time which is 51544 in MJD t0 = np.array([51544.0]) powers = np.array([[0],[1]]) out = rbf.poly.mvmonos(x - t0,powers,diff) return out return gauss.gpbfci(basis,dim=1) @set_units([]) def per(): ''' Annual and semiannual sinusoid basis functions Parameters ---------- None ''' def basis(x): out = np.array([np.sin(2*np.pi*x[:,0]/365.25), np.cos(2*np.pi*x[:,0]/365.25), np.sin(4*np.pi*x[:,0]/365.25), np.cos(4*np.pi*x[:,0]/365.25)]).T return out return gauss.gpbfci(basis,dim=1) @set_units(['mjd']) def step(t0): ''' Heaviside step function Parameters ---------- t0 [mjd] : Time of the step ''' def basis(x,diff): if diff == (0,): out = (x[:,0] >= t0).astype(float) else: # derivative is zero everywhere (ignore the step at t0) out = np.zeros(x.shape[0],dtype=float) # turn into an (N,1) array out = out[:,None] return out return gauss.gpbfci(basis,dim=1) @set_units(['mm','yr']) def mat32(sigma,cts): ''' Matern covariance function with nu=3/2 Parameters ---------- sigma [mm] : Standard deviation of displacements cts [yr] : Characteristic time-scale ''' return gauss.gpiso(rbf.basis.mat32,(0.0,sigma**2,cts),dim=1) @set_units(['mm','yr']) def mat52(sigma,cts): ''' Matern covariance function with nu=5/2 Parameters ---------- sigma [mm] : Standard deviation of displacements cts [yr] : Characteristic time-scale ''' return gauss.gpiso(rbf.basis.mat52,(0.0,sigma**2,cts),dim=1) @set_units(['mm','yr']) def wen11(sigma,cts): ''' Wendland 1-D C2 covariance function. Parameters ---------- sigma [mm] : Standard deviation of displacements cts [yr] : Characteristic time-scale ''' return gauss.gpiso(rbf.basis.wen11,(0.0,sigma**2,cts),dim=1) @set_units(['mm','yr']) def wen12(sigma,cts): ''' Wendland 1-D C4 covariance function. Parameters ---------- sigma [mm] : Standard deviation of displacements cts [yr] : Characteristic time-scale ''' return gauss.gpiso(rbf.basis.wen12,(0.0,sigma**2,cts),dim=1) @set_units(['mm','yr']) def wen30(sigma,cts): ''' Wendland 3-D C0 covariance function. Parameters ---------- sigma [mm] : Standard deviation of displacements cts [yr] : Characteristic time-scale ''' return gauss.gpiso(rbf.basis.wen30,(0.0,sigma**2,cts),dim=1) @set_units(['mm','yr']) def spwen11(sigma,cts): ''' Wendland 1-D C2 covariance function. Parameters ---------- sigma [mm] : Standard deviation of displacements cts [yr] : Characteristic time-scale ''' return gauss.gpiso(rbf.basis.spwen11,(0.0,sigma**2,cts),dim=1) @set_units(['mm','yr']) def spwen12(sigma,cts): ''' Wendland 1-D C4 covariance function. Parameters ---------- sigma [mm] : Standard deviation of displacements cts [yr] : Characteristic time-scale ''' return gauss.gpiso(rbf.basis.spwen12,(0.0,sigma**2,cts),dim=1) @set_units(['mm','yr']) def spwen30(sigma,cts): ''' Wendland 3-D C0 covariance function. Parameters ---------- sigma [mm] : Standard deviation of displacements cts [yr] : Characteristic time-scale ''' return gauss.gpiso(rbf.basis.spwen30,(0.0,sigma**2,cts),dim=1) @set_units(['mm','yr']) def se(sigma,cts): ''' Squared exponential covariance function C(t,t') = sigma^2 * exp(-|t - t'|^2/(2*cts^2)) Parameters ---------- sigma [mm] : Standard deviation of displacements cts [yr] : Characteristic time-scale ''' return gauss.gpse((0.0,sigma**2,cts),dim=1) @set_units(['mm','yr']) def exp(sigma,cts): ''' Exponential covariance function C(t,t') = sigma^2 * exp(-|t - t'|/cts) Parameters ---------- sigma [mm] : Standard deviation of displacements cts [yr] : Characteristic time-scale ''' return gauss.gpexp((0.0,sigma**2,cts),dim=1) @set_units(['mm/yr^0.5','yr^-1']) def fogm(sigma,w): ''' First-order Gauss Markov process C(t,t') = sigma^2/(2*w) * exp(-w*|t - t'|) Parameters ---------- sigma [mm/yr^0.5] : Standard deviation of the forcing term w [yr^-1] : Cutoff angular frequency ''' coeff = sigma**2/(2*w) cts = 1.0/w return gauss.gpexp((0.0,coeff,cts),dim=1) @set_units(['mm/yr^0.5','mjd']) def bm(sigma,t0): ''' Brownian motion C(t,t') = sigma^2 * min(t - t0,t' - t0) Parameters ---------- sigma [mm/yr^0.5] : Standard deviation of the forcing term t0 [mjd] : Start time ''' def mean(x): out = np.zeros(x.shape[0]) return out def cov(x1,x2): x1,x2 = np.meshgrid(x1[:,0]-t0,x2[:,0]-t0,indexing='ij') x1[x1<0.0] = 0.0 x2[x2<0.0] = 0.0 out = np.min([x1,x2],axis=0) return sigma**2*out return gauss.GaussianProcess(mean,cov,dim=1) @set_units(['mm/yr^1.5','mjd']) def ibm(sigma,t0): ''' Integrated Brownian motion s = t - t0 C(t,t') = sigma^2 * min(s,s')^2 * (max(s,s') - min(s,s')/3) / 2 Parameters ---------- sigma [mm/yr^1.5] : Standard deviation of the forcing term t0 [mjd] : Start time ''' def mean(x,diff): '''mean function which is zero for all derivatives''' out = np.zeros(x.shape[0]) return out def cov(x1,x2,diff1,diff2): '''covariance function and its derivatives''' x1,x2 = np.meshgrid(x1[:,0]-t0,x2[:,0]-t0,indexing='ij') x1[x1<0.0] = 0.0 x2[x2<0.0] = 0.0 if (diff1 == (0,)) & (diff2 == (0,)): # integrated brownian motion out = (0.5*np.min([x1,x2],axis=0)**2* (np.max([x1,x2],axis=0) - np.min([x1,x2],axis=0)/3.0)) elif (diff1 == (1,)) & (diff2 == (1,)): # brownian motion out = np.min([x1,x2],axis=0) elif (diff1 == (1,)) & (diff2 == (0,)): # derivative w.r.t x1 out = np.zeros_like(x1) idx1 = x1 >= x2 idx2 = x1 < x2 out[idx1] = 0.5*x2[idx1]**2 out[idx2] = x1[idx2]*x2[idx2] - 0.5*x1[idx2]**2 elif (diff1 == (0,)) & (diff2 == (1,)): # derivative w.r.t x2 out = np.zeros_like(x1) idx1 = x2 >= x1 idx2 = x2 < x1 out[idx1] = 0.5*x1[idx1]**2 out[idx2] = x2[idx2]*x1[idx2] - 0.5*x2[idx2]**2 else: raise ValueError( 'The *GaussianProcess* is not sufficiently differentiable') return sigma**2*out return gauss.GaussianProcess(mean,cov,dim=1) CONSTRUCTORS = {'const':const, 'linear':linear, 'per':per, 'step':step, 'bm':bm, 'ibm':ibm, 'fogm':fogm, 'mat32':mat32, 'mat52':mat52, 'wen11':wen11, 'wen12':wen12, 'wen30':wen30, 'spwen11':spwen11, 'spwen12':spwen12, 'spwen30':spwen30, 'se':se, 'exp':exp}
mit
nathansamson/OMF
omf-resctl/ruby/omf-resctl/omf_driver/ethernet.rb
5664
# # Copyright (c) 2006-2008 National ICT Australia (NICTA), Australia # # Copyright (c) 2004-2008 WINLAB, Rutgers University, USA # # 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. # # # = ethernet.rb # # == Description # # This file defines the class EthernetDevice, which is a sub-class of Device. # # require 'omf-resctl/omf_driver/device' # # This class represents an Ethernet device # class EthernetDevice < Device # # Create and set up a new EthernetDevice instance # def initialize(logicalName, deviceName) super(logicalName, deviceName) end # # Return the specific command required to configure a given property of this device. # When a property does not exist for this device, check if it does for its super-class. # # - prop = the property to configure # - value = the value to configure that property to # def getConfigCmd(prop, value) debug "looking for property '#{prop}' in ethernet" case prop when 'ip' return "/sbin/ifconfig #{@deviceName} #{value} netmask 255.255.0.0" when 'up' return "/sbin/ifconfig #{@deviceName} up" when 'down' return "/sbin/ifconfig #{@deviceName} down" when 'netmask' return "/sbin/ifconfig #{@deviceName} netmask #{value}" when 'mtu' return "/sbin/ifconfig #{@deviceName} mtu #{value}" when 'mac' return "/sbin/ifconfig #{@deviceName} hw ether #{value}" when 'arp' dash = (value == 'true') ? '' : '-' return "/sbin/ifconfig #{@deviceName} #{dash}arp" when 'forwarding' flag = (value == 'true') ? '1' : '0' return "echo #{flag} > /proc/sys/net/ipv4/conf/#{@deviceName}/forwarding" when 'route' return getCmdForRoute(value) when 'filter' return getCmdForFilter(value) when 'gateway' return "route del default dev eth1; route add default gw #{value}; route add 224.10.10.6 dev eth1" end super end # # Return the specific command required to configure a 'route' property of this device. # This command is based on the Linux 'route' command # # - value = the value to configure the 'route' property to # def getCmdForRoute(value) param = eval(value) operation = param[:op] if operation == 'add' || operation == 'del' routeCMD = "route #{operation} -net #{param[:net]} " param.each_pair { |k,v| case k when :gw routeCMD << "gw #{v} " when :mask routeCMD << "netmask #{v} " end } routeCMD << "dev #{@deviceName}" else MObject.error "Route configuration - unknown operation: '#{operation}'" routeCMD = "route xxx" # This will raise an error in the calling method end return routeCMD end # # Return the specific command required to configure a 'filter' property of this device. # This command is based on the Linux 'iptables' command # # - value = the value to configure the 'filter' property to # def getCmdForFilter(value) param = eval(value) operation = param[:op] filterCMD = "iptables " param.each {|k,v| } case operation when 'add' filterCMD << "-A " when 'del' filterCMD << "-D " when 'clear' return filterCMD << "-F" else MObject.error "Filter configuration - unknown operation: '#{operation}'" return filterCMD end filterCMD << "#{param[:chain].upcase} -i #{@deviceName} " case param[:proto] when 'tcp', 'udp' filterCMD << "-p #{param[:proto]} " param.each { |k,v| case k when :src filterCMD << "-s #{v} " when :dst filterCMD << "-d #{v} " when :sport filterCMD << "--sport #{v} " when :dport filterCMD << "--dport #{v} " end } when 'mac' filterCMD << "-m mac --mac-source #{param[:src]} " end filterCMD << "-j #{param[:target].upcase}" return filterCMD end def get_property_value(prop) return nil if !RUBY_PLATFORM.include?('linux') case prop when :mac match = /[.\da-fA-F]+\:[.\da-fA-F]+\:[.\da-fA-F]+\:[.\da-fA-F]+\:[.\da-fA-F]+\:[.\da-fA-F]+/ lines = IO.popen("/sbin/ifconfig #{@deviceName}", "r").readlines return lines[0][match] if (lines.length >= 2) return nil when :ip match = /[.\d]+\.[.\d]+\.[.\d]+\.[.\d]+/ lines = IO.popen("/sbin/ifconfig #{@deviceName}", "r").readlines return lines[1][match] if (lines.length >= 2) return nil else return nil end end end
mit
yogeshsaroya/new-cdnjs
ajax/libs/galleria/1.2.4/plugins/picasa/galleria.picasa.min.js
129
version https://git-lfs.github.com/spec/v1 oid sha256:e029d79f6a548bcbd28f03b605ae70134ae177b27287604073902c64e4b31b32 size 3079
mit
tiagosr/unravel
unravel_base.py
2984
""" * Unravel * Interactive Disassembler * (c) 2013 Tiago Rezende * * Base types, classes and algorithms """ class CodeGraphNode: def __init__(self, at, read_as="code"): self.at = at self.read_as = read_as def trace(self, code, deep = False): operation = code.decode(at) self.op = operation self.flow_goto = [] self.flow_call = [] self.flow_data = [] for arrow in operation.arrows: if arrow.type is "goto": self.flow_goto += [code.node_at(arrow.dest, deep),] elif arrow.type is "call": self.flow_call += [code.node_at(arrow.dest, deep),] elif arrow.type is "data": flow = code.node_at(arrow.dest, False) flow.set_read_as(arrow.read_as) self.flow_data += [flow,] class Arrow: def __init__(self, type_, dest, read_as=None): self.type = type_ self.dest = dest self.read_as = read_as class Insn: def __init__(self, mnemo, tags, at, size, info, arrows): self.size = size self.mnemonic = mnemo self.tags = tags self.info = info if arrows: self.arrows = arrows else: self.arrows = [Arrow('goto', at+size)] class InsnDecoder: def __init__(self, image, arch, entry_addresses): self.image = image self.entry_addresses = entry_addresses self.arch = arch self.entry_nodes = {} self.traced_nodes = {} def make_flow_graph(self): for point in self.starting_points: node = CodeGraphNode(point) self.entry_nodes[point] = node node.trace(self, True) def decode(self, at): return self.arch.decode(self.image, at) def node_at(self, at, follow = False): if at in self.traced_nodes: return self.traced_nodes[at] else: node = CodeGraphNode(at) if follow: self.traced_nodes[at] = node node.trace(self, True) return node class ArchBigEndian: def read8(self, image, at): return image.read_byte(at) def read16(self, image, at): return self.read8(image, at)*256 + self.read8(image, at+1) def read32(self, image, at): return self.read16(image, at)*65536 + self.read16(image, at+2) def decode(self, image, at): return Insn('halt', None, []) class ArchLittleEndian: def read8(self, image, at): return image.read_byte(at) def read16(self, image, at): return self.read8(image, at) + self.read8(image, at+1)*256 def read32(self, image, at): return self.read16(image, at) + self.read16(image, at+2)*65536 def decode(self, image, at): return Insn('halt', None, []) def TableMatch(op, at, image, table): for row in table: if (op & row['mask']) == row['match']: return row['fn'](op, at, image, row)
mit
wouterverweirder/kinect2
examples/electron/renderer/assets/vendors/three.js/examples/js/loaders/PCDLoader.js
10256
/** * @author Filipe Caixeta / http://filipecaixeta.com.br * @author Mugen87 / https://github.com/Mugen87 * * Description: A THREE loader for PCD ascii and binary files. * * Limitations: Compressed binary files are not supported. * */ THREE.PCDLoader = function ( manager ) { THREE.Loader.call( this, manager ); this.littleEndian = true; }; THREE.PCDLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), { constructor: THREE.PCDLoader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; var loader = new THREE.FileLoader( scope.manager ); loader.setPath( scope.path ); loader.setResponseType( 'arraybuffer' ); loader.load( url, function ( data ) { try { onLoad( scope.parse( data, url ) ); } catch ( e ) { if ( onError ) { onError( e ); } else { throw e; } } }, onProgress, onError ); }, parse: function ( data, url ) { // from https://gitlab.com/taketwo/three-pcd-loader/blob/master/decompress-lzf.js function decompressLZF( inData, outLength ) { var inLength = inData.length; var outData = new Uint8Array( outLength ); var inPtr = 0; var outPtr = 0; var ctrl; var len; var ref; do { ctrl = inData[ inPtr ++ ]; if ( ctrl < ( 1 << 5 ) ) { ctrl ++; if ( outPtr + ctrl > outLength ) throw new Error( 'Output buffer is not large enough' ); if ( inPtr + ctrl > inLength ) throw new Error( 'Invalid compressed data' ); do { outData[ outPtr ++ ] = inData[ inPtr ++ ]; } while ( -- ctrl ); } else { len = ctrl >> 5; ref = outPtr - ( ( ctrl & 0x1f ) << 8 ) - 1; if ( inPtr >= inLength ) throw new Error( 'Invalid compressed data' ); if ( len === 7 ) { len += inData[ inPtr ++ ]; if ( inPtr >= inLength ) throw new Error( 'Invalid compressed data' ); } ref -= inData[ inPtr ++ ]; if ( outPtr + len + 2 > outLength ) throw new Error( 'Output buffer is not large enough' ); if ( ref < 0 ) throw new Error( 'Invalid compressed data' ); if ( ref >= outPtr ) throw new Error( 'Invalid compressed data' ); do { outData[ outPtr ++ ] = outData[ ref ++ ]; } while ( -- len + 2 ); } } while ( inPtr < inLength ); return outData; } function parseHeader( data ) { var PCDheader = {}; var result1 = data.search( /[\r\n]DATA\s(\S*)\s/i ); var result2 = /[\r\n]DATA\s(\S*)\s/i.exec( data.substr( result1 - 1 ) ); PCDheader.data = result2[ 1 ]; PCDheader.headerLen = result2[ 0 ].length + result1; PCDheader.str = data.substr( 0, PCDheader.headerLen ); // remove comments PCDheader.str = PCDheader.str.replace( /\#.*/gi, '' ); // parse PCDheader.version = /VERSION (.*)/i.exec( PCDheader.str ); PCDheader.fields = /FIELDS (.*)/i.exec( PCDheader.str ); PCDheader.size = /SIZE (.*)/i.exec( PCDheader.str ); PCDheader.type = /TYPE (.*)/i.exec( PCDheader.str ); PCDheader.count = /COUNT (.*)/i.exec( PCDheader.str ); PCDheader.width = /WIDTH (.*)/i.exec( PCDheader.str ); PCDheader.height = /HEIGHT (.*)/i.exec( PCDheader.str ); PCDheader.viewpoint = /VIEWPOINT (.*)/i.exec( PCDheader.str ); PCDheader.points = /POINTS (.*)/i.exec( PCDheader.str ); // evaluate if ( PCDheader.version !== null ) PCDheader.version = parseFloat( PCDheader.version[ 1 ] ); if ( PCDheader.fields !== null ) PCDheader.fields = PCDheader.fields[ 1 ].split( ' ' ); if ( PCDheader.type !== null ) PCDheader.type = PCDheader.type[ 1 ].split( ' ' ); if ( PCDheader.width !== null ) PCDheader.width = parseInt( PCDheader.width[ 1 ] ); if ( PCDheader.height !== null ) PCDheader.height = parseInt( PCDheader.height[ 1 ] ); if ( PCDheader.viewpoint !== null ) PCDheader.viewpoint = PCDheader.viewpoint[ 1 ]; if ( PCDheader.points !== null ) PCDheader.points = parseInt( PCDheader.points[ 1 ], 10 ); if ( PCDheader.points === null ) PCDheader.points = PCDheader.width * PCDheader.height; if ( PCDheader.size !== null ) { PCDheader.size = PCDheader.size[ 1 ].split( ' ' ).map( function ( x ) { return parseInt( x, 10 ); } ); } if ( PCDheader.count !== null ) { PCDheader.count = PCDheader.count[ 1 ].split( ' ' ).map( function ( x ) { return parseInt( x, 10 ); } ); } else { PCDheader.count = []; for ( var i = 0, l = PCDheader.fields.length; i < l; i ++ ) { PCDheader.count.push( 1 ); } } PCDheader.offset = {}; var sizeSum = 0; for ( var i = 0, l = PCDheader.fields.length; i < l; i ++ ) { if ( PCDheader.data === 'ascii' ) { PCDheader.offset[ PCDheader.fields[ i ] ] = i; } else { PCDheader.offset[ PCDheader.fields[ i ] ] = sizeSum; sizeSum += PCDheader.size[ i ]; } } // for binary only PCDheader.rowSize = sizeSum; return PCDheader; } var textData = THREE.LoaderUtils.decodeText( new Uint8Array( data ) ); // parse header (always ascii format) var PCDheader = parseHeader( textData ); // parse data var position = []; var normal = []; var color = []; // ascii if ( PCDheader.data === 'ascii' ) { var offset = PCDheader.offset; var pcdData = textData.substr( PCDheader.headerLen ); var lines = pcdData.split( '\n' ); for ( var i = 0, l = lines.length; i < l; i ++ ) { if ( lines[ i ] === '' ) continue; var line = lines[ i ].split( ' ' ); if ( offset.x !== undefined ) { position.push( parseFloat( line[ offset.x ] ) ); position.push( parseFloat( line[ offset.y ] ) ); position.push( parseFloat( line[ offset.z ] ) ); } if ( offset.rgb !== undefined ) { var rgb = parseFloat( line[ offset.rgb ] ); var r = ( rgb >> 16 ) & 0x0000ff; var g = ( rgb >> 8 ) & 0x0000ff; var b = ( rgb >> 0 ) & 0x0000ff; color.push( r / 255, g / 255, b / 255 ); } if ( offset.normal_x !== undefined ) { normal.push( parseFloat( line[ offset.normal_x ] ) ); normal.push( parseFloat( line[ offset.normal_y ] ) ); normal.push( parseFloat( line[ offset.normal_z ] ) ); } } } // binary-compressed // normally data in PCD files are organized as array of structures: XYZRGBXYZRGB // binary compressed PCD files organize their data as structure of arrays: XXYYZZRGBRGB // that requires a totally different parsing approach compared to non-compressed data if ( PCDheader.data === 'binary_compressed' ) { var sizes = new Uint32Array( data.slice( PCDheader.headerLen, PCDheader.headerLen + 8 ) ); var compressedSize = sizes[ 0 ]; var decompressedSize = sizes[ 1 ]; var decompressed = decompressLZF( new Uint8Array( data, PCDheader.headerLen + 8, compressedSize ), decompressedSize ); var dataview = new DataView( decompressed.buffer ); var offset = PCDheader.offset; for ( var i = 0; i < PCDheader.points; i ++ ) { if ( offset.x !== undefined ) { position.push( dataview.getFloat32( ( PCDheader.points * offset.x ) + PCDheader.size[ 0 ] * i, this.littleEndian ) ); position.push( dataview.getFloat32( ( PCDheader.points * offset.y ) + PCDheader.size[ 1 ] * i, this.littleEndian ) ); position.push( dataview.getFloat32( ( PCDheader.points * offset.z ) + PCDheader.size[ 2 ] * i, this.littleEndian ) ); } if ( offset.rgb !== undefined ) { color.push( dataview.getUint8( ( PCDheader.points * ( offset.rgb + 2 ) + PCDheader.size[ 3 ] * i ) / 255.0 ) ); color.push( dataview.getUint8( ( PCDheader.points * ( offset.rgb + 1 ) + PCDheader.size[ 3 ] * i ) / 255.0 ) ); color.push( dataview.getUint8( ( PCDheader.points * ( offset.rgb + 0 ) + PCDheader.size[ 3 ] * i ) / 255.0 ) ); } if ( offset.normal_x !== undefined ) { normal.push( dataview.getFloat32( ( PCDheader.points * offset.normal_x ) + PCDheader.size[ 4 ] * i, this.littleEndian ) ); normal.push( dataview.getFloat32( ( PCDheader.points * offset.normal_y ) + PCDheader.size[ 5 ] * i, this.littleEndian ) ); normal.push( dataview.getFloat32( ( PCDheader.points * offset.normal_z ) + PCDheader.size[ 6 ] * i, this.littleEndian ) ); } } } // binary if ( PCDheader.data === 'binary' ) { var dataview = new DataView( data, PCDheader.headerLen ); var offset = PCDheader.offset; for ( var i = 0, row = 0; i < PCDheader.points; i ++, row += PCDheader.rowSize ) { if ( offset.x !== undefined ) { position.push( dataview.getFloat32( row + offset.x, this.littleEndian ) ); position.push( dataview.getFloat32( row + offset.y, this.littleEndian ) ); position.push( dataview.getFloat32( row + offset.z, this.littleEndian ) ); } if ( offset.rgb !== undefined ) { color.push( dataview.getUint8( row + offset.rgb + 2 ) / 255.0 ); color.push( dataview.getUint8( row + offset.rgb + 1 ) / 255.0 ); color.push( dataview.getUint8( row + offset.rgb + 0 ) / 255.0 ); } if ( offset.normal_x !== undefined ) { normal.push( dataview.getFloat32( row + offset.normal_x, this.littleEndian ) ); normal.push( dataview.getFloat32( row + offset.normal_y, this.littleEndian ) ); normal.push( dataview.getFloat32( row + offset.normal_z, this.littleEndian ) ); } } } // build geometry var geometry = new THREE.BufferGeometry(); if ( position.length > 0 ) geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( position, 3 ) ); if ( normal.length > 0 ) geometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( normal, 3 ) ); if ( color.length > 0 ) geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( color, 3 ) ); geometry.computeBoundingSphere(); // build material var material = new THREE.PointsMaterial( { size: 0.005 } ); if ( color.length > 0 ) { material.vertexColors = THREE.VertexColors; } else { material.color.setHex( Math.random() * 0xffffff ); } // build point cloud var mesh = new THREE.Points( geometry, material ); var name = url.split( '' ).reverse().join( '' ); name = /([^\/]*)/.exec( name ); name = name[ 1 ].split( '' ).reverse().join( '' ); mesh.name = name; return mesh; } } );
mit
groupefungo/historiqueux
spec/dummy/app/models/horse.rb
84
class Horse < ActiveRecord::Base has_paper_trail belongs_to :dummy_model end
mit
kostyadubinin/watchlist
config/initializers/session_store.rb
172
# frozen_string_literal: true # Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: "_watchlist_session"
mit
danellis/cosmo
cosmo/database.py
2581
import sqlite3 class Database(object): """Data access layer for storing and retrieving triples to/from SQLite database.""" def __init__(self, db_filename, flush=False): """Initialize the database file, creating tables and indices as necessary. :param db_filename: The name of a new or existing SQLite database file :param flush: If True, delete the existing triples """ self.db = sqlite3.connect(db_filename) cursor = self.db.cursor() # Create a table for the triples, but only if it doesn't already exist # Put an index on the page_url column for checking whether we already # crawled a URL cursor.executescript(""" CREATE TABLE IF NOT EXISTS triples ( page_url TEXT NOT NULL, link_type TEXT NOT NULL, link_url TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS triples_page_url_index ON triples(page_url); """) self.db.commit() if flush: self.flush() def flush(self): """Flush stored triples from the database. :returns: None """ cursor = self.db.cursor() cursor.execute("DELETE FROM triples") self.db.commit() def close(self): """Commit any outstanding inserts and then close cleanly :returns: None """ self.db.commit() self.db.close() def is_page_stored(self, page_url): """Check whether any triples for a given URL have already been stored :param page_url: :returns: True if the given page_url already exists in the database, otherwise False """ cursor = self.db.cursor() cursor.execute("SELECT 1 FROM triples WHERE page_url = ? LIMIT 1", (page_url,)) return len(cursor.fetchall()) > 0 def store_triples(self, triples): """Store (page URL, link type, link URL) triples in the database :param triples: Iterable of (page URL, link type, link URL) tuples :returns: None """ cursor = self.db.cursor() cursor.executemany("INSERT INTO triples VALUES (?, ?, ?)", triples) self.db.commit() def get_triples(self): """Retrieve all (page URL, link type, link URL) triples from the database :returns: Iterable of (page URL, link type, link URL) tuples """ cursor = self.db.cursor() cursor.execute("SELECT page_url, link_type, link_url FROM triples ORDER BY page_url, link_type") return cursor.fetchall()
mit
saurabh6790/frappe
frappe/www/login.py
4093
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe import frappe.utils from frappe.utils.oauth import get_oauth2_authorize_url, get_oauth_keys, login_via_oauth2, login_via_oauth2_id_token, login_oauth_user as _login_oauth_user, redirect_post_login import json from frappe import _ from frappe.auth import LoginManager from frappe.integrations.doctype.ldap_settings.ldap_settings import LDAPSettings from frappe.utils.password import get_decrypted_password from frappe.utils.html_utils import get_icon_html from frappe.integrations.oauth2_logins import decoder_compat from frappe.website.utils import get_home_page no_cache = True def get_context(context): redirect_to = frappe.local.request.args.get("redirect-to") if frappe.session.user != "Guest": if not redirect_to: if frappe.session.data.user_type=="Website User": redirect_to = get_home_page() else: redirect_to = "/app" if redirect_to != 'login': frappe.local.flags.redirect_location = redirect_to raise frappe.Redirect # get settings from site config context.no_header = True context.for_test = 'login.html' context["title"] = "Login" context["provider_logins"] = [] context["disable_signup"] = frappe.utils.cint(frappe.db.get_value("Website Settings", "Website Settings", "disable_signup")) context["logo"] = frappe.get_hooks("app_logo_url")[-1] context["app_name"] = frappe.get_system_settings("app_name") or _("Frappe") providers = [i.name for i in frappe.get_all("Social Login Key", filters={"enable_social_login":1}, order_by="name")] for provider in providers: client_id, base_url = frappe.get_value("Social Login Key", provider, ["client_id", "base_url"]) client_secret = get_decrypted_password("Social Login Key", provider, "client_secret") provider_name = frappe.get_value("Social Login Key", provider, "provider_name") icon = None icon_url = frappe.get_value("Social Login Key", provider, "icon") if icon_url: if provider_name != "Custom": icon = "<img src='{0}' alt={1}>".format(icon_url, provider_name) else: icon = get_icon_html(icon_url, small=True) if (get_oauth_keys(provider) and client_secret and client_id and base_url): context.provider_logins.append({ "name": provider, "provider_name": provider_name, "auth_url": get_oauth2_authorize_url(provider, redirect_to), "icon": icon }) context["social_login"] = True ldap_settings = LDAPSettings.get_ldap_client_settings() context["ldap_settings"] = ldap_settings login_label = [_("Email")] if frappe.utils.cint(frappe.get_system_settings("allow_login_using_mobile_number")): login_label.append(_("Mobile")) if frappe.utils.cint(frappe.get_system_settings("allow_login_using_user_name")): login_label.append(_("Username")) context['login_label'] = ' {0} '.format(_('or')).join(login_label) return context @frappe.whitelist(allow_guest=True) def login_via_google(code, state): login_via_oauth2("google", code, state, decoder=decoder_compat) @frappe.whitelist(allow_guest=True) def login_via_github(code, state): login_via_oauth2("github", code, state) @frappe.whitelist(allow_guest=True) def login_via_facebook(code, state): login_via_oauth2("facebook", code, state, decoder=decoder_compat) @frappe.whitelist(allow_guest=True) def login_via_frappe(code, state): login_via_oauth2("frappe", code, state, decoder=decoder_compat) @frappe.whitelist(allow_guest=True) def login_via_office365(code, state): login_via_oauth2_id_token("office_365", code, state, decoder=decoder_compat) @frappe.whitelist(allow_guest=True) def login_via_token(login_token): sid = frappe.cache().get_value("login_token:{0}".format(login_token), expires=True) if not sid: frappe.respond_as_web_page(_("Invalid Request"), _("Invalid Login Token"), http_status_code=417) return frappe.local.form_dict.sid = sid frappe.local.login_manager = LoginManager() redirect_post_login(desk_user = frappe.db.get_value("User", frappe.session.user, "user_type")=="System User")
mit
phavour/phavour
Phavour/Cache/AdapterMemcache.php
6303
<?php /** * Phavour PHP Framework Library * * @author Phavour Project * @copyright 2013-2014 Phavour Project * @link http://phavour-project.com * @license http://phavour-project.com/license * @since 1.0.0 * @package Phavour * * MIT LICENSE * * 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. */ namespace Phavour\Cache; use Exception; use Memcache; /** * AdapterMemcache */ class AdapterMemcache extends AdapterAbstract { /** * @var integer */ const DEFAULT_TTL = 86400; /** * @var Memcache */ private $memcache = null; /** * Construct the adapter, giving an array of servers. * @example * array( * array( * 'host' => 'cache1.example.com', * 'port' => 11211, * 'weight' => 1, * 'timeout' => 60 * ), * array( * 'host' => 'cache2.example.com', * 'port' => 11211, * 'weight' => 2, * 'timeout' => 60 * ) * ) * @param array $servers */ public function __construct(array $servers) { try { $this->memcache = new Memcache(); foreach ($servers as $server) { $this->memcache->addserver( $server['host'], $server['port'], null, $server['weight'], $server['timeout'] ); } } catch (Exception $e) { // @codeCoverageIgnoreStart $this->memcache = null; // @codeCoverageIgnoreEnd } } /** * Get a value from cache * @param string $key * @return mixed|boolean false */ public function get($key) { if (!$this->hasConnection()) { // @codeCoverageIgnoreStart return false; // @codeCoverageIgnoreEnd } try { return $this->memcache->get($key); // @codeCoverageIgnoreStart } catch (Exception $e) { } return false; // @codeCoverageIgnoreEnd } /** * Set a cache value * @param string $key * @param mixed $value * @param integer $ttl (optional) default 86400 * @return boolean */ public function set($key, $value, $ttl = self::DEFAULT_TTL) { if (!$this->hasConnection()) { // @codeCoverageIgnoreStart return false; // @codeCoverageIgnoreEnd } $flag = null; if (!is_bool($value) && !is_int($value) && !is_float($value)) { $flag = MEMCACHE_COMPRESSED; } try { return $this->memcache->set($key, $value, $flag, $ttl); // @codeCoverageIgnoreStart } catch (Exception $e) { } return false; // @codeCoverageIgnoreEnd } /** * Check if a cached key exists. * This method calls get() so if you need a value, use get() * instead. * * @param string $key * @return boolean */ public function has($key) { return ($this->get($key) !== false); } /** * Renew a cached item by key * @param string $key * @param integer $ttl (optional) default 86400 * @return boolean */ public function renew($key, $ttl = self::DEFAULT_TTL) { if (!$this->hasConnection()) { // @codeCoverageIgnoreStart return false; // @codeCoverageIgnoreEnd } $value = $this->get($key); if ($value) { $flag = null; if (!is_bool($value) && !is_int($value) && !is_float($value)) { $flag = MEMCACHE_COMPRESSED; } try { return $this->memcache->replace($key, $value, $flag, $ttl); // @codeCoverageIgnoreStart } catch (Exception $e) { } } // @codeCoverageIgnoreEnd return false; } /** * Remove a cached value by key. * @param string $key * @return boolean */ public function remove($key) { if (!$this->hasConnection()) { // @codeCoverageIgnoreStart return false; // @codeCoverageIgnoreEnd } try { return $this->memcache->delete($key); // @codeCoverageIgnoreStart } catch (Exception $e) { } return false; // @codeCoverageIgnoreEnd } /** * Flush all existing Cache * @return boolean */ public function flush() { if (!$this->hasConnection()) { // @codeCoverageIgnoreStart return false; // @codeCoverageIgnoreEnd } try { return $this->memcache->flush(); // @codeCoverageIgnoreStart } catch (Exception $e) { } return false; // @codeCoverageIgnoreEnd } /** * Check if instance of \Memcache has been assigned * @return boolean */ private function hasConnection() { return ($this->memcache instanceof Memcache); } }
mit
egore/appframework
src/test/java/de/egore911/appframework/mapping/classes/PlainSetClass.java
305
package de.egore911.appframework.mapping.classes; import java.util.HashSet; import java.util.Set; public class PlainSetClass { private Set<String> member = new HashSet<>(); public Set<String> getMember() { return member; } public void setMember(Set<String> member) { this.member = member; } }
mit
mavenlink/brainstem
lib/brainstem/api_docs.rb
4853
require 'active_support/configurable' require 'active_support/core_ext/string/strip' module Brainstem module ApiDocs include ActiveSupport::Configurable config_accessor(:write_path) do File.expand_path("./brainstem_docs") end # # Defines the naming pattern of the Open API Specification file. # # The following tokens will be substituted: # # - {{version}} : the specified version # - {{extension} : the specified file extension # # @see #output_extension # config_accessor(:oas_filename_pattern) do File.join("endpoints", "{{version}}.{{extension}}") end # # Defines the naming pattern of each controller documentation file. # # The following tokens will be substituted: # # - {{namespace}} : the namespace of the controller underscored, # i.e. 'api/v1' # - {{name}} : the underscored name of the controller without # 'controller' # - {{extension} : the specified file extension # # @see #output_extension # config_accessor(:controller_filename_pattern) do File.join("endpoints", "{{name}}.{{extension}}") end # # Defines the naming pattern of each presenter documentation file. # # The following tokens will be substituted: # # - {{name}} : the demodulized underscored name of the presenter # - {{extension} : the specified file extension # # @see #output_extension # config_accessor(:presenter_filename_pattern) do File.join("objects", "{{name}}.{{extension}}") end # # Defines the naming pattern for the relative link to each controller documentation file. # # The following tokens will be substituted: # # - {{name}} : the underscored name of the controller without 'controller' # - {{extension} : the specified file extension # # @see #output_extension # config_accessor(:controller_filename_link_pattern) do controller_filename_pattern end # # Defines the naming pattern for the relative link to each presenter documentation file. # # The following tokens will be substituted: # # - {{name}} : the demodulized underscored name of the presenter # - {{extension} : the specified file extension # # @see #output_extension # config_accessor(:presenter_filename_link_pattern) do presenter_filename_pattern end # # Defines the base path for the given API. # config_accessor(:base_path) { "/v2" } # # Defines the extension that should be used for output files. # # Excludes the '.'. # config_accessor(:output_extension) { "markdown" } # # Defines the class that all presenters should inherit from / be drawn # from. # # Is a string because most relevant classes are not loaded until much # later. # # @see Brainstem::ApiDocs::RailsIntrospector#base_presenter_class= # config_accessor(:base_presenter_class) do "::Brainstem::Presenter" end # # Defines the class that all controllers should inherit from / be drawn # from. # # Is a string because most relevant classes are not loaded until much # later. # # @see Brainstem::ApiDocs::RailsIntrospector#base_controller_class= # config_accessor(:base_controller_class) do "::ApplicationController" end # # Defines the alternate application or engine that all routes will be fetched from. # # @see Brainstem::ApiDocs::RailsIntrospector#base_application_class= # config_accessor(:base_application_class) { nil } # # If associations on a presenter have no description, i.e. no documentation, # should they be documented anyway? # config_accessor(:document_empty_presenter_associations) { true } # # If filters on a presenter have no `:info` key, i.e. no documentation, # should they be documented anyway? # config_accessor(:document_empty_presenter_filters) { true } FORMATTERS = { # Formatter for entire response document: {}, # Formatters for collections controller_collection: {}, endpoint_collection: {}, presenter_collection: {}, # Formatters for individual entities controller: {}, endpoint: {}, presenter: {}, # Formatter for Open API Specifications info: {}, response: {}, parameters: {}, security: {}, tags: {}, # Formatter for Open API Specifications Individual field / param definition endpoint_param: {}, presenter_field: {}, response_field: {}, } end end formatter_path = File.expand_path('../formatters/**/*.rb', __FILE__) Dir.glob(formatter_path).each { |f| require f }
mit
tsechingho/ajax-tutorial
spec/controllers/creatures_controller_spec.rb
6213
require 'spec_helper' # This spec was generated by rspec-rails when you ran the scaffold generator. # It demonstrates how one might use RSpec to specify the controller code that # was generated by Rails when you ran the scaffold generator. # # It assumes that the implementation code is generated by the rails scaffold # generator. If you are using any extension libraries to generate different # controller code, this generated spec may or may not pass. # # It only uses APIs available in rails and/or rspec-rails. There are a number # of tools you can use to make these specs even more expressive, but we're # sticking to rails and rspec-rails APIs to keep things simple and stable. # # Compared to earlier versions of this generator, there is very limited use of # stubs and message expectations in this spec. Stubs are only used when there # is no simpler way to get a handle on the object needed for the example. # Message expectations are only used when there is no simpler way to specify # that an instance is receiving a specific message. describe CreaturesController do # This should return the minimal set of attributes required to create a valid # Creature. As you add validations to Creature, be sure to # update the return value of this method accordingly. def valid_attributes {} end # This should return the minimal set of values that should be in the session # in order to pass any filters (e.g. authentication) defined in # CreaturesController. Be sure to keep this updated too. def valid_session {} end describe "GET index" do it "assigns all creatures as @creatures" do creature = Creature.create! valid_attributes get :index, {}, valid_session assigns(:creatures).should eq([creature]) end end describe "GET show" do it "assigns the requested creature as @creature" do creature = Creature.create! valid_attributes get :show, {:id => creature.to_param}, valid_session assigns(:creature).should eq(creature) end end describe "GET new" do it "assigns a new creature as @creature" do get :new, {}, valid_session assigns(:creature).should be_a_new(Creature) end end describe "GET edit" do it "assigns the requested creature as @creature" do creature = Creature.create! valid_attributes get :edit, {:id => creature.to_param}, valid_session assigns(:creature).should eq(creature) end end describe "POST create" do describe "with valid params" do it "creates a new Creature" do expect { post :create, {:creature => valid_attributes}, valid_session }.to change(Creature, :count).by(1) end it "assigns a newly created creature as @creature" do post :create, {:creature => valid_attributes}, valid_session assigns(:creature).should be_a(Creature) assigns(:creature).should be_persisted end it "redirects to the created creature" do post :create, {:creature => valid_attributes}, valid_session response.should redirect_to(Creature.last) end end describe "with invalid params" do it "assigns a newly created but unsaved creature as @creature" do # Trigger the behavior that occurs when invalid params are submitted Creature.any_instance.stub(:save).and_return(false) post :create, {:creature => {}}, valid_session assigns(:creature).should be_a_new(Creature) end it "re-renders the 'new' template" do # Trigger the behavior that occurs when invalid params are submitted Creature.any_instance.stub(:save).and_return(false) post :create, {:creature => {}}, valid_session response.should render_template("new") end end end describe "PUT update" do describe "with valid params" do it "updates the requested creature" do creature = Creature.create! valid_attributes # Assuming there are no other creatures in the database, this # specifies that the Creature created on the previous line # receives the :update_attributes message with whatever params are # submitted in the request. Creature.any_instance.should_receive(:update_attributes).with({'these' => 'params'}) put :update, {:id => creature.to_param, :creature => {'these' => 'params'}}, valid_session end it "assigns the requested creature as @creature" do creature = Creature.create! valid_attributes put :update, {:id => creature.to_param, :creature => valid_attributes}, valid_session assigns(:creature).should eq(creature) end it "redirects to the creature" do creature = Creature.create! valid_attributes put :update, {:id => creature.to_param, :creature => valid_attributes}, valid_session response.should redirect_to(creature) end end describe "with invalid params" do it "assigns the creature as @creature" do creature = Creature.create! valid_attributes # Trigger the behavior that occurs when invalid params are submitted Creature.any_instance.stub(:save).and_return(false) put :update, {:id => creature.to_param, :creature => {}}, valid_session assigns(:creature).should eq(creature) end it "re-renders the 'edit' template" do creature = Creature.create! valid_attributes # Trigger the behavior that occurs when invalid params are submitted Creature.any_instance.stub(:save).and_return(false) put :update, {:id => creature.to_param, :creature => {}}, valid_session response.should render_template("edit") end end end describe "DELETE destroy" do it "destroys the requested creature" do creature = Creature.create! valid_attributes expect { delete :destroy, {:id => creature.to_param}, valid_session }.to change(Creature, :count).by(-1) end it "redirects to the creatures list" do creature = Creature.create! valid_attributes delete :destroy, {:id => creature.to_param}, valid_session response.should redirect_to(creatures_url) end end end
mit
Horizon-Blue/playground
Solutions-to-Books/C++Primer/Chapter05/5.20.cpp
450
// Xiaoyan Wang 12/27/2015 #include <iostream> #include <string> using namespace std; int main() { string previous = "", current; bool repeated = false; while(cin >> current) { if(previous != current) previous = current; else { repeated = true; break; } } if(repeated) cout << "The word \"" << previous << "\" was repeated." << endl; else cout << "No word was repeated." << endl; return 0; }
mit
xincap/erp
lib/jd/Request/HostingdataJddpDataListGetPaipaiRequest.php
1650
<?php namespace Jd\Request; class HostingdataJddpDataListGetPaipaiRequest { private $apiParas = array(); public function getApiMethodName(){ return "jingdong.hostingdata.jddp.data.list.get.paipai"; } public function getApiParas(){ return json_encode($this->apiParas); } public function check(){ } public function putOtherTextParam($key, $value){ $this->apiParas[$key] = $value; $this->$key = $value; } private $sqlId; public function setSqlId($sqlId){ $this->sqlId = $sqlId; $this->apiParas["sqlId"] = $sqlId; } public function getSqlId(){ return $this->sqlId; } private $parameter; public function setParameter($parameter){ $this->parameter = $parameter; $this->apiParas["parameter"] = $parameter; } public function getParameter(){ return $this->parameter; } private $pin; public function setPin($pin){ $this->pin = $pin; $this->apiParas["pin"] = $pin; } public function getPin(){ return $this->pin; } private $venderId; public function setVenderId($venderId){ $this->venderId = $venderId; $this->apiParas["venderId"] = $venderId; } public function getVenderId(){ return $this->venderId; } }
mit
nbibler/yahoo_site_explorer
lib/yahoo_site_explorer/results_container.rb
1456
class YahooSiteExplorer class ResultsContainer #:nodoc: include Enumerable attr_reader :total_results_available, :total_results_returned, :first_result_position, :results def initialize(service, request_options, results_hash = {}) #:nodoc: @service = service @request_options = request_options parse_hash(results_hash) end protected ## # Returns the starting position for a query that would subsequently # follow the current result set. # def next_starting_position @first_result_position + @total_results_returned end def parse_hash(backlinks_hash) #:nodoc: @total_results_available = numeric(backlinks_hash[:total_results_available]) @total_results_returned = numeric(backlinks_hash[:total_results_returned]) @first_result_position = numeric(backlinks_hash[:first_result_position]) @results = collect_results(backlinks_hash[:results]) end def collect_results(results) #:nodoc: collection = [] return unless results.respond_to?(:each) results.each do |result| collection << Result.new(result[:title], result[:url], result[:click_url]) end collection end def numeric(value, nil_value = nil) #:nodoc: value ? value.to_i : nil_value end end end
mit
minjia-tang/snafoo
application/views/templates/header.php
3202
<!doctype html> <html class="no-js" lang="en-us"> <head> <!-- META DATA --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!--[if IE]><meta http-equiv="cleartype" content="on" /><![endif]--> <!-- SEO --> <title>SnaFoo - Nerdery Snack Food Ordering System</title> <!-- ICONS --> <link rel="apple-touch-icon" sizes="57x57" href="<?=base_url()?>assets/media/images/favicon/apple-touch-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="<?=base_url()?>assets/media/images/favicon/apple-touch-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="<?=base_url()?>assets/media/images/favicon/apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="<?=base_url()?>assets/media/images/favicon/apple-touch-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="<?=base_url()?>assets/media/images/favicon/apple-touch-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="<?=base_url()?>assets/media/images/favicon/apple-touch-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="<?=base_url()?>assets/media/images/favicon/apple-touch-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="<?=base_url()?>assets/media/images/favicon/apple-touch-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="<?=base_url()?>assets/media/images/favicon/apple-touch-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="<?=base_url()?>assets/media/images/favicon/favicon-192x192.png"> <link rel="icon" type="image/png" sizes="160x160" href="<?=base_url()?>assets/media/images/favicon/favicon-160x160.png"> <link rel="icon" type="image/png" sizes="96x96" href="<?=base_url()?>assets/media/images/favicon/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="32x32" href="<?=base_url()?>assets/media/images/favicon/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="<?=base_url()?>assets/media/images/favicon/favicon-16x16.png"> <meta name="msapplication-TileImage" content="<?=base_url()?>assets/media/images/favicon/mstile-144x144.png"> <meta name="msapplication-TileColor" content="#ff0000"> <!-- STYLESHEETS --> <link rel="stylesheet" media="screen, projection" href="<?=base_url()?>assets/styles/modern.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> </head> <body> <div class="masthead" role="banner"> <div class="masthead-hd"> <h1 class="hdg hdg_1 mix-hdg_extraBold"><a href="index.html">SnaFoo</a> </h1> <p class="masthead-hd-sub">Nerdery Snack Food Ordering System</p> </div> <div class="masthead-nav" role="navigation"> <ul> <li><a href="<?=base_url()?>">Voting</a> </li> <li><a href="<?=base_url()?>index.php/suggestions">Suggestions</a> </li> <li><a href="<?=base_url()?>index.php/shoppinglist">Shopping List</a> </li> </ul> </div> </div>
mit
jedi-academy/umbrella
application/controllers/Work.php
9422
<?php /** * Work service for factory apps. * * This controller provides a number of services that a factory * app can request. * * @package Panda Research Center * @author J.L. Parry * @link https://umbrella.jlparry.com/help */ class Work extends CI_Controller { // constructor function __construct() { parent::__construct(); $this->load->library('engine'); // was a PRC session token provided? $this->trader = NULL; $this->token = $this->input->get('key'); if (!empty($this->token)) { $prc_session = $this->trading->get($this->token); $this->trader = empty($prc_session) ? 'Bogus' : $prc_session->factory; } } /** * Normal entry point ... should never get here */ public function index() { redirect('/'); } /** * Register a new trading session for a factory * * @param string $team Factory (team) name * @param string $password Super-secret access token for the factory * @return The API key */ function registerme($team = NULL, $password = NULL) { $oops = ''; // verify username (group) & password presence if (empty($team)) $oops .= 'Team needed! '; if (empty($password)) $oops .= 'Password needed! '; // check user validitity $factory = NULL; // assume the worst if (empty($oops)) { $factory = $this->factories->get($team); if ($factory == NULL) $oops .= 'No such team! '; } // check the password, and its hash if needed if (empty($oops)) { $okok = FALSE; if (strlen($factory->token) < 8) { // original token still in place $okok = ($password == $factory->token); $this->harden($factory); } else { $okok = password_verify($password, $factory->token); } if (!$okok) $oops .= 'Bad password! '; } // if anything went wrong, redisplay the page if (!empty($oops)) { // ignore invalid credentials echo 'Oops: ' . $oops; } else { // otherwise, consider them good to go $apikey = $this->engine->randomToken(); $oldTrader = $this->trading->some('factory', $team); if (!empty($oldTrader)) foreach ($oldTrader as $record) $this->trading->delete($record->token); $trader = $this->trading->create(); $trader->token = $apikey; $trader->factory = $team; $this->trading->add($trader); $oldStats = $this->stats->get($team); if (!empty($oldStats)) $this->stats->delete($team); $stat = $this->stats->create(); $stat->id = $team; $stat->balance = $this->properties->get('ante'); $stat->making = $this->engine->pickapart(); $stat->last_made = date('Y-m-d H:i:s.'); $this->stats->add($stat); $this->activity->record($team, 'registered'); echo 'Ok ' . $apikey; } } // Convert plaintext token into hash, for better security private function harden($factory) { $factory->token = password_hash($factory->token, PASSWORD_DEFAULT); $this->factories->update($factory); } /** * Purchase a box of random parts for your factory to use * * @param string $key Factory's API key (passed as query parameter) * @return An array of parts certificates, JSON formatted */ function buybox() { // basic fact-checking if (empty($this->trader)) { echo "Oops: I don't recognize you!"; return; } // make sure they can afford it $cost = $this->properties->get('priceperpack'); $stat = $this->stats->get($this->trader); if ($stat->balance < $cost) { echo "Oops: you can't afford that!"; return; } // go get em $result = $this->engine->fillabox($this->trader); // charge them for it $stat->balance -= $cost; $stat->boxes_bought++; $this->stats->update($stat); $this->activity->record($this->trader, 'bought a box of parts'); $this->history->record($this->trader,'Parts bought',10, -100); echo json_encode($result); } /** * Requests any newly built parts for this factory * * @param string $key Factory's API key (passed as query parameter) * @return An array of parts certificates, JSON formatted */ function mybuilds() { // basic fact-checking if (empty($this->trader)) { echo "Oops: I don't recognize you!"; return; } // go get em $result = $this->engine->fulfill($this->trader); $stat = $this->stats->get($this->trader); $stat->last_made = date('Y-m-d H:i:s.'); $stat->parts_made += count($result); $this->stats->update($stat); if (count($result) > 0) $this->activity->record($this->trader, 'built ' . count($result) . ' parts'); echo json_encode($result); } /** * Ask the PRC to recycle up to three parts that you do not want * * @param string $part1 Certificate code for a part to return * @param string $part2 Certificate code for a part to return * @param string $part3 Certificate code for a part to return * @param string $key Factory's API key (passed as query parameter) * @return "Ok AMOUNT" (where AMOUNT is the value credited to your account balance) or an error message */ function recycle($part1 = NULL, $part2 = NULL, $part3 = NULL) { // basic fact-checking if (empty($this->trader)) { echo "Oops: I don't recognize you!"; return; } // let's do this $count = 0; $refund = 0; if (!empty($part1)) { $result = $this->engine->recycle($this->trader, $part1); if ($result > 0) { $count++; $refund += $result; } } if (!empty($part2)) { $result = $this->engine->recycle($this->trader, $part2); if ($result > 0) { $count++; $refund += $result; } } if (!empty($part3)) { $result = $this->engine->recycle($this->trader, $part3); if ($result > 0) { $count++; $refund += $result; } } $stat = $this->stats->get($this->trader); $stat->last_made = date('Y-m-d H:i:s.'); $stat->parts_returned += $count; $stat->balance += $refund; $this->stats->update($stat); if ($count > 0) { $this->activity->record($this->trader, 'returned ' . $count . ' parts'); $this->history->record($this->trader, 'Parts recycled', $count, $refund); } echo 'Ok ' . $refund; // echo $this->engine->eligible($this->trader); } /** * Ask the PRC to buy an assembled bot from you * * @param string $part1 Certificate code for the "top" part of your bot * @param string $part2 Certificate code for the "torso" part of your bot * @param string $part3 Certificate code for the "bottom" part of your bot * @param string $key Factory's API key (passed as query parameter) * @return "Ok AMOUNT" (where AMOUNT is the value credited to your account balance) or an error message */ function buymybot($part1 = NULL, $part2 = NULL, $part3 = NULL) { // basic fact-checking if (empty($this->trader)) { echo "Oops: I don't recognize you!"; return; } // Did they provide a complete bot? if (empty($part1) || empty($part2) || empty($part3)) { echo "Oops: you didn't provide a completed bot."; return; } // Check out the pieces $oops = ''; $oops .= $this->checkit($part1, 1); $oops .= $this->checkit($part2, 2); $oops .= $this->checkit($part3, 3); if (!empty($oops)) { echo "Oops: " . $oops; return; } // let's do this $result = $this->engine->buymybot($part1, $part2, $part3); $stat = $this->stats->get($this->trader); $stat->bots_built++; $stat->balance += $result; $this->stats->update($stat); $this->activity->record($this->trader, 'sold us a bot'); $this->history->record($this->trader,'Bot sold',1, $result); echo 'Ok ' . $result; } // Vet a bot piece private function checkit($part, $piece) { $result = ''; // get the part $record = $this->parts->get($part); if (empty($record)) return "Hmmm - can't find " . $part . ' '; // does this piece belong to the factory claiming it? if ($record->plant != $this->trader) $result .= $part . ' not your part! '; // is it the right kind of piece? if ($record->piece != $piece) $result .= $part . ' not the right kind of piece! '; return $result; } /** * Restart your bot factory's participation in the current trading session * * @param string $key Factory's API key (passed as query parameter) * @return "Ok AMOUNT" (where AMOUNT is the starting balance assigned to you) or an error message */ function rebootme() { // basic fact-checking if (empty($this->trader)) { echo "Oops: I don't recognize you!"; return; } $stat = $this->stats->get($this->trader); $stat->balance = $this->properties->get('ante'); $this->stats->update($stat); $records = $this->parts->some('plant', $this->trader); if (!empty($records)) foreach ($records as $record) $this->parts->delete($record->id); $this->activity->record($this->trader, 'rebooted.'); echo "Ok"; } /** * Destroy your plants' PRC trading session * * @param string $key Factory's API key (passed as query parameter) * @return "Ok" or an error message */ function goodbye() { // basic fact-checking if (empty($this->trader)) { echo "Oops: I don't recognize you!"; return; } $stat = $this->stats->get($this->trader); $stat->balance = $this->properties->get('ante'); $this->stats->update($stat); $records = $this->parts->some('plant', $this->trader); if (!empty($records)) foreach ($records as $record) $this->parts->delete($record->id); $this->trading->delete($this->token); $this->activity->record($this->trader, 'left the game.'); echo "Ok"; } }
mit
TsvetanMilanov/TelerikAcademyFinalExams
JavaScriptApplicationsFinalExam/public/js/utilities.js
1591
var utilities = (function () { var USER_KEY = 'user', AUTH_KEY = 'authKey'; function toggleAuthControls() { var currentUser = getCurrentUser(); if (currentUser != null) { $('.login-li').hide(); $('.register-li').hide(); $('.logout-li').show(); } else { $('.login-li').show(); $('.register-li').show(); $('.logout-li').hide(); } } function setCurrentUser(data) { if (!data) { localStorage.removeItem(USER_KEY); localStorage.removeItem(AUTH_KEY); } else { localStorage.setItem(USER_KEY, data.username); localStorage.setItem(AUTH_KEY, data.authKey); } } function getCurrentUser() { var currentUser = { username: localStorage.getItem(USER_KEY), authKey: localStorage.getItem(AUTH_KEY) }; if (!currentUser.username || !currentUser.authKey) { return null; } return currentUser; } function hideElements(elements) { elements.forEach(function (elementSelector) { $(elementSelector).hide(); }) } function showElements(elements) { elements.forEach(function (elementSelector) { $(elementSelector).show(); }) } return { toggleAuthControls: toggleAuthControls, setCurrentUser: setCurrentUser, getCurrentUser: getCurrentUser, hideElements: hideElements, showElements: showElements }; }());
mit
blacklabcapital/darkfeed
go/schemas/fb/SSBEntry.go
2135
// automatically generated by the FlatBuffers compiler, do not modify package fb import ( flatbuffers "github.com/google/flatbuffers/go" ) type SSBEntry struct { _tab flatbuffers.Table } func GetRootAsSSBEntry(buf []byte, offset flatbuffers.UOffsetT) *SSBEntry { n := flatbuffers.GetUOffsetT(buf[offset:]) x := &SSBEntry{} x.Init(buf, n+offset) return x } func (rcv *SSBEntry) Init(buf []byte, i flatbuffers.UOffsetT) { rcv._tab.Bytes = buf rcv._tab.Pos = i } func (rcv *SSBEntry) Table() flatbuffers.Table { return rcv._tab } func (rcv *SSBEntry) Symbol(obj *Symbol) *Symbol { o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) if o != 0 { x := rcv._tab.Indirect(o + rcv._tab.Pos) if obj == nil { obj = new(Symbol) } obj.Init(rcv._tab.Bytes, x) return obj } return nil } func (rcv *SSBEntry) RawSym() []byte { o := flatbuffers.UOffsetT(rcv._tab.Offset(6)) if o != 0 { return rcv._tab.ByteVector(o + rcv._tab.Pos) } return nil } func (rcv *SSBEntry) States(obj *SecondState, j int) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(8)) if o != 0 { x := rcv._tab.Vector(o) x += flatbuffers.UOffsetT(j) * 44 obj.Init(rcv._tab.Bytes, x) return true } return false } func (rcv *SSBEntry) StatesLength() int { o := flatbuffers.UOffsetT(rcv._tab.Offset(8)) if o != 0 { return rcv._tab.VectorLen(o) } return 0 } func SSBEntryStart(builder *flatbuffers.Builder) { builder.StartObject(3) } func SSBEntryAddSymbol(builder *flatbuffers.Builder, symbol flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(symbol), 0) } func SSBEntryAddRawSym(builder *flatbuffers.Builder, rawSym flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(1, flatbuffers.UOffsetT(rawSym), 0) } func SSBEntryAddStates(builder *flatbuffers.Builder, states flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(2, flatbuffers.UOffsetT(states), 0) } func SSBEntryStartStatesVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(44, numElems, 4) } func SSBEntryEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { return builder.EndObject() }
mit
danisio/HQC-HighQualityCode-Homeworks
11.TestDrivenDevelopment(TDD)/PokerTests/ClassHandTests.cs
1662
namespace PokerTests { using System; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Poker; [TestClass] public class ClassHandTests { [TestMethod] public void TestToString_ShouldWorkProperly() { var cards = new List<ICard>() { new Card(CardFace.Ace, CardSuit.Hearts), new Card(CardFace.Ten, CardSuit.Hearts) }; var hand = new Hand(cards); var expected = "Ace of Hearts - Ten of Hearts"; Assert.AreEqual(expected, hand.ToString()); } [TestMethod] public void CreateHand_ShouldAddCardsProperly_WhenCardsAreValid() { var cards = new List<ICard>() { new Card(CardFace.Ace, CardSuit.Hearts), new Card(CardFace.Ten, CardSuit.Hearts) }; var hand = new Hand(cards); Assert.AreEqual(hand.Cards.First(), cards.First()); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void CreateHand_ShouldThrow_WhenListOfCardsIsNull() { var hand = new Hand(null); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void CreateHand_ShouldThrow_WhenSomeOfTheCardsAreNull() { var cards = new List<ICard>() { new Card(CardFace.Ace, CardSuit.Hearts), null }; var hand = new Hand(cards); } } }
mit
peteratseneca/bti420winter2017
Week_04/AssocOneToMany/AssocOneToMany/Controllers/AccountController.cs
17400
using System; using System.Globalization; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using AssocOneToMany.Models; namespace AssocOneToMany.Controllers { [Authorize] public class AccountController : Controller { private ApplicationSignInManager _signInManager; private ApplicationUserManager _userManager; public AccountController() { } public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager ) { UserManager = userManager; SignInManager = signInManager; } public ApplicationSignInManager SignInManager { get { return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); } private set { _signInManager = value; } } public ApplicationUserManager UserManager { get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } } // // GET: /Account/Login [AllowAnonymous] public ActionResult Login(string returnUrl) { ViewBag.ReturnUrl = returnUrl; return View(); } // // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false); switch (result) { case SignInStatus.Success: return RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.RequiresVerification: return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return View(model); } } // // GET: /Account/VerifyCode [AllowAnonymous] public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe) { // Require that the user has already logged in via username/password or external login if (!await SignInManager.HasBeenVerifiedAsync()) { return View("Error"); } return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/VerifyCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model) { if (!ModelState.IsValid) { return View(model); } // The following code protects for brute force attacks against the two factor codes. // If a user enters incorrect codes for a specified amount of time then the user account // will be locked out for a specified amount of time. // You can configure the account lockout settings in IdentityConfig var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser); switch (result) { case SignInStatus.Success: return RedirectToLocal(model.ReturnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid code."); return View(model); } } // // GET: /Account/Register [AllowAnonymous] public ActionResult Register() { return View(); } // // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return RedirectToAction("Index", "Home"); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/ConfirmEmail [AllowAnonymous] public async Task<ActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return View("Error"); } var result = await UserManager.ConfirmEmailAsync(userId, code); return View(result.Succeeded ? "ConfirmEmail" : "Error"); } // // GET: /Account/ForgotPassword [AllowAnonymous] public ActionResult ForgotPassword() { return View(); } // // POST: /Account/ForgotPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { var user = await UserManager.FindByNameAsync(model.Email); if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id))) { // Don't reveal that the user does not exist or is not confirmed return View("ForgotPasswordConfirmation"); } // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id); // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>"); // return RedirectToAction("ForgotPasswordConfirmation", "Account"); } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/ForgotPasswordConfirmation [AllowAnonymous] public ActionResult ForgotPasswordConfirmation() { return View(); } // // GET: /Account/ResetPassword [AllowAnonymous] public ActionResult ResetPassword(string code) { return code == null ? View("Error") : View(); } // // POST: /Account/ResetPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await UserManager.FindByNameAsync(model.Email); if (user == null) { // Don't reveal that the user does not exist return RedirectToAction("ResetPasswordConfirmation", "Account"); } var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password); if (result.Succeeded) { return RedirectToAction("ResetPasswordConfirmation", "Account"); } AddErrors(result); return View(); } // // GET: /Account/ResetPasswordConfirmation [AllowAnonymous] public ActionResult ResetPasswordConfirmation() { return View(); } // // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult ExternalLogin(string provider, string returnUrl) { // Request a redirect to the external login provider return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl })); } // // GET: /Account/SendCode [AllowAnonymous] public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe) { var userId = await SignInManager.GetVerifiedUserIdAsync(); if (userId == null) { return View("Error"); } var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId); var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList(); return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/SendCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> SendCode(SendCodeViewModel model) { if (!ModelState.IsValid) { return View(); } // Generate the token and send it if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider)) { return View("Error"); } return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe }); } // // GET: /Account/ExternalLoginCallback [AllowAnonymous] public async Task<ActionResult> ExternalLoginCallback(string returnUrl) { var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { return RedirectToAction("Login"); } // Sign in the user with this external login provider if the user already has a login var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false); switch (result) { case SignInStatus.Success: return RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.RequiresVerification: return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }); case SignInStatus.Failure: default: // If the user does not have an account, then prompt the user to create an account ViewBag.ReturnUrl = returnUrl; ViewBag.LoginProvider = loginInfo.Login.LoginProvider; return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email }); } } // // POST: /Account/ExternalLoginConfirmation [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Index", "Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); } // // POST: /Account/LogOff [HttpPost] [ValidateAntiForgeryToken] public ActionResult LogOff() { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); return RedirectToAction("Index", "Home"); } // // GET: /Account/ExternalLoginFailure [AllowAnonymous] public ActionResult ExternalLoginFailure() { return View(); } protected override void Dispose(bool disposing) { if (disposing) { if (_userManager != null) { _userManager.Dispose(); _userManager = null; } if (_signInManager != null) { _signInManager.Dispose(); _signInManager = null; } } base.Dispose(disposing); } #region Helpers // Used for XSRF protection when adding external logins private const string XsrfKey = "XsrfId"; private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } private ActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } return RedirectToAction("Index", "Home"); } internal class ChallengeResult : HttpUnauthorizedResult { public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null) { } public ChallengeResult(string provider, string redirectUri, string userId) { LoginProvider = provider; RedirectUri = redirectUri; UserId = userId; } public string LoginProvider { get; set; } public string RedirectUri { get; set; } public string UserId { get; set; } public override void ExecuteResult(ControllerContext context) { var properties = new AuthenticationProperties { RedirectUri = RedirectUri }; if (UserId != null) { properties.Dictionary[XsrfKey] = UserId; } context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider); } } #endregion } }
mit
luma211/snowflake
SampleTest/DetectHMD/Oculus/OculusPch.cpp
22
#include "OculusPch.h"
mit
ruudgreven/homewizard-lib-java
src/main/java/nl/rgonline/homewizardlib/sensors/HWSensor.java
760
package nl.rgonline.homewizardlib.sensors; import lombok.Getter; import lombok.Setter; import lombok.ToString; import nl.rgonline.homewizardlib.AbstractHwEntity; import nl.rgonline.homewizardlib.HWConnection; /** * Represents a sensor in the HomeWizard system. * @author pdegeus */ @ToString(callSuper = true) public class HWSensor extends AbstractHwEntity { @Getter @Setter protected boolean on; /** * Constructor. * @param connection Connection to use. * @param id Sensor ID. * @param name Sensor name. * @param isOn True if sensor is currently 'on'. */ protected HWSensor(HWConnection connection, int id, String name, boolean isOn) { super(connection, id, name); this.on = isOn; } }
mit
drcypher/phpbogo
src/main/Util/Json.php
4649
<?php namespace Bogo\Util; /** * Json helper functions. * * Adds the following functionality: * <ul> * <li>JSON string validation: Util\Json::isValid()</li> * <li>JSON formatting/indentation: Util\Json::indent()</li> * <li>JSON soft decoding: Util\Json::softDecode*() (<i>does not fail if json is invalid</i>)</li> * </ul> * * @since 1.0 * @package Components * @author Konstantinos Filios <[email protected]> */ class Json { /** * Check if passed string is valid json. * * @param string $json Json string. * * @return boolean True if passed $json is valid */ static public function isValid($json) { return is_string($json) && (json_decode($json) != null); } /** * Indent passed $json string to increase human-readability. * * @see http://recursive-design.com/blog/2008/03/11/format-json-with-php/ * * @param string $json Unformatted json. * @param string $indentStr Indentation string (tabulator). * @param string $newLine Line terminator. * * @return string */ static public function indent($json, $indentStr = ' ', $newLine = "\n") { $result = ''; $pos = 0; $strLen = strlen($json); $prevChar = ''; $outOfQuotes = true; for ($i = 0; $i <= $strLen; $i++) { // Grab the next character in the string. $char = substr($json, $i, 1); // Are we inside a quoted string? if ($char == '"' && $prevChar != '\\') { $outOfQuotes = !$outOfQuotes; // If this character is the end of an element, // output a new line and indent the next line. } else if (($char == '}' || $char == ']') && $outOfQuotes) { $result .= $newLine; $pos--; for ($j = 0; $j < $pos; $j++) { $result .= $indentStr; } } // Add the character to the result string. $result .= $char; // If the last character was the beginning of an element, // output a new line and indent the next line. if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes) { $result .= $newLine; if ($char == '{' || $char == '[') { $pos++; } for ($j = 0; $j < $pos; $j++) { $result .= $indentStr; } } $prevChar = $char; } return $result; } /** * Returns string/text describing the last error occured while json encoding/decoding. * * This is supported only for php 5.3 or later. * * @see http://www.php.net/manual/en/function.json-last-error.php * * @return string */ static public function getLastErrorString() { if (function_exists('json_last_error')) { $errorCode = json_last_error(); switch ($errorCode) { case JSON_ERROR_NONE: return false; case JSON_ERROR_DEPTH: return 'Maximum stack depth exceeded'; case JSON_ERROR_STATE_MISMATCH: return 'Invalid or malformed JSON'; case JSON_ERROR_CTRL_CHAR: return 'Control character error, possibly incorrectly encoded'; case JSON_ERROR_SYNTAX: return 'Syntax error'; case JSON_ERROR_UTF8: return 'Malformed UTF-8 characters, possibly incorrectly encoded'; default: return 'Unsupported error code '.$errorCode; } } else { return false; // $error = error_get_last(); // if (empty($error) || empty($error['message'])) { // return false; // } // return $error['message']; } } /** * Try to json-decode input. * * @param string $jsonInput * @return mixed */ static public function softDecode($jsonInput) { try { $jsonOutput = self::decodeAssoc($jsonInput); } catch (Exception $e) { // Could not json decode, retain value $jsonOutput = $jsonInput; } return $jsonOutput; } /** * Try to json-decode array elements. * * If elements are not json-decoded their original values are retained. * * @param array $jsonInputs * @return array */ static public function softDecodeArray(array $jsonInputs) { $jsonOutputs = array(); foreach ($jsonInputs as $key=>$jsonInput) { $jsonOutputs[$key] = (is_array($jsonInput) || is_object($jsonInput)) ? self::softDecodeArray($jsonInput) : self::softDecode($jsonInput); } return $jsonOutputs; } /** * Decode json input. * * @param string $jsonInput * @return mixed * @throws CException */ static public function decodeAssoc($jsonInput) { // Object is optional if (empty($jsonInput)) { // Input string is empty, nothing to json-decode return null; } // Decode the object into an array $objectOutput = json_decode($jsonInput, true); if (($objectOutput === null) && ($jsonInput !== 'null')) { // Json_decode failed throw new \Exception('Could not JSON-decode input object'); } return $objectOutput; } }
mit
CarlosDevlp/ToDoListMaterial
bower_components/angular-material/modules/closure/tooltip/tooltip.js
10119
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v0.11.4-master-f966d0f */ goog.provide('ng.material.components.tooltip'); goog.require('ng.material.core'); /** * @ngdoc module * @name material.components.tooltip */ angular .module('material.components.tooltip', [ 'material.core' ]) .directive('mdTooltip', MdTooltipDirective); /** * @ngdoc directive * @name mdTooltip * @module material.components.tooltip * @description * Tooltips are used to describe elements that are interactive and primarily graphical (not textual). * * Place a `<md-tooltip>` as a child of the element it describes. * * A tooltip will activate when the user focuses, hovers over, or touches the parent. * * @usage * <hljs lang="html"> * <md-button class="md-fab md-accent" aria-label="Play"> * <md-tooltip> * Play Music * </md-tooltip> * <md-icon icon="img/icons/ic_play_arrow_24px.svg"></md-icon> * </md-button> * </hljs> * * @param {expression=} md-visible Boolean bound to whether the tooltip is * currently visible. * @param {number=} md-delay How many milliseconds to wait to show the tooltip after the user focuses, hovers, or touches the parent. Defaults to 300ms. * @param {string=} md-direction Which direction would you like the tooltip to go? Supports left, right, top, and bottom. Defaults to bottom. * @param {boolean=} md-autohide If present or provided with a boolean value, the tooltip will hide on mouse leave, regardless of focus */ function MdTooltipDirective($timeout, $window, $$rAF, $document, $mdUtil, $mdTheming, $rootElement, $animate, $q) { var TOOLTIP_SHOW_DELAY = 0; var TOOLTIP_WINDOW_EDGE_SPACE = 8; return { restrict: 'E', transclude: true, priority:210, // Before ngAria template: '<div class="md-content" ng-transclude></div>', scope: { visible: '=?mdVisible', delay: '=?mdDelay', autohide: '=?mdAutohide' }, link: postLink }; function postLink(scope, element, attr) { $mdTheming(element); var parent = getParentWithPointerEvents(), content = angular.element(element[0].getElementsByClassName('md-content')[0]), direction = attr.mdDirection, current = getNearestContentElement(), tooltipParent = angular.element(current || document.body), debouncedOnResize = $$rAF.throttle(function () { if (scope.visible) positionTooltip(); }); // Initialize element setDefaults(); manipulateElement(); bindEvents(); configureWatchers(); addAriaLabel(); content.css('transform-origin', getTransformOrigin(direction)); function setDefaults () { if (!angular.isDefined(attr.mdDelay)) scope.delay = TOOLTIP_SHOW_DELAY; } function getTransformOrigin (direction) { switch (direction) { case 'left': return 'right center'; case 'right': return 'left center'; case 'top': return 'center bottom'; case 'bottom': return 'center top'; } } function configureWatchers () { scope.$on('$destroy', function() { scope.visible = false; element.remove(); angular.element($window).off('resize', debouncedOnResize); }); scope.$watch('visible', function (isVisible) { if (isVisible) showTooltip(); else hideTooltip(); }); } function addAriaLabel () { if (!parent.attr('aria-label') && !parent.text().trim()) { parent.attr('aria-label', element.text().trim()); } } function manipulateElement () { element.detach(); element.attr('role', 'tooltip'); } /** * Scan up dom hierarchy for enabled parent; */ function getParentWithPointerEvents () { var parent = element.parent(); // jqLite might return a non-null, but still empty, parent; so check for parent and length while (hasComputedStyleValue('pointer-events','none', parent)) { parent = parent.parent(); } return parent; } function getNearestContentElement () { var current = element.parent()[0]; // Look for the nearest parent md-content, stopping at the rootElement. while (current && current !== $rootElement[0] && current !== document.body && current.nodeName !== 'MD-CONTENT') { current = current.parentNode; } return current; } function hasComputedStyleValue(key, value, target) { var hasValue = false; if ( target && target.length ) { key = attr.$normalize(key); target = target[0] || element[0]; var computedStyles = $window.getComputedStyle(target); hasValue = angular.isDefined(computedStyles[key]) && (computedStyles[key] == value); } return hasValue; } function bindEvents () { var mouseActive = false; var ngWindow = angular.element($window); // Store whether the element was focused when the window loses focus. var windowBlurHandler = function() { elementFocusedOnWindowBlur = document.activeElement === parent[0]; }; var elementFocusedOnWindowBlur = false; ngWindow.on('blur', windowBlurHandler); scope.$on('$destroy', function() { ngWindow.off('blur', windowBlurHandler); }); var enterHandler = function(e) { // Prevent the tooltip from showing when the window is receiving focus. if (e.type === 'focus' && elementFocusedOnWindowBlur) { elementFocusedOnWindowBlur = false; return; } parent.on('blur mouseleave touchend touchcancel', leaveHandler ); setVisible(true); }; var leaveHandler = function () { var autohide = scope.hasOwnProperty('autohide') ? scope.autohide : attr.hasOwnProperty('mdAutohide'); if (autohide || mouseActive || ($document[0].activeElement !== parent[0]) ) { parent.off('blur mouseleave touchend touchcancel', leaveHandler ); parent.triggerHandler("blur"); setVisible(false); } mouseActive = false; }; // to avoid `synthetic clicks` we listen to mousedown instead of `click` parent.on('mousedown', function() { mouseActive = true; }); parent.on('focus mouseenter touchstart', enterHandler ); angular.element($window).on('resize', debouncedOnResize); } function setVisible (value) { setVisible.value = !!value; if (!setVisible.queued) { if (value) { setVisible.queued = true; $timeout(function() { scope.visible = setVisible.value; setVisible.queued = false; }, scope.delay); } else { $mdUtil.nextTick(function() { scope.visible = false; }); } } } function showTooltip() { // Insert the element before positioning it, so we can get the position // and check if we should display it tooltipParent.append(element); // Check if we should display it or not. // This handles hide-* and show-* along with any user defined css if ( hasComputedStyleValue('display','none') ) { scope.visible = false; element.detach(); return; } positionTooltip(); angular.forEach([element, content], function (element) { $animate.addClass(element, 'md-show'); }); } function hideTooltip() { var promises = []; angular.forEach([element, content], function (it) { if (it.parent() && it.hasClass('md-show')) { promises.push($animate.removeClass(it, 'md-show')); } }); $q.all(promises) .then(function () { if (!scope.visible) element.detach(); }); } function positionTooltip() { var tipRect = $mdUtil.offsetRect(element, tooltipParent); var parentRect = $mdUtil.offsetRect(parent, tooltipParent); var newPosition = getPosition(direction); // If the user provided a direction, just nudge the tooltip onto the screen // Otherwise, recalculate based on 'top' since default is 'bottom' if (direction) { newPosition = fitInParent(newPosition); } else if (newPosition.top > element.prop('offsetParent').scrollHeight - tipRect.height - TOOLTIP_WINDOW_EDGE_SPACE) { newPosition = fitInParent(getPosition('top')); } element.css({top: newPosition.top + 'px', left: newPosition.left + 'px'}); function fitInParent (pos) { var newPosition = { left: pos.left, top: pos.top }; newPosition.left = Math.min( newPosition.left, tooltipParent.prop('scrollWidth') - tipRect.width - TOOLTIP_WINDOW_EDGE_SPACE ); newPosition.left = Math.max( newPosition.left, TOOLTIP_WINDOW_EDGE_SPACE ); newPosition.top = Math.min( newPosition.top, tooltipParent.prop('scrollHeight') - tipRect.height - TOOLTIP_WINDOW_EDGE_SPACE ); newPosition.top = Math.max( newPosition.top, TOOLTIP_WINDOW_EDGE_SPACE ); return newPosition; } function getPosition (dir) { return dir === 'left' ? { left: parentRect.left - tipRect.width - TOOLTIP_WINDOW_EDGE_SPACE, top: parentRect.top + parentRect.height / 2 - tipRect.height / 2 } : dir === 'right' ? { left: parentRect.left + parentRect.width + TOOLTIP_WINDOW_EDGE_SPACE, top: parentRect.top + parentRect.height / 2 - tipRect.height / 2 } : dir === 'top' ? { left: parentRect.left + parentRect.width / 2 - tipRect.width / 2, top: parentRect.top - tipRect.height - TOOLTIP_WINDOW_EDGE_SPACE } : { left: parentRect.left + parentRect.width / 2 - tipRect.width / 2, top: parentRect.top + parentRect.height + TOOLTIP_WINDOW_EDGE_SPACE }; } } } } MdTooltipDirective.$inject = ["$timeout", "$window", "$$rAF", "$document", "$mdUtil", "$mdTheming", "$rootElement", "$animate", "$q"]; ng.material.components.tooltip = angular.module("material.components.tooltip");
mit
jmartty/tpcim2
data/flot-data.js
40760
//Flot Line Chart $(document).ready(function() { var offset = 0; plot(); function plot() { var sin = [], cos = []; for (var i = 0; i < 12; i += 0.2) { // sin.push([i, Math.sin(i + offset)]); sin.push([i, Math.tan(i + offset)]); cos.push([i, Math.cos(i + offset)]); } var options = { series: { lines: { show: true }, points: { show: true } }, grid: { hoverable: true //IMPORTANT! this is needed for tooltip to work }, yaxis: { min: -1.2, max: 1.2 }, tooltip: true, tooltipOpts: { content: "'%s' of %x.1 is %y.4", shifts: { x: -60, y: 25 } } }; var plotObj = $.plot($("#flot-line-chart"), [{ data: sin, label: "sin(x)" }, { data: cos, label: "cos(x)" }], options); } }); //Flot Pie Chart $(function() { var data = [{ label: "Series 0", data: 1 }, { label: "Series 1", data: 3 }, { label: "Series 2", data: 9 }, { label: "Series 3", data: 20 }]; var plotObj = $.plot($("#flot-pie-chart"), data, { series: { pie: { show: true } }, grid: { hoverable: true }, tooltip: true, tooltipOpts: { content: "%p.0%, %s", // show percentages, rounding to 2 decimal places shifts: { x: 20, y: 0 }, defaultTheme: false } }); }); //Flot Multiple Axes Line Chart $(function() { var oilprices = [ [1167692400000, 61.05], [1167778800000, 58.32], [1167865200000, 57.35], [1167951600000, 56.31], [1168210800000, 55.55], [1168297200000, 55.64], [1168383600000, 54.02], [1168470000000, 51.88], [1168556400000, 52.99], [1168815600000, 52.99], [1168902000000, 51.21], [1168988400000, 52.24], [1169074800000, 50.48], [1169161200000, 51.99], [1169420400000, 51.13], [1169506800000, 55.04], [1169593200000, 55.37], [1169679600000, 54.23], [1169766000000, 55.42], [1170025200000, 54.01], [1170111600000, 56.97], [1170198000000, 58.14], [1170284400000, 58.14], [1170370800000, 59.02], [1170630000000, 58.74], [1170716400000, 58.88], [1170802800000, 57.71], [1170889200000, 59.71], [1170975600000, 59.89], [1171234800000, 57.81], [1171321200000, 59.06], [1171407600000, 58.00], [1171494000000, 57.99], [1171580400000, 59.39], [1171839600000, 59.39], [1171926000000, 58.07], [1172012400000, 60.07], [1172098800000, 61.14], [1172444400000, 61.39], [1172530800000, 61.46], [1172617200000, 61.79], [1172703600000, 62.00], [1172790000000, 60.07], [1173135600000, 60.69], [1173222000000, 61.82], [1173308400000, 60.05], [1173654000000, 58.91], [1173740400000, 57.93], [1173826800000, 58.16], [1173913200000, 57.55], [1173999600000, 57.11], [1174258800000, 56.59], [1174345200000, 59.61], [1174518000000, 61.69], [1174604400000, 62.28], [1174860000000, 62.91], [1174946400000, 62.93], [1175032800000, 64.03], [1175119200000, 66.03], [1175205600000, 65.87], [1175464800000, 64.64], [1175637600000, 64.38], [1175724000000, 64.28], [1175810400000, 64.28], [1176069600000, 61.51], [1176156000000, 61.89], [1176242400000, 62.01], [1176328800000, 63.85], [1176415200000, 63.63], [1176674400000, 63.61], [1176760800000, 63.10], [1176847200000, 63.13], [1176933600000, 61.83], [1177020000000, 63.38], [1177279200000, 64.58], [1177452000000, 65.84], [1177538400000, 65.06], [1177624800000, 66.46], [1177884000000, 64.40], [1178056800000, 63.68], [1178143200000, 63.19], [1178229600000, 61.93], [1178488800000, 61.47], [1178575200000, 61.55], [1178748000000, 61.81], [1178834400000, 62.37], [1179093600000, 62.46], [1179180000000, 63.17], [1179266400000, 62.55], [1179352800000, 64.94], [1179698400000, 66.27], [1179784800000, 65.50], [1179871200000, 65.77], [1179957600000, 64.18], [1180044000000, 65.20], [1180389600000, 63.15], [1180476000000, 63.49], [1180562400000, 65.08], [1180908000000, 66.30], [1180994400000, 65.96], [1181167200000, 66.93], [1181253600000, 65.98], [1181599200000, 65.35], [1181685600000, 66.26], [1181858400000, 68.00], [1182117600000, 69.09], [1182204000000, 69.10], [1182290400000, 68.19], [1182376800000, 68.19], [1182463200000, 69.14], [1182722400000, 68.19], [1182808800000, 67.77], [1182895200000, 68.97], [1182981600000, 69.57], [1183068000000, 70.68], [1183327200000, 71.09], [1183413600000, 70.92], [1183586400000, 71.81], [1183672800000, 72.81], [1183932000000, 72.19], [1184018400000, 72.56], [1184191200000, 72.50], [1184277600000, 74.15], [1184623200000, 75.05], [1184796000000, 75.92], [1184882400000, 75.57], [1185141600000, 74.89], [1185228000000, 73.56], [1185314400000, 75.57], [1185400800000, 74.95], [1185487200000, 76.83], [1185832800000, 78.21], [1185919200000, 76.53], [1186005600000, 76.86], [1186092000000, 76.00], [1186437600000, 71.59], [1186696800000, 71.47], [1186956000000, 71.62], [1187042400000, 71.00], [1187301600000, 71.98], [1187560800000, 71.12], [1187647200000, 69.47], [1187733600000, 69.26], [1187820000000, 69.83], [1187906400000, 71.09], [1188165600000, 71.73], [1188338400000, 73.36], [1188511200000, 74.04], [1188856800000, 76.30], [1189116000000, 77.49], [1189461600000, 78.23], [1189548000000, 79.91], [1189634400000, 80.09], [1189720800000, 79.10], [1189980000000, 80.57], [1190066400000, 81.93], [1190239200000, 83.32], [1190325600000, 81.62], [1190584800000, 80.95], [1190671200000, 79.53], [1190757600000, 80.30], [1190844000000, 82.88], [1190930400000, 81.66], [1191189600000, 80.24], [1191276000000, 80.05], [1191362400000, 79.94], [1191448800000, 81.44], [1191535200000, 81.22], [1191794400000, 79.02], [1191880800000, 80.26], [1191967200000, 80.30], [1192053600000, 83.08], [1192140000000, 83.69], [1192399200000, 86.13], [1192485600000, 87.61], [1192572000000, 87.40], [1192658400000, 89.47], [1192744800000, 88.60], [1193004000000, 87.56], [1193090400000, 87.56], [1193176800000, 87.10], [1193263200000, 91.86], [1193612400000, 93.53], [1193698800000, 94.53], [1193871600000, 95.93], [1194217200000, 93.98], [1194303600000, 96.37], [1194476400000, 95.46], [1194562800000, 96.32], [1195081200000, 93.43], [1195167600000, 95.10], [1195426800000, 94.64], [1195513200000, 95.10], [1196031600000, 97.70], [1196118000000, 94.42], [1196204400000, 90.62], [1196290800000, 91.01], [1196377200000, 88.71], [1196636400000, 88.32], [1196809200000, 90.23], [1196982000000, 88.28], [1197241200000, 87.86], [1197327600000, 90.02], [1197414000000, 92.25], [1197586800000, 90.63], [1197846000000, 90.63], [1197932400000, 90.49], [1198018800000, 91.24], [1198105200000, 91.06], [1198191600000, 90.49], [1198710000000, 96.62], [1198796400000, 96.00], [1199142000000, 99.62], [1199314800000, 99.18], [1199401200000, 95.09], [1199660400000, 96.33], [1199833200000, 95.67], [1200351600000, 91.90], [1200438000000, 90.84], [1200524400000, 90.13], [1200610800000, 90.57], [1200956400000, 89.21], [1201042800000, 86.99], [1201129200000, 89.85], [1201474800000, 90.99], [1201561200000, 91.64], [1201647600000, 92.33], [1201734000000, 91.75], [1202079600000, 90.02], [1202166000000, 88.41], [1202252400000, 87.14], [1202338800000, 88.11], [1202425200000, 91.77], [1202770800000, 92.78], [1202857200000, 93.27], [1202943600000, 95.46], [1203030000000, 95.46], [1203289200000, 101.74], [1203462000000, 98.81], [1203894000000, 100.88], [1204066800000, 99.64], [1204153200000, 102.59], [1204239600000, 101.84], [1204498800000, 99.52], [1204585200000, 99.52], [1204671600000, 104.52], [1204758000000, 105.47], [1204844400000, 105.15], [1205103600000, 108.75], [1205276400000, 109.92], [1205362800000, 110.33], [1205449200000, 110.21], [1205708400000, 105.68], [1205967600000, 101.84], [1206313200000, 100.86], [1206399600000, 101.22], [1206486000000, 105.90], [1206572400000, 107.58], [1206658800000, 105.62], [1206914400000, 101.58], [1207000800000, 100.98], [1207173600000, 103.83], [1207260000000, 106.23], [1207605600000, 108.50], [1207778400000, 110.11], [1207864800000, 110.14], [1208210400000, 113.79], [1208296800000, 114.93], [1208383200000, 114.86], [1208728800000, 117.48], [1208815200000, 118.30], [1208988000000, 116.06], [1209074400000, 118.52], [1209333600000, 118.75], [1209420000000, 113.46], [1209592800000, 112.52], [1210024800000, 121.84], [1210111200000, 123.53], [1210197600000, 123.69], [1210543200000, 124.23], [1210629600000, 125.80], [1210716000000, 126.29], [1211148000000, 127.05], [1211320800000, 129.07], [1211493600000, 132.19], [1211839200000, 128.85], [1212357600000, 127.76], [1212703200000, 138.54], [1212962400000, 136.80], [1213135200000, 136.38], [1213308000000, 134.86], [1213653600000, 134.01], [1213740000000, 136.68], [1213912800000, 135.65], [1214172000000, 134.62], [1214258400000, 134.62], [1214344800000, 134.62], [1214431200000, 139.64], [1214517600000, 140.21], [1214776800000, 140.00], [1214863200000, 140.97], [1214949600000, 143.57], [1215036000000, 145.29], [1215381600000, 141.37], [1215468000000, 136.04], [1215727200000, 146.40], [1215986400000, 145.18], [1216072800000, 138.74], [1216159200000, 134.60], [1216245600000, 129.29], [1216332000000, 130.65], [1216677600000, 127.95], [1216850400000, 127.95], [1217282400000, 122.19], [1217455200000, 124.08], [1217541600000, 125.10], [1217800800000, 121.41], [1217887200000, 119.17], [1217973600000, 118.58], [1218060000000, 120.02], [1218405600000, 114.45], [1218492000000, 113.01], [1218578400000, 116.00], [1218751200000, 113.77], [1219010400000, 112.87], [1219096800000, 114.53], [1219269600000, 114.98], [1219356000000, 114.98], [1219701600000, 116.27], [1219788000000, 118.15], [1219874400000, 115.59], [1219960800000, 115.46], [1220306400000, 109.71], [1220392800000, 109.35], [1220565600000, 106.23], [1220824800000, 106.34] ]; var exchangerates = [ [1167606000000, 0.7580], [1167692400000, 0.7580], [1167778800000, 0.75470], [1167865200000, 0.75490], [1167951600000, 0.76130], [1168038000000, 0.76550], [1168124400000, 0.76930], [1168210800000, 0.76940], [1168297200000, 0.76880], [1168383600000, 0.76780], [1168470000000, 0.77080], [1168556400000, 0.77270], [1168642800000, 0.77490], [1168729200000, 0.77410], [1168815600000, 0.77410], [1168902000000, 0.77320], [1168988400000, 0.77270], [1169074800000, 0.77370], [1169161200000, 0.77240], [1169247600000, 0.77120], [1169334000000, 0.7720], [1169420400000, 0.77210], [1169506800000, 0.77170], [1169593200000, 0.77040], [1169679600000, 0.7690], [1169766000000, 0.77110], [1169852400000, 0.7740], [1169938800000, 0.77450], [1170025200000, 0.77450], [1170111600000, 0.7740], [1170198000000, 0.77160], [1170284400000, 0.77130], [1170370800000, 0.76780], [1170457200000, 0.76880], [1170543600000, 0.77180], [1170630000000, 0.77180], [1170716400000, 0.77280], [1170802800000, 0.77290], [1170889200000, 0.76980], [1170975600000, 0.76850], [1171062000000, 0.76810], [1171148400000, 0.7690], [1171234800000, 0.7690], [1171321200000, 0.76980], [1171407600000, 0.76990], [1171494000000, 0.76510], [1171580400000, 0.76130], [1171666800000, 0.76160], [1171753200000, 0.76140], [1171839600000, 0.76140], [1171926000000, 0.76070], [1172012400000, 0.76020], [1172098800000, 0.76110], [1172185200000, 0.76220], [1172271600000, 0.76150], [1172358000000, 0.75980], [1172444400000, 0.75980], [1172530800000, 0.75920], [1172617200000, 0.75730], [1172703600000, 0.75660], [1172790000000, 0.75670], [1172876400000, 0.75910], [1172962800000, 0.75820], [1173049200000, 0.75850], [1173135600000, 0.76130], [1173222000000, 0.76310], [1173308400000, 0.76150], [1173394800000, 0.760], [1173481200000, 0.76130], [1173567600000, 0.76270], [1173654000000, 0.76270], [1173740400000, 0.76080], [1173826800000, 0.75830], [1173913200000, 0.75750], [1173999600000, 0.75620], [1174086000000, 0.7520], [1174172400000, 0.75120], [1174258800000, 0.75120], [1174345200000, 0.75170], [1174431600000, 0.7520], [1174518000000, 0.75110], [1174604400000, 0.7480], [1174690800000, 0.75090], [1174777200000, 0.75310], [1174860000000, 0.75310], [1174946400000, 0.75270], [1175032800000, 0.74980], [1175119200000, 0.74930], [1175205600000, 0.75040], [1175292000000, 0.750], [1175378400000, 0.74910], [1175464800000, 0.74910], [1175551200000, 0.74850], [1175637600000, 0.74840], [1175724000000, 0.74920], [1175810400000, 0.74710], [1175896800000, 0.74590], [1175983200000, 0.74770], [1176069600000, 0.74770], [1176156000000, 0.74830], [1176242400000, 0.74580], [1176328800000, 0.74480], [1176415200000, 0.7430], [1176501600000, 0.73990], [1176588000000, 0.73950], [1176674400000, 0.73950], [1176760800000, 0.73780], [1176847200000, 0.73820], [1176933600000, 0.73620], [1177020000000, 0.73550], [1177106400000, 0.73480], [1177192800000, 0.73610], [1177279200000, 0.73610], [1177365600000, 0.73650], [1177452000000, 0.73620], [1177538400000, 0.73310], [1177624800000, 0.73390], [1177711200000, 0.73440], [1177797600000, 0.73270], [1177884000000, 0.73270], [1177970400000, 0.73360], [1178056800000, 0.73330], [1178143200000, 0.73590], [1178229600000, 0.73590], [1178316000000, 0.73720], [1178402400000, 0.7360], [1178488800000, 0.7360], [1178575200000, 0.7350], [1178661600000, 0.73650], [1178748000000, 0.73840], [1178834400000, 0.73950], [1178920800000, 0.74130], [1179007200000, 0.73970], [1179093600000, 0.73960], [1179180000000, 0.73850], [1179266400000, 0.73780], [1179352800000, 0.73660], [1179439200000, 0.740], [1179525600000, 0.74110], [1179612000000, 0.74060], [1179698400000, 0.74050], [1179784800000, 0.74140], [1179871200000, 0.74310], [1179957600000, 0.74310], [1180044000000, 0.74380], [1180130400000, 0.74430], [1180216800000, 0.74430], [1180303200000, 0.74430], [1180389600000, 0.74340], [1180476000000, 0.74290], [1180562400000, 0.74420], [1180648800000, 0.7440], [1180735200000, 0.74390], [1180821600000, 0.74370], [1180908000000, 0.74370], [1180994400000, 0.74290], [1181080800000, 0.74030], [1181167200000, 0.73990], [1181253600000, 0.74180], [1181340000000, 0.74680], [1181426400000, 0.7480], [1181512800000, 0.7480], [1181599200000, 0.7490], [1181685600000, 0.74940], [1181772000000, 0.75220], [1181858400000, 0.75150], [1181944800000, 0.75020], [1182031200000, 0.74720], [1182117600000, 0.74720], [1182204000000, 0.74620], [1182290400000, 0.74550], [1182376800000, 0.74490], [1182463200000, 0.74670], [1182549600000, 0.74580], [1182636000000, 0.74270], [1182722400000, 0.74270], [1182808800000, 0.7430], [1182895200000, 0.74290], [1182981600000, 0.7440], [1183068000000, 0.7430], [1183154400000, 0.74220], [1183240800000, 0.73880], [1183327200000, 0.73880], [1183413600000, 0.73690], [1183500000000, 0.73450], [1183586400000, 0.73450], [1183672800000, 0.73450], [1183759200000, 0.73520], [1183845600000, 0.73410], [1183932000000, 0.73410], [1184018400000, 0.7340], [1184104800000, 0.73240], [1184191200000, 0.72720], [1184277600000, 0.72640], [1184364000000, 0.72550], [1184450400000, 0.72580], [1184536800000, 0.72580], [1184623200000, 0.72560], [1184709600000, 0.72570], [1184796000000, 0.72470], [1184882400000, 0.72430], [1184968800000, 0.72440], [1185055200000, 0.72350], [1185141600000, 0.72350], [1185228000000, 0.72350], [1185314400000, 0.72350], [1185400800000, 0.72620], [1185487200000, 0.72880], [1185573600000, 0.73010], [1185660000000, 0.73370], [1185746400000, 0.73370], [1185832800000, 0.73240], [1185919200000, 0.72970], [1186005600000, 0.73170], [1186092000000, 0.73150], [1186178400000, 0.72880], [1186264800000, 0.72630], [1186351200000, 0.72630], [1186437600000, 0.72420], [1186524000000, 0.72530], [1186610400000, 0.72640], [1186696800000, 0.7270], [1186783200000, 0.73120], [1186869600000, 0.73050], [1186956000000, 0.73050], [1187042400000, 0.73180], [1187128800000, 0.73580], [1187215200000, 0.74090], [1187301600000, 0.74540], [1187388000000, 0.74370], [1187474400000, 0.74240], [1187560800000, 0.74240], [1187647200000, 0.74150], [1187733600000, 0.74190], [1187820000000, 0.74140], [1187906400000, 0.73770], [1187992800000, 0.73550], [1188079200000, 0.73150], [1188165600000, 0.73150], [1188252000000, 0.7320], [1188338400000, 0.73320], [1188424800000, 0.73460], [1188511200000, 0.73280], [1188597600000, 0.73230], [1188684000000, 0.7340], [1188770400000, 0.7340], [1188856800000, 0.73360], [1188943200000, 0.73510], [1189029600000, 0.73460], [1189116000000, 0.73210], [1189202400000, 0.72940], [1189288800000, 0.72660], [1189375200000, 0.72660], [1189461600000, 0.72540], [1189548000000, 0.72420], [1189634400000, 0.72130], [1189720800000, 0.71970], [1189807200000, 0.72090], [1189893600000, 0.7210], [1189980000000, 0.7210], [1190066400000, 0.7210], [1190152800000, 0.72090], [1190239200000, 0.71590], [1190325600000, 0.71330], [1190412000000, 0.71050], [1190498400000, 0.70990], [1190584800000, 0.70990], [1190671200000, 0.70930], [1190757600000, 0.70930], [1190844000000, 0.70760], [1190930400000, 0.7070], [1191016800000, 0.70490], [1191103200000, 0.70120], [1191189600000, 0.70110], [1191276000000, 0.70190], [1191362400000, 0.70460], [1191448800000, 0.70630], [1191535200000, 0.70890], [1191621600000, 0.70770], [1191708000000, 0.70770], [1191794400000, 0.70770], [1191880800000, 0.70910], [1191967200000, 0.71180], [1192053600000, 0.70790], [1192140000000, 0.70530], [1192226400000, 0.7050], [1192312800000, 0.70550], [1192399200000, 0.70550], [1192485600000, 0.70450], [1192572000000, 0.70510], [1192658400000, 0.70510], [1192744800000, 0.70170], [1192831200000, 0.70], [1192917600000, 0.69950], [1193004000000, 0.69940], [1193090400000, 0.70140], [1193176800000, 0.70360], [1193263200000, 0.70210], [1193349600000, 0.70020], [1193436000000, 0.69670], [1193522400000, 0.6950], [1193612400000, 0.6950], [1193698800000, 0.69390], [1193785200000, 0.6940], [1193871600000, 0.69220], [1193958000000, 0.69190], [1194044400000, 0.69140], [1194130800000, 0.68940], [1194217200000, 0.68910], [1194303600000, 0.69040], [1194390000000, 0.6890], [1194476400000, 0.68340], [1194562800000, 0.68230], [1194649200000, 0.68070], [1194735600000, 0.68150], [1194822000000, 0.68150], [1194908400000, 0.68470], [1194994800000, 0.68590], [1195081200000, 0.68220], [1195167600000, 0.68270], [1195254000000, 0.68370], [1195340400000, 0.68230], [1195426800000, 0.68220], [1195513200000, 0.68220], [1195599600000, 0.67920], [1195686000000, 0.67460], [1195772400000, 0.67350], [1195858800000, 0.67310], [1195945200000, 0.67420], [1196031600000, 0.67440], [1196118000000, 0.67390], [1196204400000, 0.67310], [1196290800000, 0.67610], [1196377200000, 0.67610], [1196463600000, 0.67850], [1196550000000, 0.68180], [1196636400000, 0.68360], [1196722800000, 0.68230], [1196809200000, 0.68050], [1196895600000, 0.67930], [1196982000000, 0.68490], [1197068400000, 0.68330], [1197154800000, 0.68250], [1197241200000, 0.68250], [1197327600000, 0.68160], [1197414000000, 0.67990], [1197500400000, 0.68130], [1197586800000, 0.68090], [1197673200000, 0.68680], [1197759600000, 0.69330], [1197846000000, 0.69330], [1197932400000, 0.69450], [1198018800000, 0.69440], [1198105200000, 0.69460], [1198191600000, 0.69640], [1198278000000, 0.69650], [1198364400000, 0.69560], [1198450800000, 0.69560], [1198537200000, 0.6950], [1198623600000, 0.69480], [1198710000000, 0.69280], [1198796400000, 0.68870], [1198882800000, 0.68240], [1198969200000, 0.67940], [1199055600000, 0.67940], [1199142000000, 0.68030], [1199228400000, 0.68550], [1199314800000, 0.68240], [1199401200000, 0.67910], [1199487600000, 0.67830], [1199574000000, 0.67850], [1199660400000, 0.67850], [1199746800000, 0.67970], [1199833200000, 0.680], [1199919600000, 0.68030], [1200006000000, 0.68050], [1200092400000, 0.6760], [1200178800000, 0.6770], [1200265200000, 0.6770], [1200351600000, 0.67360], [1200438000000, 0.67260], [1200524400000, 0.67640], [1200610800000, 0.68210], [1200697200000, 0.68310], [1200783600000, 0.68420], [1200870000000, 0.68420], [1200956400000, 0.68870], [1201042800000, 0.69030], [1201129200000, 0.68480], [1201215600000, 0.68240], [1201302000000, 0.67880], [1201388400000, 0.68140], [1201474800000, 0.68140], [1201561200000, 0.67970], [1201647600000, 0.67690], [1201734000000, 0.67650], [1201820400000, 0.67330], [1201906800000, 0.67290], [1201993200000, 0.67580], [1202079600000, 0.67580], [1202166000000, 0.6750], [1202252400000, 0.6780], [1202338800000, 0.68330], [1202425200000, 0.68560], [1202511600000, 0.69030], [1202598000000, 0.68960], [1202684400000, 0.68960], [1202770800000, 0.68820], [1202857200000, 0.68790], [1202943600000, 0.68620], [1203030000000, 0.68520], [1203116400000, 0.68230], [1203202800000, 0.68130], [1203289200000, 0.68130], [1203375600000, 0.68220], [1203462000000, 0.68020], [1203548400000, 0.68020], [1203634800000, 0.67840], [1203721200000, 0.67480], [1203807600000, 0.67470], [1203894000000, 0.67470], [1203980400000, 0.67480], [1204066800000, 0.67330], [1204153200000, 0.6650], [1204239600000, 0.66110], [1204326000000, 0.65830], [1204412400000, 0.6590], [1204498800000, 0.6590], [1204585200000, 0.65810], [1204671600000, 0.65780], [1204758000000, 0.65740], [1204844400000, 0.65320], [1204930800000, 0.65020], [1205017200000, 0.65140], [1205103600000, 0.65140], [1205190000000, 0.65070], [1205276400000, 0.6510], [1205362800000, 0.64890], [1205449200000, 0.64240], [1205535600000, 0.64060], [1205622000000, 0.63820], [1205708400000, 0.63820], [1205794800000, 0.63410], [1205881200000, 0.63440], [1205967600000, 0.63780], [1206054000000, 0.64390], [1206140400000, 0.64780], [1206226800000, 0.64810], [1206313200000, 0.64810], [1206399600000, 0.64940], [1206486000000, 0.64380], [1206572400000, 0.63770], [1206658800000, 0.63290], [1206745200000, 0.63360], [1206831600000, 0.63330], [1206914400000, 0.63330], [1207000800000, 0.6330], [1207087200000, 0.63710], [1207173600000, 0.64030], [1207260000000, 0.63960], [1207346400000, 0.63640], [1207432800000, 0.63560], [1207519200000, 0.63560], [1207605600000, 0.63680], [1207692000000, 0.63570], [1207778400000, 0.63540], [1207864800000, 0.6320], [1207951200000, 0.63320], [1208037600000, 0.63280], [1208124000000, 0.63310], [1208210400000, 0.63420], [1208296800000, 0.63210], [1208383200000, 0.63020], [1208469600000, 0.62780], [1208556000000, 0.63080], [1208642400000, 0.63240], [1208728800000, 0.63240], [1208815200000, 0.63070], [1208901600000, 0.62770], [1208988000000, 0.62690], [1209074400000, 0.63350], [1209160800000, 0.63920], [1209247200000, 0.640], [1209333600000, 0.64010], [1209420000000, 0.63960], [1209506400000, 0.64070], [1209592800000, 0.64230], [1209679200000, 0.64290], [1209765600000, 0.64720], [1209852000000, 0.64850], [1209938400000, 0.64860], [1210024800000, 0.64670], [1210111200000, 0.64440], [1210197600000, 0.64670], [1210284000000, 0.65090], [1210370400000, 0.64780], [1210456800000, 0.64610], [1210543200000, 0.64610], [1210629600000, 0.64680], [1210716000000, 0.64490], [1210802400000, 0.6470], [1210888800000, 0.64610], [1210975200000, 0.64520], [1211061600000, 0.64220], [1211148000000, 0.64220], [1211234400000, 0.64250], [1211320800000, 0.64140], [1211407200000, 0.63660], [1211493600000, 0.63460], [1211580000000, 0.6350], [1211666400000, 0.63460], [1211752800000, 0.63460], [1211839200000, 0.63430], [1211925600000, 0.63460], [1212012000000, 0.63790], [1212098400000, 0.64160], [1212184800000, 0.64420], [1212271200000, 0.64310], [1212357600000, 0.64310], [1212444000000, 0.64350], [1212530400000, 0.6440], [1212616800000, 0.64730], [1212703200000, 0.64690], [1212789600000, 0.63860], [1212876000000, 0.63560], [1212962400000, 0.6340], [1213048800000, 0.63460], [1213135200000, 0.6430], [1213221600000, 0.64520], [1213308000000, 0.64670], [1213394400000, 0.65060], [1213480800000, 0.65040], [1213567200000, 0.65030], [1213653600000, 0.64810], [1213740000000, 0.64510], [1213826400000, 0.6450], [1213912800000, 0.64410], [1213999200000, 0.64140], [1214085600000, 0.64090], [1214172000000, 0.64090], [1214258400000, 0.64280], [1214344800000, 0.64310], [1214431200000, 0.64180], [1214517600000, 0.63710], [1214604000000, 0.63490], [1214690400000, 0.63330], [1214776800000, 0.63340], [1214863200000, 0.63380], [1214949600000, 0.63420], [1215036000000, 0.6320], [1215122400000, 0.63180], [1215208800000, 0.6370], [1215295200000, 0.63680], [1215381600000, 0.63680], [1215468000000, 0.63830], [1215554400000, 0.63710], [1215640800000, 0.63710], [1215727200000, 0.63550], [1215813600000, 0.6320], [1215900000000, 0.62770], [1215986400000, 0.62760], [1216072800000, 0.62910], [1216159200000, 0.62740], [1216245600000, 0.62930], [1216332000000, 0.63110], [1216418400000, 0.6310], [1216504800000, 0.63120], [1216591200000, 0.63120], [1216677600000, 0.63040], [1216764000000, 0.62940], [1216850400000, 0.63480], [1216936800000, 0.63780], [1217023200000, 0.63680], [1217109600000, 0.63680], [1217196000000, 0.63680], [1217282400000, 0.6360], [1217368800000, 0.6370], [1217455200000, 0.64180], [1217541600000, 0.64110], [1217628000000, 0.64350], [1217714400000, 0.64270], [1217800800000, 0.64270], [1217887200000, 0.64190], [1217973600000, 0.64460], [1218060000000, 0.64680], [1218146400000, 0.64870], [1218232800000, 0.65940], [1218319200000, 0.66660], [1218405600000, 0.66660], [1218492000000, 0.66780], [1218578400000, 0.67120], [1218664800000, 0.67050], [1218751200000, 0.67180], [1218837600000, 0.67840], [1218924000000, 0.68110], [1219010400000, 0.68110], [1219096800000, 0.67940], [1219183200000, 0.68040], [1219269600000, 0.67810], [1219356000000, 0.67560], [1219442400000, 0.67350], [1219528800000, 0.67630], [1219615200000, 0.67620], [1219701600000, 0.67770], [1219788000000, 0.68150], [1219874400000, 0.68020], [1219960800000, 0.6780], [1220047200000, 0.67960], [1220133600000, 0.68170], [1220220000000, 0.68170], [1220306400000, 0.68320], [1220392800000, 0.68770], [1220479200000, 0.69120], [1220565600000, 0.69140], [1220652000000, 0.70090], [1220738400000, 0.70120], [1220824800000, 0.7010], [1220911200000, 0.70050] ]; function euroFormatter(v, axis) { return v.toFixed(axis.tickDecimals) + "€"; } function doPlot(position) { $.plot($("#flot-line-chart-multi"), [{ data: oilprices, label: "Oil price ($)" }, { data: exchangerates, label: "USD/EUR exchange rate", yaxis: 2 }], { xaxes: [{ mode: 'time' }], yaxes: [{ min: 0 }, { // align if we are to the right alignTicksWithAxis: position == "right" ? 1 : null, position: position, tickFormatter: euroFormatter }], legend: { position: 'sw' }, grid: { hoverable: true //IMPORTANT! this is needed for tooltip to work }, tooltip: true, tooltipOpts: { content: "%s for %x was %y", xDateFormat: "%y-%0m-%0d", onHover: function(flotItem, $tooltipEl) { // console.log(flotItem, $tooltipEl); } } }); } doPlot("right"); $("button").click(function() { doPlot($(this).text()); }); }); //Flot Moving Line Chart $(function() { var container = $("#flot-line-chart-moving-hume"); // Determine how many data points to keep based on the placeholder's initial size; // this gives us a nice high-res plot while avoiding more than one point per pixel. var maximum = container.outerWidth() / 2 || 300; // var data = []; function getRandomData() { if (data.length) { data = data.slice(1); } while (data.length < maximum) { var previous = data.length ? data[data.length - 1] : 50; var y = previous + (Math.random() * 10 - 5)*0.25; data.push(y < 0 ? 0 : y > 100 ? 100 : y); } // zip the generated y values with the x values var res = []; for (var i = 0; i < data.length; ++i) { res.push([i, data[i]]) } return res; } // series = [{ data: getRandomData(), lines: { fill: false } }]; // var plot = $.plot(container, series, { grid: { borderWidth: 1, minBorderMargin: 20, labelMargin: 10, backgroundColor: { colors: ["#fff", "#e4f4f4"] }, margin: { top: 8, bottom: 20, left: 20 }, markings: function(axes) { var markings = []; var xaxis = axes.xaxis; for (var x = Math.floor(xaxis.min); x < xaxis.max; x += xaxis.tickSize * 2) { markings.push({ xaxis: { from: x, to: x + xaxis.tickSize }, color: "rgba(232, 232, 255, 0.2)" }); } return markings; } }, xaxis: { tickFormatter: function() { return ""; } }, yaxis: { min: 0, max: 110 }, legend: { show: true } }); // Update the random dataset at 25FPS for a smoothly-animating chart setInterval(function updateRandom() { series[0].data = getRandomData(); plot.setData(series); plot.draw(); }, 800); }); $(function() { var container = $("#flot-line-chart-moving-temp"); // Determine how many data points to keep based on the placeholder's initial size; // this gives us a nice high-res plot while avoiding more than one point per pixel. var maximum = container.outerWidth() / 2 || 300; // var data = []; function getRandomData() { if (data.length) { data = data.slice(1); } while (data.length < maximum) { var previous = data.length ? data[data.length - 1] : 18; var y = previous + (Math.random() -0.5 )*0.1 data.push(y < 10 ? 10 : y > 30 ? 30 : y); } // zip the generated y values with the x values var res = []; for (var i = 0; i < data.length; ++i) { res.push([i, data[i]]) } return res; } // series = [{ data: getRandomData(), lines: { fill: false } }]; // var plot = $.plot(container, series, { grid: { borderWidth: 1, minBorderMargin: 20, labelMargin: 10, backgroundColor: { colors: ["#fff", "#e4f4f4"] }, margin: { top: 8, bottom: 20, left: 20 }, markings: function(axes) { var markings = []; var xaxis = axes.xaxis; for (var x = Math.floor(xaxis.min); x < xaxis.max; x += xaxis.tickSize * 2) { markings.push({ xaxis: { from: x, to: x + xaxis.tickSize }, color: "rgba(232, 232, 255, 0.2)" }); } return markings; } }, xaxis: { tickFormatter: function() { return ""; } }, yaxis: { min: 12, max: 32 }, legend: { show: true } }); // Update the random dataset at 25FPS for a smoothly-animating chart setInterval(function updateRandom() { series[0].data = getRandomData(); plot.setData(series); plot.draw(); }, 800); }); //Flot Bar Chart $(function() { var barOptions = { series: { bars: { show: true, barWidth: 43200000 } }, xaxis: { mode: "time", timeformat: "%m/%d", minTickSize: [1, "day"] }, grid: { hoverable: true }, legend: { show: false }, tooltip: true, tooltipOpts: { content: "x: %x, y: %y" } }; var barData = { label: "bar", data: [ [1354521600000, 1000], [1355040000000, 2000], [1355223600000, 3000], [1355306400000, 4000], [1355487300000, 5000], [1355571900000, 6000] ] }; $.plot($("#flot-bar-chart"), [barData], barOptions); });
mit
ekylibre/formize
vendor/assets/javascripts/jquery-ui/datepicker/ar.js
1300
/* Arabic Translation for jQuery UI date picker plugin. */ /* Khaled Alhourani -- [email protected] */ /* NOTE: monthNames are the original months names and they are the Arabic names, not the new months name فبراير - يناير and there isn't any Arabic roots for these months */ jQuery(function($){ $.datepicker.regional['ar'] = { closeText: 'إغلاق', prevText: '&#x3C;السابق', nextText: 'التالي&#x3E;', currentText: 'اليوم', monthNames: ['كانون الثاني', 'شباط', 'آذار', 'نيسان', 'مايو', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول'], monthNamesShort: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'], dayNames: ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], dayNamesShort: ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], dayNamesMin: ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], weekHeader: 'أسبوع', dateFormat: 'dd/mm/yy', firstDay: 6, isRTL: true, showMonthAfterYear: false, yearSuffix: ''}; // $.datepicker.setDefaults($.datepicker.regional['ar']); });
mit
hoburg/gpkit
gpkit/constraints/sgp.py
12935
"""Implement the SequentialGeometricProgram class""" import warnings as pywarnings from time import time from collections import defaultdict import numpy as np from ..exceptions import (InvalidGPConstraint, Infeasible, UnnecessarySGP, InvalidPosynomial, InvalidSGPConstraint) from ..keydict import KeyDict from ..nomials import Variable from .gp import GeometricProgram from ..nomials import PosynomialInequality, Posynomial from .. import NamedVariables from ..small_scripts import appendsolwarning, initsolwarning EPS = 1e-6 # 1 +/- this is used in a few relative differences # pylint: disable=too-many-instance-attributes class SequentialGeometricProgram: """Prepares a collection of signomials for a SP solve. Arguments --------- cost : Posynomial Objective to minimize when solving constraints : list of Constraint or SignomialConstraint objects Constraints to maintain when solving (implicitly Signomials <= 1) verbosity : int (optional) Currently has no effect: SequentialGeometricPrograms don't know anything new after being created, unlike GeometricPrograms. Attributes with side effects ---------------------------- `gps` is set during a solve `result` is set at the end of a solve Examples -------- >>> gp = gpkit.geometric_program.SequentialGeometricProgram( # minimize x, [ # subject to 1/x - y/x, # <= 1, implicitly y/10 # <= 1 ]) >>> gp.solve() """ gps = solver_outs = _results = result = model = None with NamedVariables("RelaxPCCP"): slack = Variable("C") def __init__(self, cost, model, substitutions, *, use_pccp=True, pccp_penalty=2e2, **kwargs): self.pccp_penalty = pccp_penalty if cost.any_nonpositive_cs: raise InvalidPosynomial("""an SGP's cost must be Posynomial The equivalent of a Signomial objective can be constructed by constraining a dummy variable `z` to be greater than the desired Signomial objective `s` (z >= s) and then minimizing that dummy variable.""") self.gpconstraints, self.sgpconstraints = [], [] if not use_pccp: self.slack = 1 else: self.gpconstraints.append(self.slack >= 1) cost *= self.slack**pccp_penalty self.approxconstraints = [] self.sgpvks = set() x0 = KeyDict(substitutions) x0.vks = model.vks # for string access and so forth for cs in model.flat(): try: if not hasattr(cs, "as_hmapslt1"): raise InvalidGPConstraint(cs) if not isinstance(cs, PosynomialInequality): cs.as_hmapslt1(substitutions) # gp-compatible? self.gpconstraints.append(cs) except InvalidGPConstraint: if not hasattr(cs, "as_gpconstr"): raise InvalidSGPConstraint(cs) self.sgpconstraints.append(cs) for hmaplt1 in cs.as_gpconstr(x0).as_hmapslt1({}): constraint = (Posynomial(hmaplt1) <= self.slack) constraint.generated_by = cs self.approxconstraints.append(constraint) self.sgpvks.update(constraint.vks) if not self.sgpconstraints: raise UnnecessarySGP("""Model valid as a Geometric Program. SequentialGeometricPrograms should only be created with Models containing Signomial Constraints, since Models without Signomials have global solutions and can be solved with 'Model.solve()'.""") self._gp = GeometricProgram( cost, self.approxconstraints + self.gpconstraints, substitutions, **kwargs) self._gp.x0 = x0 self.a_idxs = defaultdict(list) last_cost_mon = self._gp.k[0] first_gp_mon = sum(self._gp.k[:1+len(self.approxconstraints)]) for row_idx, m_idx in enumerate(self._gp.A.row): if last_cost_mon <= m_idx <= first_gp_mon: self.a_idxs[self._gp.p_idxs[m_idx]].append(row_idx) # pylint: disable=too-many-locals,too-many-branches,too-many-statements def localsolve(self, solver=None, *, verbosity=1, x0=None, reltol=1e-4, iteration_limit=50, **solveargs): """Locally solves a SequentialGeometricProgram and returns the solution. Arguments --------- solver : str or function (optional) By default uses one of the solvers found during installation. If set to "mosek", "mosek_cli", or "cvxopt", uses that solver. If set to a function, passes that function cs, A, p_idxs, and k. verbosity : int (optional) If greater than 0, prints solve time and number of iterations. Each GP is created and solved with verbosity one less than this, so if greater than 1, prints solver name and time for each GP. x0 : dict (optional) Initial location to approximate signomials about. reltol : float Iteration ends when this is greater than the distance between two consecutive solve's objective values. iteration_limit : int Maximum GP iterations allowed. mutategp: boolean Prescribes whether to mutate the previously generated GP or to create a new GP with every solve. **solveargs : Passed to solver function. Returns ------- result : dict A dictionary containing the translated solver result. """ self.gps, self.solver_outs, self._results = [], [], [] starttime = time() if verbosity > 0: print("Starting a sequence of GP solves") print(" for %i free variables" % len(self.sgpvks)) print(" in %i locally-GP constraints" % len(self.sgpconstraints)) print(" and for %i free variables" % len(self._gp.varlocs)) print(" in %i posynomial inequalities." % len(self._gp.k)) prevcost, cost, rel_improvement = None, None, None while rel_improvement is None or rel_improvement > reltol: prevcost = cost if len(self.gps) > iteration_limit: raise Infeasible( "Unsolved after %s iterations. Check `m.program.results`;" " if they're converging, try `.localsolve(...," " iteration_limit=NEWLIMIT)`." % len(self.gps)) gp = self.gp(x0, cleanx0=(len(self.gps) >= 1)) # clean the first x0 self.gps.append(gp) # NOTE: SIDE EFFECTS if verbosity > 1: print("\nGP Solve %i" % len(self.gps)) if verbosity > 2: print("===============") solver_out = gp.solve(solver, verbosity=verbosity-1, gen_result=False, **solveargs) self.solver_outs.append(solver_out) cost = float(solver_out["objective"]) x0 = dict(zip(gp.varlocs, np.exp(solver_out["primal"]))) if verbosity > 2: result = gp.generate_result(solver_out, verbosity=verbosity-3) self._results.append(result) print(result.table(self.sgpvks)) elif verbosity > 1: print("Solved cost was %.4g." % cost) if prevcost is None: continue rel_improvement = (prevcost - cost)/(prevcost + cost) if cost/prevcost >= 1 + 10*EPS: pywarnings.warn( "SGP not convergent: Cost rose by %.2g%% (%.6g to %.6g) on" " GP solve %i. Details can be found in `m.program.results`" " or by solving at a higher verbosity. Note convergence" " is not guaranteed for models with SignomialEqualities." % (100*(cost - prevcost)/prevcost, prevcost, cost, len(self.gps))) rel_improvement = cost = None # solved successfully! self.result = gp.generate_result(solver_out, verbosity=verbosity-3) self.result["soltime"] = time() - starttime if verbosity > 1: print() if verbosity > 0: print("Solving took %.3g seconds and %i GP solves." % (self.result["soltime"], len(self.gps))) if hasattr(self.slack, "key"): initsolwarning(self.result, "Slack Non-GP Constraints") excess_slack = self.result["variables"][self.slack.key] - 1 # pylint: disable=no-member if excess_slack > EPS: msg = ("Final PCCP solution let non-GP constraints slacken by" " %.2g%%." % (100*excess_slack)) appendsolwarning(msg, (1 + excess_slack), self.result, "Slack Non-GP Constraints") if verbosity > -1: print(msg + " Calling .localsolve(pccp_penalty=...) with a higher" " `pccp_penalty` (it was %.3g this time) will reduce" " slack if the model is solvable with less. To verify" " that the slack is needed, generate an SGP with" " `use_pccp=False` and start it from this model's" " solution: e.g. `m.localsolve(use_pccp=False, x0=" "m.solution[\"variables\"])`." % self.pccp_penalty) del self.result["freevariables"][self.slack.key] # pylint: disable=no-member del self.result["variables"][self.slack.key] # pylint: disable=no-member del self.result["sensitivities"]["variables"][self.slack.key] # pylint: disable=no-member slcon = self.gpconstraints[0] slconsenss = self.result["sensitivities"]["constraints"][slcon] del self.result["sensitivities"]["constraints"][slcon] # TODO: create constraint in RelaxPCCP namespace self.result["sensitivities"]["models"][""] -= slconsenss if not self.result["sensitivities"]["models"][""]: del self.result["sensitivities"]["models"][""] return self.result @property def results(self): "Creates and caches results from the raw solver_outs" if not self._results: self._results = [gp.generate_result(s_o, dual_check=False) for gp, s_o in zip(self.gps, self.solver_outs)] return self._results def gp(self, x0=None, *, cleanx0=False): "Update self._gp for x0 and return it." if not x0: return self._gp # return last generated if not cleanx0: cleanedx0 = KeyDict() cleanedx0.vks = self._gp.x0.vks cleanedx0.update(x0) x0 = cleanedx0 self._gp.x0.update({vk: x0[vk] for vk in self.sgpvks if vk in x0}) p_idx = 0 for sgpc in self.sgpconstraints: for hmaplt1 in sgpc.as_gpconstr(self._gp.x0).as_hmapslt1({}): approxc = self.approxconstraints[p_idx] approxc.left = self.slack approxc.right.hmap = hmaplt1 approxc.unsubbed = [Posynomial(hmaplt1)/self.slack] p_idx += 1 # p_idx=0 is the cost; sp constraints are after it hmap, = approxc.as_hmapslt1(self._gp.substitutions) self._gp.hmaps[p_idx] = hmap m_idx = self._gp.m_idxs[p_idx].start a_idxs = list(self.a_idxs[p_idx]) # A's entries we can modify for i, (exp, c) in enumerate(hmap.items()): self._gp.exps[m_idx + i] = exp self._gp.cs[m_idx + i] = c for var, x in exp.items(): try: # modify a particular A entry row_idx = a_idxs.pop() self._gp.A.row[row_idx] = m_idx + i self._gp.A.col[row_idx] = self._gp.varidxs[var] self._gp.A.data[row_idx] = x except IndexError: # numbers of exps increased self.a_idxs[p_idx].append(len(self._gp.A.row)) self._gp.A.row.append(m_idx + i) self._gp.A.col.append(self._gp.varidxs[var]) self._gp.A.data.append(x) for row_idx in a_idxs: # number of exps decreased self._gp.A.row[row_idx] = 0 # zero out this entry self._gp.A.col[row_idx] = 0 self._gp.A.data[row_idx] = 0 return self._gp
mit
xbnewbie/kaler
assets/js/inc/demo.js
896
$(window).load(function(){ /*------------------------------------------- Welcome Message ---------------------------------------------*/ function notify(message, type){ $.growl({ message: message },{ type: type, allow_dismiss: false, label: 'Cancel', className: 'btn-xs btn-inverse', placement: { from: 'bottom', align: 'left' }, delay: 2500, animate: { enter: 'animated fadeInUp', exit: 'animated fadeOutDown' }, offset: { x: 30, y: 30 } }); }; setTimeout(function () { if (!$('.login-content')[0]) { notify('Welcome back Mallinda Hollaway', 'inverse'); } }, 1000) });
mit
shesuyo/crud
crud.go
17503
package crud import ( "database/sql" "errors" "fmt" "log" "net/http" "reflect" "runtime" "strings" "sync" _ "github.com/go-sql-driver/mysql" //mysql driver ) // 变量 var ( TimeFormat = "2006-01-02 15:04:05" //错误 ErrExec = errors.New("执行错误") ErrArgs = errors.New("参数错误") ErrInsertRepeat = errors.New("重复插入") ErrSQLSyntaxc = errors.New("SQL语法错误") ErrInsertData = errors.New("插入数据库异常") ErrNoUpdateKey = errors.New("没有更新主键") ErrMustBeAddr = errors.New("必须为值引用") ErrMustBeSlice = errors.New("必须为Slice") ErrMustNeedID = errors.New("必须要有ID") ErrNotSupportType = errors.New("不支持类型") ) // Render 用于对接http.HandleFunc直接调用CRUD type Render func(w http.ResponseWriter, err error, data ...interface{}) // DataBase 数据库链接 type DataBase struct { debug bool Schema string //数据库表名 tableColumns map[string]Columns dataSourceName string db *sql.DB mm *sync.Mutex // 用于getColumns的写锁 render Render //crud本身不渲染数据,通过其他地方传入一个渲染的函数,然后渲染都是那边处理。 } // NewDataBase 创建一个新的数据库链接 func NewDataBase(dataSourceName string, render ...Render) (*DataBase, error) { db, err := sql.Open("mysql", dataSourceName) if err != nil { return nil, err } db.SetMaxIdleConns(10) db.SetMaxOpenConns(10) crud := &DataBase{ debug: false, tableColumns: make(map[string]Columns), dataSourceName: dataSourceName, db: db, mm: new(sync.Mutex), render: func(w http.ResponseWriter, err error, data ...interface{}) { if len(render) == 1 { if render[0] != nil { render[0](w, err, data...) } } }, } crud.Schema = crud.Query("SELECT DATABASE()").String() if crud.Schema == "" { log.Println("FBI WARNING: 这是一个没有选择数据库的链接。") } tables := crud.Query("SELECT TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME,COLUMN_COMMENT,COLUMN_TYPE,DATA_TYPE,IS_NULLABLE FROM information_schema.`COLUMNS` WHERE TABLE_SCHEMA = ?", crud.Schema).RowsMap().MapIndexs("TABLE_NAME") for tableName, cols := range tables { cm := make(map[string]Column) for _, v := range cols { cm[v["COLUMN_NAME"]] = Column{ Schema: v["TABLE_SCHEMA"], Table: v["TABLE_NAME"], Name: v["COLUMN_NAME"], Comment: v["COLUMN_COMMENT"], ColumnType: v["COLUMN_TYPE"], DataType: v["DATA_TYPE"], IsNullAble: v["IS_NULLABLE"] == "YES", } } crud.tableColumns[tableName] = cm } return crud, nil } /* CRUD table */ // ExecSuccessRender 渲染成功模板 func (db *DataBase) ExecSuccessRender(w http.ResponseWriter) { db.render(w, nil, nil) } func (db *DataBase) argsErrorRender(w http.ResponseWriter) { db.render(w, ErrArgs) } func (db *DataBase) execErrorRender(w http.ResponseWriter) { db.render(w, ErrExec) } func (db *DataBase) dataRender(w http.ResponseWriter, data interface{}) { db.render(w, nil, data) } /* CRUD colums table */ // HaveTable 是否有这张表 func (db *DataBase) HaveTable(tablename string) bool { return db.haveTablename(tablename) } func (db *DataBase) haveTablename(tableName string) bool { _, ok := db.tableColumns[tableName] return ok } // 获取表中所有列名 func (db *DataBase) getColumns(tableName string) Columns { names, ok := db.tableColumns[tableName] if ok { return names } rows := db.Query("SELECT COLUMN_NAME,COLUMN_COMMENT,COLUMN_TYPE,DATA_TYPE,IS_NULLABLE FROM information_schema.`COLUMNS` WHERE table_name= ? ", tableName).RowsMap() cols := make(map[string]Column) for _, v := range rows { cols[v["COLUMN_NAME"]] = Column{ Name: v["COLUMN_NAME"], Comment: v["COLUMN_COMMENT"], ColumnType: v["COLUMN_TYPE"], DataType: v["DATA_TYPE"], IsNullAble: v["IS_NULLABLE"] == "YES", } dbcM.Lock() DBColums[v["COLUMN_NAME"]] = cols[v["COLUMN_NAME"]] dbcM.Unlock() } db.mm.Lock() db.tableColumns[tableName] = cols db.mm.Unlock() return cols } // Table 返回一个Table func (db *DataBase) Table(tableName string) *Table { if !db.HaveTable(tableName) { // fmt.Println("FBI WARNING:表" + tableName + "不存在!") } table := new(Table) table.DataBase = db table.tableName = tableName table.Search = &Search{ table: table, tableName: tableName, } table.Columns = db.tableColumns[tableName] return table } /* CRUD debug */ // Debug 是否开启debug功能 true为开启 func (db *DataBase) Debug(isDebug bool) *DataBase { db.debug = isDebug return db } // X 用于DEBUG func (*DataBase) X(args ...interface{}) { fmt.Println("[DEBUG]", args) } // Log 打印日志 func (db *DataBase) Log(args ...interface{}) { if db.debug { db.log(args...) } } // LogSQL 会将sql语句中的?替换成相应的参数,让DEBUG的时候可以直接复制SQL语句去使用。 func (db *DataBase) LogSQL(sql string, args ...interface{}) { if db.debug { db.log(getFullSQL(sql, args...)) } } func (db *DataBase) log(args ...interface{}) { log.Println(args...) } func getFullSQL(sql string, args ...interface{}) string { for _, arg := range args { sql = strings.Replace(sql, "?", fmt.Sprintf("'%v'", arg), 1) } return sql } // 如果发生了异常就打印调用栈。 func (db *DataBase) stack(err error, sql string, args ...interface{}) { buf := make([]byte, 1<<10) runtime.Stack(buf, true) log.Printf("%s\n%s\n%s\n", err.Error(), getFullSQL(sql, args...), buf) } // RowSQL Query alias func (db *DataBase) RowSQL(sql string, args ...interface{}) *SQLRows { return db.Query(sql, args...) } /* CRUD 查询 */ // Query 用于底层查询,一般是SELECT语句 func (db *DataBase) Query(sql string, args ...interface{}) *SQLRows { db.LogSQL(sql, args...) rows, err := db.DB().Query(sql, args...) if err != nil { db.stack(err, sql, args...) } return &SQLRows{rows: rows, err: err} } // Exec 用于底层执行,一般是INSERT INTO、DELETE、UPDATE。 func (db *DataBase) Exec(sql string, args ...interface{}) sql.Result { db.LogSQL(sql, args...) ret, err := db.DB().Exec(sql, args...) if err != nil { db.stack(err, sql, args...) } return ret } // DB 返回一个DB链接,查询后一定要关闭col,而不能关闭*sql.DB。 func (db *DataBase) DB() *sql.DB { return db.db } // Create 根据相应单个结构体进行创建 func (db *DataBase) Create(obj interface{}) (int64, error) { //一定要是地址 //需要检查Before函数 //需要按需转换成map(考虑ignore) //需要检查After函数 //TODO 一次性创建整个嵌套结构体 v := reflect.ValueOf(obj) if v.Kind() != reflect.Ptr { return 0, ErrMustBeAddr } beforeFunc := v.MethodByName(BeforeCreate) afterFunc := v.MethodByName(AfterCreate) tableName := getStructDBName(v) // 这里的处理应该是有才处理,没有不管。 if beforeFunc.IsValid() { vals := beforeFunc.Call(nil) if len(vals) == 1 { if err, ok := vals[0].Interface().(error); ok { if err != nil { return 0, err } } } } m := structToMap(v) table := db.Table(tableName) for k, v := range m { if k == "id" && v == "" { delete(m, "id") } if table.Columns[k].DataType == "datetime" && v == "" { delete(m, k) } } id, err := table.Create(m) rID := v.Elem().FieldByName("ID") if rID.IsValid() { rID.SetInt(id) } if afterFunc.IsValid() { afterFunc.Call(nil) } return id, err } // Creates 根据相应多个结构体进行创建 func (db *DataBase) Creates(objs interface{}) ([]int64, error) { ids := []int64{} v := reflect.ValueOf(objs) if v.Kind() != reflect.Ptr { return ids, ErrMustBeAddr } if v.Elem().Kind() != reflect.Slice { return ids, ErrMustBeSlice } for i, num := 0, v.Elem().Len(); i < num; i++ { id, err := db.Create(v.Elem().Index(i).Addr().Interface()) if err != nil { return ids, err } ids = append(ids, id) } return ids, nil } // Update Update func (db *DataBase) Update(obj interface{}) error { //根据ID进行Update v := reflect.ValueOf(obj) if v.Kind() != reflect.Ptr { return ErrMustBeAddr } beforeFunc := v.MethodByName(BeforeUpdate) afterFunc := v.MethodByName(AfterUpdate) if beforeFunc.IsValid() { beforeFunc.Call(nil) } tableName := getStructDBName(v) m := structToMap(v) err := db.Table(tableName).Update(m) if err != nil { return err } if afterFunc.IsValid() { afterFunc.Call(nil) } return nil } // Updates Updates func (db *DataBase) Updates(objs interface{}) error { v := reflect.ValueOf(objs) if v.Kind() != reflect.Ptr { return ErrMustBeAddr } if v.Elem().Kind() != reflect.Slice { return ErrMustBeSlice } for i, num := 0, v.Elem().Len(); i < num; i++ { err := db.Update(v.Elem().Index(i).Addr().Interface()) if err != nil { return err } } return nil } // Delete Delete func (db *DataBase) Delete(obj interface{}) (int64, error) { v := reflect.ValueOf(obj) if v.Kind() != reflect.Ptr { return 0, ErrMustBeAddr } beforeFunc := v.MethodByName(BeforeDelete) afterFunc := v.MethodByName(AfterDelete) if beforeFunc.IsValid() { beforeFunc.Call(nil) } id := getStructID(v) if id == 0 { return 0, ErrMustNeedID } tableName := getStructDBName(v) count, err := db.Table(tableName).Delete(map[string]interface{}{"id": id}) if afterFunc.IsValid() { afterFunc.Call(nil) } return count, err } // Deletes Deletes func (db *DataBase) Deletes(objs interface{}) (int64, error) { var affCount int64 v := reflect.ValueOf(objs) if v.Kind() != reflect.Ptr { return 0, ErrMustBeAddr } if v.Elem().Kind() != reflect.Slice { return 0, ErrMustBeSlice } for i, num := 0, v.Elem().Len(); i < num; i++ { aff, err := db.Delete(v.Elem().Index(i).Addr().Interface()) affCount += aff if err != nil { return affCount, err } } return 0, nil } // FormCreate 创建,表单创建。 func (db *DataBase) FormCreate(v interface{}, w http.ResponseWriter, r *http.Request) { tableName := getStructDBName(reflect.ValueOf(v)) m := parseRequest(v, r, C) if m == nil || len(m) == 0 { db.argsErrorRender(w) return } id, err := db.Table(tableName).Create(m) if err != nil { db.execErrorRender(w) return } m["id"] = id delete(m, IsDeleted) db.dataRender(w, m) } // FormRead 表单查找 /* 查找 id = 1 id = 1 AND hospital_id = 1 CRUD FormRead -> table Read */ func (db *DataBase) FormRead(v interface{}, w http.ResponseWriter, r *http.Request) { // 这里传进来的参数一定是要有用的参数,如果是没有用的参数被传进来了,那么会报参数错误,或者显示执行成功数据会乱。 // 这里处理last_XXX // 处理翻页的问题 // 首先判断这个里面有没有这个字段 m := parseRequest(v, r, R) tableName := getStructDBName(reflect.ValueOf(v)) data := db.Table(tableName).Reads(m) db.dataRender(w, data) } // FormUpdate 表单更新 func (db *DataBase) FormUpdate(v interface{}, w http.ResponseWriter, r *http.Request) { tableName := getStructDBName(reflect.ValueOf(v)) m := parseRequest(v, r, R) if m == nil || len(m) == 0 { db.argsErrorRender(w) return } err := db.Table(tableName).Update(m) if err != nil { db.execErrorRender(w) return } db.ExecSuccessRender(w) } // FormDelete 表单删除 func (db *DataBase) FormDelete(v interface{}, w http.ResponseWriter, r *http.Request) { tableName := getStructDBName(reflect.ValueOf(v)) m := parseRequest(v, r, R) if m == nil || len(m) == 0 { db.argsErrorRender(w) return } _, err := db.Table(tableName).Delete(m) if err != nil { db.execErrorRender(w) return } db.ExecSuccessRender(w) } // Find 将查找数据放到结构体里面 // 如果不传条件则是查找所有人 // Read Find Select func (db *DataBase) Find(obj interface{}, args ...interface{}) error { var ( v = reflect.ValueOf(obj) tableName = "" elem = v.Elem() where = " WHERE 1 " rawSqlflag = false ) if v.Kind() != reflect.Ptr { return ErrMustBeAddr } if len(args) > 0 { if sql, ok := args[0].(string); ok { if strings.Contains(sql, "SELECT") { rawSqlflag = true err := db.Query(sql, args[1:]...).Find(obj) if err != nil { return err } } } } if !rawSqlflag { if elem.Kind() == reflect.Slice { tableName = getStructDBName(reflect.New(elem.Type().Elem())) } else { tableName = getStructDBName(elem) } if len(args) == 1 { where += " AND id = ? " args = append(args, args[0]) } else if len(args) > 1 { where += "AND " + args[0].(string) } else { //avoid args[1:]... bounds out of range args = append(args, nil) //如果没有传参数,那么参数就在结构体本身。(只支持ID,而且是结构体的时候) if elem.Kind() == reflect.Struct { rID := elem.FieldByName("ID") if rID.IsValid() { rIDInt64 := rID.Int() if rIDInt64 != 0 { where += " AND id = ? " args = append(args, rIDInt64) } } } } if db.tableColumns[tableName].HaveColumn(IsDeleted) { where += " AND is_deleted = 0" } err := db.Query(fmt.Sprintf("SELECT * FROM `%s` %s", tableName, where), args[1:]...).Find(obj) if err != nil { return err } } switch elem.Kind() { case reflect.Slice: for i, num := 0, elem.Len(); i < num; i++ { afterFunc := elem.Index(i).Addr().MethodByName("AfterFind") if !afterFunc.IsValid() { return nil } afterFunc.Call(nil) } case reflect.Struct: afterFunc := v.MethodByName("AfterFind") if afterFunc.IsValid() { afterFunc.Call(nil) } } return nil } // connection 找出两张表之间的关联 /* 根据belong查询master master是要查找的,belong是已知的。 */ func (db *DataBase) connection(target string, got reflect.Value) ([]interface{}, bool) { //"SELECT `master`.* FROM `master` WHERE `belong_id` = ? ", belongID //"SELECT `master`.* FROM `master` LEFT JOIN `belong` ON `master`.id = `belong`.master_id WHERE `belong`.id = ?" //"SELECT `master`.* FROM `master` LEFT JOIN `belong` ON `master`.belong_id = `belong`.id WHERE `belong`.id = ?" //"SELECT `master`.* FROM `master` LEFT JOIN `master_belong` ON `master_belong`.master_id = `master`.id WHERE `master_belong`.belong_id = ?", belongID //"SELECT `master`.* FROM `master` LEFT JOIN `belong_master` ON `belong_master`.master_id = `master`.id WHERE `belong_master`.belong_id = ?", belongID // 首先实现正常的逻辑,然后再进行所有逻辑的判断。 ttn := target //target table name gtn := ToDBName(got.Type().Name()) // got table name //fmt.Println(ttn, gtn) if db.tableColumns[gtn].HaveColumn(ttn + "_id") { // got: question_option question_id // target: question // select * from question where id = question_option.question_id //return db.RowSQL(fmt.Sprintf("SELECT `%s`.* FROM `%s` WHERE %s = ?", gtn, gtn, "id"), got.FieldByName(ttn+"_id").Interface()) return []interface{}{fmt.Sprintf("SELECT `%s`.* FROM `%s` WHERE %s = ?", gtn, gtn, "id"), got.FieldByName(ToStructName(ttn + "_id")).Interface()}, true } if db.tableColumns[ttn].HaveColumn(gtn + "_id") { //got: question //target:question_options //select * from question_options where question.options.question_id = question.id // return db.RowSQL(fmt.Sprintf("SELECT * FROM `%s` WHERE %s = ?", ttn, gtn+"_id"), got.FieldByName("id").Interface()) return []interface{}{fmt.Sprintf("SELECT * FROM `%s` WHERE %s = ?", ttn, gtn+"_id"), got.FieldByName("ID").Interface()}, true } //group_section //got: group //target: section //SELECT section.* FROM section LEFT JOIN group_section ON group_section.section_id = section.id WHERE group_section.group_id = group.id ctn := "" if db.haveTablename(ttn + "_" + gtn) { ctn = ttn + "_" + gtn } if db.haveTablename(gtn + "_" + ttn) { ctn = gtn + "_" + ttn } if ctn != "" { if db.tableColumns[ctn].HaveColumn(gtn+"_id") && db.tableColumns[ctn].HaveColumn(ttn+"_id") { // return db.RowSQL(fmt.Sprintf("SELECT `%s`.* FROM `%s` LEFT JOIN %s ON %s.%s = %s.%s WHERE %s.%s = ?", ttn, ttn, ctn, ctn, ttn+"_id", ttn, "id", ctn, gtn+"_id"), // got.FieldByName("id").Interface()) return []interface{}{fmt.Sprintf("SELECT `%s`.* FROM `%s` LEFT JOIN %s ON %s.%s = %s.%s WHERE %s.%s = ?", ttn, ttn, ctn, ctn, ttn+"_id", ttn, "id", ctn, gtn+"_id"), got.FieldByName("ID").Interface()}, true } } return []interface{}{}, false } // FindAll 在需要的时候将自动查询结构体子结构体 func (db *DataBase) FindAll(v interface{}, args ...interface{}) error { if err := db.Find(v, args...); err != nil { return err } //首先查找字段,然后再查找结构体和Slice /* 首先实现结构体 //不处理指针 */ rv := reflect.ValueOf(v).Elem() switch rv.Kind() { case reflect.Struct: db.setStructField(rv) case reflect.Slice: for i := 0; i < rv.Len(); i++ { db.setStructField(rv.Index(i)) } default: return ErrNotSupportType } return nil } func (db *DataBase) setStructField(rv reflect.Value) { for i := 0; i < rv.NumField(); i++ { if rv.Field(i).Kind() == reflect.Struct { con, ok := db.connection(ToDBName(rv.Field(i).Type().Name()), rv) if ok { db.FindAll(rv.Field(i).Addr().Interface(), con...) } } if rv.Field(i).Kind() == reflect.Slice { con, ok := db.connection(ToDBName(rv.Field(i).Type().Elem().Name()), rv) if ok { db.FindAll(rv.Field(i).Addr().Interface(), con...) } } } }
mit
omicrono/EDEngineer_Spanish_Version
EDEngineer/Converters/RarityToIconConverter.cs
1123
using System; using System.Globalization; using System.Windows.Data; using EDEngineer.Models; namespace EDEngineer.Converters { public class RarityToIconConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { switch ((Rarity) value) { case Rarity.VeryCommon: return "Resources/Images/very-common.png"; case Rarity.Common: return "Resources/Images/common.png"; case Rarity.Standard: return "Resources/Images/standard.png"; case Rarity.Rare: return "Resources/Images/rare.png"; case Rarity.VeryRare: return "Resources/Images/very-rare.png"; default: throw new NotImplementedException(); } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
mit
mohsinhijazee/s3_attachment
init.rb
196
# Include hook code here require 's3_attachment.rb' require File.dirname(__FILE__) + '/../../../lib/dedomenon.rb' register_datatype :name => 'madb_s3_attachment', :class_name => 'S3Attachment'
mit
somebee/imba
polyfills/crypto/esm/lib/randomfill/index.js
3095
import randombytes from "../randombytes"; 'use strict'; function oldBrowser() { throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11'); } var kBufferMaxLength = Buffer.kMaxLength; var crypto = global.crypto || global.msCrypto; var kMaxUint32 = Math.pow(2, 32) - 1; function assertOffset(offset, length) { if (typeof offset !== 'number' || offset !== offset) { // eslint-disable-line no-self-compare throw new TypeError('offset must be a number'); } if (offset > kMaxUint32 || offset < 0) { throw new TypeError('offset must be a uint32'); } if (offset > kBufferMaxLength || offset > length) { throw new RangeError('offset out of range'); } } function assertSize(size, offset, length) { if (typeof size !== 'number' || size !== size) { // eslint-disable-line no-self-compare throw new TypeError('size must be a number'); } if (size > kMaxUint32 || size < 0) { throw new TypeError('size must be a uint32'); } if (size + offset > length || size > kBufferMaxLength) { throw new RangeError('buffer too small'); } } if ((crypto && crypto.getRandomValues) || !process.browser) { } else { } function randomFill(buf, offset, size, cb) { if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) { throw new TypeError('"buf" argument must be a Buffer or Uint8Array'); } if (typeof offset === 'function') { cb = offset; offset = 0; size = buf.length; } else if (typeof size === 'function') { cb = size; size = buf.length - offset; } else if (typeof cb !== 'function') { throw new TypeError('"cb" argument must be a function'); } assertOffset(offset, buf.length); assertSize(size, offset, buf.length); return actualFill(buf, offset, size, cb); } function actualFill(buf, offset, size, cb) { if (process.browser) { var ourBuf = buf.buffer; var uint = new Uint8Array(ourBuf, offset, size); crypto.getRandomValues(uint); if (cb) { process.nextTick(function () { cb(null, buf); }); return; } return buf; } if (cb) { randombytes(size, function (err, bytes) { if (err) { return cb(err); } bytes.copy(buf, offset); cb(null, buf); }); return; } var bytes = randombytes(size); bytes.copy(buf, offset); return buf; } function randomFillSync(buf, offset, size) { if (typeof offset === 'undefined') { offset = 0; } if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) { throw new TypeError('"buf" argument must be a Buffer or Uint8Array'); } assertOffset(offset, buf.length); if (size === undefined) size = buf.length - offset; assertSize(size, offset, buf.length); return actualFill(buf, offset, size); } export { randomFill }; export { randomFillSync };
mit
hankmorgan/UnderworldExporter
Skunkworks/CritterAnimInfo.cs
365
using UnityEngine; using System.Collections; public class CritterAnimInfo { public string[,] animSequence; public int[,] animIndices; public Sprite[] animSprites; public string[] animName; public CritterAnimInfo() { animSequence=new string[32,8]; animIndices=new int[32,8]; animSprites=new Sprite[200];//In order animName=new string[32]; } }
mit
danrg/RGT-tool
static/js/external/ajaxPostDjangoFix.js
1757
//from https://docs.djangoproject.com/en/dev/ref/contrib/csrf/ $(document).ready(function(){ $(document).ajaxSend(function(event, xhr, settings) { function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function sameOrigin(url) { // url could be relative or scheme relative or absolute var host = document.location.host; // host + port var protocol = document.location.protocol; var sr_origin = '//' + host; var origin = protocol + sr_origin; // Allow absolute or scheme relative URLs to same origin return (url == origin || url.slice(0, origin.length + 1) == origin + '/') || (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') || // or any other URL that isn't scheme relative or absolute i.e relative. !(/^(\/\/|http:|https:).*/.test(url)); } function safeMethod(method) { return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } if (!safeMethod(settings.type) && sameOrigin(settings.url)) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } }); });
mit
Python-Tools/pmfp
pmfp/config/verify.py
3869
"""用于验证pmfp.json的schema.""" import getpass from typing import Dict from typing import Any as typeAny from voluptuous import (All, Any, Email, Equal, In, Invalid, NotIn, Required, Schema, Url) NOT_NAME_RANGE = ["app", "application", "module", "project"] STATUS_RANGE = ["prod", "release", "dev", "test"] LANGUAGE_RANGE = ["Python", "Javascript", "Golang"] ENV_RANGE = ["env", "conda", "node", "frontend", "webpack", "vue", "vue-electron", "vue-native", "vue-nativescript", "gomod"] TYPE_RANGE = ["application", "module"] LICENSE_RANGE = ["MIT", "Apache", "BSD", "Mozilla", "LGPL", "GPL", "GNU"] DEFAULT_AUTHOR = getpass.getuser() def env_match(language: str, env: str) -> bool: """检测language和env是否匹配. Args: language (str): language env (str): env Returns: bool: 是否匹配 """ if language == "Python": if env not in ("env", "conda"): return False else: return True elif language in ("Javascript", ): if env not in ("node", "frontend", "webpack", "vue", "vue-electron", "vue-native", "vue-nativescript"): return False else: return True elif language in ("Golang",): if env not in ("gomod", ): return False else: return True else: raise AttributeError(f"unknown language {language}") def config_must_match(config: Dict[str, typeAny]) -> Dict[str, typeAny]: """检测配置是否符合要求的函数. Args: config (Dict[str, Any]): 项目当前配置. Raises: Invalid: 项目非法. Returns: Dict[str, Any]: 如果项目配置没问题,返回项目配置 """ env = config['env'] language = config['project-language'] if not env_match(language, env): raise Invalid(f'{env}不是{language}允许的环境') return config config_schema = Schema( All( { Required("project-name"): All( str, NotIn( NOT_NAME_RANGE, msg=f"项目名不可以在{NOT_NAME_RANGE}中" ) ), Required('license', default="MIT"): All( str, In(LICENSE_RANGE, msg=f"license 只能在{LICENSE_RANGE}范围内") ), Required('version', default="0.0.0"): str, Required('status', default="dev"): All( str, In( STATUS_RANGE, msg=f"status只能在{STATUS_RANGE}范围内" ) ), Required('url', default=""): Any(Equal(""), Url(None)), Required('author', default=DEFAULT_AUTHOR): str, Required('author-email', default=""): Any(Equal(""), Email(None)), Required('keywords', default=["tools"]): list, Required('description', default="simple tools"): str, Required('project-language'): All( str, In( LANGUAGE_RANGE, msg=f"项目语言只能在{LANGUAGE_RANGE}范围内" ) ), Required('gcc', default="gcc"): str, Required('env'): All(str, In(ENV_RANGE, msg=f"项目环境只能在{ENV_RANGE}范围内")), Required('global-python', default="python"): str, Required('project-type'): All(str, In(TYPE_RANGE, msg=f"项目类型只能在{TYPE_RANGE}范围内")), Required('template'): str, Required('remote_registry', default=""): str, Required("requirement", default=[]): list, Required("requirement-dev", default=[]): list, Required("entry", default=""): str }, config_must_match ) )
mit
phase/Pore
src/main/java/blue/lapis/pore/impl/block/PoreChest.java
1993
/* * Pore * Copyright (c) 2014-2015, Lapis <https://github.com/LapisBlue> * * The MIT License * * 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. */ package blue.lapis.pore.impl.block; import blue.lapis.pore.converter.wrapper.WrapperConverter; import org.apache.commons.lang.NotImplementedException; import org.bukkit.inventory.Inventory; import org.spongepowered.api.block.data.Chest; public class PoreChest extends PoreBlockState implements org.bukkit.block.Chest { public static PoreChest of(Chest handle) { return WrapperConverter.of(PoreChest.class, handle); } protected PoreChest(Chest handle) { super(handle); } @Override public Chest getHandle() { return (Chest) super.getHandle(); } @Override public Inventory getBlockInventory() { throw new NotImplementedException(); } @Override public Inventory getInventory() { throw new NotImplementedException(); } }
mit
BrianHicks/emit
tests/message_tests.py
2002
'tests for message' import json from unittest import TestCase from emit.messages import Message class MessageTests(TestCase): 'tests for Message' def test_dot_access(self): 'accessing attributes' x = Message(x=1) self.assertEqual(1, x.x) def test_access_missing(self): 'accessing attributes that do not exist' x = Message(x=1) try: self.assertRaisesRegex( AttributeError, '"y" is not included in this message', getattr, x, 'y' ) except AttributeError: # python 2.6 self.assertRaises( AttributeError, getattr, x, 'y' ) def test_repr(self): x = Message(x=1, y=2) try: self.assertRegexpMatches( repr(x), r'Message\(((x=1|y=2)(, )?){2}\)' ) except AttributeError: # python 2.6 self.assertEqual( 'Message(y=2, x=1)', repr(x) ) def test_dir(self): 'dir includes attributes' x = Message(x=1, y=2) try: self.assertIn('x', dir(x)) self.assertIn('y', dir(x)) except AttributeError: # python 2.6 self.assertTrue('x' in dir(x), '"x" not in dir(x)') self.assertTrue('y' in dir(x), '"y" not in dir(x)') def test_as_dict(self): 'returns dict from .as_dict' x = Message(x=1, y=2) self.assertEqual( {'x': 1, 'y': 2}, x.as_dict() ) def test_as_json(self): 'returns string from .as_msgpack' d = {'x': 1, 'y': 2} x = Message(**d) self.assertEqual( json.dumps(d), x.as_json() ) def test_equality(self): 'two messages are equal if their bundles are equal' d = {'x': 1, 'y': 2} x = Message(**d) y = Message(**d) self.assertEqual(x, y)
mit
plast-lab/DelphJ
examples/berkeleydb/com/sleepycat/persist/impl/Format.java
32107
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2002,2008 Oracle. All rights reserved. * * $Id: Format.java,v 1.39 2008/01/07 14:28:59 cwl Exp $ */ package com.sleepycat.persist.impl; import java.io.Serializable; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.sleepycat.persist.evolve.Converter; import com.sleepycat.persist.model.ClassMetadata; import com.sleepycat.persist.model.EntityMetadata; import com.sleepycat.persist.raw.RawField; import com.sleepycat.persist.raw.RawObject; import com.sleepycat.persist.raw.RawType; /** * The base class for all object formats. Formats are used to define the * stored layout for all persistent classes, including simple types. * * The design documentation below describes the storage format for entities and * its relationship to information stored per format in the catalog. * * Requirements * ------------ * + Provides EntityBinding for objects and EntryBinding for keys. * + Provides SecondaryKeyCreator, SecondaryMultiKeyCreator and * SecondaryMultiKeyNullifier (SecondaryKeyNullifier is redundant). * + Works with reflection and bytecode enhancement. * + For reflection only, works with any entity model not just annotations. * + Bindings are usable independently of the persist API. * + Performance is almost equivalent to hand coded tuple bindings. * + Small performance penalty for compatible class changes (new fields, * widening). * + Secondary key create/nullify do not have to deserialize the entire record; * in other words, store secondary keys at the start of the data. * * Class Format * ------------ * Every distinct class format is given a unique format ID. Class IDs are not * equivalent to class version numbers (as in the version property of @Entity * and @Persistent) because the format can change when the version number does * not. Changes that cause a unique format ID to be assigned are: * * + Add field. * + Widen field type. * + Change primitive type to primitive wrapper class. * + Add or drop secondary key. * + Any incompatible class change. * * The last item, incompatible class changes, also correspond to a class * version change. * * For each distinct class format the following information is conceptually * stored in the catalog, keyed by format ID. * * - Class name * - Class version number * - Superclass format * - Kind: simple, enum, complex, array * - For kind == simple: * - Primitive class * - For kind == enum: * - Array of constant names, sorted by name. * - For kind == complex: * - Primary key fieldInfo, or null if no primary key is declared * - Array of secondary key fieldInfo, sorted by field name * - Array of other fieldInfo, sorted by field name * - For kind == array: * - Component class format * - Number of array dimensions * - Other metadata for RawType * * Where fieldInfo is: * - Field name * - Field class * - Other metadata for RawField * * Data Layout * ----------- * For each entity instance the data layout is as follows: * * instanceData: formatId keyFields... nonKeyFields... * keyFields: fieldValue... * nonKeyFields: fieldValue... * * The formatId is the (positive non-zero) ID of a class format, defined above. * This is ID of the most derived class of the instance. It is stored as a * packed integer. * * Following the format ID, zero or more sets of secondary key field values * appear, followed by zero or more sets of other class field values. * * The keyFields are the sets of secondary key fields for each class in order * of the highest superclass first. Within a class, fields are ordered by * field name. * * The nonKeyFields are the sets of other non-key fields for each class in * order of the highest superclass first. Within a class, fields are ordered * by field name. * * A field value is: * * fieldValue: primitiveValue * | nullId * | instanceRef * | instanceData * | simpleValue * | enumValue * | arrayValue * * For a primitive type, a primitive value is used as defined for tuple * bindings. For float and double, sorted float and sorted double tuple values * are used. * * For a non-primitive type with a null value, a nullId is used that has a zero * (illegal formatId) value. This includes String and other simple reference * types. The formatId is stored as a packed integer, meaning that it is * stored as a single zero byte. * * For a non-primitive type, an instanceRef is used for a non-null instance * that appears earlier in the data byte array. An instanceRef is the negation * of the byte offset of the instanceData that appears earlier. It is stored * as a packed integer. * * The remaining rules apply only to reference types with non-null values that * do not appear earlier in the data array. * * For an array type, an array formatId is used that identifies the component * type and the number of array dimensions. This is followed by an array * length (stored as a packed integer) and zero or more fieldValue elements. * For an array with N+1 dimensions where N is greater than zero, the leftmost * dimension is enumerated such that each fieldValue element is itself an array * of N dimensions or null. * * arrayValue: formatId length fieldValue... * * For an enum type, an enumValue is used, consisting of a formatId that * identifies the enum class and an enumIndex (stored as a packed integer) that * identifies the constant name in the enum constant array of the enum class * format: * * enumValue: formatId enumIndex * * For a simple type, a simpleValue is used. This consists of the formatId * that identifies the class followed by the simple type value. For a * primitive wrapper type the simple type value is the corresponding primitive, * for a Date it is the milliseconds as a long primitive, and for BigInteger or * BigDecimal it is a byte array as defined for tuple bindings of these types. * * simpleValue: formatId value * * For all other complex types, an instanceData is used, which is defined * above. * * Secondary Keys * -------------- * For secondary key support we must account for writing and nullifying * specific keys. Rather than instantiating the entity and then performing * the secondary key operation, we strive to perform the secondary key * operation directly on the byte format. * * To create a secondary key we skip over other fields and then copy the bytes * of the embedded key. This approach is very efficient because a) the entity * is not instantiated, and b) the secondary keys are stored at the beginning * of the byte format and can be quickly read. * * To nullify we currently instantiate the raw entity, set the key field to null * (or remove it from the array/collection), and convert the raw entity back to * bytes. Although the performance of this approach is not ideal because it * requires serialization, it avoids the complexity of modifying the packed * serialized format directly, adjusting references to key objects, etc. Plus, * when we nullify a key we are going to write the record, so the serialization * overhead may not be significant. For the record, I tried implementing * nullification of the bytes directly and found it was much too complex. * * Lifecycle * --------- * Format are managed by a Catalog class. Simple formats are managed by * SimpleCatalog, and are copied from the SimpleCatalog by PersistCatalog. * Other formats are managed by PersistCatalog. The lifecycle of a format * instance is: * * - Constructed by the catalog when a format is requested for a Class * that currently has no associated format. * * - The catalog calls setId() and adds the format to its format list * (indexed by format id) and map (keyed by class name). * * - The catalog calls collectRelatedFormats(), where a format can create * additional formats that it needs, or that should also be persistent. * * - The catalog calls initializeIfNeeded(), which calls the initialize() * method of the format class. * * - initialize() should initialize any transient fields in the format. * initialize() can assume that all related formats are available in the * catalog. It may call initializeIfNeeded() for those related formats, if * it needs to interact with an initialized related format; this does not * cause a cycle, because initializeIfNeeded() does nothing for an already * initialized format. * * - The catalog creates a group of related formats at one time, and then * writes its entire list of formats to the catalog DB as a single record. * This grouping reduces the number of writes. * * - When a catalog is opened and the list of existing formats is read. After * a format is deserialized, its initializeIfNeeded() method is called. * setId() and collectRelatedFormats() are not called, since the ID and * related formats are stored in serialized fields. * * - There are two modes for opening an existing catalog: raw mode and normal * mode. In raw mode, the old format is used regardless of whether it * matches the current class definition; in fact the class is not accessed * and does not need to be present. * * - In normal mode, for each existing format that is initialized, a new format * is also created based on the current class and metadata definition. If * the two formats are equal, the new format is discarded. If they are * unequal, the new format becomes the current format and the old format's * evolve() method is called. evolve() is responsible for adjusting the * old format for class evolution. Any number of non-current formats may * exist for a given class, and are setup to evolve the single current format * for the class. * * @author Mark Hayes */ public abstract class Format implements Reader, RawType, Serializable { private static final long serialVersionUID = 545633644568489850L; /** Null reference. */ static final int ID_NULL = 0; /** Object */ static final int ID_OBJECT = 1; /** Boolean */ static final int ID_BOOL = 2; static final int ID_BOOL_W = 3; /** Byte */ static final int ID_BYTE = 4; static final int ID_BYTE_W = 5; /** Short */ static final int ID_SHORT = 6; static final int ID_SHORT_W = 7; /** Integer */ static final int ID_INT = 8; static final int ID_INT_W = 9; /** Long */ static final int ID_LONG = 10; static final int ID_LONG_W = 11; /** Float */ static final int ID_FLOAT = 12; static final int ID_FLOAT_W = 13; /** Double */ static final int ID_DOUBLE = 14; static final int ID_DOUBLE_W = 15; /** Character */ static final int ID_CHAR = 16; static final int ID_CHAR_W = 17; /** String */ static final int ID_STRING = 18; /** BigInteger */ static final int ID_BIGINT = 19; /** BigDecimal */ static final int ID_BIGDEC = 20; /** Date */ static final int ID_DATE = 21; /** Number */ static final int ID_NUMBER = 22; /** First simple type. */ static final int ID_SIMPLE_MIN = 2; /** Last simple type. */ static final int ID_SIMPLE_MAX = 21; /** Last predefined ID, after which dynamic IDs are assigned. */ static final int ID_PREDEFINED = 30; static boolean isPredefined(Format format) { return format.getId() <= ID_PREDEFINED; } private int id; private String className; private Reader reader; private Format superFormat; private Format latestFormat; private Format previousFormat; private Set<String> supertypes; private boolean deleted; private boolean unused; private transient Catalog catalog; private transient Class type; private transient Format proxiedFormat; private transient boolean initialized; /** * Creates a new format for a given class. */ Format(Class type) { this(type.getName()); this.type = type; addSupertypes(); } /** * Creates a format for class evolution when no class may be present. */ Format(String className) { this.className = className; latestFormat = this; supertypes = new HashSet<String>(); } /** * Special handling for JE 3.0.12 beta formats. */ void migrateFromBeta(Map<String,Format> formatMap) { if (latestFormat == null) { latestFormat = this; } } final boolean isNew() { return id == 0; } final Catalog getCatalog() { return catalog; } /** * Returns the format ID. */ final int getId() { return id; } /** * Called by the Catalog to set the format ID when a new format is added to * the format list, before calling initializeIfNeeded(). */ final void setId(int id) { this.id = id; } /** * Returns the class that this format represents. This method will return * null in rawAccess mode, or for an unevolved format. */ final Class getType() { return type; } /** * Called to get the type when it is known to exist for an uninitialized * format. */ final Class getExistingType() { if (type == null) { try { type = SimpleCatalog.classForName(className); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } } return type; } /** * Returns the object for reading objects of the latest format. For the * latest version format, 'this' is returned. For prior version formats, a * reader that converts this version to the latest version is returned. */ final Reader getReader() { /* * For unit testing, record whether any un-evolved formats are * encountered. */ if (this != reader) { PersistCatalog.unevolvedFormatsEncountered = true; } return reader; } /** * Changes the reader during format evolution. */ final void setReader(Reader reader) { this.reader = reader; } /** * Returns the format of the superclass. */ final Format getSuperFormat() { return superFormat; } /** * Called to set the format of the superclass during initialize(). */ final void setSuperFormat(Format superFormat) { this.superFormat = superFormat; } /** * Returns the format that is proxied by this format. If non-null is * returned, then this format is a PersistentProxy. */ final Format getProxiedFormat() { return proxiedFormat; } /** * Called by ProxiedFormat to set the proxied format. */ final void setProxiedFormat(Format proxiedFormat) { this.proxiedFormat = proxiedFormat; } /** * If this is the latest/evolved format, returns this; otherwise, returns * the current version of this format. Note that this WILL return a * format for a deleted class if the latest format happens to be deleted. */ final Format getLatestVersion() { return latestFormat; } /** * Returns the previous version of this format in the linked list of * versions, or null if this is the only version. */ public final Format getPreviousVersion() { return previousFormat; } /** * Called by Evolver to set the latest format when this old format is * evolved. */ final void setLatestVersion(Format newFormat) { /* * If this old format is the former latest version, link it to the new * latest version. This creates a singly linked list of versions * starting with the latest. */ if (latestFormat == this) { newFormat.previousFormat = this; } latestFormat = newFormat; } /** * Returns whether the class for this format was deleted. */ final boolean isDeleted() { return deleted; } /** * Called by the Evolver when applying a Deleter mutation. */ final void setDeleted(boolean deleted) { this.deleted = deleted; } /** * Called by the Evolver for a format that is never referenced. */ final void setUnused(boolean unused) { this.unused = unused; } /** * Called by the Evolver with true when an entity format or any of its * nested format were changed. Called by Store.evolve when an entity has * been fully converted. Overridden by ComplexFormat. */ void setEvolveNeeded(boolean needed) { throw new UnsupportedOperationException(); } /** * Overridden by ComplexFormat. */ boolean getEvolveNeeded() { throw new UnsupportedOperationException(); } final boolean isInitialized() { return initialized; } /** * Called by the Catalog to initialize a format, and may also be called * during initialize() for a related format to ensure that the related * format is initialized. This latter case is allowed to support * bidirectional dependencies. This method will do nothing if the format * is already intialized. */ final void initializeIfNeeded(Catalog catalog) { if (!initialized) { initialized = true; this.catalog = catalog; /* Initialize objects serialized by an older Format class. */ if (latestFormat == null) { latestFormat = this; } if (reader == null) { reader = this; } /* * The class is only guaranteed to be available in live (not raw) * mode, for the current version of the format. */ if (type == null && isCurrentVersion() && (isSimple() || !catalog.isRawAccess())) { getExistingType(); } /* Perform subclass-specific initialization. */ initialize (catalog, catalog.getInitVersion(this, false /*forReader*/)); reader.initializeReader (catalog, catalog.getInitVersion(this, true /*forReader*/), this); } } /** * Called to initialize a separate Reader implementation. This method is * called when no separate Reader exists, and does nothing. */ public void initializeReader(Catalog catalog, int initVersion, Format oldFormat) { } /** * Adds all interfaces and superclasses to the supertypes set. */ private void addSupertypes() { addInterfaces(type); Class stype = type.getSuperclass(); while (stype != null && stype != Object.class) { supertypes.add(stype.getName()); addInterfaces(stype); stype = stype.getSuperclass(); } } /** * Recursively adds interfaces to the supertypes set. */ private void addInterfaces(Class cls) { Class[] interfaces = cls.getInterfaces(); for (Class iface : interfaces) { if (iface != Enhanced.class) { supertypes.add(iface.getName()); addInterfaces(iface); } } } /** * Certain formats (ProxiedFormat for example) prohibit nested fields that * reference the parent object. [#15815] */ boolean areNestedRefsProhibited() { return false; } /* -- Start of RawType interface methods. -- */ public String getClassName() { return className; } public int getVersion() { ClassMetadata meta = getClassMetadata(); if (meta != null) { return meta.getVersion(); } else { return 0; } } public Format getSuperType() { return superFormat; } /* -- RawType methods that are overridden as needed in subclasses. -- */ public boolean isSimple() { return false; } public boolean isPrimitive() { return false; } public boolean isEnum() { return false; } public List<String> getEnumConstants() { return null; } public boolean isArray() { return false; } public int getDimensions() { return 0; } public Format getComponentType() { return null; } public Map<String,RawField> getFields() { return null; } /* -- End of RawType methods. -- */ /* -- Methods that may optionally be overridden by subclasses. -- */ /** * Called by EntityOutput in rawAccess mode to determine whether an object * type is allowed to be assigned to a given field type. */ boolean isAssignableTo(Format format) { if (proxiedFormat != null) { return proxiedFormat.isAssignableTo(format); } else { return format == this || format.id == ID_OBJECT || supertypes.contains(format.className); } } /** * For primitive types only, returns their associated wrapper type. */ Format getWrapperFormat() { return null; } /** * Returns whether this format class is an entity class. */ boolean isEntity() { return false; } /** * Returns whether this class is present in the EntityModel. Returns false * for a simple type, array type, or enum type. */ boolean isModelClass() { return false; } /** * Returns the original model class metadata used to create this class, or * null if this is not a model class. */ ClassMetadata getClassMetadata() { return null; } /** * Returns the original model entity metadata used to create this class, or * null if this is not an entity class. */ EntityMetadata getEntityMetadata() { return null; } /** * For an entity class or subclass, returns the base entity class; returns * null in other cases. */ Format getEntityFormat() { return null; } /** * Called for an existing format that may not equal the current format for * the same class. * * <p>If this method returns true, then it must have determined that the * old and new formats are equal, and it must have called either * Evolver.useOldFormat or useEvolvedFormat. If this method returns false, * then it must have determined that the old format could not be evolved to * the new format, and it must have called Evolver.addInvalidMutation, * addMissingMutation or addEvolveError.</p> */ abstract boolean evolve(Format newFormat, Evolver evolver); /** * Called when a Converter handles evolution of a class, but we may still * need to evolve the metadata. */ boolean evolveMetadata(Format newFormat, Converter converter, Evolver evolver) { return true; } /** * Returns whether this format is the current format for its class. If * false is returned, this format is setup to evolve to the current format. */ final boolean isCurrentVersion() { return latestFormat == this && !deleted; } /** * Returns whether this format has the same class as the given format, * irrespective of version changes and renaming. */ final boolean isSameClass(Format other) { return latestFormat == other.latestFormat; } /* -- Abstract methods that must be implemented by subclasses. -- */ /** * Initializes an uninitialized format, initializing its related formats * (superclass formats and array component formats) first. */ abstract void initialize(Catalog catalog, int initVersion); /** * Calls catalog.createFormat for formats that this format depends on, or * that should also be persistent. */ abstract void collectRelatedFormats(Catalog catalog, Map<String,Format> newFormats); /* * The remaining methods are used to read objects from data bytes via * EntityInput, and to write objects as data bytes via EntityOutput. * Ultimately these methods call methods in the Accessor interface to * get/set fields in the object. Most methods have a rawAccess parameter * that determines whether the object is a raw object or a real persistent * object. * * The first group of methods are abstract and must be implemented by * format classes. The second group have default implementations that * throw UnsupportedOperationException and may optionally be overridden. */ /** * Creates an array of the format's class of the given length, as if * Array.newInstance(getType(), len) were called. Formats implement this * method for specific classes, or call the accessor, to avoid the * reflection overhead of Array.newInstance. */ abstract Object newArray(int len); /** * Creates a new instance of the target class using its default * constructor. Normally this creates an empty object, and readObject() is * called next to fill in the contents. This is done in two steps to allow * the instance to be registered by EntityInput before reading the * contents. This allows the fields in an object or a nested object to * refer to the parent object in a graph. * * Alternatively, this method may read all or the first portion of the * data, rather than that being done by readObject(). This is required for * simple types and enums, where the object cannot be created without * reading the data. In these cases, there is no possibility that the * parent object will be referenced by the child object in the graph. It * should not be done in other cases, or the graph references may not be * maintained faithfully. * * Is public only in order to implement the Reader interface. Note that * this method should only be called directly in raw conversion mode or * during conversion of an old format. Normally it should be called via * the getReader method and the Reader interface. */ public abstract Object newInstance(EntityInput input, boolean rawAccess); /** * Called after newInstance() to read the rest of the data bytes and fill * in the object contents. If the object was read completely by * newInstance(), this method does nothing. * * Is public only in order to implement the Reader interface. Note that * this method should only be called directly in raw conversion mode or * during conversion of an old format. Normally it should be called via * the getReader method and the Reader interface. */ public abstract Object readObject(Object o, EntityInput input, boolean rawAccess); /** * Writes a given instance of the target class to the output data bytes. * This is the complement of the newInstance()/readObject() pair. */ abstract void writeObject(Object o, EntityOutput output, boolean rawAccess); /** * Skips over the object's contents, as if readObject() were called, but * without returning an object. Used for extracting secondary key bytes * without having to instantiate the object. For reference types, the * format ID is read just before calling this method, so this method is * responsible for skipping everything following the format ID. */ abstract void skipContents(RecordInput input); /* -- More methods that may optionally be overridden by subclasses. -- */ /** * When extracting a secondary key, called to skip over all fields up to * the given secondary key field. Returns the format of the key field * found, or null if the field is not present (nullified) in the object. */ Format skipToSecKey(RecordInput input, String keyName) { throw new UnsupportedOperationException(toString()); } /** * Called after skipToSecKey() to copy the data bytes of a singular * (XXX_TO_ONE) key field. */ void copySecKey(RecordInput input, RecordOutput output) { throw new UnsupportedOperationException(toString()); } /** * Called after skipToSecKey() to copy the data bytes of an array or * collection (XXX_TO_MANY) key field. */ void copySecMultiKey(RecordInput input, Format keyFormat, Set results) { throw new UnsupportedOperationException(toString()); } /** * Nullifies the given key field in the given RawObject -- rawAccess mode * is implied. */ boolean nullifySecKey(Catalog catalog, Object entity, String keyName, Object keyElement) { throw new UnsupportedOperationException(toString()); } /** * Returns whether the entity's primary key field is null or zero, as * defined for primary keys that are assigned from a sequence. */ boolean isPriKeyNullOrZero(Object o, boolean rawAccess) { throw new UnsupportedOperationException(toString()); } /** * Gets the primary key field from the given object and writes it to the * given output data bytes. This is a separate operation because the * primary key data bytes are stored separately from the rest of the * record. */ void writePriKey(Object o, EntityOutput output, boolean rawAccess) { throw new UnsupportedOperationException(toString()); } /** * Reads the primary key from the given input bytes and sets the primary * key field in the given object. This is complement of writePriKey(). * * Is public only in order to implement the Reader interface. Note that * this method should only be called directly in raw conversion mode or * during conversion of an old format. Normally it should be called via * the getReader method and the Reader interface. */ public void readPriKey(Object o, EntityInput input, boolean rawAccess) { throw new UnsupportedOperationException(toString()); } /** * Validates and returns the simple integer key format for a sequence key * associated with this format. * * For a composite key type, the format of the one and only field is * returned. For a simple integer type, this format is returned. * Otherwise (the default implementation), an IllegalArgumentException is * thrown. */ Format getSequenceKeyFormat() { throw new IllegalArgumentException ("Type not allowed for sequence: " + getClassName()); } /** * Converts a RawObject to a current class object and adds the converted * pair to the converted map. */ Object convertRawObject(Catalog catalog, boolean rawAccess, RawObject rawObject, IdentityHashMap converted) { throw new UnsupportedOperationException(toString()); } @Override public String toString() { return "[RawType class: " + getClassName() + " version: " + getVersion() + " internal: " + getClass().getName() + ((reader != null) ? (" reader: " + reader.getClass().getName()) : "") + ']'; } }
mit
revida/sitecore-assurance
Revida.Sitecore.Assurance.Configuration/InvalidConfigurationException.cs
653
using System; using System.Runtime.Serialization; namespace Revida.Sitecore.Assurance.Configuration { public class InvalidConfigurationException : Exception { public InvalidConfigurationException() { } public InvalidConfigurationException(string message) : base(message) { } public InvalidConfigurationException(string message, Exception innerException) : base(message, innerException) { } protected InvalidConfigurationException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
mit
Kaishiyoku/Crystal-RSS
resources/views/errors/404.blade.php
311
@extends('errors::illustrated-layout') @section('code', '404') @section('title', __('errors.404.title')) @section('image') <div style="background-image: url('/svg/404.svg');" class="absolute pin bg-cover bg-no-repeat md:bg-left lg:bg-center"> </div> @endsection @section('message', __('errors.404.message'))
mit
mainconceptx/DAS
src/qt/overviewpage.cpp
28663
// Copyright (c) 2011-2015 The Bitcoin Core developers // Copyright (c) 2014-2016 The Das Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "overviewpage.h" #include "ui_overviewpage.h" #include "bitcoinunits.h" #include "clientmodel.h" #include "darksend.h" #include "darksendconfig.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include "platformstyle.h" #include "transactionfilterproxy.h" #include "transactiontablemodel.h" #include "walletmodel.h" #include "init.h" #include "masternode-sync.h" #include <QAbstractItemDelegate> #include <QPainter> #include <QSettings> #include <QTimer> #define ICON_OFFSET 16 #define DECORATION_SIZE 54 #define NUM_ITEMS 5 #define NUM_ITEMS_ADV 7 class TxViewDelegate : public QAbstractItemDelegate { Q_OBJECT public: TxViewDelegate(const PlatformStyle *platformStyle): QAbstractItemDelegate(), unit(BitcoinUnits::DAS), platformStyle(platformStyle) { } inline void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const { painter->save(); QIcon icon = qvariant_cast<QIcon>(index.data(TransactionTableModel::RawDecorationRole)); QRect mainRect = option.rect; mainRect.moveLeft(ICON_OFFSET); QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE)); int xspace = DECORATION_SIZE + 8; int ypad = 6; int halfheight = (mainRect.height() - 2*ypad)/2; QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace - ICON_OFFSET, halfheight); QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight); icon = platformStyle->SingleColorIcon(icon); icon.paint(painter, decorationRect); QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime(); QString address = index.data(Qt::DisplayRole).toString(); qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong(); bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool(); QVariant value = index.data(Qt::ForegroundRole); QColor foreground = option.palette.color(QPalette::Text); if(value.canConvert<QBrush>()) { QBrush brush = qvariant_cast<QBrush>(value); foreground = brush.color(); } painter->setPen(foreground); QRect boundingRect; painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address, &boundingRect); if (index.data(TransactionTableModel::WatchonlyRole).toBool()) { QIcon iconWatchonly = qvariant_cast<QIcon>(index.data(TransactionTableModel::WatchonlyDecorationRole)); QRect watchonlyRect(boundingRect.right() + 5, mainRect.top()+ypad+halfheight, 16, halfheight); iconWatchonly.paint(painter, watchonlyRect); } if(amount < 0) { foreground = COLOR_NEGATIVE; } else if(!confirmed) { foreground = COLOR_UNCONFIRMED; } else { foreground = option.palette.color(QPalette::Text); } painter->setPen(foreground); QString amountText = BitcoinUnits::floorWithUnit(unit, amount, true, BitcoinUnits::separatorAlways); if(!confirmed) { amountText = QString("[") + amountText + QString("]"); } painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText); painter->setPen(option.palette.color(QPalette::Text)); painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date)); painter->restore(); } inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { return QSize(DECORATION_SIZE, DECORATION_SIZE); } int unit; const PlatformStyle *platformStyle; }; #include "overviewpage.moc" OverviewPage::OverviewPage(const PlatformStyle *platformStyle, QWidget *parent) : QWidget(parent), ui(new Ui::OverviewPage), clientModel(0), walletModel(0), currentBalance(-1), currentUnconfirmedBalance(-1), currentImmatureBalance(-1), currentWatchOnlyBalance(-1), currentWatchUnconfBalance(-1), currentWatchImmatureBalance(-1), txdelegate(new TxViewDelegate(platformStyle)), filter(0) { ui->setupUi(this); QString theme = GUIUtil::getThemeName(); // Recent transactions ui->listTransactions->setItemDelegate(txdelegate); ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE)); // Note: minimum height of listTransactions will be set later in updateAdvancedPSUI() to reflect actual settings ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false); connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex))); // init "out of sync" warning labels ui->labelWalletStatus->setText("(" + tr("out of sync") + ")"); ui->labelPrivateSendSyncStatus->setText("(" + tr("out of sync") + ")"); ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")"); // hide PS frame (helps to preserve saved size) // we'll setup and make it visible in updateAdvancedPSUI() later if we are not in litemode ui->framePrivateSend->setVisible(false); // start with displaying the "out of sync" warnings showOutOfSyncWarning(true); // that's it for litemode if(fLiteMode) return; // Disable any PS UI for masternode or when autobackup is disabled or failed for whatever reason if(fMasterNode || nWalletBackups <= 0){ DisablePrivateSendCompletely(); if (nWalletBackups <= 0) { ui->labelPrivateSendEnabled->setToolTip(tr("Automatic backups are disabled, no mixing available!")); } } else { if(!fEnablePrivateSend){ ui->togglePrivateSend->setText(tr("Start Mixing")); } else { ui->togglePrivateSend->setText(tr("Stop Mixing")); } // Disable darkSendPool builtin support for automatic backups while we are in GUI, // we'll handle automatic backups and user warnings in privateSendStatus() darkSendPool.fCreateAutoBackups = false; timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(privateSendStatus())); timer->start(1000); } } void OverviewPage::handleTransactionClicked(const QModelIndex &index) { if(filter) Q_EMIT transactionClicked(filter->mapToSource(index)); } OverviewPage::~OverviewPage() { if(!fLiteMode && !fMasterNode) disconnect(timer, SIGNAL(timeout()), this, SLOT(privateSendStatus())); delete ui; } void OverviewPage::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& anonymizedBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance) { currentBalance = balance; currentUnconfirmedBalance = unconfirmedBalance; currentImmatureBalance = immatureBalance; currentAnonymizedBalance = anonymizedBalance; currentWatchOnlyBalance = watchOnlyBalance; currentWatchUnconfBalance = watchUnconfBalance; currentWatchImmatureBalance = watchImmatureBalance; ui->labelBalance->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, balance, false, BitcoinUnits::separatorAlways)); ui->labelUnconfirmed->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, unconfirmedBalance, false, BitcoinUnits::separatorAlways)); ui->labelImmature->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, immatureBalance, false, BitcoinUnits::separatorAlways)); ui->labelAnonymized->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, anonymizedBalance, false, BitcoinUnits::separatorAlways)); ui->labelTotal->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, balance + unconfirmedBalance + immatureBalance, false, BitcoinUnits::separatorAlways)); ui->labelWatchAvailable->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchOnlyBalance, false, BitcoinUnits::separatorAlways)); ui->labelWatchPending->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchUnconfBalance, false, BitcoinUnits::separatorAlways)); ui->labelWatchImmature->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchImmatureBalance, false, BitcoinUnits::separatorAlways)); ui->labelWatchTotal->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchOnlyBalance + watchUnconfBalance + watchImmatureBalance, false, BitcoinUnits::separatorAlways)); // only show immature (newly mined) balance if it's non-zero, so as not to complicate things // for the non-mining users bool showImmature = immatureBalance != 0; bool showWatchOnlyImmature = watchImmatureBalance != 0; // for symmetry reasons also show immature label when the watch-only one is shown ui->labelImmature->setVisible(showImmature || showWatchOnlyImmature); ui->labelImmatureText->setVisible(showImmature || showWatchOnlyImmature); ui->labelWatchImmature->setVisible(showWatchOnlyImmature); // show watch-only immature balance updatePrivateSendProgress(); static int cachedTxLocks = 0; if(cachedTxLocks != nCompleteTXLocks){ cachedTxLocks = nCompleteTXLocks; ui->listTransactions->update(); } } // show/hide watch-only labels void OverviewPage::updateWatchOnlyLabels(bool showWatchOnly) { ui->labelSpendable->setVisible(showWatchOnly); // show spendable label (only when watch-only is active) ui->labelWatchonly->setVisible(showWatchOnly); // show watch-only label ui->lineWatchBalance->setVisible(showWatchOnly); // show watch-only balance separator line ui->labelWatchAvailable->setVisible(showWatchOnly); // show watch-only available balance ui->labelWatchPending->setVisible(showWatchOnly); // show watch-only pending balance ui->labelWatchTotal->setVisible(showWatchOnly); // show watch-only total balance if (!showWatchOnly){ ui->labelWatchImmature->hide(); } else{ ui->labelBalance->setIndent(20); ui->labelUnconfirmed->setIndent(20); ui->labelImmature->setIndent(20); ui->labelTotal->setIndent(20); } } void OverviewPage::setClientModel(ClientModel *model) { this->clientModel = model; if(model) { // Show warning if this is a prerelease version connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString))); updateAlerts(model->getStatusBarWarnings()); } } void OverviewPage::setWalletModel(WalletModel *model) { this->walletModel = model; if(model && model->getOptionsModel()) { // Keep up to date with wallet setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getAnonymizedBalance(), model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance()); connect(model, SIGNAL(balanceChanged(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)), this, SLOT(setBalance(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount,CAmount))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); connect(model->getOptionsModel(), SIGNAL(privateSendRoundsChanged()), this, SLOT(updatePrivateSendProgress())); connect(model->getOptionsModel(), SIGNAL(anonymizeDasAmountChanged()), this, SLOT(updatePrivateSendProgress())); connect(model->getOptionsModel(), SIGNAL(advancedPSUIChanged(bool)), this, SLOT(updateAdvancedPSUI(bool))); // explicitly update PS frame and transaction list to reflect actual settings updateAdvancedPSUI(model->getOptionsModel()->getShowAdvancedPSUI()); connect(ui->privateSendAuto, SIGNAL(clicked()), this, SLOT(privateSendAuto())); connect(ui->privateSendReset, SIGNAL(clicked()), this, SLOT(privateSendReset())); connect(ui->togglePrivateSend, SIGNAL(clicked()), this, SLOT(togglePrivateSend())); updateWatchOnlyLabels(model->haveWatchOnly()); connect(model, SIGNAL(notifyWatchonlyChanged(bool)), this, SLOT(updateWatchOnlyLabels(bool))); } // update the display unit, to not use the default ("DAS") updateDisplayUnit(); } void OverviewPage::updateDisplayUnit() { if(walletModel && walletModel->getOptionsModel()) { nDisplayUnit = walletModel->getOptionsModel()->getDisplayUnit(); if(currentBalance != -1) setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance, currentAnonymizedBalance, currentWatchOnlyBalance, currentWatchUnconfBalance, currentWatchImmatureBalance); // Update txdelegate->unit with the current unit txdelegate->unit = nDisplayUnit; ui->listTransactions->update(); } } void OverviewPage::updateAlerts(const QString &warnings) { this->ui->labelAlerts->setVisible(!warnings.isEmpty()); this->ui->labelAlerts->setText(warnings); } void OverviewPage::showOutOfSyncWarning(bool fShow) { ui->labelWalletStatus->setVisible(fShow); ui->labelPrivateSendSyncStatus->setVisible(fShow); ui->labelTransactionsStatus->setVisible(fShow); } void OverviewPage::updatePrivateSendProgress() { if(!masternodeSync.IsBlockchainSynced() || ShutdownRequested()) return; if(!pwalletMain) return; QString strAmountAndRounds; QString strAnonymizeDasAmount = BitcoinUnits::formatHtmlWithUnit(nDisplayUnit, nAnonymizeDasAmount * COIN, false, BitcoinUnits::separatorAlways); if(currentBalance == 0) { ui->privateSendProgress->setValue(0); ui->privateSendProgress->setToolTip(tr("No inputs detected")); // when balance is zero just show info from settings strAnonymizeDasAmount = strAnonymizeDasAmount.remove(strAnonymizeDasAmount.indexOf("."), BitcoinUnits::decimals(nDisplayUnit) + 1); strAmountAndRounds = strAnonymizeDasAmount + " / " + tr("%n Rounds", "", nPrivateSendRounds); ui->labelAmountRounds->setToolTip(tr("No inputs detected")); ui->labelAmountRounds->setText(strAmountAndRounds); return; } CAmount nDenominatedConfirmedBalance; CAmount nDenominatedUnconfirmedBalance; CAmount nAnonymizableBalance; CAmount nNormalizedAnonymizedBalance; double nAverageAnonymizedRounds; { nDenominatedConfirmedBalance = pwalletMain->GetDenominatedBalance(); nDenominatedUnconfirmedBalance = pwalletMain->GetDenominatedBalance(true); nAnonymizableBalance = pwalletMain->GetAnonymizableBalance(); nNormalizedAnonymizedBalance = pwalletMain->GetNormalizedAnonymizedBalance(); nAverageAnonymizedRounds = pwalletMain->GetAverageAnonymizedRounds(); } CAmount nMaxToAnonymize = nAnonymizableBalance + currentAnonymizedBalance + nDenominatedUnconfirmedBalance; // If it's more than the anon threshold, limit to that. if(nMaxToAnonymize > nAnonymizeDasAmount*COIN) nMaxToAnonymize = nAnonymizeDasAmount*COIN; if(nMaxToAnonymize == 0) return; if(nMaxToAnonymize >= nAnonymizeDasAmount * COIN) { ui->labelAmountRounds->setToolTip(tr("Found enough compatible inputs to anonymize %1") .arg(strAnonymizeDasAmount)); strAnonymizeDasAmount = strAnonymizeDasAmount.remove(strAnonymizeDasAmount.indexOf("."), BitcoinUnits::decimals(nDisplayUnit) + 1); strAmountAndRounds = strAnonymizeDasAmount + " / " + tr("%n Rounds", "", nPrivateSendRounds); } else { QString strMaxToAnonymize = BitcoinUnits::formatHtmlWithUnit(nDisplayUnit, nMaxToAnonymize, false, BitcoinUnits::separatorAlways); ui->labelAmountRounds->setToolTip(tr("Not enough compatible inputs to anonymize <span style='color:red;'>%1</span>,<br>" "will anonymize <span style='color:red;'>%2</span> instead") .arg(strAnonymizeDasAmount) .arg(strMaxToAnonymize)); strMaxToAnonymize = strMaxToAnonymize.remove(strMaxToAnonymize.indexOf("."), BitcoinUnits::decimals(nDisplayUnit) + 1); strAmountAndRounds = "<span style='color:red;'>" + QString(BitcoinUnits::factor(nDisplayUnit) == 1 ? "" : "~") + strMaxToAnonymize + " / " + tr("%n Rounds", "", nPrivateSendRounds) + "</span>"; } ui->labelAmountRounds->setText(strAmountAndRounds); // calculate parts of the progress, each of them shouldn't be higher than 1 // progress of denominating float denomPart = 0; // mixing progress of denominated balance float anonNormPart = 0; // completeness of full amount anonimization float anonFullPart = 0; CAmount denominatedBalance = nDenominatedConfirmedBalance + nDenominatedUnconfirmedBalance; denomPart = (float)denominatedBalance / nMaxToAnonymize; denomPart = denomPart > 1 ? 1 : denomPart; denomPart *= 100; anonNormPart = (float)nNormalizedAnonymizedBalance / nMaxToAnonymize; anonNormPart = anonNormPart > 1 ? 1 : anonNormPart; anonNormPart *= 100; anonFullPart = (float)currentAnonymizedBalance / nMaxToAnonymize; anonFullPart = anonFullPart > 1 ? 1 : anonFullPart; anonFullPart *= 100; // apply some weights to them ... float denomWeight = 1; float anonNormWeight = nPrivateSendRounds; float anonFullWeight = 2; float fullWeight = denomWeight + anonNormWeight + anonFullWeight; // ... and calculate the whole progress float denomPartCalc = ceilf((denomPart * denomWeight / fullWeight) * 100) / 100; float anonNormPartCalc = ceilf((anonNormPart * anonNormWeight / fullWeight) * 100) / 100; float anonFullPartCalc = ceilf((anonFullPart * anonFullWeight / fullWeight) * 100) / 100; float progress = denomPartCalc + anonNormPartCalc + anonFullPartCalc; if(progress >= 100) progress = 100; ui->privateSendProgress->setValue(progress); QString strToolPip = ("<b>" + tr("Overall progress") + ": %1%</b><br/>" + tr("Denominated") + ": %2%<br/>" + tr("Mixed") + ": %3%<br/>" + tr("Anonymized") + ": %4%<br/>" + tr("Denominated inputs have %5 of %n rounds on average", "", nPrivateSendRounds)) .arg(progress).arg(denomPart).arg(anonNormPart).arg(anonFullPart) .arg(nAverageAnonymizedRounds); ui->privateSendProgress->setToolTip(strToolPip); } void OverviewPage::updateAdvancedPSUI(bool fShowAdvancedPSUI) { this->fShowAdvancedPSUI = fShowAdvancedPSUI; int nNumItems = (fLiteMode || !fShowAdvancedPSUI) ? NUM_ITEMS : NUM_ITEMS_ADV; SetupTransactionList(nNumItems); if (fLiteMode) return; ui->framePrivateSend->setVisible(true); ui->labelCompletitionText->setVisible(fShowAdvancedPSUI); ui->privateSendProgress->setVisible(fShowAdvancedPSUI); ui->labelSubmittedDenomText->setVisible(fShowAdvancedPSUI); ui->labelSubmittedDenom->setVisible(fShowAdvancedPSUI); ui->privateSendAuto->setVisible(fShowAdvancedPSUI); ui->privateSendReset->setVisible(fShowAdvancedPSUI); ui->labelPrivateSendLastMessage->setVisible(fShowAdvancedPSUI); } void OverviewPage::privateSendStatus() { if(!masternodeSync.IsBlockchainSynced() || ShutdownRequested()) return; static int64_t nLastDSProgressBlockTime = 0; int nBestHeight = clientModel->getNumBlocks(); // We are processing more then 1 block per second, we'll just leave if(((nBestHeight - darkSendPool.cachedNumBlocks) / (GetTimeMillis() - nLastDSProgressBlockTime + 1) > 1)) return; nLastDSProgressBlockTime = GetTimeMillis(); QString strKeysLeftText(tr("keys left: %1").arg(pwalletMain->nKeysLeftSinceAutoBackup)); if(pwalletMain->nKeysLeftSinceAutoBackup < PS_KEYS_THRESHOLD_WARNING) { strKeysLeftText = "<span style='color:red;'>" + strKeysLeftText + "</span>"; } ui->labelPrivateSendEnabled->setToolTip(strKeysLeftText); // Warn user that wallet is running out of keys if (nWalletBackups > 0 && pwalletMain->nKeysLeftSinceAutoBackup < PS_KEYS_THRESHOLD_WARNING) { QString strWarn = tr("Very low number of keys left since last automatic backup!") + "<br><br>" + tr("We are about to create a new automatic backup for you, however " "<span style='color:red;'> you should always make sure you have backups " "saved in some safe place</span>!"); ui->labelPrivateSendEnabled->setToolTip(strWarn); LogPrintf("OverviewPage::privateSendStatus - Very low number of keys left since last automatic backup, warning user and trying to create new backup...\n"); QMessageBox::warning(this, tr("PrivateSend"), strWarn, QMessageBox::Ok, QMessageBox::Ok); std::string warningString; std::string errorString; if(!AutoBackupWallet(pwalletMain, "", warningString, errorString)) { if (!warningString.empty()) { // It's still more or less safe to continue but warn user anyway LogPrintf("OverviewPage::privateSendStatus - WARNING! Something went wrong on automatic backup: %s\n", warningString); QMessageBox::warning(this, tr("PrivateSend"), tr("WARNING! Something went wrong on automatic backup") + ":<br><br>" + warningString.c_str(), QMessageBox::Ok, QMessageBox::Ok); } if (!errorString.empty()) { // Things are really broken, warn user and stop mixing immediately LogPrintf("OverviewPage::privateSendStatus - ERROR! Failed to create automatic backup: %s\n", errorString); QMessageBox::warning(this, tr("PrivateSend"), tr("ERROR! Failed to create automatic backup") + ":<br><br>" + errorString.c_str() + "<br>" + tr("Mixing is disabled, please close your wallet and fix the issue!"), QMessageBox::Ok, QMessageBox::Ok); } } } QString strEnabled = fEnablePrivateSend ? tr("Enabled") : tr("Disabled"); // Show how many keys left in advanced PS UI mode only if(fShowAdvancedPSUI) strEnabled += ", " + strKeysLeftText; ui->labelPrivateSendEnabled->setText(strEnabled); if(nWalletBackups == -1) { // Automatic backup failed, nothing else we can do until user fixes the issue manually DisablePrivateSendCompletely(); QString strError = tr("ERROR! Failed to create automatic backup") + ", " + tr("see debug.log for details.") + "<br><br>" + tr("Mixing is disabled, please close your wallet and fix the issue!"); ui->labelPrivateSendEnabled->setToolTip(strError); return; } else if(nWalletBackups == -2) { // We were able to create automatic backup but keypool was not replenished because wallet is locked. QString strWarning = tr("WARNING! Failed to replenish keypool, please unlock your wallet to do so."); ui->labelPrivateSendEnabled->setToolTip(strWarning); } if(!fEnablePrivateSend) { if(nBestHeight != darkSendPool.cachedNumBlocks) { darkSendPool.cachedNumBlocks = nBestHeight; updatePrivateSendProgress(); } ui->labelPrivateSendLastMessage->setText(""); ui->togglePrivateSend->setText(tr("Start Mixing")); return; } // check darksend status and unlock if needed if(nBestHeight != darkSendPool.cachedNumBlocks) { // Balance and number of transactions might have changed darkSendPool.cachedNumBlocks = nBestHeight; updatePrivateSendProgress(); } QString strStatus = QString(darkSendPool.GetStatus().c_str()); QString s = tr("Last PrivateSend message:\n") + strStatus; if(s != ui->labelPrivateSendLastMessage->text()) LogPrintf("OverviewPage::privateSendStatus - Last PrivateSend message: %s\n", strStatus.toStdString()); ui->labelPrivateSendLastMessage->setText(s); if(darkSendPool.sessionDenom == 0){ ui->labelSubmittedDenom->setText(tr("N/A")); } else { std::string out; darkSendPool.GetDenominationsToString(darkSendPool.sessionDenom, out); QString s2(out.c_str()); ui->labelSubmittedDenom->setText(s2); } } void OverviewPage::privateSendAuto(){ darkSendPool.DoAutomaticDenominating(); } void OverviewPage::privateSendReset(){ darkSendPool.Reset(); QMessageBox::warning(this, tr("PrivateSend"), tr("PrivateSend was successfully reset."), QMessageBox::Ok, QMessageBox::Ok); } void OverviewPage::togglePrivateSend(){ QSettings settings; // Popup some information on first mixing QString hasMixed = settings.value("hasMixed").toString(); if(hasMixed.isEmpty()){ QMessageBox::information(this, tr("PrivateSend"), tr("If you don't want to see internal PrivateSend fees/transactions select \"Most Common\" as Type on the \"Transactions\" tab."), QMessageBox::Ok, QMessageBox::Ok); settings.setValue("hasMixed", "hasMixed"); } if(!fEnablePrivateSend){ int64_t balance = currentBalance; float minAmount = 1.49 * COIN; if(balance < minAmount){ QString strMinAmount(BitcoinUnits::formatWithUnit(nDisplayUnit, minAmount)); QMessageBox::warning(this, tr("PrivateSend"), tr("PrivateSend requires at least %1 to use.").arg(strMinAmount), QMessageBox::Ok, QMessageBox::Ok); return; } // if wallet is locked, ask for a passphrase if (walletModel->getEncryptionStatus() == WalletModel::Locked) { WalletModel::UnlockContext ctx(walletModel->requestUnlock(false)); if(!ctx.isValid()) { //unlock was cancelled darkSendPool.cachedNumBlocks = std::numeric_limits<int>::max(); QMessageBox::warning(this, tr("PrivateSend"), tr("Wallet is locked and user declined to unlock. Disabling PrivateSend."), QMessageBox::Ok, QMessageBox::Ok); LogPrint("privatesend", "OverviewPage::togglePrivateSend - Wallet is locked and user declined to unlock. Disabling PrivateSend.\n"); return; } } } fEnablePrivateSend = !fEnablePrivateSend; darkSendPool.cachedNumBlocks = std::numeric_limits<int>::max(); if(!fEnablePrivateSend){ ui->togglePrivateSend->setText(tr("Start Mixing")); darkSendPool.UnlockCoins(); } else { ui->togglePrivateSend->setText(tr("Stop Mixing")); /* show darksend configuration if client has defaults set */ if(nAnonymizeDasAmount == 0){ DarksendConfig dlg(this); dlg.setModel(walletModel); dlg.exec(); } } } void OverviewPage::SetupTransactionList(int nNumItems) { ui->listTransactions->setMinimumHeight(nNumItems * (DECORATION_SIZE + 2)); if(walletModel && walletModel->getOptionsModel()) { // Set up transaction list filter = new TransactionFilterProxy(); filter->setSourceModel(walletModel->getTransactionTableModel()); filter->setLimit(nNumItems); filter->setDynamicSortFilter(true); filter->setSortRole(Qt::EditRole); filter->setShowInactive(false); filter->sort(TransactionTableModel::Status, Qt::DescendingOrder); ui->listTransactions->setModel(filter); ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress); } } void OverviewPage::DisablePrivateSendCompletely() { ui->togglePrivateSend->setText("(" + tr("Disabled") + ")"); ui->privateSendAuto->setText("(" + tr("Disabled") + ")"); ui->privateSendReset->setText("(" + tr("Disabled") + ")"); ui->framePrivateSend->setEnabled(false); if (nWalletBackups <= 0) { ui->labelPrivateSendEnabled->setText("<span style='color:red;'>(" + tr("Disabled") + ")</span>"); } fEnablePrivateSend = false; }
mit
ycabon/presentations
2020-devsummit/arcgis-js-api-road-ahead/js-api/esri/widgets/Legend/nls/el/Legend.js
2515
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.16/esri/copyright.txt for details. //>>built define({widgetLabel:"\u03a5\u03c0\u03cc\u03bc\u03bd\u03b7\u03bc\u03b1",points:"\u03a3\u03b7\u03bc\u03b5\u03af\u03b1",lines:"\u0393\u03c1\u03b1\u03bc\u03bc\u03ad\u03c2",polygons:"\u03a0\u03bf\u03bb\u03cd\u03b3\u03c9\u03bd\u03b1",creatingLegend:"\u0394\u03b7\u03bc\u03b9\u03bf\u03c5\u03c1\u03b3\u03af\u03b1 \u03c5\u03c0\u03bf\u03bc\u03bd\u03ae\u03bc\u03b1\u03c4\u03bf\u03c2",noLegend:"\u03a7\u03c9\u03c1\u03af\u03c2 \u03c5\u03c0\u03cc\u03bc\u03bd\u03b7\u03bc\u03b1",dotValue:"1 \u03ba\u03bf\u03c5\u03ba\u03ba\u03af\u03b4\u03b1 \x3d {value} {unit}", currentObservations:"\u03a4\u03c1\u03ad\u03c7\u03bf\u03c5\u03c3\u03b5\u03c2 \u03c0\u03b1\u03c1\u03b1\u03c4\u03b7\u03c1\u03ae\u03c3\u03b5\u03b9\u03c2",previousObservations:"\u03a0\u03c1\u03bf\u03b7\u03b3\u03bf\u03cd\u03bc\u03b5\u03bd\u03b5\u03c2 \u03c0\u03b1\u03c1\u03b1\u03c4\u03b7\u03c1\u03ae\u03c3\u03b5\u03b9\u03c2",high:"\u03a5\u03c8\u03b7\u03bb\u03cc",low:"\u03a7\u03b1\u03bc\u03b7\u03bb\u03cc",esriMetersPerSecond:"\u03bc./\u03b4\u03b5\u03c5\u03c4.",esriKilometersPerHour:"\u03c7\u03bb\u03bc/\u03ce\u03c1\u03b1", esriKnots:"\u03ba\u03cc\u03bc\u03b2\u03bf\u03b9",esriFeetPerSecond:"\u03c0\u03cc\u03b4./\u03b4\u03b5\u03c5\u03c4.",esriMilesPerHour:"\u03bc\u03af\u03bb./\u03ce\u03c1\u03b1",showNormField:"{field} \u03b4\u03b9\u03b1\u03b9\u03c1\u03bf\u03cd\u03bc\u03b5\u03bd\u03bf \u03bc\u03b5 {normField}",showNormPct:"{field} \u03c9\u03c2 \u03c0\u03bf\u03c3\u03bf\u03c3\u03c4\u03cc \u03c4\u03bf\u03c5 \u03c3\u03c5\u03bd\u03cc\u03bb\u03bf\u03c5",showRatio:"\u039b\u03cc\u03b3\u03bf\u03c2 \u03c4\u03bf\u03c5 {field} \u03c0\u03c1\u03bf\u03c2 {normField}", showRatioPercent:"{field} \u03c9\u03c2 \u03c0\u03bf\u03c3\u03bf\u03c3\u03c4\u03cc \u03c4\u03bf\u03c5 {normField}",showRatioPercentTotal:"{field} \u03c9\u03c2 \u03c0\u03bf\u03c3\u03bf\u03c3\u03c4\u03cc \u03c4\u03bf\u03c5 {field} \u03ba\u03b1\u03b9 \u03c4\u03bf\u03c5 {normField}",band0:"\u03c6\u03b1\u03c3\u03bc\u03b1\u03c4\u03b9\u03ba\u03ae \u03b6\u03ce\u03bd\u03b7_0",band1:"\u03c6\u03b1\u03c3\u03bc\u03b1\u03c4\u03b9\u03ba\u03ae \u03b6\u03ce\u03bd\u03b7_1",band2:"\u03c6\u03b1\u03c3\u03bc\u03b1\u03c4\u03b9\u03ba\u03ae \u03b6\u03ce\u03bd\u03b7_2", red:"\u039a\u03cc\u03ba\u03ba\u03b9\u03bd\u03bf",green:"\u03a0\u03c1\u03ac\u03c3\u03b9\u03bd\u03bf",blue:"\u039c\u03c0\u03bb\u03b5",clusterCountTitle:"\u03c0_Number of features___________________\u03a9"});
mit
patrickneubauer/XMLIntellEdit
xmlintelledit/xmltext/src/main/java/isostdisois_13584_32ed_1techxmlschemaontomlSimplified/STANDARDSIZEType.java
5445
/** */ package isostdisois_13584_32ed_1techxmlschemaontomlSimplified; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.util.Enumerator; /** * <!-- begin-user-doc --> * A representation of the literals of the enumeration '<em><b>STANDARDSIZE Type</b></em>', * and utility methods for working with them. * <!-- end-user-doc --> * @see isostdisois_13584_32ed_1techxmlschemaontomlSimplified.Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage#getSTANDARDSIZEType() * @model * @generated */ public enum STANDARDSIZEType implements Enumerator { /** * The '<em><b>A6 Illustration</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #A6_ILLUSTRATION_VALUE * @generated * @ordered */ A6_ILLUSTRATION(0, "a6Illustration", "a6_illustration"), /** * The '<em><b>A9 Illustration</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #A9_ILLUSTRATION_VALUE * @generated * @ordered */ A9_ILLUSTRATION(1, "a9Illustration", "a9_illustration"); /** * The '<em><b>A6 Illustration</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>A6 Illustration</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #A6_ILLUSTRATION * @model name="a6Illustration" literal="a6_illustration" * @generated * @ordered */ public static final int A6_ILLUSTRATION_VALUE = 0; /** * The '<em><b>A9 Illustration</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>A9 Illustration</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #A9_ILLUSTRATION * @model name="a9Illustration" literal="a9_illustration" * @generated * @ordered */ public static final int A9_ILLUSTRATION_VALUE = 1; /** * An array of all the '<em><b>STANDARDSIZE Type</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static final STANDARDSIZEType[] VALUES_ARRAY = new STANDARDSIZEType[] { A6_ILLUSTRATION, A9_ILLUSTRATION, }; /** * A public read-only list of all the '<em><b>STANDARDSIZE Type</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List<STANDARDSIZEType> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY)); /** * Returns the '<em><b>STANDARDSIZE Type</b></em>' literal with the specified literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param literal the literal. * @return the matching enumerator or <code>null</code>. * @generated */ public static STANDARDSIZEType get(String literal) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { STANDARDSIZEType result = VALUES_ARRAY[i]; if (result.toString().equals(literal)) { return result; } } return null; } /** * Returns the '<em><b>STANDARDSIZE Type</b></em>' literal with the specified name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param name the name. * @return the matching enumerator or <code>null</code>. * @generated */ public static STANDARDSIZEType getByName(String name) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { STANDARDSIZEType result = VALUES_ARRAY[i]; if (result.getName().equals(name)) { return result; } } return null; } /** * Returns the '<em><b>STANDARDSIZE Type</b></em>' literal with the specified integer value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the integer value. * @return the matching enumerator or <code>null</code>. * @generated */ public static STANDARDSIZEType get(int value) { switch (value) { case A6_ILLUSTRATION_VALUE: return A6_ILLUSTRATION; case A9_ILLUSTRATION_VALUE: return A9_ILLUSTRATION; } return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final int value; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String name; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String literal; /** * Only this class can construct instances. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private STANDARDSIZEType(int value, String name, String literal) { this.value = value; this.name = name; this.literal = literal; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getLiteral() { return literal; } /** * Returns the literal value of the enumerator, which is its string representation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { return literal; } } //STANDARDSIZEType
mit
joker23/ACM
chef/2015_2_Long/RANKLIST.java
1384
import java.util.*; import java.math.*; import java.io.*; import java.text.*; import java.awt.Point; import static java.util.Arrays.*; import static java.lang.Integer.*; import static java.lang.Double.*; import static java.lang.Long.*; import static java.lang.Short.*; import static java.lang.Math.*; import static java.math.BigInteger.*; import static java.util.Collections.*; public class Main { private Scanner in; private StringTokenizer st; private PrintWriter out; private DecimalFormat fmt = new DecimalFormat("0.0000000000"); public void solve() throws Exception { int t = in.nextInt(); while (t --> 0) { int n = in.nextInt(); long s = in.nextLong(); int[] rankedList = new int[n]; long target = 0; for (int i=0; i<n; i++) { rankedList[i] = i + 1; target += rankedList[i]; } int ans = 0; int ptr = n - 1; target -= s; while (target > 0) { int curr = rankedList[ptr--]; ans ++; target -= (curr - 1); } out.println(ans); } } public Main() { this.in = new Scanner(System.in); this.out = new PrintWriter(System.out); } public void end() { try { this.out.flush(); this.out.close(); this.in.close(); } catch (Exception e){ //do nothing then :) } } public static void main(String[] args) throws Exception { Main solver = new Main(); solver.solve(); solver.end(); } }
mit
Casava/OneCamera
OneCamera/OneCamera/Scripts/recevier.js
935
$(function(){ var socket; var receiver = $("#receiver"); receiver.css("width", 500); receiver.css("height", 250); receiver.css("background-color", "#000000"); receiver.css("display", "block"); $('#start').on('click', function(){ console.log("started"); // socket = new WebSocket("ws://onecamera.azurewebsites.net/OneCamera/OneCameraWebSocketHandler.ashx"); socket = new WebSocket("ws://localhost:8080/receive", 'echo-portocol'); socket.onopen = function(){ console.log("connected"); } socket.onmessage = function(data){ receiver.attr('src', data.data); } socket.onerror = function(env){ console.log(env.message); } socket.onclose = function(){ console.log("disconnected"); } console.log("Start Receving"); }); $('#close').on('click', function(){ if(socket != undefined && socket.readyState == WebSocket.OPEN) { console.log('Close Receving'); socket.close(); } }); });
mit
rohitmukherjee/High-Performance-DSLs
Reporting Tool/main.py
68
from reporter import Reporter reporter = Reporter() reporter.run()
mit
jsJunky/store
config/session.js
4320
/** * Session Configuration * (sails.config.session) * * Sails session integration leans heavily on the great work already done by * Express, but also unifies Socket.io with the Connect session store. It uses * Connect's cookie parser to normalize configuration differences between Express * and Socket.io and hooks into Sails' middleware interpreter to allow you to access * and auto-save to `req.session` with Socket.io the same way you would with Express. * * For more information on configuring the session, check out: * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.session.html */ module.exports.session = { /*************************************************************************** * * * Session secret is automatically generated when your new app is created * * Replace at your own risk in production-- you will invalidate the cookies * * of your users, forcing them to log in again. * * * ***************************************************************************/ secret: '9cca808690a63344de5223bed5327d74', /*************************************************************************** * * * Set the session cookie expire time The maxAge is set by milliseconds, * * the example below is for 24 hours * * * ***************************************************************************/ // cookie: { // maxAge: 24 * 60 * 60 * 1000 // } /*************************************************************************** * * * In production, uncomment the following lines to set up a shared redis * * session store that can be shared across multiple Sails.js servers * ***************************************************************************/ // adapter: 'redis', /*************************************************************************** * * * The following values are optional, if no options are set a redis * * instance running on localhost is expected. Read more about options at: * * https://github.com/visionmedia/connect-redis * * * * * ***************************************************************************/ // host: 'localhost', // port: 6379, // ttl: <redis session TTL in seconds>, // db: 0, // pass: <redis auth password> // prefix: 'sess:' /*************************************************************************** * * * Uncomment the following lines to use your Mongo adapter as a session * * store * * * ***************************************************************************/ // adapter: 'mongo', // host: 'localhost', // port: 27017, // db: 'sails', // collection: 'sessions', /*************************************************************************** * * * Optional Values: * * * * # Note: url will override other connection settings url: * * 'mongodb://user:pass@host:port/database/collection', * * * ***************************************************************************/ // username: '', // password: '', // auto_reconnect: false, // ssl: false, // stringify: true };
mit
clinwiki-org/cw-app
front/app/containers/EditWorkflowsPage/index.ts
48
export { default } from './EditWorkflowsPage';
mit
polarkac/PolarBird
polarbird/polarbird.py
2100
import os import twitter import curses import logging from polarbird.settings import settings from polarbird.tokens import TOKENS_FILE, CONSUMER_KEY, CONSUMER_SECRET from polarbird.tweets import TweetDatabase from polarbird.windows import Screen from polarbird.streams import UserStreamThread logging.basicConfig(filename='polarbird.log', level=logging.DEBUG) logger = logging.getLogger('polarbird') class PolarBird(object): """ Main class that everything starts. Creates OAuth instance for authentication to Twitter. """ def __init__(self, screen): curses.noecho() curses.cbreak() curses.raw() self.tweet_database = TweetDatabase() self.screen = Screen(screen, self) self._create_user_dir() self._auth = None self._stream_thread = UserStreamThread(self) def start_app(self): """ Call for new stream thread for realtime tweets and start the app loop. """ self._stream_thread.start() self._app_loop() @property def auth(self): """ Read token file for tokens, if exists, or get new tokens from Twitter and return OAuth instance. """ if not self._auth: if not os.path.exists(TOKENS_FILE): token, token_key = twitter.oauth_dance( 'PolarBird', CONSUMER_KEY, CONSUMER_SECRET, TOKENS_FILE ) else: token, token_key = twitter.read_token_file(TOKENS_FILE) self._auth = twitter.OAuth( token, token_key, CONSUMER_KEY, CONSUMER_SECRET ) return self._auth def _create_user_dir(self): """ Create user directory where settings and tokens are stored. """ if not os.path.isdir(settings.USER_DIR): os.makedirs(settings.USER_DIR) def _app_loop(self): """ Main app loop. """ while True: self.screen.refresh_all_windows() self.screen.command_line_window.handle_input()
mit
superphil0/opendoor
client/www/js/view/app-view.js
1899
// Generated by CoffeeScript 1.6.3 (function() { var _ref, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; app.AppView = (function(_super) { __extends(AppView, _super); function AppView() { _ref = AppView.__super__.constructor.apply(this, arguments); return _ref; } AppView.prototype.el = "#app"; AppView.prototype.model = app.model; AppView.prototype.template = Handlebars.compile($("#app-template").html()); AppView.prototype.initialize = function() { this.listenTo(this.model, "change:page", this.changePage); return this.render(); }; AppView.prototype.render = function() { this.$el.html(this.template(this.model.toJSON())); this.newDoorView = new app.NewDoorView({ model: this.model, el: "#page-new-door" }); this.openDoorView = new app.OpenDoorView({ model: this.model, el: "#page-open-door" }); return this.changePage(); }; AppView.prototype.changePage = function() { switch (this.model.get("page")) { case "newDoor": this.newDoorView.render(); this.$("#page-new-door").removeClass("page-right").addClass("page-middle"); return this.$("#page-open-door").removeClass("page-middle").addClass("page-left"); case "openDoor": this.openDoorView.render(); this.$("#page-new-door").removeClass("page-middle").addClass("page-right"); return this.$("#page-open-door").removeClass("page-left").addClass("page-middle"); } }; return AppView; })(Backbone.View); }).call(this);
mit
hmemcpy/AgentMulder
src/Test/Data/Ninject/KernelTestCases/BindNonGenericToNonGeneric.cs
403
// Patterns: 1 // Matches: CommonImpl1.cs // NotMatches: Foo.cs using Ninject; using TestApplication.Types; namespace TestApplication.Ninject.KernelTestCases { public class BindNonGenericToNonGeneric { public BindNonGenericToNonGeneric() { var kernel = new StandardKernel(); kernel.Bind(typeof(ICommon)).To(typeof(CommonImpl1)); } } }
mit
sjmariogolf/petecoin
src/qt/locale/bitcoin_es_MX.ts
116059
<TS language="es_MX" version="2.0"> <context> <name>AboutDialog</name> <message> <source>About Petecoin Core</source> <translation>Acerca de Petecoin Core</translation> </message> <message> <source>&lt;b&gt;Petecoin Core&lt;/b&gt; version</source> <translation>&lt;b&gt;Petecoin Core&lt;/b&gt; versión</translation> </message> <message> <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 type="unfinished"/> </message> <message> <source>Copyright</source> <translation>Copyright</translation> </message> <message> <source>The Petecoin Core developers</source> <translation>Los desarrolladores de Petecoin Core</translation> </message> <message> <source>(%1-bit)</source> <translation>(%1-bit)</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <source>Double-click to edit address or label</source> <translation>Haga doble clic para editar el domicilio o la etiqueta</translation> </message> <message> <source>Create a new address</source> <translation>Crear una dirección nueva</translation> </message> <message> <source>&amp;New</source> <translation>&amp;Nuevo</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Copiar el domicilio seleccionado al portapapeles del sistema</translation> </message> <message> <source>&amp;Copy</source> <translation>&amp;Copiar</translation> </message> <message> <source>C&amp;lose</source> <translation>Cerrar</translation> </message> <message> <source>&amp;Copy Address</source> <translation>&amp;Copiar dirección</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>Eliminar la dirección actualmente seleccionada de la lista</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportar la información en la tabla actual a un archivo</translation> </message> <message> <source>&amp;Export</source> <translation>&amp;Exportar</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;Borrar</translation> </message> <message> <source>Choose the address to send coins to</source> <translation>Elija una dirección a la cual enviar monedas</translation> </message> <message> <source>Choose the address to receive coins with</source> <translation>Elija la dirección con la cual recibir monedas</translation> </message> <message> <source>C&amp;hoose</source> <translation>Elegir</translation> </message> <message> <source>Please sending addresses</source> <translation>Enviando direcciones</translation> </message> <message> <source>Beg receiving addresses</source> <translation>Recibiendo direcciones</translation> </message> <message> <source>These are your Petecoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Estas son tus direcciones de Petecoin para enviar pagos. Siempre revise la cantidad y la dirección receptora antes de enviar monedas</translation> </message> <message> <source>These are your Petecoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation>Estas son tus direcciones Petecoin para recibir pagos. Es recomendado usar una nueva dirección receptora para cada transacción.</translation> </message> <message> <source>Copy &amp;Label</source> <translation>Copiar &amp;Etiqueta</translation> </message> <message> <source>&amp;Edit</source> <translation>&amp;Editar</translation> </message> <message> <source>Export Address List</source> <translation>Exportar Lista de direcciones</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Archivo separado por comas (*.CSV)</translation> </message> <message> <source>Exporting Failed</source> <translation>Exportación fallida</translation> </message> <message> <source>There was an error trying to save the address list to %1.</source> <translation>Ocurrio un error al intentar guardar la lista de direcciones en %1</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <source>Address</source> <translation>Domicilio</translation> </message> <message> <source>(no label)</source> <translation>(sin etiqueta)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <source>Enter passphrase</source> <translation>Ingrese la contraseña</translation> </message> <message> <source>New passphrase</source> <translation>Nueva contraseña</translation> </message> <message> <source>Repeat new passphrase</source> <translation>Repita la nueva contraseña</translation> </message> <message> <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>Ingrese la nueva contraseña a la cartera&lt;br/&gt;Por favor use una contraseña de&lt;b&gt;10 o más caracteres aleatorios&lt;/b&gt; o &lt;b&gt;ocho o más palabras&lt;/b&gt;.</translation> </message> <message> <source>Encrypt wallet</source> <translation>Encriptar cartera.</translation> </message> <message> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Esta operación necesita la contraseña de su cartera para desbloquear su cartera.</translation> </message> <message> <source>Unlock wallet</source> <translation>Desbloquear cartera.</translation> </message> <message> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Esta operación necesita la contraseña de su cartera para desencriptar su cartera.</translation> </message> <message> <source>Decrypt wallet</source> <translation>Desencriptar cartera</translation> </message> <message> <source>Change passphrase</source> <translation>Cambiar contraseña</translation> </message> <message> <source>Enter the old and new passphrase to the wallet.</source> <translation>Ingrese la antugüa y nueva contraseña de la cartera</translation> </message> <message> <source>Confirm wallet encryption</source> <translation>Confirmar la encriptación de cartera</translation> </message> <message> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR PETECOINS&lt;/b&gt;!</source> <translation>Advertencia: Si encripta su cartera y pierde su contraseña, &lt;b&gt;PERDERÁ TODOS SUS PETECOINS&lt;/b&gt;!</translation> </message> <message> <source>Are you sure you wish to encrypt your wallet?</source> <translation>¿Está seguro que desea encriptar su cartera?</translation> </message> <message> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <source>Warning: The Caps Lock key is on!</source> <translation>Advertencia: ¡La tecla Bloq Mayus está activada!</translation> </message> <message> <source>Wallet encrypted</source> <translation>Cartera encriptada</translation> </message> <message> <source>Petecoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your petecoins from being stolen by malware infecting your computer.</source> <translation>Petecoin se cerrará para finalizar el proceso de encriptación. Recuerda que encriptar tu cartera no protege completamente a tus petecoins de ser robadas por malware infectando tu computadora.</translation> </message> <message> <source>Wallet encryption failed</source> <translation>Encriptación de la cartera fallida</translation> </message> <message> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>La encriptación de la cartera falló debido a un error interno. Su cartera no fue encriptada.</translation> </message> <message> <source>The supplied passphrases do not match.</source> <translation>Las contraseñas dadas no coinciden</translation> </message> <message> <source>Wallet unlock failed</source> <translation>El desbloqueo de la cartera falló</translation> </message> <message> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>La contraseña ingresada para la desencriptación de la cartera es incorrecto</translation> </message> <message> <source>Wallet decryption failed</source> <translation>La desencriptación de la cartera fallo</translation> </message> <message> <source>Wallet passphrase was successfully changed.</source> <translation>La contraseña de la cartera ha sido exitosamente cambiada.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <source>Sign &amp;message...</source> <translation>Sign &amp;mensaje</translation> </message> <message> <source>Synchronizing with network...</source> <translation>Sincronizando con la red...</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;Vista previa</translation> </message> <message> <source>Node</source> <translation>Nodo</translation> </message> <message> <source>Show general overview of wallet</source> <translation>Mostrar la vista previa general de la cartera</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;Transacciones</translation> </message> <message> <source>Browse transaction history</source> <translation>Explorar el historial de transacciones</translation> </message> <message> <source>E&amp;xit</source> <translation>S&amp;alir</translation> </message> <message> <source>Quit application</source> <translation>Salir de la aplicación</translation> </message> <message> <source>Show information about Petecoin</source> <translation>Mostrar información acerca de Petecoin</translation> </message> <message> <source>About &amp;Qt</source> <translation>Acerca de &amp;Qt</translation> </message> <message> <source>Show information about Qt</source> <translation>Mostrar información acerca de Qt</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;Opciones</translation> </message> <message> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Encriptar cartera</translation> </message> <message> <source>&amp;Backup Wallet...</source> <translation>&amp;Respaldar cartera</translation> </message> <message> <source>&amp;Change Passphrase...</source> <translation>&amp;Cambiar contraseña...</translation> </message> <message> <source>Please &amp;sending addresses...</source> <translation>&amp;Enviando direcciones...</translation> </message> <message> <source>Beg &amp;receiving addresses...</source> <translation>&amp;Recibiendo direcciones...</translation> </message> <message> <source>Open &amp;URI...</source> <translation>Abrir &amp;URL...</translation> </message> <message> <source>Importing blocks from disk...</source> <translation>Importando bloques desde el disco...</translation> </message> <message> <source>Reindexing blocks on disk...</source> <translation>Reindexando bloques en el disco...</translation> </message> <message> <source>Send coins to a Petecoin address</source> <translation>Enviar monedas a una dirección Petecoin</translation> </message> <message> <source>Modify configuration options for Petecoin Core</source> <translation>Modificar las opciones de configuración de Petecoin</translation> </message> <message> <source>Backup wallet to another location</source> <translation>Respaldar cartera en otra ubicación</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>Cambiar la contraseña usada para la encriptación de la cartera</translation> </message> <message> <source>&amp;Debug window</source> <translation>&amp;Depurar ventana</translation> </message> <message> <source>Open debugging and diagnostic console</source> <translation>Abrir la consola de depuración y disgnostico</translation> </message> <message> <source>&amp;Verify message...</source> <translation>&amp;Verificar mensaje...</translation> </message> <message> <source>Petecoin</source> <translation type="unfinished"/> </message> <message> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <source>Sign messages with your Petecoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <source>Verify messages to ensure they were signed with specified Petecoin addresses</source> <translation type="unfinished"/> </message> <message> <source>&amp;File</source> <translation>&amp;Archivo</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;Configuraciones</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;Ayuda</translation> </message> <message> <source>Tabs toolbar</source> <translation>Pestañas</translation> </message> <message> <source>[testnet]</source> <translation type="unfinished"/> </message> <message> <source>Petecoin Core</source> <translation>nucleo Petecoin</translation> </message> <message> <source>Request payments (generates QR codes and petecoin: URIs)</source> <translation type="unfinished"/> </message> <message> <source>&amp;About Petecoin Core</source> <translation type="unfinished"/> </message> <message> <source>Show the list of used sending addresses and labels</source> <translation type="unfinished"/> </message> <message> <source>Show the list of used receiving addresses and labels</source> <translation type="unfinished"/> </message> <message> <source>Open a petecoin: URI or payment request</source> <translation type="unfinished"/> </message> <message> <source>&amp;Command-line options</source> <translation>opciones de la &amp;Linea de comandos</translation> </message> <message> <source>Show the Petecoin Core help message to get a list with possible command-line options</source> <translation>Mostrar mensaje de ayuda del nucleo de Petecoin para optener una lista con los posibles comandos de Petecoin</translation> </message> <message> <source>Petecoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <source>%n active connection(s) to Petecoin network</source> <translation><numerusform>%n Activar conexión a la red de Petecoin</numerusform><numerusform>%n Activar conexiones a la red de Petecoin</numerusform></translation> </message> <message> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <source>%n hour(s)</source> <translation type="unfinished"><numerusform/><numerusform/></translation> </message> <message numerus="yes"> <source>%n day(s)</source> <translation type="unfinished"><numerusform/><numerusform/></translation> </message> <message numerus="yes"> <source>%n week(s)</source> <translation type="unfinished"><numerusform/><numerusform/></translation> </message> <message> <source>%1 and %2</source> <translation type="unfinished"/> </message> <message numerus="yes"> <source>%n year(s)</source> <translation type="unfinished"><numerusform/><numerusform/></translation> </message> <message> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <source>Error</source> <translation type="unfinished"/> </message> <message> <source>Warning</source> <translation type="unfinished"/> </message> <message> <source>Information</source> <translation type="unfinished"/> </message> <message> <source>Up to date</source> <translation>Actualizado al dia </translation> </message> <message> <source>Catching up...</source> <translation>Resiviendo...</translation> </message> <message> <source>Sent transaction</source> <translation>Enviar Transacción</translation> </message> <message> <source>Incoming transaction</source> <translation>Transacción entrante</translation> </message> <message> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>La cartera esta &lt;b&gt;encriptada&lt;/b&gt; y &lt;b&gt;desbloqueada&lt;/b&gt; actualmente </translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>La cartera esta &lt;b&gt;encriptada&lt;/b&gt; y &lt;b&gt;bloqueada&lt;/b&gt; actualmente </translation> </message> <message> <source>A fatal error occurred. Petecoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Coin Control Address Selection</source> <translation type="unfinished"/> </message> <message> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <source>Amount:</source> <translation>Monto:</translation> </message> <message> <source>Priority:</source> <translation>Prioridad:</translation> </message> <message> <source>Fee:</source> <translation>Cuota:</translation> </message> <message> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <source>Change:</source> <translation type="unfinished"/> </message> <message> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <source>List mode</source> <translation type="unfinished"/> </message> <message> <source>Amount</source> <translation>Monto</translation> </message> <message> <source>Label</source> <translation type="unfinished"/> </message> <message> <source>Address</source> <translation>Domicilio</translation> </message> <message> <source>Date</source> <translation>Fecha</translation> </message> <message> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <source>Confirmed</source> <translation>Confirmado </translation> </message> <message> <source>Priority</source> <translation type="unfinished"/> </message> <message> <source>Copy address</source> <translation>Copiar dirección </translation> </message> <message> <source>Copy label</source> <translation>Copiar capa </translation> </message> <message> <source>Copy amount</source> <translation>copiar monto</translation> </message> <message> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <source>Lock unspent</source> <translation type="unfinished"/> </message> <message> <source>Unlock unspent</source> <translation type="unfinished"/> </message> <message> <source>Copy quantity</source> <translation>copiar cantidad</translation> </message> <message> <source>Copy fee</source> <translation>copiar cuota</translation> </message> <message> <source>Copy after fee</source> <translation>copiar despues de cuota</translation> </message> <message> <source>Copy bytes</source> <translation>copiar bytes</translation> </message> <message> <source>Copy priority</source> <translation>copiar prioridad</translation> </message> <message> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <source>Copy change</source> <translation>copiar cambio</translation> </message> <message> <source>highest</source> <translation type="unfinished"/> </message> <message> <source>higher</source> <translation type="unfinished"/> </message> <message> <source>high</source> <translation type="unfinished"/> </message> <message> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <source>medium</source> <translation type="unfinished"/> </message> <message> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <source>low</source> <translation type="unfinished"/> </message> <message> <source>lower</source> <translation type="unfinished"/> </message> <message> <source>lowest</source> <translation type="unfinished"/> </message> <message> <source>(%1 locked)</source> <translation type="unfinished"/> </message> <message> <source>none</source> <translation type="unfinished"/> </message> <message> <source>Dust</source> <translation type="unfinished"/> </message> <message> <source>yes</source> <translation type="unfinished"/> </message> <message> <source>no</source> <translation type="unfinished"/> </message> <message> <source>This label turns red, if the transaction size is greater than 1000 bytes.</source> <translation type="unfinished"/> </message> <message> <source>This means a fee of at least %1 per kB is required.</source> <translation type="unfinished"/> </message> <message> <source>Can vary +/- 1 byte per input.</source> <translation type="unfinished"/> </message> <message> <source>Transactions with higher priority are more likely to get included into a block.</source> <translation type="unfinished"/> </message> <message> <source>This label turns red, if the priority is smaller than &quot;medium&quot;.</source> <translation type="unfinished"/> </message> <message> <source>This label turns red, if any recipient receives an amount smaller than %1.</source> <translation type="unfinished"/> </message> <message> <source>This means a fee of at least %1 is required.</source> <translation type="unfinished"/> </message> <message> <source>Amounts below 0.546 times the minimum relay fee are shown as dust.</source> <translation type="unfinished"/> </message> <message> <source>This label turns red, if the change is smaller than %1.</source> <translation type="unfinished"/> </message> <message> <source>(no label)</source> <translation>(sin etiqueta)</translation> </message> <message> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>Editar dirección</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;Etiqueta</translation> </message> <message> <source>The label associated with this address list entry</source> <translation type="unfinished"/> </message> <message> <source>The address associated with this address list entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <source>&amp;Address</source> <translation>&amp;Dirección</translation> </message> <message> <source>New receiving address</source> <translation>Nueva dirección de entregas</translation> </message> <message> <source>New sending address</source> <translation>Nueva dirección de entregas</translation> </message> <message> <source>Edit receiving address</source> <translation>Editar dirección de entregas</translation> </message> <message> <source>Edit sending address</source> <translation>Editar dirección de envios</translation> </message> <message> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>El domicilio ingresado &quot;%1&quot; ya existe en la libreta de direcciones</translation> </message> <message> <source>The entered address &quot;%1&quot; is not a valid Petecoin address.</source> <translation type="unfinished"/> </message> <message> <source>Could not unlock wallet.</source> <translation>No se puede desbloquear la cartera</translation> </message> <message> <source>New key generation failed.</source> <translation>La generación de la nueva clave fallo</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <source>A new data directory will be created.</source> <translation type="unfinished"/> </message> <message> <source>name</source> <translation type="unfinished"/> </message> <message> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation type="unfinished"/> </message> <message> <source>Path already exists, and is not a directory.</source> <translation type="unfinished"/> </message> <message> <source>Cannot create data directory here.</source> <translation type="unfinished"/> </message> </context> <context> <name>HelpMessageDialog</name> <message> <source>Petecoin Core - Command-line options</source> <translation>Opciones de lineas de comando del nucleo de Petecoin</translation> </message> <message> <source>Petecoin Core</source> <translation>nucleo Petecoin</translation> </message> <message> <source>version</source> <translation>Versión</translation> </message> <message> <source>Usage:</source> <translation>Uso:</translation> </message> <message> <source>command-line options</source> <translation>Opciones de comando de lineas</translation> </message> <message> <source>UI options</source> <translation>Opciones de interfaz</translation> </message> <message> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Definir idioma, por ejemplo &quot;de_DE&quot; (por defecto: Sistema local)</translation> </message> <message> <source>Start minimized</source> <translation>Iniciar minimizado</translation> </message> <message> <source>Set SSL root certificates for payment request (default: -system-)</source> <translation type="unfinished"/> </message> <message> <source>Show splash screen on startup (default: 1)</source> <translation>Mostrar pantalla de arraque al iniciar (por defecto: 1)</translation> </message> <message> <source>Choose data directory on startup (default: 0)</source> <translation>Escojer el directorio de información al iniciar (por defecto : 0)</translation> </message> </context> <context> <name>Intro</name> <message> <source>Welcome</source> <translation type="unfinished"/> </message> <message> <source>Welcome to Petecoin Core.</source> <translation type="unfinished"/> </message> <message> <source>As this is the first time the program is launched, you can choose where Petecoin Core will store its data.</source> <translation type="unfinished"/> </message> <message> <source>Petecoin Core will download and store a copy of the Petecoin block chain. At least %1GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source> <translation type="unfinished"/> </message> <message> <source>Use the default data directory</source> <translation type="unfinished"/> </message> <message> <source>Use a custom data directory:</source> <translation type="unfinished"/> </message> <message> <source>Petecoin</source> <translation type="unfinished"/> </message> <message> <source>Error: Specified data directory &quot;%1&quot; can not be created.</source> <translation type="unfinished"/> </message> <message> <source>Error</source> <translation type="unfinished"/> </message> <message> <source>GB of free space available</source> <translation type="unfinished"/> </message> <message> <source>(of %1GB needed)</source> <translation type="unfinished"/> </message> </context> <context> <name>OpenURIDialog</name> <message> <source>Open URI</source> <translation type="unfinished"/> </message> <message> <source>Open payment request from URI or file</source> <translation type="unfinished"/> </message> <message> <source>URI:</source> <translation type="unfinished"/> </message> <message> <source>Select payment request file</source> <translation type="unfinished"/> </message> <message> <source>Select payment request file to open</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>Opciones</translation> </message> <message> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <source>Automatically start Petecoin Core after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <source>&amp;Start Petecoin Core on system login</source> <translation type="unfinished"/> </message> <message> <source>Size of &amp;database cache</source> <translation type="unfinished"/> </message> <message> <source>MB</source> <translation type="unfinished"/> </message> <message> <source>Number of script &amp;verification threads</source> <translation type="unfinished"/> </message> <message> <source>Connect to the Petecoin network through a SOCKS proxy.</source> <translation type="unfinished"/> </message> <message> <source>&amp;Connect through SOCKS proxy (default proxy):</source> <translation type="unfinished"/> </message> <message> <source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source> <translation type="unfinished"/> </message> <message> <source>Active command-line options that override above options:</source> <translation>Activar las opciones de linea de comando que sobre escriben las siguientes opciones:</translation> </message> <message> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <source>(0 = auto, &lt;0 = leave that many cores free)</source> <translation type="unfinished"/> </message> <message> <source>W&amp;allet</source> <translation type="unfinished"/> </message> <message> <source>Expert</source> <translation type="unfinished"/> </message> <message> <source>Enable coin &amp;control features</source> <translation type="unfinished"/> </message> <message> <source>If you disable the spending of unconfirmed change, the change from a transaction cannot be used until that transaction has at least one confirmation. This also affects how your balance is computed.</source> <translation type="unfinished"/> </message> <message> <source>&amp;Spend unconfirmed change</source> <translation type="unfinished"/> </message> <message> <source>Automatically open the Petecoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <source>The user interface language can be set here. This setting will take effect after restarting Petecoin Core.</source> <translation type="unfinished"/> </message> <message> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <source>Whether to show Petecoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <source>default</source> <translation type="unfinished"/> </message> <message> <source>none</source> <translation type="unfinished"/> </message> <message> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <source>Client restart required to activate changes.</source> <translation type="unfinished"/> </message> <message> <source>Client will be shutdown, do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <source>This change would require a client restart.</source> <translation type="unfinished"/> </message> <message> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>Formulario</translation> </message> <message> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Petecoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <source>Available:</source> <translation type="unfinished"/> </message> <message> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <source>Pending:</source> <translation type="unfinished"/> </message> <message> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation type="unfinished"/> </message> <message> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <source>Total:</source> <translation type="unfinished"/> </message> <message> <source>Your current total balance</source> <translation type="unfinished"/> </message> <message> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Transacciones recientes&lt;/b&gt;</translation> </message> <message> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <source>URI can not be parsed! This can be caused by an invalid Petecoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <source>Requested payment amount of %1 is too small (considered dust).</source> <translation type="unfinished"/> </message> <message> <source>Payment request error</source> <translation type="unfinished"/> </message> <message> <source>Cannot start petecoin: click-to-pay handler</source> <translation type="unfinished"/> </message> <message> <source>Net manager warning</source> <translation>advertencia del administrador de red.</translation> </message> <message> <source>Your active proxy doesn&apos;t support SOCKS5, which is required for payment requests via proxy.</source> <translation>Tu active proxy no soporta SOCKS5, el cual es requerido para solicitud de pago via proxy. </translation> </message> <message> <source>Payment request fetch URL is invalid: %1</source> <translation type="unfinished"/> </message> <message> <source>Payment request file handling</source> <translation type="unfinished"/> </message> <message> <source>Payment request file can not be read or processed! This can be caused by an invalid payment request file.</source> <translation type="unfinished"/> </message> <message> <source>Unverified payment requests to custom payment scripts are unsupported.</source> <translation type="unfinished"/> </message> <message> <source>Refund from %1</source> <translation type="unfinished"/> </message> <message> <source>Error communicating with %1: %2</source> <translation type="unfinished"/> </message> <message> <source>Payment request can not be parsed or processed!</source> <translation type="unfinished"/> </message> <message> <source>Bad response from server %1</source> <translation type="unfinished"/> </message> <message> <source>Payment acknowledged</source> <translation type="unfinished"/> </message> <message> <source>Network request error</source> <translation type="unfinished"/> </message> </context> <context> <name>QObject</name> <message> <source>Petecoin</source> <translation type="unfinished"/> </message> <message> <source>Error: Specified data directory &quot;%1&quot; does not exist.</source> <translation type="unfinished"/> </message> <message> <source>Error: Cannot parse configuration file: %1. Only use key=value syntax.</source> <translation type="unfinished"/> </message> <message> <source>Error: Invalid combination of -regtest and -testnet.</source> <translation type="unfinished"/> </message> <message> <source>Petecoin Core did&apos;t yet exit safely...</source> <translation type="unfinished"/> </message> <message> <source>Enter a Petecoin address (e.g. PMvgvan5TULVfJihSXXKJ4bPB8YTGKUFn3)</source> <translation>Ingrese una direccion Petecoin (ejem. PMvgvan5TULVfJihSXXKJ4bPB8YTGKUFn3)</translation> </message> </context> <context> <name>QRImageWidget</name> <message> <source>&amp;Save Image...</source> <translation type="unfinished"/> </message> <message> <source>&amp;Copy Image</source> <translation type="unfinished"/> </message> <message> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <source>PNG Image (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <source>Client name</source> <translation type="unfinished"/> </message> <message> <source>N/A</source> <translation type="unfinished"/> </message> <message> <source>Client version</source> <translation type="unfinished"/> </message> <message> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <source>Debug window</source> <translation type="unfinished"/> </message> <message> <source>General</source> <translation type="unfinished"/> </message> <message> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <source>Network</source> <translation type="unfinished"/> </message> <message> <source>Name</source> <translation type="unfinished"/> </message> <message> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <source>&amp;Network Traffic</source> <translation type="unfinished"/> </message> <message> <source>&amp;Clear</source> <translation type="unfinished"/> </message> <message> <source>Totals</source> <translation type="unfinished"/> </message> <message> <source>In:</source> <translation type="unfinished"/> </message> <message> <source>Out:</source> <translation type="unfinished"/> </message> <message> <source>Build date</source> <translation type="unfinished"/> </message> <message> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <source>Open the Petecoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <source>Welcome to the Petecoin RPC console.</source> <translation type="unfinished"/> </message> <message> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> <message> <source>%1 B</source> <translation type="unfinished"/> </message> <message> <source>%1 KB</source> <translation type="unfinished"/> </message> <message> <source>%1 MB</source> <translation type="unfinished"/> </message> <message> <source>%1 GB</source> <translation type="unfinished"/> </message> <message> <source>%1 m</source> <translation type="unfinished"/> </message> <message> <source>%1 h</source> <translation type="unfinished"/> </message> <message> <source>%1 h %2 m</source> <translation type="unfinished"/> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Amount:</source> <translation type="unfinished"/> </message> <message> <source>&amp;Label:</source> <translation>&amp;Etiqueta</translation> </message> <message> <source>&amp;Message:</source> <translation type="unfinished"/> </message> <message> <source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source> <translation type="unfinished"/> </message> <message> <source>R&amp;euse an existing receiving address (not recommended)</source> <translation type="unfinished"/> </message> <message> <source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Petecoin network.</source> <translation>Mensaje opcional para agregar a la solicitud de pago, el cual será mostrado cuando la solicitud este abierta. Nota: El mensaje no se manda con el pago a travéz de la red de Petecoin.</translation> </message> <message> <source>An optional label to associate with the new receiving address.</source> <translation type="unfinished"/> </message> <message> <source>Use this form to request payments. All fields are &lt;b&gt;optional&lt;/b&gt;.</source> <translation>Use este formulario para la solicitud de pagos. Todos los campos son &lt;b&gt;opcionales&lt;/b&gt;</translation> </message> <message> <source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source> <translation>Monto opcional a solicitar. Dejarlo vacion o en cero no solicita un monto especifico.</translation> </message> <message> <source>Clear all fields of the form.</source> <translation type="unfinished"/> </message> <message> <source>Clear</source> <translation type="unfinished"/> </message> <message> <source>Requested payments history</source> <translation type="unfinished"/> </message> <message> <source>&amp;Request payment</source> <translation type="unfinished"/> </message> <message> <source>Show the selected request (does the same as double clicking an entry)</source> <translation type="unfinished"/> </message> <message> <source>Show</source> <translation type="unfinished"/> </message> <message> <source>Remove the selected entries from the list</source> <translation type="unfinished"/> </message> <message> <source>Remove</source> <translation type="unfinished"/> </message> <message> <source>Copy label</source> <translation>Copiar capa </translation> </message> <message> <source>Copy message</source> <translation type="unfinished"/> </message> <message> <source>Copy amount</source> <translation>copiar monto</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>QR Code</source> <translation type="unfinished"/> </message> <message> <source>Copy &amp;URI</source> <translation type="unfinished"/> </message> <message> <source>Copy &amp;Address</source> <translation type="unfinished"/> </message> <message> <source>&amp;Save Image...</source> <translation type="unfinished"/> </message> <message> <source>Request payment to %1</source> <translation type="unfinished"/> </message> <message> <source>Payment information</source> <translation type="unfinished"/> </message> <message> <source>URI</source> <translation type="unfinished"/> </message> <message> <source>Address</source> <translation>Domicilio</translation> </message> <message> <source>Amount</source> <translation>Monto</translation> </message> <message> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <source>Message</source> <translation type="unfinished"/> </message> <message> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <source>Date</source> <translation>Fecha</translation> </message> <message> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <source>Message</source> <translation type="unfinished"/> </message> <message> <source>Amount</source> <translation>Monto</translation> </message> <message> <source>(no label)</source> <translation>(sin etiqueta)</translation> </message> <message> <source>(no message)</source> <translation type="unfinished"/> </message> <message> <source>(no amount)</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>Mandar monedas</translation> </message> <message> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <source>Amount:</source> <translation>Monto:</translation> </message> <message> <source>Priority:</source> <translation>Prioridad:</translation> </message> <message> <source>Fee:</source> <translation>Cuota:</translation> </message> <message> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <source>Change:</source> <translation type="unfinished"/> </message> <message> <source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source> <translation type="unfinished"/> </message> <message> <source>Custom change address</source> <translation type="unfinished"/> </message> <message> <source>Send to multiple recipients at once</source> <translation>Enviar a múltiples receptores a la vez</translation> </message> <message> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <source>Clear all fields of the form.</source> <translation type="unfinished"/> </message> <message> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <source>Confirm the send action</source> <translation>Confirme la acción de enviar</translation> </message> <message> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <source>Confirm send coins</source> <translation>Confirme para mandar monedas</translation> </message> <message> <source>%1 to %2</source> <translation type="unfinished"/> </message> <message> <source>Copy quantity</source> <translation>copiar cantidad</translation> </message> <message> <source>Copy amount</source> <translation>copiar monto</translation> </message> <message> <source>Copy fee</source> <translation>copiar cuota</translation> </message> <message> <source>Copy after fee</source> <translation>copiar despues de cuota</translation> </message> <message> <source>Copy bytes</source> <translation>copiar bytes</translation> </message> <message> <source>Copy priority</source> <translation>copiar prioridad</translation> </message> <message> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <source>Copy change</source> <translation>copiar cambio</translation> </message> <message> <source>Total Amount %1 (= %2)</source> <translation>Monto total %1(=%2)</translation> </message> <message> <source>or</source> <translation>o</translation> </message> <message> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <source>The amount to pay must be larger than 0.</source> <translation>El monto a pagar debe ser mayor a 0</translation> </message> <message> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <source>Transaction creation failed!</source> <translation>¡La creación de transacion falló!</translation> </message> <message> <source>The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>¡La transación fue rechazada! Esto puede ocurrir si algunas de tus monedas en tu cartera han sido gastadas, al igual que si usas una cartera copiada y la monedas fueron gastadas en la copia pero no se marcaron como gastadas.</translation> </message> <message> <source>Warning: Invalid Petecoin address</source> <translation>Advertencia: Dirección de Petecoin invalida</translation> </message> <message> <source>(no label)</source> <translation>(sin etiqueta)</translation> </message> <message> <source>Warning: Unknown change address</source> <translation>Advertencia: Cambio de dirección desconocido</translation> </message> <message> <source>Are you sure you want to send?</source> <translation type="unfinished"/> </message> <message> <source>added as transaction fee</source> <translation type="unfinished"/> </message> <message> <source>Payment request expired</source> <translation type="unfinished"/> </message> <message> <source>Invalid payment address %1</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation>M&amp;onto</translation> </message> <message> <source>Pay &amp;To:</source> <translation>Pagar &amp;a:</translation> </message> <message> <source>The address to send the payment to (e.g. PMvgvan5TULVfJihSXXKJ4bPB8YTGKUFn3)</source> <translation type="unfinished"/> </message> <message> <source>Enter a label for this address to add it to your address book</source> <translation>Ingrese una etiqueta para esta dirección para agregarlo en su libreta de direcciones.</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Etiqueta</translation> </message> <message> <source>Choose previously used address</source> <translation type="unfinished"/> </message> <message> <source>This is a normal payment.</source> <translation>Este es un pago normal</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Pegar dirección del portapapeles</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Remove this entry</source> <translation>Quitar esta entrada</translation> </message> <message> <source>Message:</source> <translation>Mensaje:</translation> </message> <message> <source>This is a verified payment request.</source> <translation>Esta es una verificación de solicituda de pago.</translation> </message> <message> <source>Enter a label for this address to add it to the list of used addresses</source> <translation type="unfinished"/> </message> <message> <source>A message that was attached to the petecoin: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Petecoin network.</source> <translation type="unfinished"/> </message> <message> <source>This is an unverified payment request.</source> <translation>Esta es una solicitud de pago no verificada.</translation> </message> <message> <source>Pay To:</source> <translation>Pago para:</translation> </message> <message> <source>Memo:</source> <translation type="unfinished"/> </message> </context> <context> <name>ShutdownWindow</name> <message> <source>Petecoin Core is shutting down...</source> <translation>Apagando el nucleo de Petecoin...</translation> </message> <message> <source>Do not shut down the computer until this window disappears.</source> <translation>No apague su computadora hasta que esta ventana desaparesca.</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <source>The address to sign the message with (e.g. PMvgvan5TULVfJihSXXKJ4bPB8YTGKUFn3)</source> <translation type="unfinished"/> </message> <message> <source>Choose previously used address</source> <translation type="unfinished"/> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Pegar dirección del portapapeles</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <source>Signature</source> <translation type="unfinished"/> </message> <message> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <source>Sign the message to prove you own this Petecoin address</source> <translation type="unfinished"/> </message> <message> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <source>The address the message was signed with (e.g. PMvgvan5TULVfJihSXXKJ4bPB8YTGKUFn3)</source> <translation type="unfinished"/> </message> <message> <source>Verify the message to ensure it was signed with the specified Petecoin address</source> <translation type="unfinished"/> </message> <message> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <source>Enter a Petecoin address (e.g. PMvgvan5TULVfJihSXXKJ4bPB8YTGKUFn3)</source> <translation>Ingrese una direccion Petecoin (ejem. PMvgvan5TULVfJihSXXKJ4bPB8YTGKUFn3)</translation> </message> <message> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <source>Petecoin Core</source> <translation>nucleo Petecoin</translation> </message> <message> <source>The Petecoin Core developers</source> <translation>El nucleo de Petecoin de desarrolladores</translation> </message> <message> <source>[testnet]</source> <translation type="unfinished"/> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <source>KB/s</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <source>Open until %1</source> <translation>Abrir hasta %1</translation> </message> <message> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <source>%1/unconfirmed</source> <translation>%1/No confirmado</translation> </message> <message> <source>%1 confirmations</source> <translation>%1 confirmaciones</translation> </message> <message> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform/><numerusform/></translation> </message> <message> <source>Date</source> <translation>Fecha</translation> </message> <message> <source>Source</source> <translation type="unfinished"/> </message> <message> <source>Generated</source> <translation type="unfinished"/> </message> <message> <source>From</source> <translation type="unfinished"/> </message> <message> <source>To</source> <translation type="unfinished"/> </message> <message> <source>own address</source> <translation type="unfinished"/> </message> <message> <source>label</source> <translation type="unfinished"/> </message> <message> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform/><numerusform/></translation> </message> <message> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <source>Debit</source> <translation type="unfinished"/> </message> <message> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <source>Message</source> <translation type="unfinished"/> </message> <message> <source>Comment</source> <translation type="unfinished"/> </message> <message> <source>Transaction ID</source> <translation>ID</translation> </message> <message> <source>Merchant</source> <translation type="unfinished"/> </message> <message> <source>Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &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 type="unfinished"/> </message> <message> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <source>Amount</source> <translation>Monto</translation> </message> <message> <source>true</source> <translation type="unfinished"/> </message> <message> <source>false</source> <translation type="unfinished"/> </message> <message> <source>, has not been successfully broadcast yet</source> <translation>, no ha sido transmitido aun</translation> </message> <message numerus="yes"> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform/><numerusform/></translation> </message> <message> <source>unknown</source> <translation>desconocido</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <source>Transaction details</source> <translation>Detalles de la transacción</translation> </message> <message> <source>This pane shows a detailed description of the transaction</source> <translation>Este panel muestras una descripción detallada de la transacción</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <source>Date</source> <translation>Fecha</translation> </message> <message> <source>Type</source> <translation>Tipo</translation> </message> <message> <source>Address</source> <translation>Domicilio</translation> </message> <message> <source>Amount</source> <translation>Monto</translation> </message> <message> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform/><numerusform/></translation> </message> <message> <source>Open until %1</source> <translation>Abrir hasta %1</translation> </message> <message> <source>Confirmed (%1 confirmations)</source> <translation>Confimado (%1 confirmaciones)</translation> </message> <message> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Este bloque no fue recibido por ningun nodo y probablemente no fue aceptado !</translation> </message> <message> <source>Generated but not accepted</source> <translation>Generado pero no aprovado</translation> </message> <message> <source>Offline</source> <translation type="unfinished"/> </message> <message> <source>Unconfirmed</source> <translation type="unfinished"/> </message> <message> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation type="unfinished"/> </message> <message> <source>Conflicted</source> <translation type="unfinished"/> </message> <message> <source>Received with</source> <translation>Recivido con</translation> </message> <message> <source>Received from</source> <translation type="unfinished"/> </message> <message> <source>Sent to</source> <translation>Enviar a</translation> </message> <message> <source>Payment to yourself</source> <translation>Pagar a si mismo</translation> </message> <message> <source>Mined</source> <translation>Minado</translation> </message> <message> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"/> </message> <message> <source>Date and time that the transaction was received.</source> <translation>Fecha y hora en que la transacción fue recibida </translation> </message> <message> <source>Type of transaction.</source> <translation>Escriba una transacción</translation> </message> <message> <source>Destination address of transaction.</source> <translation>Direccion del destinatario de la transacción</translation> </message> <message> <source>Amount removed from or added to balance.</source> <translation>Cantidad removida del saldo o agregada </translation> </message> </context> <context> <name>TransactionView</name> <message> <source>All</source> <translation>Todo</translation> </message> <message> <source>Today</source> <translation>Hoy</translation> </message> <message> <source>This week</source> <translation>Esta semana </translation> </message> <message> <source>This month</source> <translation>Este mes </translation> </message> <message> <source>Last month</source> <translation>El mes pasado </translation> </message> <message> <source>This year</source> <translation>Este año</translation> </message> <message> <source>Range...</source> <translation type="unfinished"/> </message> <message> <source>Received with</source> <translation>Recivido con</translation> </message> <message> <source>Sent to</source> <translation>Enviar a</translation> </message> <message> <source>To yourself</source> <translation>Para ti mismo</translation> </message> <message> <source>Mined</source> <translation>Minado </translation> </message> <message> <source>Other</source> <translation>Otro</translation> </message> <message> <source>Enter address or label to search</source> <translation>Ingrese dirección o capa a buscar </translation> </message> <message> <source>Min amount</source> <translation>Monto minimo </translation> </message> <message> <source>Copy address</source> <translation>Copiar dirección </translation> </message> <message> <source>Copy label</source> <translation>Copiar capa </translation> </message> <message> <source>Copy amount</source> <translation>copiar monto</translation> </message> <message> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <source>Edit label</source> <translation>Editar capa </translation> </message> <message> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <source>Export Transaction History</source> <translation>Exportar el historial de transacción</translation> </message> <message> <source>Exporting Failed</source> <translation>Fallo en la exportación</translation> </message> <message> <source>There was an error trying to save the transaction history to %1.</source> <translation>Ocurrio un error intentando guardar el historial de transaciones a %1</translation> </message> <message> <source>Exporting Successful</source> <translation>Exportacion satisfactoria</translation> </message> <message> <source>The transaction history was successfully saved to %1.</source> <translation>el historial de transaciones ha sido guardado exitosamente en %1</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Arhchivo separado por comas (*.CSV)</translation> </message> <message> <source>Confirmed</source> <translation>Confirmado </translation> </message> <message> <source>Date</source> <translation>Fecha</translation> </message> <message> <source>Type</source> <translation>Tipo</translation> </message> <message> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <source>Address</source> <translation>Domicilio</translation> </message> <message> <source>Amount</source> <translation>Monto</translation> </message> <message> <source>ID</source> <translation>ID</translation> </message> <message> <source>Range:</source> <translation type="unfinished"/> </message> <message> <source>to</source> <translation>Para</translation> </message> </context> <context> <name>WalletFrame</name> <message> <source>No wallet has been loaded.</source> <translation>No se há cargado la cartera.</translation> </message> </context> <context> <name>WalletModel</name> <message> <source>Send Coins</source> <translation>Mandar monedas</translation> </message> </context> <context> <name>WalletView</name> <message> <source>&amp;Export</source> <translation>&amp;Exportar</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportar la información en la tabla actual a un archivo</translation> </message> <message> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <source>There was an error trying to save the wallet data to %1.</source> <translation>Ocurrio un error tratando de guardar la información de la cartera %1</translation> </message> <message> <source>The wallet data was successfully saved to %1.</source> <translation>La información de la cartera fué guardada exitosamente a %1</translation> </message> <message> <source>Backup Successful</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <source>Usage:</source> <translation>Uso:</translation> </message> <message> <source>List commands</source> <translation>Lista de comandos</translation> </message> <message> <source>Get help for a command</source> <translation type="unfinished"/> </message> <message> <source>Options:</source> <translation type="unfinished"/> </message> <message> <source>Specify configuration file (default: petecoin.conf)</source> <translation type="unfinished"/> </message> <message> <source>Specify pid file (default: bitcoind.pid)</source> <translation type="unfinished"/> </message> <message> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation type="unfinished"/> </message> <message> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation type="unfinished"/> </message> <message> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <source>Petecoin Core RPC client version</source> <translation type="unfinished"/> </message> <message> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=bitcoinrpc 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;Petecoin Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <source>Continuously rate-limit free transactions to &lt;n&gt;*1000 bytes per minute (default:15)</source> <translation type="unfinished"/> </message> <message> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly.</source> <translation type="unfinished"/> </message> <message> <source>Error: Listening for incoming connections failed (listen returned error %d)</source> <translation type="unfinished"/> </message> <message> <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 type="unfinished"/> </message> <message> <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 type="unfinished"/> </message> <message> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <source>Fees smaller than this are considered zero fee (for transaction creation) (default:</source> <translation type="unfinished"/> </message> <message> <source>Flush database activity from memory pool to disk log every &lt;n&gt; megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <source>How thorough the block verification of -checkblocks is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <source>In this mode -genproclimit controls how many blocks are generated immediately.</source> <translation type="unfinished"/> </message> <message> <source>Set the number of script verification threads (%u to %d, 0 = auto, &lt;0 = leave that many cores free, default: %d)</source> <translation type="unfinished"/> </message> <message> <source>Set the processor limit for when generation is on (-1 = unlimited, default: -1)</source> <translation type="unfinished"/> </message> <message> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <source>Unable to bind to %s on this computer. Petecoin Core is probably already running.</source> <translation type="unfinished"/> </message> <message> <source>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: -proxy)</source> <translation type="unfinished"/> </message> <message> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Petecoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source> <translation type="unfinished"/> </message> <message> <source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <source>(default: 1)</source> <translation type="unfinished"/> </message> <message> <source>(default: wallet.dat)</source> <translation type="unfinished"/> </message> <message> <source>&lt;category&gt; can be:</source> <translation>&lt;categoria&gt; puede ser:</translation> </message> <message> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <source>Petecoin Core Daemon</source> <translation type="unfinished"/> </message> <message> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <source>Clear list of wallet transactions (diagnostic tool; implies -rescan)</source> <translation type="unfinished"/> </message> <message> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <source>Connect through SOCKS proxy</source> <translation type="unfinished"/> </message> <message> <source>Connect to JSON-RPC on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation type="unfinished"/> </message> <message> <source>Connection options:</source> <translation type="unfinished"/> </message> <message> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <source>Debugging/Testing options:</source> <translation type="unfinished"/> </message> <message> <source>Disable safemode, override a real safe mode event (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <source>Do not load the wallet and disable wallet RPC calls</source> <translation type="unfinished"/> </message> <message> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <source>Fee per kB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <source>Fees smaller than this are considered zero fee (for relaying) (default:</source> <translation type="unfinished"/> </message> <message> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <source>Force safe mode (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <source>If &lt;category&gt; is not supplied, output all debugging information.</source> <translation type="unfinished"/> </message> <message> <source>Importing...</source> <translation type="unfinished"/> </message> <message> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation type="unfinished"/> </message> <message> <source>Invalid -onion address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <source>Prepend debug output with timestamp (default: 1)</source> <translation type="unfinished"/> </message> <message> <source>RPC client options:</source> <translation type="unfinished"/> </message> <message> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <source>Select SOCKS version for -proxy (4 or 5, default: 5)</source> <translation type="unfinished"/> </message> <message> <source>Set database cache size in megabytes (%d to %d, default: %d)</source> <translation type="unfinished"/> </message> <message> <source>Set maximum block size in bytes (default: %d)</source> <translation type="unfinished"/> </message> <message> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <source>Spend unconfirmed change when sending transactions (default: 1)</source> <translation type="unfinished"/> </message> <message> <source>This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <source>Usage (deprecated, use petecoin-cli):</source> <translation type="unfinished"/> </message> <message> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <source>Wait for RPC server to start</source> <translation type="unfinished"/> </message> <message> <source>Wallet %s resides outside data directory %s</source> <translation type="unfinished"/> </message> <message> <source>Wallet options:</source> <translation>Opciones de cartera:</translation> </message> <message> <source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source> <translation type="unfinished"/> </message> <message> <source>You need to rebuild the database using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <source>Cannot obtain a lock on data directory %s. Petecoin Core is probably already running.</source> <translation type="unfinished"/> </message> <message> <source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <source>Output debugging information (default: 0, supplying &lt;category&gt; is optional)</source> <translation type="unfinished"/> </message> <message> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source> <translation type="unfinished"/> </message> <message> <source>Information</source> <translation type="unfinished"/> </message> <message> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <source>Limit size of signature cache to &lt;n&gt; entries (default: 50000)</source> <translation type="unfinished"/> </message> <message> <source>Log transaction priority and fee per kB when mining blocks (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <source>Print block on startup, if found in block index</source> <translation type="unfinished"/> </message> <message> <source>Print block tree on startup (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <source>RPC server options:</source> <translation type="unfinished"/> </message> <message> <source>Randomly drop 1 of every &lt;n&gt; network messages</source> <translation type="unfinished"/> </message> <message> <source>Randomly fuzz 1 of every &lt;n&gt; network messages</source> <translation type="unfinished"/> </message> <message> <source>Run a thread to flush wallet periodically (default: 1)</source> <translation type="unfinished"/> </message> <message> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <source>Send command to Petecoin Core</source> <translation type="unfinished"/> </message> <message> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>Sets the DB_PRIVATE flag in the wallet db environment (default: 1)</source> <translation type="unfinished"/> </message> <message> <source>Show all debugging options (usage: --help -help-debug)</source> <translation type="unfinished"/> </message> <message> <source>Show benchmark information (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <source>Start Petecoin Core Daemon</source> <translation type="unfinished"/> </message> <message> <source>System error: </source> <translation type="unfinished"/> </message> <message> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <source>Warning</source> <translation type="unfinished"/> </message> <message> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <source>Zapping all transactions from wallet...</source> <translation type="unfinished"/> </message> <message> <source>on startup</source> <translation type="unfinished"/> </message> <message> <source>version</source> <translation>Versión</translation> </message> <message> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <source>This help message</source> <translation type="unfinished"/> </message> <message> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <source>Loading addresses...</source> <translation>Cargando direcciones...</translation> </message> <message> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <source>Error loading wallet.dat: Wallet requires newer version of Petecoin</source> <translation type="unfinished"/> </message> <message> <source>Wallet needed to be rewritten: restart Petecoin to complete</source> <translation type="unfinished"/> </message> <message> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <source>Loading block index...</source> <translation>Cargando indice de bloques... </translation> </message> <message> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <source>Loading wallet...</source> <translation>Cargando billetera...</translation> </message> <message> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <source>Rescanning...</source> <translation type="unfinished"/> </message> <message> <source>Done loading</source> <translation>Carga completa</translation> </message> <message> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <source>Error</source> <translation type="unfinished"/> </message> <message> <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 type="unfinished"/> </message> </context> </TS>
mit
sharadbhat/Video-Sharing-Platform
Server/static/js/upload.js
555
$(document).ready(function(){ $('form input').change(function () { var fullPath = this.value; if (fullPath) { var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/')); var filename = fullPath.substring(startIndex); if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) { filename = filename.substring(1); } } var res = filename.slice(0,-4); $('form p').text(filename); document.getElementById("title").value = res; }); });
mit
jtpaasch/armyguys
armyguys/jobs/availabilityzones.py
1576
# -*- coding: utf-8 -*- """Jobs for availability zones.""" from ..aws import availabilityzone from . import utils # Some zones are currently unavailable in AWS. # We want to ignore them. ZONE_BLACKLIST = ["us-east-1a"] def fetch_all(profile): """Fetch all availability zones. Args: profile A profile to connect to AWS with. Returns: A list of zones. """ params = {} params["profile"] = profile response = utils.do_request(availabilityzone, "get", params) data = utils.get_data("AvailabilityZones", response) return [x for x in data if x["ZoneName"] not in ZONE_BLACKLIST] def fetch_by_name(profile, name): """Fetch availability zones by name. Args: profile A profile to connect to AWS with. name The name of an availability zone. Returns: A list of zones with the specified name. """ params = {} params["profile"] = profile params["filters"] = [{"Name": "zone-name", "Values": [name]}] response = utils.do_request(availabilityzone, "get", params) data = utils.get_data("AvailabilityZones", response) return [x for x in data if x["ZoneName"] not in ZONE_BLACKLIST] def is_zone(profile, ref): """Check if an availability zone exists. Args: profile A profile to connect to AWS with. ref The name of an availability zone. Returns: True if it exists. False if not. """ records = fetch_by_name(profile, ref) return len(records) > 0
mit
greedo/Presentations
PyGotham2015/create_db.py
437
from sqlalchemy import create_engine, engine from sqlalchemy.ext.declarative import declarative_base from models import Pars, Spots, Base import passwords engine = create_engine('postgresql+psycopg2://'+passwords.PyGotham.username+':'+passwords.PyGotham.password+'@'+passwords.PyGotham.hostname+':5432/'+passwords.PyGotham.db, echo=True) #Base.metadata.tables['par'].create(bind=engine) Base.metadata.tables['spot'].create(bind=engine)
mit
mikesmitty/unixgroup
main.go
1568
package main import ( "fmt" "os" "os/user" "strconv" "strings" ) func main() { // Get our user and group list un := os.Getenv("USER") if un == "" { os.Exit(3) } gl := strings.Split(os.Getenv("GROUP"), ",") if len(gl) == 0 || gl[0] == "" { os.Exit(4) } // Get user struct, primary gid, and gid (string) array u, err := user.Lookup(un) if err != nil { os.Exit(2) } gid, err := strconv.ParseInt(u.Gid, 10, 64) if err != nil { os.Exit(2) } gs, err := u.GroupIds() if err != nil { os.Exit(2) } // Convert gid strings to gid ints var gids []int64 for _, v := range gs { g, err := strconv.ParseInt(v, 10, 64) if err == nil { gids = append(gids, g) } } // Check each of the supplied group names/gids for _, v := range gl { ggid, err := strconv.ParseInt(v, 10, 64) if err == nil { // Group is a gid if ggid == gid { // gid matches primary group os.Exit(0) } else { for _, v := range gids { if ggid == v { // gid matches secondary group os.Exit(0) } } } } else { // Group is a group name fmt.Printf("v: %s\n", v) g, err := user.LookupGroup(v) if err != nil { // Group is invalid continue } ggid, err := strconv.ParseInt(g.Gid, 10, 64) if err != nil { // Group doesn't exist or gid isn't numeric continue } if ggid == gid { // gid matches primary group os.Exit(0) } else { for _, v := range gids { if ggid == v { // gid matches secondary group os.Exit(0) } } } } } os.Exit(1) }
mit
kostyrin/SysAnalytics
SysAnalytics.Data/Conventions/TableNameConvention.cs
964
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FluentNHibernate.Conventions; using FluentNHibernate.Conventions.Instances; namespace SysAnalytics.Data.Conventions { public class TableNameConvention : IClassConvention { public void Apply(IClassInstance instance) { string typeName = instance.EntityType.Name; instance.Table(Inflector.Inflector.Pluralize(typeName).ToLower()); } private string ToSnakeCase(string name) { var result = new StringBuilder(name.Length); for (int i = 0; i < name.Length; i++) { if (i > 0 && char.IsUpper(name[i])) result.Append('_').Append(char.ToLower(name[i])); else result.Append(char.ToLower(name[i])); } return result.ToString(); } } }
mit
cggaurav/document-js
lib/class/class.js
2036
/* Simple JavaScript Inheritance * By John Resig http://ejohn.org/ * MIT Licensed. */ // Inspired by base2 and Prototype // SEE: http://ejohn.org/blog/simple-javascript-inheritance/ (function(){ var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/; // The base Class implementation (does nothing) this.Class = function(){}; // Create a new Class that inherits from this class Class.extend = function(prop) { var _super = this.prototype; // Instantiate a base class (but only create the instance, // don't run the init constructor) initializing = true; var prototype = new this(); initializing = false; // Copy the properties over onto the new prototype for (var name in prop) { // Check if we're overwriting an existing function prototype[name] = typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name]) ? (function(name, fn){ return function() { var tmp = this._super; // Add a new ._super() method that is the same method // but on the super-class this._super = _super[name]; // The method only need to be bound temporarily, so we // remove it when we're done executing var ret = fn.apply(this, arguments); this._super = tmp; return ret; }; })(name, prop[name]) : prop[name]; } // The dummy class constructor function Class() { // All construction is actually done in the init method if ( !initializing && this.init ) this.init.apply(this, arguments); } // Populate our constructed prototype object Class.prototype = prototype; // Enforce the constructor to be what we expect Class.prototype.constructor = Class; // And make this class extendable Class.extend = arguments.callee; return Class; }; })();
mit
PMenezes/RUReady
RUReady.project/RUReadyAPI/Controllers/AuthenticationController.cs
236
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace RUReadyAPI.Controllers { public class AuthenticationController { } }
mit
OpenSourcePolicyCenter/taxdata
history/report.py
12365
""" Script used to automatically generate PDF report comparing TaxData outputs after updates """ # flake8: noqa: E501 import argparse import pandas as pd import taxcalc as tc import altair as alt from report_utils import ( run_calc, distplot, write_page, growth_scatter_plot, compare_vars, cbo_bar_chart, agg_liability_table, compare_calcs, ) from pathlib import Path from datetime import datetime from collections import defaultdict from requests_html import HTMLSession CUR_PATH = Path(__file__).resolve().parent STAGE1_PATH = Path(CUR_PATH, "..", "puf_stage1") CBO_PATH = Path(STAGE1_PATH, "CBO_baseline.csv") SOI_PATH = Path(STAGE1_PATH, "SOI_estimates.csv") GROW_FACTORS_PATH = Path(STAGE1_PATH, "growfactors.csv") META_PATH = Path(CUR_PATH, "..", "tests", "records_metadata.json") CBO_URL = "https://raw.githubusercontent.com/PSLmodels/taxdata/master/puf_stage1/CBO_baseline.csv" SOI_URL = "https://raw.githubusercontent.com/PSLmodels/taxdata/master/puf_stage1/SOI_estimates.csv" META_URL = "https://raw.githubusercontent.com/PSLmodels/taxdata/master/tests/records_metadata.json" GROW_FACTORS_URL = "https://raw.githubusercontent.com/PSLmodels/taxdata/master/puf_stage1/growfactors.csv" PUF_PATH = Path(CUR_PATH, "..", "data", "puf.csv") PUF_AVAILABLE = PUF_PATH.exists() TEMPLATE_PATH = Path(CUR_PATH, "report_template.md") CBO_LABELS = { "GDP": "GDP (Billions)", "TPY": "Personal Income (Billions)", "Wages": "Wages and Salaries (Billions)", "SCHC": "Proprietors Income, Non Farm with IVA & CCAdj (Billions)", "SCHF": "Proprietors Income, Farm with IVA & CCAdj (Billions)", "INTS": "Personal Interest Income (Billions)", "DIVS": "Personal Dividend Income (Billions)", "RENTS": "Rental Income with CCADJ (Billions)", "BOOK": "Corporate Profits with IVA & CCADJ (Billions)", "CPIU": "Consumer Pricing Index, All Urban Consumers (CPI-U) - 1982-84=100", "CGNS": "Capital Gains Realizations", "RETS": "IRS Projections of Individual Returns (Millions)", "SOCSEC": "Scheduled Social Security Benefits", "CPIM": "CPI Medical Care", "UCOMP": "Unemployment Compensation (Billions)", } def report(): """ Generate TaxData history report """ parser = argparse.ArgumentParser() parser.add_argument( "prs", help=( "prs is a list of prs that were used for this report. " "Enter them as a string separated by commas" ), default="", type=str, ) parser.add_argument( "--desc", help=( "File path to a text or markdown file with additonal information " "that will appear at the beginning of the report" ), default="", type=str, ) parser.add_argument( "--basepuf", help=( "File path to the previous puf.csv file. Use when the proposed " "changes affect puf.csv" ), ) args = parser.parse_args() desc = args.desc base_puf_path = args.basepuf if desc: desc = Path(args.desc).open("r").read() plot_paths = [] date = datetime.today().date() template_args = {"date": date, "desc": desc} pull_str = "* [#{}: {}]({})" _prs = args.prs.split(",") session = HTMLSession() prs = [] for pr in _prs: url = f"https://github.com/PSLmodels/taxdata/pull/{pr}" # extract PR title r = session.get(url) elm = r.html.find("span.js-issue-title")[0] title = elm.text prs.append(pull_str.format(pr, title, url)) template_args["prs"] = prs # CBO projection comparisons cbo_projections = [] cur_cbo = pd.read_csv(CBO_URL, index_col=0) new_cbo = pd.read_csv(CBO_PATH, index_col=0) cbo_years = new_cbo.columns.astype(int) last_year = cbo_years.max() first_year = last_year - 9 if new_cbo.equals(cur_cbo): cbo_projections.append("No changes to CBO projections.") else: # we're only going to include the final ten years in our bar chart keep_years = [str(year) for year in range(first_year, last_year + 1)] cur_cbo = cur_cbo.filter(keep_years, axis=1).transpose().reset_index() cur_cbo["Projections"] = "Current" new_cbo = new_cbo.filter(keep_years, axis=1).transpose().reset_index() new_cbo["Projections"] = "New" cbo_data = pd.concat([cur_cbo, new_cbo], axis=0) for col in cbo_data.columns: if col == "index" or col == "Projections": continue chart = cbo_bar_chart(cbo_data, col, CBO_LABELS[col]) img_path = Path(CUR_PATH, f"{col}.png") chart.save(str(img_path)) plot_paths.append(img_path) cbo_projections.append(f"![]({str(img_path)})" + "{.center}") template_args["cbo_projections"] = cbo_projections # changes in data availability cur_meta = pd.read_json(META_URL, orient="index") new_meta = pd.read_json(META_PATH, orient="index") puf_added, puf_removed = compare_vars(cur_meta, new_meta, "puf") cps_added, cps_removed = compare_vars(cur_meta, new_meta, "cps") template_args["puf_added"] = puf_added template_args["puf_removed"] = puf_removed template_args["cps_added"] = cps_added template_args["cps_removed"] = cps_removed # growth rate changes growth_rate_projections = [] cur_grow = pd.read_csv(GROW_FACTORS_URL) new_grow = pd.read_csv(GROW_FACTORS_PATH) if new_grow.equals(cur_grow): growth_rate_projections.append("No changes to growth rate projections") else: new_grow = new_grow[ (new_grow["YEAR"] >= first_year) & (new_grow["YEAR"] <= last_year) ] cur_grow = cur_grow[ (cur_grow["YEAR"] >= first_year) & (cur_grow["YEAR"] <= last_year) ] new_grow["Growth Factors"] = "New" cur_grow["Growth Factors"] = "Current" growth_data = pd.concat([new_grow, cur_grow]) rows = list(growth_data.columns) rows.remove("YEAR"), rows.remove("Growth Factors") n = len(rows) // 3 chart1 = growth_scatter_plot(growth_data, rows[:n]) img_path = Path(CUR_PATH, "growth_factors1.png") chart1.save(str(img_path)) plot_paths.append(img_path) growth_rate_projections.append(f"![]({str(img_path)})" + "{.center}") chart2 = growth_scatter_plot(growth_data, rows[n : 2 * n]) img_path = Path(CUR_PATH, "growth_factors2.png") chart2.save(str(img_path)) plot_paths.append(img_path) growth_rate_projections.append(f"![]({str(img_path)})" + "{.center}") chart3 = growth_scatter_plot(growth_data, rows[2 * n :]) img_path = Path(CUR_PATH, "growth_factors3.png") chart3.save(str(img_path)) plot_paths.append(img_path) growth_rate_projections.append(f"![]({str(img_path)})" + "{.center}") template_args["growth_rate_projections"] = growth_rate_projections # compare tax calculator projections # baseline CPS calculator base_cps = tc.Calculator(records=tc.Records.cps_constructor(), policy=tc.Policy()) base_cps.advance_to_year(first_year) base_cps.calc_all() # updated CPS calculator cps = pd.read_csv(Path(CUR_PATH, "..", "data", "cps.csv.gz"), index_col=None) cps_weights = pd.read_csv( Path(CUR_PATH, "..", "cps_stage2", "cps_weights.csv.gz"), index_col=None ) new_cps = tc.Calculator( records=tc.Records( data=cps, weights=cps_weights, adjust_ratios=None, start_year=2014 ), policy=tc.Policy(), ) new_cps.advance_to_year(first_year) new_cps.calc_all() template_args, plot_paths = compare_calcs( base_cps, new_cps, "cps", template_args, plot_paths ) # PUF comparison if base_puf_path and PUF_AVAILABLE: template_args["puf_msg"] = None # base puf calculator base_puf = tc.Calculator( records=tc.Records(data=base_puf_path), policy=tc.Policy() ) base_puf.advance_to_year(first_year) base_puf.calc_all() # updated puf calculator puf_weights = pd.read_csv( Path(CUR_PATH, "..", "puf_stage2", "puf_weights.csv.gz"), index_col=None ) puf_ratios = pd.read_csv( Path(CUR_PATH, "..", "puf_stage3", "puf_ratios.csv"), index_col=0 ).transpose() new_records = tc.Records( data=str(PUF_PATH), weights=puf_weights, adjust_ratios=puf_ratios ) new_puf = tc.Calculator(records=new_records, policy=tc.Policy()) new_puf.advance_to_year(first_year) new_puf.calc_all() template_args, plot_paths = compare_calcs( base_puf, new_puf, "puf", template_args, plot_paths ) else: msg = "PUF comparisons are not included in this report." template_args["puf_msg"] = msg template_args["puf_agg_plot"] = None template_args["puf_combined_table"] = None template_args["puf_income_table"] = None template_args["puf_payroll_table"] = None # # distribution plots # dist_vars = [ # ("c00100", "AGI Distribution"), # ("combined", "Tax Liability Distribution"), # ] # dist_plots = [] # for var, title in dist_vars: # plot = distplot(calcs, calc_labels, var, title=title) # img_path = Path(CUR_PATH, f"{var}_dist.png") # plot.save(str(img_path)) # plot_paths.append(img_path) # dist_plots.append(f"![]({str(img_path)})" + "{.center}") # template_args["cps_dist_plots"] = dist_plots # # aggregate totals # aggs = defaultdict(list) # var_list = ["payrolltax", "iitax", "combined", "standard", "c04470"] # for year in range(first_year, tc.Policy.LAST_BUDGET_YEAR + 1): # base_aggs = run_calc(base_cps, year, var_list) # new_aggs = run_calc(new_cps, year, var_list) # aggs["Tax Liability"].append(base_aggs["payrolltax"]) # aggs["Tax"].append("Current Payroll") # aggs["Year"].append(year) # aggs["Tax Liability"].append(new_aggs["payrolltax"]) # aggs["Tax"].append("New Payroll") # aggs["Year"].append(year) # aggs["Tax Liability"].append(base_aggs["iitax"]) # aggs["Tax"].append("Current Income") # aggs["Year"].append(year) # aggs["Tax Liability"].append(new_aggs["iitax"]) # aggs["Tax"].append("New Income") # aggs["Year"].append(year) # aggs["Tax Liability"].append(base_aggs["combined"]) # aggs["Tax"].append("Current Combined") # aggs["Year"].append(year) # aggs["Tax Liability"].append(new_aggs["combined"]) # aggs["Tax"].append("New Combined") # aggs["Year"].append(year) # agg_df = pd.DataFrame(aggs) # title = "Aggregate Tax Liability by Year" # agg_chart = ( # alt.Chart(agg_df, title=title) # .mark_line() # .encode( # x=alt.X( # "Year:O", # axis=alt.Axis(labelAngle=0, titleFontSize=20, labelFontSize=15), # ), # y=alt.Y( # "Tax Liability", # title="Tax Liability (Billions)", # axis=alt.Axis(titleFontSize=20, labelFontSize=15), # ), # color=alt.Color( # "Tax", # legend=alt.Legend(symbolSize=150, labelFontSize=15, titleFontSize=20), # ), # ) # .properties(width=800, height=350) # .configure_title(fontSize=24) # ) # img_path = Path(CUR_PATH, "agg_plot.png") # agg_chart.save(str(img_path)) # plot_paths.append(img_path) # template_args["agg_plot"] = f"![]({str(img_path)})" + "{.center}" # # create tax liability tables # template_args["combined_table"] = agg_liability_table(agg_df, "Combined") # template_args["payroll_table"] = agg_liability_table(agg_df, "Payroll") # template_args["income_table"] = agg_liability_table(agg_df, "Income") # write report and delete images used output_path = Path(CUR_PATH, "reports", f"taxdata_report_{date}.pdf") write_page(output_path, TEMPLATE_PATH, **template_args) for path in plot_paths: path.unlink() if __name__ == "__main__": report()
mit
wolny/keras-image-net
src/vgg16.py
467
from keras.applications.vgg16 import VGG16 from keras.preprocessing import image from keras.applications.vgg16 import preprocess_input, decode_predictions import numpy as np model = VGG16(weights='imagenet') img_path = 'data/german_shepard.jpg' img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) print('Predicted:', decode_predictions(preds, top=5)[0])
mit
marthlab/pipeline_builder
public/js/util/bam.iobio.js
19719
// extending Thomas Down's original BAM js work function Bam (bamUri, options) { if (!(this instanceof arguments.callee)) { throw new Error("Constructor may not be called as a function"); } this.bamUri = bamUri; this.options = options; // *** add options mapper *** // test if file or url if (typeof(this.bamUri) == "object") { this.sourceType = "file"; this.bamBlob = new BlobFetchable(bamUri); // *** add if statement if here *** this.baiBlob = new BlobFetchable(this.options.bai); this.promises = []; this.bam = undefined; var me = this; makeBam(this.bamBlob, this.baiBlob, function(bam) { me.setHeader(bam.header); me.provide(bam); }); } else if ( this.bamUri.slice(0,4) == "http" ) { this.sourceType = "url"; } // set iobio servers this.iobio = {} this.iobio.bamtools = "ws://bamtools.iobio.io"; this.iobio.samtools = "ws://samtools.iobio.io"; this.iobio.bamReadDepther = "ws://bamReadDepther.iobio.io"; this.iobio.bamMerger = "ws://bammerger.iobio.io"; this.iobio.bamstatsAlive = "ws://bamstatsalive.iobio.io" return this; } _.extend(Bam.prototype,{ fetch: function( name, start, end, callback, options ) { var me = this; // handle bam has been created yet if(this.bam == undefined) // **** TEST FOR BAD BAM *** this.promise( function() {me.fetch(name, start, end, callback, options);}); else this.bam.fetch( name, start, end, callback, options ); }, promise: function( callback ) { this.promises.push( callback ); }, provide: function(bam) { this.bam = bam; while( this.promises.length != 0 ) this.promises.shift()(); }, _makeid: function() { // make unique string id; var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for( var i=0; i < 5; i++ ) text += possible.charAt(Math.floor(Math.random() * possible.length)); return text; }, _getBamUrl: function(name, start, end) { return this._getBamRegionsUrl([ {'name':name,'start':start,'end':end} ]); }, _getBamRegionsUrl: function(regions) { if ( this.sourceType == "url") { var regionStr = ""; regions.forEach( function(region) { if (region.start) { regionStr += " " + region.name + ":" + region.start + "-" + region.end; } else { console.log("ERROR, undefined region start", region); } }); var url = this.iobio.samtools + "?cmd= view -b " + this.bamUri + regionStr + "&encoding=binary"; } else { // creates a url for a new bam that is sliced from an old bam // // open connection to iobio webservice that will request this // data, since connections can only be opened from browser var me = this; var connectionID = this._makeid(); var client = BinaryClient(this.iobio.samtools + '?id=', {'connectionID' : connectionID}); client.on('open', function(stream){ var stream = client.createStream( {event:'setID', 'connectionID':connectionID}); stream.end(); }); var url = this.iobio.samtools + "?protocol=websocket&encoding=binary&cmd=view -S -b " + encodeURIComponent("http://client?&id="+connectionID); var ended = 0; var me = this; // send data to samtools when it asks for it client.on('stream', function(stream, options) { stream.write(me.header.toStr); regions.forEach( function(region){ me.convert( 'sam', region.name, region.start, region.end, function(data,e) { stream.write(data); ended += 1; if (ended == regions.length) stream.end(); }, {noHeader:true}); }) }) } return encodeURI(url); }, _generateExomeBed: function(id) { var bed = ""; var readDepth = this.readDepth[id]; var start, end; var sum =0; // for (var i=0; i < readDepth.length; i++){ // sum += readDepth[i].depth; // } // console.log("avg = " + parseInt(sum / readDepth.length)); // merge contiguous blocks into a single block and convert to bed format for( var i=0; i < readDepth.length; i++){ if (readDepth[i].depth < 20) { if (start != undefined) bed += id + "\t" + start + "\t" + end + "\t.\t.\t.\t.\t.\t.\t.\t.\t.\n" start = undefined; } else { if (start == undefined) start = readDepth[i].pos; end = readDepth[i].pos + 16384; } } // add final record if data stopped on non-zero if (start != undefined) bed += id + "\t" + start + "\t" + end + "\t.\t.\t.\t.\t.\t.\t.\t.\t.\n" return bed; }, _mapToBedCoordinates: function(ref, regions, bed) { var a = this._bedToCoordinateArray(ref, bed); var a_i = 0; var bedRegions = []; if (a.length == 0) { alert("Bed file doesn't have coordinates for reference: " + regions[0].name + ". Sampling normally"); return null; } regions.forEach(function(reg){ for (a_i; a_i < a.length; a_i++) { if (a[a_i].end > reg.end) break; if (a[a_i].start >= reg.start) bedRegions.push( {name:reg.name, start:a[a_i].start, end:a[a_i].end}) } }) return bedRegions }, _bedToCoordinateArray: function(ref, bed) { var a = []; bed.split("\n").forEach(function(line){ if (line[0] == '#' || line == "") return; var fields = line.split("\t"); if (fields[0] == ref) a.push({ chr:fields[0], start:parseInt(fields[1]), end:parseInt(fields[2]) }); }); return a; }, _getClosestValueIndex: function(a, x) { var lo = -1, hi = a.length; while (hi - lo > 1) { var mid = Math.round((lo + hi)/2); if (a[mid].start <= x) { lo = mid; } else { hi = mid; } } if (lo == -1 ) return 0; if ( a[lo].end > x ) return lo; else return hi; }, getReferencesWithReads: function(callback) { var refs = []; var me = this; if (this.sourceType == 'url') { } else { this.getHeader(function(header) { for (var i=0; i < header.sq.length; i++) { if ( me.bam.indices[me.bam.chrToIndex[header.sq[i].name]] != undefined ) refs.push( header.sq[i] ); } callback(refs); }) } }, // *** bamtools functionality *** convert: function(format, name, start, end, callback, options) { // Converts between BAM and a number of other formats if (!format || !name || !start || !end) return "Error: must supply format, sequenceid, start nucleotide and end nucleotide" if (format.toLowerCase() != "sam") return "Error: format + " + options.format + " is not supported" var me = this; this.fetch(name, start, end, function(data,e) { if(options && options.noHeader) callback(data, e); else { me.getHeader(function(h) { callback(h.toStr + data, e); }) } }, { 'format': format }) }, estimateBaiReadDepth: function(callback) { var me = this, readDepth = {}; me.readDepth = {}; function cb() { if (me.header) { for (var id in readDepth) { if (readDepth.hasOwnProperty(id)) var name = me.header.sq[parseInt(id)].name; if ( me.readDepth[ name ] == undefined){ me.readDepth[ name ] = readDepth[id]; callback( name, readDepth[id] ); } } } } me.getHeader(function(header) { if (Object.keys(me.readDepth).length > 0) cb(); }); if ( Object.keys(me.readDepth).length > 0 ) callback(me.readDepth) else if (me.sourceType == 'url') { var client = BinaryClient(me.iobio.bamReadDepther); var url = encodeURI( me.iobio.bamReadDepther + '?cmd=-i ' + me.bamUri + ".bai"); client.on('open', function(stream){ var stream = client.createStream({event:'run', params : {'url':url}}); var currentSequence; stream.on('data', function(data, options) { data = data.split("\n"); for (var i=0; i < data.length; i++) { if ( data[i][0] == '#' ) { if ( Object.keys(readDepth).length > 0 ) { cb() }; currentSequence = data[i].substr(1); readDepth[currentSequence] = []; } else { if (data[i] != "") { var d = data[i].split("\t"); readDepth[currentSequence].push({ pos:parseInt(d[0]), depth:parseInt(d[1]) }); } } } }); stream.on('end', function() { cb(); }); }); } else if (me.sourceType == 'file') { me.baiBlob.fetch(function(header){ if (!header) { return dlog("Couldn't access BAI"); } var uncba = new Uint8Array(header); var baiMagic = readInt(uncba, 0); if (baiMagic != BAI_MAGIC) { return dlog('Not a BAI file'); } var nref = readInt(uncba, 4); bam.indices = []; var p = 8; for (var ref = 0; ref < nref; ++ref) { var bins = []; var blockStart = p; var nbin = readInt(uncba, p); p += 4; if (nbin > 0) readDepth[ref] = []; for (var b = 0; b < nbin; ++b) { var bin = readInt(uncba, p); var nchnk = readInt(uncba, p+4); p += 8; // p += 8 + (nchnk * 16); var byteCount = 0; for (var c=0; c < nchnk; ++c) { var startBlockAddress = readVob(uncba, p); var endBlockAddress = readVob(uncba, p+8); p += 16; byteCount += (endBlockAddress.block - startBlockAddress.block); } if ( bin >= 4681 && bin <= 37449) { var position = (bin - 4681) * 16384; readDepth[ref][bin-4681] = {pos:position, depth:byteCount}; // readDepth[ref].push({pos:position, depth:byteCount}); //bins[bin - 4681] = byteCount; } } var nintv = readInt(uncba, p); p += 4; p += (nintv * 8); if (nbin > 0) { for (var i=0 ; i < readDepth[ref].length; i++) { if(readDepth[ref][i] == undefined) readDepth[ref][i] = {pos : (i+1)*16000, depth:0}; } } } cb(); }); } }, getHeader: function(callback) { var me = this; if (me.header) callback(me.header); else if (me.sourceType == 'file') me.promise(function() { me.getHeader(callback); }) else { var client = BinaryClient(me.iobio.samtools); var url = encodeURI( me.iobio.samtools + '?cmd=view -H ' + this.bamUri); client.on('open', function(stream){ var stream = client.createStream({event:'run', params: {'url':url}}); var rawHeader = "" stream.on('data', function(data, options) { rawHeader += data; }); stream.on('end', function() { me.setHeader(rawHeader); callback( me.header); }); }); } // need to make this work for URL bams // need to incorporate real promise framework throughout }, setHeader: function(headerStr) { var header = { sq:[], toStr : headerStr }; var lines = headerStr.split("\n"); for ( var i=0; i<lines.length > 0; i++) { var fields = lines[i].split("\t"); if (fields[0] == "@SQ") { var name = fields[1].split("SN:")[1]; var length = parseInt(fields[2].split("LN:")[1]); header.sq.push({name:name, end:1+length}); } } this.header = header; }, stats: function(name, start, end, callback) { // Prints some basic statistics from input BAM file(s) var client = BinaryClient(this.iobio.bamstatsAlive); var url = encodeURI(this.iobio.bamstatsAlive + '?cmd=-u 1000 -s ' + start + " -l " + parseInt(end-start) + " " + encodeURIComponent(this._getBamUrl(name,start,end))); client.on('open', function(stream){ var stream = client.createStream({event:'run', params : {'url':url}}); var buffer = ""; stream.on('data', function(data, options) { if (data == undefined) return; var success = true; try { var obj = JSON.parse(buffer + data) } catch(e) { success = false; buffer += data; } if(success) { buffer = ""; callback(obj); } }); }); }, samplingRegions: function (SQs, options) { options = $.extend({ binSize : 40000, // defaults binNumber : 20, start : 1, },options); var me = this; var regions = []; var bedRegions; for (var j=0; j < SQs.length; j++) { var sqStart = options.start; var length = SQs[j].end - sqStart; if ( length < options.binSize * options.binNumber) { regions.push(SQs[j]) } else { // create random reference coordinates //var regions = []; // WTF is the deal here!??! for (var i=0; i < options.binNumber; i++) { var s=sqStart + parseInt(Math.random()*length); if (s) { regions.push({ name: SQs[j].name, start: s, end: s+options.binSize}); } else { console.log("ERROR: region start s undefined", i, s, sqStart, SQs[j].name); }; } // sort by start value regions = regions.sort(function(a,b) { var x = a.start; var y = b.start; return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }); // intelligently determine exome bed coordinates if (options.exomeSampling) options.bed = me._generateExomeBed(options.sequenceNames[0]); // map random region coordinates to bed coordinates if (options.bed != undefined) bedRegions = me._mapToBedCoordinates(SQs[0].name, regions, options.bed) } } return {regions: regions, bedRegions: bedRegions, regStr: JSON.stringify((bedRegions || regions).map( function(d){return {start:d.start,end:d.end,chr:d.name};})) }; }, bamStatsAliveSamplingURL: function (SQs, options) { var me = this; var regionInfo = me.samplingRegions(SQs, options); var regions = regionInfo.regions; var regStr = regionInfo.regStr; // var url = encodeURI( me.iobio.bamstatsAlive + '?cmd=-u // 30000 -f 2000 -r \'' + regStr + '\' ' + // encodeURIComponent(me._getBamRegionsUrl(regions))); return encodeURI(me.iobio.bamstatsAlive + '?cmd=-u 3000 -r \'' + regStr + '\' ' + encodeURIComponent(me._getBamRegionsUrl(regions))); }, sampleStats: function(callback, options) { // Prints some basic statistics from sampled input BAM file(s) options = $.extend({ binSize : 40000, // defaults binNumber : 20, start : 1, },options); var me = this; function goSampling(SQs) { var buffer = ""; var client = BinaryClient(me.iobio.bamstatsAlive); var url = me.bamStatsAliveSamplingURL(SQs, options); client.on( 'open', function(){ var stream = client.createStream( {event:'run', params: {'url':url}}); stream.on('data', function(data) { if (data == undefined) return; var success = true; try { var obj = JSON.parse(buffer + data) } catch(e) { console.log("ERROR", e); success = false; buffer += data; } if(success) { me.bufdata = buffer + data; buffer = ""; callback(obj); } }); stream.on('end', function() { if (options.onEnd != undefined) options.onEnd(); }); }); } if ( options.sequenceNames != undefined && options.end != undefined) { var sqs = options.sequenceNames.map( function(d) { return {name:d, end:options.end}}); goSampling(sqs); } else if (options.sequenceNames != undefined){ this.getHeader(function(header){ var sq = []; $(header.sq).each( function(i,d) { if(options.sequenceNames.indexOf(d.name) != -1) sq.push( d ); }) goSampling(sq); }); } else { this.getHeader(function(header){ var sqs = header.sq; if (options.end != undefined) var sqs = options.sequenceNames.map( function(d) { return {name:d, end:options.end}}); goSampling(sqs); }); // this.getReferencesWithReads(function(refs) { // goSampling(refs); // }) } } });
mit
OscarCid/DumphineAndOrsen
asset/src/WoT/WoT.js
15687
/** * Created by Orsen on 06-03-2016. */ var APIKEY = "6be59cbefdddc1454074718eb3434a96"; var all_logros = []; $(document).ready(function(){ $('#search').click(function() { $("#text_event").text("Buscando ID"); if ($('#nickname').val() != '') { var nickname = $('#nickname').val(); $('.cargando').show(); buscarID(nickname); } else { $("#text_event").text("no se ingreso una ID"); alert("Ingrese un Nickname Porfavor"); } }); }); function buscarID(nickname) { $.ajax({ url: 'https://api.worldoftanks.com/wot/account/list/?application_id='+ APIKEY +'&language=es&search=' + nickname, type: 'GET', dataType: 'json', data: {}, success: function (json) { if (json.status =="error" || json.meta.count == "0") { alert("El usuario ingresado no existe, porfavor intente nuevamente"); $('.cargando').hide(); } else { id = json.data[0].account_id; document.getElementById("acc_id").innerHTML = "Account ID: "+ id; info_user(id); logros_user(id); player_vehiculos(id); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("Problemas al obtener la id del jugador"); } }); } function info_user(ID) { $.ajax({ url: 'https://api.worldoftanks.com/wot/account/info/?application_id='+ APIKEY +'&account_id=' + ID, type: 'GET', dataType: 'json', data: {}, success: function (json) { $("#text_event").text("Cargando Resumen del Usuario"); created_at = json.data[ID].created_at; last_battle_time = json.data[ID].last_battle_time; wins = json.data[ID].statistics["all"].wins; losses = json.data[ID].statistics["all"].losses; batallas = json.data[ID].statistics["all"].battles; battle_exp_avg = json.data[ID].statistics["all"].battle_avg_xp; max_xp = json.data[ID].statistics["all"].max_xp; hits = json.data[ID].statistics["all"].hits; draws = json.data[ID].statistics["all"].draws; survived_battles = json.data[ID].statistics["all"].survived_battles; shots = json.data[ID].statistics["all"].shots; max_frags = json.data[ID].statistics["all"].max_frags; damage_dealt = json.data[ID].statistics["all"].damage_dealt; xp = json.data[ID].statistics["all"].xp; frags = json.data[ID].statistics["all"].frags; spotted = json.data[ID].statistics["all"].spotted; max_damage = json.data[ID].statistics["all"].max_damage; shots_fail = shots - hits; battle_avg_dmg = (damage_dealt / batallas).toFixed(0); var f_creada = new Date( created_at *1000); var f_ultimaBatalla = new Date( last_battle_time *1000); var meses = new Array ("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"); var diasSemana = new Array("Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado"); fecha_creada = diasSemana[f_creada.getDay()] + ", " + f_creada.getDate() + " de " + meses[f_creada.getMonth()] + " del " + f_creada.getFullYear(); ultima_batalla = diasSemana[f_ultimaBatalla.getDay()] + ", " + f_ultimaBatalla.getDate() + " de " + meses[f_ultimaBatalla.getMonth()] + " del " + f_ultimaBatalla.getFullYear() + " " + f_ultimaBatalla.getHours() + ":" + f_ultimaBatalla.getMinutes(); document.getElementById("fechas").innerHTML = "Creada: " + fecha_creada + " Ultima Batalla: " + ultima_batalla; max_xp_format = formatNumber(max_xp); batallas_format = formatNumber(batallas); victorias_format = formatNumber(wins); derrotas_format = formatNumber(losses); empates_format = formatNumber(draws); bSobrevividas_format = formatNumber(survived_battles); xp_format = formatNumber(xp); frags_format = formatNumber(frags); spotted_format = formatNumber(spotted); shots_format = formatNumber(shots); hits_format = formatNumber(hits); shots_fail_format = formatNumber(shots_fail); damage_dealt_format = formatNumber(damage_dealt); max_damage_format = formatNumber(max_damage); percent_hits = (hits*100)/ shots; percent_hits = percent_hits.toFixed(2); percent_shots_fail = (shots_fail*100)/ shots; percent_shots_fail = percent_shots_fail.toFixed(2); percent_wins = (wins*100)/ batallas; percent_wins = percent_wins.toFixed(2); percent_losses = (losses*100)/ batallas; percent_losses = percent_losses.toFixed(2); percent_draws = (draws*100)/ batallas; percent_draws = percent_draws.toFixed(2); percent_BAxp = (battle_exp_avg*100)/ xp; percent_BAxp = percent_BAxp.toFixed(2); percent_BMxp = (max_xp*100)/ xp; percent_BMxp = percent_BMxp.toFixed(2); percent_BAdmg = (battle_avg_dmg*100)/ damage_dealt; percent_BAdmg = percent_BAdmg.toFixed(2); percent_max_damage = (max_damage*100)/ damage_dealt; percent_max_damage = percent_max_damage.toFixed(2); percent_survived_battles = (survived_battles*100)/ batallas; percent_survived_battles = percent_survived_battles.toFixed(2); // codigo para la tab resumen document.getElementById("batallas").innerHTML = batallas_format; document.getElementById("percent_wins").innerHTML = percent_wins+"%"; document.getElementById("battle_exp_avg").innerHTML = battle_exp_avg; document.getElementById("max_xp").innerHTML = max_xp_format; document.getElementById("percent_hits").innerHTML = percent_hits+"%"; document.getElementById("max_frags").innerHTML = max_frags; document.getElementById("battle_avg_dmg").innerHTML = battle_avg_dmg; // codigo para la tab estadisticas document.getElementById("batallas2").innerHTML = batallas_format; document.getElementById("percent_wins2").innerHTML = percent_wins+"%"; document.getElementById("battle_avg_dmg2").innerHTML = battle_avg_dmg; //tabla Resultados Generales document.getElementById("batallas-table1").innerHTML = batallas_format; document.getElementById("victorias-table1").innerHTML = percent_wins+"%"; document.getElementById("victorias-table2").innerHTML = victorias_format; document.getElementById("derrotas-table1").innerHTML = percent_losses+"%"; document.getElementById("derrotas-table2").innerHTML = derrotas_format; document.getElementById("empates-table1").innerHTML = percent_draws+"%"; document.getElementById("empates-table2").innerHTML = empates_format; document.getElementById("bSobrevividas-table1").innerHTML = percent_survived_battles+"%"; document.getElementById("bSobrevividas-table2").innerHTML = bSobrevividas_format; document.getElementById("xp-table1").innerHTML = xp_format; document.getElementById("BAxp-table1").innerHTML = percent_BAxp+"%"; document.getElementById("BAxp-table2").innerHTML = battle_exp_avg; document.getElementById("BMxp-table1").innerHTML = percent_BMxp+"%"; document.getElementById("BMxp-table2").innerHTML = max_xp_format; //tabla Rendimiento de Batalla document.getElementById("frags-table1").innerHTML = frags_format; document.getElementById("spotted-table1").innerHTML = spotted_format; document.getElementById("shots-table1").innerHTML = shots_format; document.getElementById("hits-table1").innerHTML = percent_hits+"%"; document.getElementById("hits-table2").innerHTML = hits_format; document.getElementById("shots_fail-table1").innerHTML = percent_shots_fail+"%"; document.getElementById("shots_fail-table2").innerHTML = shots_fail_format; document.getElementById("damage-table1").innerHTML = damage_dealt_format; document.getElementById("BAdmg-table1").innerHTML = percent_BAdmg+"%"; document.getElementById("BAdmg-table2").innerHTML = battle_avg_dmg; document.getElementById("max_damage-table1").innerHTML = percent_max_damage+"%"; document.getElementById("max_damage-table2").innerHTML = max_damage_format; }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("Problemas al obtener el resumen del jugador!"); } }); } function logros_user(ID) { $( ".logro").addClass( "opaco" ); $( ".b-achivements_wrpr" ).remove(); $( ".logro_resumen" ).remove(); $("#text_event").text("Cargando Logros del usuario"); $.ajax({ url: 'https://api.worldoftanks.com/wot/account/achievements/?application_id='+ APIKEY +'&language=es&account_id=' + ID, type: 'GET', dataType: 'json', data: {}, success: function (json) { var contador = 0; for (var logros in json.data[ID].achievements) { if ($("."+logros).hasClass('class') != true) { if (json.data[ID].achievements[logros] > 1) { if (contador <= 6) { $( ".fondo_rojo" ).append ( "<div class='b-achivements_item logro_resumen opaco "+all_logros.data[logros].name+"'>" + "<img class='centrar' src='"+all_logros.data[logros].image+"'>" + "</div>" ); contador++; } $( "."+logros ).removeClass( "opaco" ); $( "."+logros ).append ( "<div class='b-achivements_wrpr'>" + "<span class='b-achivements_num'>" + "<span>"+json.data[ID].achievements[logros]+"</span>" + "</span>" + "</div>" ); } else { $( "."+logros ).removeClass( "opaco" ); if (contador <= 6) { $( ".fondo_rojo" ).append ( "<div class='b-achivements_item logro_resumen "+all_logros.data[logros].name+"'>" + "<img class='centrar' src='"+all_logros.data[logros].image+"'>" + "</div>" ); contador++; } } } else { $( "."+logros ).removeClass( "opaco" ); $('#'+logros).attr('src',"http://api.worldoftanks.com/static/2.36.2/wot/encyclopedia/achievement/"+logros+json.data[ID].achievements[logros]+".png"); } } //end for ocultar_div(); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("Problemas al obtener los logros del jugador!"); } }); } function logros() { $.ajax({ url: 'https://api.worldoftanks.com/wot/encyclopedia/achievements/?application_id='+ APIKEY +'&language=es', type: 'GET', dataType: 'json', data: {}, success: function (json) { all_logros = json; $("#text_event").text("Cargando Logros Valiosos del usuario"); for (var logros in json.data) { if (json.data[logros].image != null) { //linea para colocar la imagen $( "#"+json.data[logros].section ) .append( "<div class='col-md-1 col-sm-2 col-xs-3 logro opaco "+json.data[logros].name+"'>" + "<img class='centrar' src='"+json.data[logros].image+"'>" + "</div>"); //monton de mierda para el tooltipo $('.'+json.data[logros].name).tipso({ speed : 100, titleBackground : 'url(http://static-ptl-us.gcdn.co/static/3.35.4/wotp_static/img/core/frontend/scss/common/components/tooltip/img/tooltip_bg.jpg)', color : '#979899', width : 300, maxWidth : '500', size : 'default', background : 'url(http://static-ptl-us.gcdn.co/static/3.35.4/wotp_static/img/core/frontend/scss/common/components/tooltip/img/tooltip_bg.jpg)' }); jQuery('.'+json.data[logros].name).tipso('update', 'titleContent', json.data[logros].name_i18n); jQuery('.'+json.data[logros].name).tipso('update', 'content', json.data[logros].description); } else { if (json.data[logros].name != "markOfMastery") { if (json.data[logros].name != "marksOnGun") { // AQUI FALTA CONTINUAR CON LOS ULTIMOS LOGROOOOOOOSSS (PONER IMAGENES EN CASO DE QUE NO SE MODIFIQUEN EN TIER IV)!!!! $( "#"+json.data[logros].section ).append("<div class='col-md-1 col-sm-2 col-xs-3 logro opaco "+json.data[logros].name+" "+json.data[logros].section+"'><img id='"+json.data[logros].name+"' src='"+json.data[logros].options["3"].image+"'></div>"); } } } } //end for }, //end json success error: function (XMLHttpRequest, textStatus, errorThrown) { alert("Problemas al obtener todos los logros"); } }); } function player_vehiculos(ID) { $.ajax({ url: 'https://api.worldoftanks.com/wot/account/tanks/?application_id=' + APIKEY + '&account_id=' + ID, type: 'GET', dataType: 'json', data: {}, success: function (json) { }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("Problemas al obtener Informacion de los vehiculos"); } }); } function ocultar_div() { $('.cargando').hide(); } function formatNumber(num) { return ("" + num).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, function($1) { return $1 + "." }); } //cosas paja ejecutar cuando carga la web $(window).load(function () { // Una vez se cargue al completo la página desaparecerá el div "cargando" logros(); $('.cargando').hide(); });
mit
garmoshka-mo/neo4j
lib/neo4j/active_node/validations.rb
1740
module Neo4j module ActiveNode # This mixin replace the original save method and performs validation before the save. module Validations extend ActiveSupport::Concern include Neo4j::Shared::Validations # @return [Boolean] true if valid def valid?(context = nil) context ||= (new_record? ? :create : :update) super(context) errors.empty? end module ClassMethods def validates_uniqueness_of(*attr_names) validates_with UniquenessValidator, _merge_attributes(attr_names) end end class UniquenessValidator < ::ActiveModel::EachValidator def initialize(options) super(options.reverse_merge(case_sensitive: true)) end def validate_each(record, attribute, value) return unless found(record, attribute, value).exists? record.errors.add(attribute, :taken, options.except(:case_sensitive, :scope).merge(value: value)) end def found(record, attribute, value) conditions = scope_conditions(record) value = '' if value.nil? conditions[attribute] = options[:case_sensitive] ? value : /^#{Regexp.escape(value.to_s)}$/i found = record.class.as(:result).where(conditions) found = found.where('ID(result) <> {record_neo_id}').params(record_neo_id: record.neo_id) if record.persisted? found end def message(instance) super || 'has already been taken' end def scope_conditions(instance) Array(options[:scope] || []).inject({}) do |conditions, key| conditions.merge(key => instance[key]) end end end end end end
mit
jValdron/portfolio
controllers/api/articles.js
1124
/** * articles.js * Returns the dynamic elements of the articles in JSON. * * @author Jason Valdron <[email protected]> * @package di-api */ (function() { 'use strict'; var async = require('async'); // Export the route function. module.exports = function(app){ var cache = { data: {}, lastHit: null }; // GET /api/articles - Responds with the articles in JSON format. app.get('/api/articles', function(req, res){ var Article = app.db.models.article; var validCacheTime = (new Date()).getTime() - (30 * 60 * 1000); // Use use a 30 minutes cache. // Let's see if we have to grab our data back or we can use our cache. if (cache.lastHit && cache.lastHit.getTime() > validCacheTime) { return res.status(200).json(cache.data); } else { // Get all of our articles. Article.all({}, function(err, articles){ cache.data = articles; cache.lastHit = new Date(); return res.status(200).json(articles); }); } }); }; })();
mit
EFLFE/Psybot
Psybot/Program.cs
1467
using System; using System.IO; using System.Reflection; using System.Threading; using Psybot.Modules; using Psybot.UI; namespace Psybot { public static class Program { public const string VERSION = "0.3.0"; private static PsybotCore core; public static void Main(string[] args) { Console.WriteLine("Psybot v" + VERSION + " Loading..."); Console.Title = "Psybot v" + VERSION; AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; try { core = new PsybotCore(); core.Run(); Term.Stop(); } catch (Exception ex) { Term.Stop(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Psybot destroyed!"); Console.WriteLine(ex.ToString()); Console.ForegroundColor = ConsoleColor.Gray; Console.ReadLine(); } Thread.Sleep(333); Console.WriteLine("\nterminated"); Console.ForegroundColor = ConsoleColor.Gray; //Console.ReadLine(); } private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { var dllFileName = args.Name.Remove(args.Name.IndexOf(',')) + ".dll"; var dllPah = Path.Combine(Environment.CurrentDirectory, ModuleManager.DEFAULT_MODULE_PATH, dllFileName); core.SendLog("Resolve: " + dllFileName, ConsoleColor.Yellow); if (File.Exists(dllPah)) return Assembly.Load(File.ReadAllBytes(dllPah)); else core.SendLog("Assembly not found", ConsoleColor.Red); return null; } } }
mit
EndangeredMassa/boxes
lib/ansi.js
923
// Generated by CoffeeScript 2.0.0-beta8 void function () { var clearFrom, Parser; Parser = require('../vendor/ansi_parse'); clearFrom = function (history, position) { var lastLine, lines; lines = history.split('\n'); lastLine = lines.pop(); lastLine = lastLine.substr(0, position); lines.push(lastLine); return lines.join('\n'); }; module.exports = { parse: function (history, data) { var parser; parser = new Parser; parser.on('command', function (character, params, intermediate) { var param1; param1 = params[0]; switch (character) { case 'H': return history = ''; case 'J': return history = clearFrom(history, param1); } }); parser.on('data', function (newData) { return history += newData; }); parser.parse(data); return history; } }; }.call(this);
mit
nilsding/twittbot
lib/twittbot.rb
75
require "twittbot/defaults" # Twittbot default module module Twittbot end
mit
madbadPi/RecipeBook
src/Web/RecipeBook.Web/wwwroot/js/imageFileSelector.js
1015
class ImageFileSelector { constructor(elementId, handleImageSelected, handleError) { this.elementId = elementId; this.handleImageSelected = handleImageSelected; this.handleError = handleError; } startListen() { let fileSelector = document.getElementById(this.elementId); fileSelector?.addEventListener('change', (event) => { const fileList = event.target?.files; if (fileList && fileList.length == 1 && fileList[0][Const.FILE_MEDIA_TYPE_KEY].split('/')[0] === Const.FILE_IMAGE_TYPE_KEY) { let reader = new FileReader(); reader.onload = (event) => { this.handleImageSelected(reader.result); }; reader.readAsDataURL(fileList[0]); } else { this.handleError(ImageFileSelector.ERROR_MSG); } }); } } ImageFileSelector.ERROR_MSG = "Error loading file"; //# sourceMappingURL=imageFileSelector.js.map
mit
PawelBor/Year-4-Offer
Android/app/src/main/java/com/ioffer/gediminas/ioffer_android/RegisterActivity.java
2169
package com.ioffer.gediminas.ioffer_android; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Base64; import android.util.Log; import android.view.View; import android.widget.TextView; import android.widget.Toast; import org.json.JSONException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class RegisterActivity extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); } public void register(View view)throws NoSuchAlgorithmException,JSONException,java.io.IOException{ TextView name_txt = (TextView)findViewById(R.id.name); TextView email_txt = (TextView)findViewById(R.id.email); TextView password_txt = (TextView)findViewById(R.id.password); String name = name_txt.getText().toString(); String email = email_txt.getText().toString().replaceAll("\\s+",""); String password = sha256(password_txt.getText().toString()); RequestService rs = new RequestService(); boolean isInserted = rs.postUser(name,email,password); if(!isInserted) Toast.makeText(RegisterActivity.this, "Client exists", Toast.LENGTH_SHORT).show(); else{ Intent myIntent = new Intent(RegisterActivity.this, LoginActivity.class); startActivity(myIntent); } } public static String sha256(String base) { try{ MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(base.getBytes("UTF-8")); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String hex = Integer.toHexString(0xff & hash[i]); if(hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } catch(Exception ex){ throw new RuntimeException(ex); } } }
mit
Azure/azure-sdk-for-go
services/preview/sql/mgmt/v4.0/sql/manageddatabaserestoredetails.go
5048
package sql // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/tracing" "net/http" ) // ManagedDatabaseRestoreDetailsClient is the the Azure SQL Database management API provides a RESTful set of web // services that interact with Azure SQL Database services to manage your databases. The API enables you to create, // retrieve, update, and delete databases. type ManagedDatabaseRestoreDetailsClient struct { BaseClient } // NewManagedDatabaseRestoreDetailsClient creates an instance of the ManagedDatabaseRestoreDetailsClient client. func NewManagedDatabaseRestoreDetailsClient(subscriptionID string) ManagedDatabaseRestoreDetailsClient { return NewManagedDatabaseRestoreDetailsClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewManagedDatabaseRestoreDetailsClientWithBaseURI creates an instance of the ManagedDatabaseRestoreDetailsClient // client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI // (sovereign clouds, Azure stack). func NewManagedDatabaseRestoreDetailsClientWithBaseURI(baseURI string, subscriptionID string) ManagedDatabaseRestoreDetailsClient { return ManagedDatabaseRestoreDetailsClient{NewWithBaseURI(baseURI, subscriptionID)} } // Get gets managed database restore details. // Parameters: // resourceGroupName - the name of the resource group that contains the resource. You can obtain this value // from the Azure Resource Manager API or the portal. // managedInstanceName - the name of the managed instance. // databaseName - the name of the database. func (client ManagedDatabaseRestoreDetailsClient) Get(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string) (result ManagedDatabaseRestoreDetailsResult, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ManagedDatabaseRestoreDetailsClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.GetPreparer(ctx, resourceGroupName, managedInstanceName, databaseName) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseRestoreDetailsClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseRestoreDetailsClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseRestoreDetailsClient", "Get", resp, "Failure responding to request") return } return } // GetPreparer prepares the Get request. func (client ManagedDatabaseRestoreDetailsClient) GetPreparer(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "databaseName": autorest.Encode("path", databaseName), "managedInstanceName": autorest.Encode("path", managedInstanceName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "restoreDetailsName": autorest.Encode("path", "Default"), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2020-02-02-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/restoreDetails/{restoreDetailsName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client ManagedDatabaseRestoreDetailsClient) GetSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client ManagedDatabaseRestoreDetailsClient) GetResponder(resp *http.Response) (result ManagedDatabaseRestoreDetailsResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
mit
fgrid/iso20022
FailingReason11Choice.go
593
package iso20022 // Choice of format for the failing reason. type FailingReason11Choice struct { // Specifies the reason why the instruction has a failing settlement status. Code *FailingReason2Code `xml:"Cd"` // Specifies the reason why the instruction has a failing settlement status. Proprietary *GenericIdentification47 `xml:"Prtry"` } func (f *FailingReason11Choice) SetCode(value string) { f.Code = (*FailingReason2Code)(&value) } func (f *FailingReason11Choice) AddProprietary() *GenericIdentification47 { f.Proprietary = new(GenericIdentification47) return f.Proprietary }
mit
jmcguire/learning
algorithms/searching/binary_search.py
945
# binary search # # divide and conquer # best time: O(1) # average time: O(logn) # worst time: O(logn) # # required a list of sorted elements # look at the half-way mark, compare to e, move up or down, repeat def binary_search(A, e, start=0, end=None): if end is None: end = len(A)-1 middle = (start + end) // 2 check = A[middle] #print " start %d, end %d, middle %d (%s), prev_middle %s" % (start, end, middle, str(check), str(prev_middle)) # check for failure if start > end: return False if e == check: return middle elif e > check: return binary_search(A, e, middle+1, end) elif e < check: return binary_search(A, e, start, middle-1) # testing def test(A, e): print "looking for", e position = binary_search(A, e) if position is not False: print " -> found item at", position else: print " -> did not find item" A = range(1,100) for e in xrange (0,101): test(A, e)
mit
n3vrax/dot-api
src/Dot/ContentNegotiation/src/Factory/ContentTypeFilterMiddlewareFactory.php
896
<?php /** * @see https://github.com/dotkernel/dot-api/ for the canonical source repository * @copyright Copyright (c) 2017 Apidemia (https://www.apidemia.com) * @license https://github.com/dotkernel/dot-api/blob/master/LICENSE.md MIT License */ namespace Dot\ContentNegotiation\Factory; use Dot\ContentNegotiation\ContentNegotiationOptions; use Dot\ContentNegotiation\Middleware\ContentTypeFilterMiddleware; use Psr\Container\ContainerInterface; /** * Class ContentTypeFilterMiddlewareFactory * @package Dot\ContentNegotiation\Factory */ class ContentTypeFilterMiddlewareFactory { /** * @param ContainerInterface $container * @return ContentTypeFilterMiddleware */ public function __invoke(ContainerInterface $container) { $options = $container->get(ContentNegotiationOptions::class); return new ContentTypeFilterMiddleware($options); } }
mit
Mirobit/bitcoin
src/policy/policy.cpp
9748
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // NOTE: This file is intended to be customised by the end user, and includes only local node policy logic #include "policy/policy.h" #include "validation.h" #include "coins.h" #include "tinyformat.h" #include "util.h" #include "utilstrencodings.h" #include <boost/foreach.hpp> CAmount GetDustThreshold(const CTxOut& txout, const CFeeRate& dustRelayFeeIn) { // "Dust" is defined in terms of dustRelayFee, // which has units satoshis-per-kilobyte. // If you'd pay more than 1/3 in fees // to spend something, then we consider it dust. // A typical spendable non-segwit txout is 34 bytes big, and will // need a CTxIn of at least 148 bytes to spend: // so dust is a spendable txout less than // 546*dustRelayFee/1000 (in satoshis). // A typical spendable segwit txout is 31 bytes big, and will // need a CTxIn of at least 67 bytes to spend: // so dust is a spendable txout less than // 294*dustRelayFee/1000 (in satoshis). if (txout.scriptPubKey.IsUnspendable()) return 0; size_t nSize = GetSerializeSize(txout, SER_DISK, 0); int witnessversion = 0; std::vector<unsigned char> witnessprogram; if (txout.scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) { // sum the sizes of the parts of a transaction input // with 75% segwit discount applied to the script size. nSize += (32 + 4 + 1 + (107 / WITNESS_SCALE_FACTOR) + 4); } else { nSize += (32 + 4 + 1 + 107 + 4); // the 148 mentioned above } return 3 * dustRelayFeeIn.GetFee(nSize); } bool IsDust(const CTxOut& txout, const CFeeRate& dustRelayFeeIn) { return (txout.nValue < GetDustThreshold(txout, dustRelayFeeIn)); } /** * Check transaction inputs to mitigate two * potential denial-of-service attacks: * * 1. scriptSigs with extra data stuffed into them, * not consumed by scriptPubKey (or P2SH script) * 2. P2SH scripts with a crazy number of expensive * CHECKSIG/CHECKMULTISIG operations * * Why bother? To avoid denial-of-service attacks; an attacker * can submit a standard HASH... OP_EQUAL transaction, * which will get accepted into blocks. The redemption * script can be anything; an attacker could use a very * expensive-to-check-upon-redemption script like: * DUP CHECKSIG DROP ... repeated 100 times... OP_1 */ bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType, const bool witnessEnabled) { std::vector<std::vector<unsigned char> > vSolutions; if (!Solver(scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_MULTISIG) { unsigned char m = vSolutions.front()[0]; unsigned char n = vSolutions.back()[0]; // Support up to x-of-3 multisig txns as standard if (n < 1 || n > 3) return false; if (m < 1 || m > n) return false; } else if (whichType == TX_NULL_DATA && (!fAcceptDatacarrier || scriptPubKey.size() > nMaxDatacarrierBytes)) return false; else if (!witnessEnabled && (whichType == TX_WITNESS_V0_KEYHASH || whichType == TX_WITNESS_V0_SCRIPTHASH)) return false; return whichType != TX_NONSTANDARD; } bool IsStandardTx(const CTransaction& tx, std::string& reason, const bool witnessEnabled) { if (tx.nVersion > CTransaction::MAX_STANDARD_VERSION || tx.nVersion < 1) { reason = "version"; return false; } // Extremely large transactions with lots of inputs can cost the network // almost as much to process as they cost the sender in fees, because // computing signature hashes is O(ninputs*txsize). Limiting transactions // to MAX_STANDARD_TX_WEIGHT mitigates CPU exhaustion attacks. unsigned int sz = GetTransactionWeight(tx); if (sz >= MAX_STANDARD_TX_WEIGHT) { reason = "tx-size"; return false; } BOOST_FOREACH(const CTxIn& txin, tx.vin) { // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed // keys (remember the 520 byte limit on redeemScript size). That works // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627 // bytes of scriptSig, which we round off to 1650 bytes for some minor // future-proofing. That's also enough to spend a 20-of-20 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not // considered standard. if (txin.scriptSig.size() > 1650) { reason = "scriptsig-size"; return false; } if (!txin.scriptSig.IsPushOnly()) { reason = "scriptsig-not-pushonly"; return false; } } unsigned int nDataOut = 0; txnouttype whichType; BOOST_FOREACH(const CTxOut& txout, tx.vout) { if (!::IsStandard(txout.scriptPubKey, whichType, witnessEnabled)) { reason = "scriptpubkey"; return false; } if (whichType == TX_NULL_DATA) nDataOut++; else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) { reason = "bare-multisig"; return false; } else if (IsDust(txout, ::dustRelayFee)) { reason = "dust"; return false; } } // only one OP_RETURN txout is permitted if (nDataOut > 1) { reason = "multi-op-return"; return false; } return true; } bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs) { if (tx.IsCoinBase()) return true; // Coinbases don't use vin normally for (unsigned int i = 0; i < tx.vin.size(); i++) { const CTxOut& prev = mapInputs.AccessCoin(tx.vin[i].prevout).out; std::vector<std::vector<unsigned char> > vSolutions; txnouttype whichType; // get the scriptPubKey corresponding to this input: const CScript& prevScript = prev.scriptPubKey; if (!Solver(prevScript, whichType, vSolutions)) return false; if (whichType == TX_SCRIPTHASH) { std::vector<std::vector<unsigned char> > stack; // convert the scriptSig into a stack, so we can inspect the redeemScript if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SIGVERSION_BASE)) return false; if (stack.empty()) return false; CScript subscript(stack.back().begin(), stack.back().end()); if (subscript.GetSigOpCount(true) > MAX_P2SH_SIGOPS) { return false; } } } return true; } bool IsWitnessStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs) { if (tx.IsCoinBase()) return true; // Coinbases are skipped for (unsigned int i = 0; i < tx.vin.size(); i++) { // We don't care if witness for this input is empty, since it must not be bloated. // If the script is invalid without witness, it would be caught sooner or later during validation. if (tx.vin[i].scriptWitness.IsNull()) continue; const CTxOut &prev = mapInputs.AccessCoin(tx.vin[i].prevout).out; // get the scriptPubKey corresponding to this input: CScript prevScript = prev.scriptPubKey; if (prevScript.IsPayToScriptHash()) { std::vector <std::vector<unsigned char> > stack; // If the scriptPubKey is P2SH, we try to extract the redeemScript casually by converting the scriptSig // into a stack. We do not check IsPushOnly nor compare the hash as these will be done later anyway. // If the check fails at this stage, we know that this txid must be a bad one. if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SIGVERSION_BASE)) return false; if (stack.empty()) return false; prevScript = CScript(stack.back().begin(), stack.back().end()); } int witnessversion = 0; std::vector<unsigned char> witnessprogram; // Non-witness program must not be associated with any witness if (!prevScript.IsWitnessProgram(witnessversion, witnessprogram)) return false; // Check P2WSH standard limits if (witnessversion == 0 && witnessprogram.size() == 32) { if (tx.vin[i].scriptWitness.stack.back().size() > MAX_STANDARD_P2WSH_SCRIPT_SIZE) return false; size_t sizeWitnessStack = tx.vin[i].scriptWitness.stack.size() - 1; if (sizeWitnessStack > MAX_STANDARD_P2WSH_STACK_ITEMS) return false; for (unsigned int j = 0; j < sizeWitnessStack; j++) { if (tx.vin[i].scriptWitness.stack[j].size() > MAX_STANDARD_P2WSH_STACK_ITEM_SIZE) return false; } } } return true; } CFeeRate incrementalRelayFee = CFeeRate(DEFAULT_INCREMENTAL_RELAY_FEE); CFeeRate dustRelayFee = CFeeRate(DUST_RELAY_TX_FEE); unsigned int nBytesPerSigOp = DEFAULT_BYTES_PER_SIGOP; int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost) { return (std::max(nWeight, nSigOpCost * nBytesPerSigOp) + WITNESS_SCALE_FACTOR - 1) / WITNESS_SCALE_FACTOR; } int64_t GetVirtualTransactionSize(const CTransaction& tx, int64_t nSigOpCost) { return GetVirtualTransactionSize(GetTransactionWeight(tx), nSigOpCost); }
mit