code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
# Namespace for library module P3 module TV # Settings for P3 TV class Settings attr_accessor :path DEFAULT_PATH = File::expand_path( "~/.p3tv/p3tv" ) EPISODES_JSON = 'episodes.json' DEFAULTS = { :library_path => '~/Movies/P3TV', :download_path => '~/Downloads', :delete_duplicate_downloads => false, :overwrite_duplicates => false, :allowed_types => ['.avi', '.mkv', '.mp4'], :language => 'en', :subtitles => ['.srt'], :high_def => true, :verbose => false, :dry_run => false, :series => [] } def self.exists?( path = DEFAULT_PATH ) File::exist?( path ) end def self.create_default!( path = DEFAULT_PATH ) raise "a settings file already exists. please delete #{path} first" if exists?( path ) FileUtils::mkdir_p( File::dirname( path ) ) settings = Settings.new( path ) DEFAULTS.each do | key, value | settings[ key ] = value end settings.save! end def self.set!( key, value, path = DEFAULT_PATH ) settings = Settings.new( path ) settings[ key ] = value settings.save! end def initialize( path = DEFAULT_PATH ) @path = path @values = {} @episodes = {} return unless File::exists?( @path ) FileUtils::mkdir_p( File::dirname( @path ) ) f = File::open( @path, 'r' ) @values = JSON.parse(f.read, symbolize_names: true) f.close self[:library_path] = File::expand_path( self[:library_path ] ) FileUtils::mkdir_p( self[:library_path] ) self[:download_path] = File::expand_path( self[:download_path ] ) self[:series].uniq! if( self[:overwrite_duplicates] and self[:delete_duplicate_downloads] ) raise "you cannot have 'overwrite_duplicates' and 'delete_duplicate_downloads' both set to true" end end def to_h @values end def []( key ) @values[ key.to_sym ] end def []=( key, value ) @values[ key.to_sym ] = value self.save! end def supported_paths_in_dir(dir = self[:download_path]) glob = File.join(dir, '**/*') all_file_paths = Dir.glob(glob) all_file_paths.select do |file_path| supported_file_extension?(file_path) end end def supported_file_extension?(path) return ( self[:allowed_types].include?( File::extname( path ) ) or self[:allowed_types].include?( File::extname( path ) ) ) end def get_series( seriesid ) return self[:series].detect{|s| s[:id] == seriesid } end def download_url!( url, path ) # http://stackoverflow.com/questions/2515931/how-can-i-download-a-file-from-a-url-and-save-it-in-rails return path if File::exists?( path ) begin download = open( url ) IO.copy_stream( download, path ) rescue => e return "" end return path end def download_banners!( banners, path ) FileUtils::mkdir_p( File::dirname( path ) ) return if banners.empty? banner = banners.detect{|b| b.url.length } return "" unless banner return download_url!( banner.url, path ) end def episodes( seriesid ) unless @episodes.has_key?( seriesid ) episode_file = File::join( series_dir( seriesid ), EPISODES_JSON ) if( File::exists?( episode_file ) ) f = File::open( episode_file ) @episodes[ seriesid ] = JSON::parse( f.read, :symbolize_names => true ) end end return @episodes[ seriesid ] end def each_series_episode_file_status( seriesid, search, downloads, library ) today = Date::today.to_s series_hash = self[:series].detect{|s| s[:id] == seriesid} return unless series_hash episodes( seriesid ).each do | episode_hash | next if episode_hash[:season_number] == 0 ep_file = P3::TV::EpisodeFile.new ep_file.series_id = episode_hash[:id] ep_file.series = series_hash[:name] ep_file.season = episode_hash[:season_number] ep_file.episode = episode_hash[:number] ep_file.title = episode_hash[:name] ep_file.air_date = episode_hash[:air_date] ep_file.thumbnail = episode_hash[:thumb_path] if( ( ep_file.air_date == nil ) or ( ep_file.air_date > today ) ) ep_file.percent_done = 0 ep_file.status = :upcoming ep_file.path = '' elsif( library.exists?( ep_file ) ) ep_file.percent_done = 1 ep_file.status = :cataloged ep_file.path = library.episode_path( ep_file ) elsif( download_path = downloads.get_path_if_exists( ep_file ) ) ep_file.percent_done = 1 ep_file.status = :downloaded ep_file.path = download_path elsif( torrent = downloads.get_torrent_if_exists( ep_file ) ) ep_file.percent_done = torrent['percentDone'] ep_file.status = :downloading ep_file.path = '' elsif( magnet_link = search.get_magnet_link_if_exists( ep_file ) ) ep_file.percent_done = 0 ep_file.status = :available ep_file.path = magnet_link else ep_file.percent_done = 0 ep_file.status = :missing ep_file.path = '' end yield( ep_file ) end end def series_dir( seriesid ) return File::join( File::dirname( @path ), 'series', seriesid ) end def download_episodes!( series ) meta_path = series_dir( series.id ) episodes = [] series.episodes.each do |episode| episode_hash = episode.to_h episode_hash[:thumb_path] = download_url!( episode_hash[:thumb], File::join( meta_path, "#{episode.id}.jpg" ) ) episodes << episode_hash end f = File::open( File::join( meta_path, EPISODES_JSON ), 'w' ) f.puts JSON::pretty_generate( episodes ) f.close() @episodes.delete( series.id ) #clear the cache end def add_series!( series ) meta_path = series_dir( series.id ) hash = series.to_h hash[:banners] = {} hash[:banners][:poster] = download_banners!(series.posters( self[:language] ), File::join( meta_path, 'poster.jpg' ) ) hash[:banners][:banner] = download_banners!( series.series_banners( self[:language] ), File::join( meta_path, 'banner.jpg' ) ) download_episodes!( series ) remove_series!( hash[:id] ) self[:series] << hash leading_the = /^The / self[:series].sort!{|a,b| a[:name].gsub(leading_the,'') <=> b[:name].gsub(leading_the,'') } self.save! end def update_series!( series ) return unless series.status == "Continuing" ep = self.episodes( series.id ) return unless( ep ) ep.select!{|e| e[:air_date] } ep.sort!{|a,b| b[:air_date] <=> a[:air_date] } #newest episode first today = Date::today.to_s if( ep.empty? or ( ep[0][:air_date] < today ) ) download_episodes!( series ) end end def remove_series!( seriesid ) self[:series].reject!{|s| s[:id] == seriesid } self.save! end def save! f = File::open( @path, 'w' ) f.puts( JSON::pretty_generate( @values ) ) f.close end end end end
poulh/tvtime
lib/p3-tv/settings.rb
Ruby
mit
7,815
import * as React from 'react'; function CubeIcon(props) { return ( <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" {...props} > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" /> </svg> ); } export default CubeIcon;
dreamyguy/gitinsight
frontend/src/components/primitives/Icon/Cube.js
JavaScript
mit
442
# module Hello class Identity < ActiveRecord::Base module Password extend ActiveSupport::Concern included do validates_presence_of :email, :password, if: :is_password? # email validates_email_format_of :email, if: :is_password? validates_uniqueness_of :email, message: 'already exists', if: :is_password? puts "username should be unique too".on_red # password validates_length_of :password, in: 4..200, too_long: 'pick a longer password', too_short: 'pick a shorter password', if: :is_password? end def is_password? strategy.to_s.inquiry.password? end module ClassMethods def encrypt(unencrypted_string) Digest::MD5.hexdigest(unencrypted_string) end end def should_reset_token? token_digested_at.blank? || token_digested_at < 7.days.ago end def reset_token uuid = SecureRandom.hex(8) # probability = 1 / (16 ** 16) digest = self.class.encrypt(uuid) update(token_digest: digest, token_digested_at: 1.second.ago) return uuid end def invalidate_token update(token_digest: nil, token_digested_at: nil) end private end end # end
stulzer/hello
app/models/concerns/identity/password.rb
Ruby
mit
1,455
var repl = require('repl'); var server = repl.start({}); var con = server.context; con.name='zfpx'; con.age = 5; con.grow = function(){ return ++con.age; }
liushaohua/node-demo
part01/repl.js
JavaScript
mit
160
// // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved // LICENSE: Atomic Game Engine Editor and Tools EULA // Please see LICENSE_ATOMIC_EDITOR_AND_TOOLS.md in repository root for // license information: https://github.com/AtomicGameEngine/AtomicGameEngine // #include <Atomic/Core/ProcessUtils.h> #include <Atomic/IO/Log.h> #include <Atomic/IO/FileSystem.h> #include <Atomic/Engine/Engine.h> #include <Atomic/Resource/ResourceCache.h> #include <ToolCore/ToolSystem.h> #include <ToolCore/ToolEnvironment.h> #include <ToolCore/Build/BuildSystem.h> #include <ToolCore/License/LicenseEvents.h> #include <ToolCore/License/LicenseSystem.h> #include <ToolCore/Command/Command.h> #include <ToolCore/Command/CommandParser.h> #include "AtomicTool.h" DEFINE_APPLICATION_MAIN(AtomicTool::AtomicTool); using namespace ToolCore; namespace AtomicTool { AtomicTool::AtomicTool(Context* context) : Application(context), deactivate_(false) { } AtomicTool::~AtomicTool() { } void AtomicTool::Setup() { const Vector<String>& arguments = GetArguments(); for (unsigned i = 0; i < arguments.Size(); ++i) { if (arguments[i].Length() > 1) { String argument = arguments[i].ToLower(); String value = i + 1 < arguments.Size() ? arguments[i + 1] : String::EMPTY; if (argument == "--cli-data-path") { if (!value.Length()) ErrorExit("Unable to parse --cli-data-path"); cliDataPath_ = AddTrailingSlash(value); } else if (argument == "--activate") { if (!value.Length()) ErrorExit("Unable to parse --activation product key"); activationKey_ = value; } else if (argument == "--deactivate") { deactivate_ = true; } } } engineParameters_["Headless"] = true; engineParameters_["LogLevel"] = LOG_INFO; // no default resources (will be initialized later) engineParameters_["ResourcePaths"] = ""; } void AtomicTool::HandleCommandFinished(StringHash eventType, VariantMap& eventData) { GetSubsystem<Engine>()->Exit(); } void AtomicTool::HandleCommandError(StringHash eventType, VariantMap& eventData) { String error = "Command Error"; const String& message = eventData[CommandError::P_MESSAGE].ToString(); if (message.Length()) error = message; ErrorExit(error); } void AtomicTool::HandleLicenseEulaRequired(StringHash eventType, VariantMap& eventData) { ErrorExit("\nActivation Required: Please run: atomic-cli activate\n"); } void AtomicTool::HandleLicenseActivationRequired(StringHash eventType, VariantMap& eventData) { ErrorExit("\nActivation Required: Please run: atomic-cli activate\n"); } void AtomicTool::HandleLicenseSuccess(StringHash eventType, VariantMap& eventData) { if (command_.Null()) { GetSubsystem<Engine>()->Exit(); return; } command_->Run(); } void AtomicTool::HandleLicenseError(StringHash eventType, VariantMap& eventData) { ErrorExit("\nActivation Required: Please run: atomic-cli activate\n"); } void AtomicTool::HandleLicenseActivationError(StringHash eventType, VariantMap& eventData) { String message = eventData[LicenseActivationError::P_MESSAGE].ToString(); ErrorExit(message); } void AtomicTool::HandleLicenseActivationSuccess(StringHash eventType, VariantMap& eventData) { LOGRAW("\nActivation successful, thank you!\n\n"); GetSubsystem<Engine>()->Exit(); } void AtomicTool::DoActivation() { LicenseSystem* licenseSystem = GetSubsystem<LicenseSystem>(); if (!licenseSystem->ValidateKey(activationKey_)) { ErrorExit(ToString("\nProduct key \"%s\" is invalid, keys are in the form ATOMIC-XXXX-XXXX-XXXX-XXXX\n", activationKey_.CString())); return; } licenseSystem->LicenseAgreementConfirmed(); SubscribeToEvent(E_LICENSE_ACTIVATIONERROR, HANDLER(AtomicTool, HandleLicenseActivationError)); SubscribeToEvent(E_LICENSE_ACTIVATIONSUCCESS, HANDLER(AtomicTool, HandleLicenseActivationSuccess)); licenseSystem->RequestServerActivation(activationKey_); } void AtomicTool::HandleLicenseDeactivationError(StringHash eventType, VariantMap& eventData) { String message = eventData[LicenseDeactivationError::P_MESSAGE].ToString(); ErrorExit(message); } void AtomicTool::HandleLicenseDeactivationSuccess(StringHash eventType, VariantMap& eventData) { LOGRAW("\nDeactivation successful\n\n"); GetSubsystem<Engine>()->Exit(); } void AtomicTool::DoDeactivation() { LicenseSystem* licenseSystem = GetSubsystem<LicenseSystem>(); if (!licenseSystem->LoadLicense()) { ErrorExit("\nNot activated"); return; } if (!licenseSystem->Deactivate()) { ErrorExit("\nNot activated\n"); return; } SubscribeToEvent(E_LICENSE_DEACTIVATIONERROR, HANDLER(AtomicTool, HandleLicenseDeactivationError)); SubscribeToEvent(E_LICENSE_DEACTIVATIONSUCCESS, HANDLER(AtomicTool, HandleLicenseDeactivationSuccess)); } void AtomicTool::Start() { // Subscribe to events SubscribeToEvent(E_COMMANDERROR, HANDLER(AtomicTool, HandleCommandError)); SubscribeToEvent(E_COMMANDFINISHED, HANDLER(AtomicTool, HandleCommandFinished)); SubscribeToEvent(E_LICENSE_EULAREQUIRED, HANDLER(AtomicTool, HandleLicenseEulaRequired)); SubscribeToEvent(E_LICENSE_ACTIVATIONREQUIRED, HANDLER(AtomicTool, HandleLicenseActivationRequired)); SubscribeToEvent(E_LICENSE_ERROR, HANDLER(AtomicTool, HandleLicenseError)); SubscribeToEvent(E_LICENSE_SUCCESS, HANDLER(AtomicTool, HandleLicenseSuccess)); const Vector<String>& arguments = GetArguments(); ToolSystem* tsystem = new ToolSystem(context_); context_->RegisterSubsystem(tsystem); ToolEnvironment* env = new ToolEnvironment(context_); context_->RegisterSubsystem(env); //#ifdef ATOMIC_DEV_BUILD if (!env->InitFromJSON()) { ErrorExit(ToString("Unable to initialize tool environment from %s", env->GetDevConfigFilename().CString())); return; } if (!cliDataPath_.Length()) { cliDataPath_ = env->GetRootSourceDir() + "/Resources/"; } //#endif ResourceCache* cache = GetSubsystem<ResourceCache>(); cache->AddResourceDir(env->GetCoreDataDir()); cache->AddResourceDir(env->GetPlayerDataDir()); tsystem->SetCLI(); tsystem->SetDataPath(cliDataPath_); if (activationKey_.Length()) { DoActivation(); return; } else if (deactivate_) { DoDeactivation(); return; } BuildSystem* buildSystem = GetSubsystem<BuildSystem>(); SharedPtr<CommandParser> parser(new CommandParser(context_)); SharedPtr<Command> cmd(parser->Parse(arguments)); if (!cmd) { String error = "No command found"; if (parser->GetErrorMessage().Length()) error = parser->GetErrorMessage(); ErrorExit(error); return; } if (cmd->RequiresProjectLoad()) { FileSystem* fileSystem = GetSubsystem<FileSystem>(); String projectDirectory = fileSystem->GetCurrentDir(); Vector<String> projectFiles; fileSystem->ScanDir(projectFiles, projectDirectory, "*.atomic", SCAN_FILES, false); if (!projectFiles.Size()) { ErrorExit(ToString("No .atomic project file in %s", projectDirectory.CString())); return; } else if (projectFiles.Size() > 1) { ErrorExit(ToString("Multiple .atomic project files found in %s", projectDirectory.CString())); return; } String projectFile = projectDirectory + "/" + projectFiles[0]; if (!tsystem->LoadProject(projectFile)) { //ErrorExit(ToString("Failed to load project: %s", projectFile.CString())); //return; } // Set the build path String buildFolder = projectDirectory + "/" + "Build"; buildSystem->SetBuildPath(buildFolder); if (!fileSystem->DirExists(buildFolder)) { fileSystem->CreateDir(buildFolder); if (!fileSystem->DirExists(buildFolder)) { ErrorExit(ToString("Failed to create build folder: %s", buildFolder.CString())); return; } } } command_ = cmd; // BEGIN LICENSE MANAGEMENT if (cmd->RequiresLicenseValidation()) { GetSubsystem<LicenseSystem>()->Initialize(); } else { if (command_.Null()) { GetSubsystem<Engine>()->Exit(); return; } command_->Run(); } // END LICENSE MANAGEMENT } void AtomicTool::Stop() { } void AtomicTool::ErrorExit(const String& message) { engine_->Exit(); // Close the rendering window exitCode_ = EXIT_FAILURE; // Only for WIN32, otherwise the error messages would be double posted on Mac OS X and Linux platforms if (!message.Length()) { #ifdef WIN32 Atomic::ErrorExit(startupErrors_.Length() ? startupErrors_ : "Application has been terminated due to unexpected error.", exitCode_); #endif } else Atomic::ErrorExit(message, exitCode_); } }
nonconforme/AtomicGameEngine
Source/AtomicTool/AtomicTool.cpp
C++
mit
9,385
/* * boatWithSupport.cpp * * Created on: 16 de Abr de 2013 * Author: Windows */ #include "BoatWithSupport.h" BoatWithSupport::BoatWithSupport(int extraCapacity) : Boat() { extraCap = extraCapacity; lastMaxCap = 0; lastTransported = 0; } BoatWithSupport::BoatWithSupport(int capacity, int extraCapacity) : Boat(capacity) { extraCap = extraCapacity; lastMaxCap = 0; lastTransported = 0; } int BoatWithSupport::getExtraCapacity() { return extraCap; } int BoatWithSupport::getMaxCapacity() { return this->maxCapacity + this->extraCap; } BoatWithSupport::~BoatWithSupport() { // TODO Auto-generated destructor stub } void BoatWithSupport::reset() { this->transportedQuantity = lastTransported; this->maxCapacity = lastMaxCap; } void BoatWithSupport::resize() { this->lastMaxCap = this->maxCapacity; this->maxCapacity = this->extraCap; lastTransported = this->transportedQuantity; this->transportedQuantity = this->extraCap; }
jnadal/CAL
Projecto 1/codigo/source/BoatWithSupport.cpp
C++
mit
1,007
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "corponovo.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
hhalmeida/corponovo
manage.py
Python
mit
807
import time t1=.3 t2=.1 path="~/Dropbox/Ingenieria/asignaturas_actuales" time.sleep(t2) keyboard.send_key("<f6>") time.sleep(t2) keyboard.send_keys(path) time.sleep(t1) keyboard.send_key("<enter>")
andresgomezvidal/autokey_scripts
data/General/file manager/asignaturas_actuales.py
Python
mit
200
package org.bitbucket.ytimes.client.main; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by andrey on 27.05.17. */ public class Main { public static void main( String[] args ) throws Exception { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("root-context.xml"); } }
ytimesru/kkm-pc-client
src/main/java/org/bitbucket/ytimes/client/main/Main.java
Java
mit
372
require 'oplogjam/noop' require 'oplogjam/insert' require 'oplogjam/update' require 'oplogjam/delete' require 'oplogjam/command' require 'oplogjam/apply_ops' module Oplogjam InvalidOperation = Class.new(ArgumentError) class Operation def self.from(bson) op = bson.fetch(OP, UNKNOWN) case op when N then Noop.from(bson) when I then Insert.from(bson) when U then Update.from(bson) when D then Delete.from(bson) when C if bson.fetch(O, {}).key?(APPLY_OPS) ApplyOps.from(bson) else Command.from(bson) end else raise InvalidOperation, "invalid operation: #{bson}" end end end end
mudge/oplogjam
lib/oplogjam/operation.rb
Ruby
mit
698
package alexp.blog.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import alexp.blog.repository.*; import alexp.blog.model.Schedule; @Service("ScheduleService") public class ScheduleServiceImpl implements ScheduleService{ @Autowired private ScheduleRepository schedulerepository; @Override public Schedule getSchedule(String username) { // TODO Auto-generated method stub System.out.println("I am in service"); return schedulerepository.findByUsernameIgnoreCase(username); } }
ericjin527/MockInterview
src/main/java/alexp/blog/service/ScheduleServiceImpl.java
Java
mit
569
export default { queryRouteList: '/routes', queryUserInfo: '/user', logoutUser: '/user/logout', loginUser: 'POST /user/login', queryUser: '/user/:id', queryUserList: '/users', updateUser: 'Patch /user/:id', createUser: 'POST /user', removeUser: 'DELETE /user/:id', removeUserList: 'POST /users/delete', queryPostList: '/posts', queryDashboard: '/dashboard', }
zuiidea/antd-admin
src/services/api.js
JavaScript
mit
388
import Controller from '@ember/controller'; import { debounce } from '@ember/runloop'; import fetch from 'fetch'; import RSVP from 'rsvp'; export default class extends Controller { searchRepo(term) { return new RSVP.Promise((resolve, reject) => { debounce(_performSearch, term, resolve, reject, 600); }); } } function _performSearch(term, resolve, reject) { let url = `https://api.github.com/search/repositories?q=${term}`; fetch(url).then((resp) => resp.json()).then((json) => resolve(json.items), reject); }
cibernox/ember-power-select
tests/dummy/app/templates/snippets/debounce-searches-1-js.js
JavaScript
mit
534
import controller from './controller'; import template from './template.pug'; routes.$inject = ['$stateProvider', '$urlRouterProvider']; export default function routes($stateProvider, $urlRouterProvider){ $stateProvider.state('main.item', { url: '/:id/item', template: template, controllerAs: 'ctrl', controller: controller }) }
bfunc/AngularWebpack
src/main/item/routes.js
JavaScript
mit
346
import { OnInit, SimpleChanges, OnChanges } from '@angular/core'; import { Validator, AbstractControl } from '@angular/forms'; export declare class NotEqualValidator implements Validator, OnInit, OnChanges { notEqual: any; private validator; private onChange; ngOnInit(): void; ngOnChanges(changes: SimpleChanges): void; validate(c: AbstractControl): { [key: string]: any; }; registerOnValidatorChange(fn: () => void): void; }
Dackng/eh-unmsm-client
node_modules/ng2-validation/dist/not-equal/directive.d.ts
TypeScript
mit
467
var margin = {top: 0, right: 0, bottom: 0, left: 130}, width = 1500 - margin.right - margin.left, height = 470 - margin.top - margin.bottom; var i = 0, duration = 750, root; var tree = d3.layout.tree() .size([height, width]); var diagonal = d3.svg.diagonal() .projection(function(d) { return [d.y, d.x]; }); var svg = d3.select("#treeplot").append("svg") .attr("width", width + margin.right + margin.left) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); d3.json("/pattern_discovery/data?id={{selections.current_dataset}}", function(error, flare) { if (error) throw error; $("#wait").empty(); root = flare; root.x0 = height / 2; root.y0 = 0; function collapse(d) { if (d.children) { d._children = d.children; d._children.forEach(collapse); d.children = null; } } root.children.forEach(collapse); update(root); }); d3.select(self.frameElement).style("height", "800px"); function update(source) { // Compute the new tree layout. var nodes = tree.nodes(root).reverse(), links = tree.links(nodes); // Normalize for fixed-depth. nodes.forEach(function(d) { d.y = d.depth * 300; }); // Update the nodes… var node = svg.selectAll("g.node") .data(nodes, function(d) { return d.id || (d.id = ++i); }); // Enter any new nodes at the parent's previous position. var nodeEnter = node.enter().append("g") .attr("class", "node") .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; }) .on("click", click); nodeEnter.append("circle") .attr("r", 1e-6) .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; }); nodeEnter.append("text") .attr("x", function(d) { return d.children || d._children ? -10 : 10; }) .attr("dy", ".35em") .attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; }) .text(function(d) { return d.name; }) .style("fill-opacity", 1e-6); // Transition nodes to their new position. var nodeUpdate = node.transition() .duration(duration) .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; }); nodeUpdate.select("circle") .attr("r", 4.5) .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; }); nodeUpdate.select("text") .style("fill-opacity", 1); // Transition exiting nodes to the parent's new position. var nodeExit = node.exit().transition() .duration(duration) .attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; }) .remove(); nodeExit.select("circle") .attr("r", 1e-6); nodeExit.select("text") .style("fill-opacity", 1e-6); // Update the links… var link = svg.selectAll("path.link") .data(links, function(d) { return d.target.id; }); // Enter any new links at the parent's previous position. link.enter().insert("path", "g") .attr("class", "link") .attr("d", function(d) { var o = {x: source.x0, y: source.y0}; return diagonal({source: o, target: o}); }); // Transition links to their new position. link.transition() .duration(duration) .attr("d", diagonal); // Transition exiting nodes to the parent's new position. link.exit().transition() .duration(duration) .attr("d", function(d) { var o = {x: source.x, y: source.y}; return diagonal({source: o, target: o}); }) .remove(); // Stash the old positions for transition. nodes.forEach(function(d) { d.x0 = d.x; d.y0 = d.y; }); } // Toggle children on click. function click(d) { if (d.children) { d._children = d.children; d.children = null; } else { d.children = d._children; d._children = null; } update(d); }
lzlarryli/limelight
app/templates/js/treeplot.js
JavaScript
mit
4,263
import { EventBus } from '../wires/event_bus'; class EventStore { constructor(storeAdapter) { this.adapter = storeAdapter; } appendToStream(streamId, expectedVersion, events) { if (events.length === 0) { return; } events.forEach(function(event) { this.adapter.append(streamId, expectedVersion, event); EventBus.publish('domain.'+streamId+'.'+event.name, event); expectedVersion++; }, this); } loadEventStream(streamId) { var version = 0, events = [], records = this.readEventStream(streamId, 0, null); records.forEach(function(r) { version = r.version; events.push(r.data); }); return new EventStream(streamId, events, version); } readEventStream(streamId, skipEvents, maxCount) { return this.adapter.read(streamId, skipEvents, maxCount); } } class EventStream { constructor(streamId, events, version) { this.streamId = streamId; this.events = events; this.version = version; } } export { EventStore, EventStream };
goldoraf/osef
src/storage/event_store.js
JavaScript
mit
1,162
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Numerics; namespace _02_Convert_from_base_N_to_base_10 { public class ConvertFromBaseNToBase10 { public static void Main() { string[] parameters = Console.ReadLine() .Split() .ToArray(); int toBase = int.Parse(parameters[0]); List<int> number = parameters[1].Select(x => (int)(x - '0')).ToList(); BigInteger result = number[number.Count - 1] + (number[number.Count - 2] * toBase); int index = 0; int pow = number.Count - 1; while (pow > 1) { result += number[index] * PowerNumber(toBase, pow); index++; pow--; } Console.WriteLine(result); } public static BigInteger PowerNumber(int toBase, int pow) { BigInteger poweredNumber = toBase; for (int i = 1; i < pow; i++) { poweredNumber *= toBase; } return poweredNumber; } } }
akkirilov/SoftUniProject
01_ProgrammingFundamentals/Homeworks/09_Strings-Ex/02_Convert from base-N to base-10/ConvertFromBaseNToBase10.cs
C#
mit
1,199
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.Collections; using System.Threading; namespace Joddgewe { public partial class Form1 : Form { private string filenameOrto; public Form1() { InitializeComponent(); toolStripStatusLabel1.Text = "Venter på at brukeren skal åpne ortofoto..."; } private void openToolStripMenuItem_Click(object sender, EventArgs e) { addFiles(); } private void closeToolStripMenuItem_Click(object sender, EventArgs e) { closeApp(); } public void closeApp() { this.Dispose(); } public void addFiles() { Stream myStream; OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "Ortofoto(*.tif;*.jpg;*.gif)|*.TIF;*.JPG;*.GIF"; openFileDialog1.FilterIndex = 3; openFileDialog1.RestoreDirectory = true; openFileDialog1.Multiselect = true; if (openFileDialog1.ShowDialog(this) == DialogResult.OK) { if ((myStream = openFileDialog1.OpenFile()) != null) { string[] files = openFileDialog1.FileNames; foreach (string file in files ) { Image bm = Image.FromFile(file); FileHandler fh = new FileHandler(file, bm.Width, bm.Height); bm.Dispose(); listBoxFiler.Items.Add(fh); } myStream.Close(); enableButtons(); toolStripStatusLabel1.Text = "Venter på at brukeren skal velge utformat..."; } myStream.Dispose(); lblVisEgenskaper.Visible = true; lblUtformat.Visible = true; } openFileDialog1.Dispose(); } private void removeFiles() { listBoxFiler.Items.Remove(listBoxFiler.SelectedItem); textBoxMMM.Text = ""; textBoxJGW.Text = ""; textBoxSOSI.Text = ""; } private void btnKonverter_Click(object sender, EventArgs e) { } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { Form2 frm = new Form2(this); frm.ShowDialog(); } private void btnAdd_Click(object sender, EventArgs e) { addFiles(); } private void btnRemove_Click(object sender, EventArgs e) { removeFiles(); } private void listBoxFiler_SelectedIndexChanged(object sender, EventArgs e) { pictboxOrtofoto.Image.Dispose(); if (listBoxFiler.SelectedItems.Count == 0) { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); pictboxOrtofoto.Image = ((System.Drawing.Image)(resources.GetObject("pictboxOrtofoto.Image"))); } else { FileHandler fh = (FileHandler)listBoxFiler.SelectedItem; filenameOrto = fh.ToString(); try { pictboxOrtofoto.Image = (Bitmap)Image.FromFile(filenameOrto); displayStyringsfiler(); } catch { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); pictboxOrtofoto.Image = ((System.Drawing.Image)(resources.GetObject("pictboxOrtofoto.ErrorImage"))); } } if (listBoxFiler.Items.Count > 0) enableButtons(); else disableButtons(); } private void disableButtons() { radioButtonJGW.Enabled = false; radioButtonMMM.Enabled = false; radioButtonSOSI.Enabled = false; checkBoxFilliste.Enabled = false; btnFullfør.Enabled = false; } private void enableButtons() { radioButtonJGW.Enabled = true; radioButtonMMM.Enabled = true; radioButtonSOSI.Enabled = true; checkBoxFilliste.Enabled = true; if (radioButtonJGW.Checked || radioButtonMMM.Checked || radioButtonSOSI.Checked) btnFullfør.Enabled = true; } private void displayStyringsfiler() { try { FileHandler fh = (FileHandler) listBoxFiler.SelectedItem; textBoxJGW.Text = fh.toJGW(); textBoxMMM.Text = fh.toMMM(); textBoxSOSI.Text = fh.toSOSI(); } catch { textBoxMMM.Text = ""; textBoxJGW.Text = ""; textBoxSOSI.Text = ""; } } private void btnFullfør_Click(object sender, EventArgs e) { string fileList = ""; FileHandler fh1 = null; foreach (FileHandler fh in listBoxFiler.Items) { if (checkBoxFilliste.Checked) fileList += fh.ToString() + "\r\n"; if (radioButtonJGW.Checked) fh.writeToFile(FileHandler.TYPE_JGW); if (radioButtonMMM.Checked) fh.writeToFile(FileHandler.TYPE_MMM); if (radioButtonSOSI.Checked) fh.writeToFile(FileHandler.TYPE_SOSI); } try { fh1 = (FileHandler)listBoxFiler.Items[0]; } catch { } if (fh1 != null && checkBoxFilliste.Checked) { fh1.createFileList(fileList); } toolStripStatusLabel1.Text = "Suksess!"; MessageBox.Show("Ferdig med å konvertere!", "JoddGewe 0.1", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void radioButtonJGW_CheckedChanged(object sender, EventArgs e) { btnFullfør.Enabled = true; toolStripStatusLabel1.Text = "Klar til å konvertere styringsfiler!"; } private void radioButtonMMM_CheckedChanged(object sender, EventArgs e) { btnFullfør.Enabled = true; toolStripStatusLabel1.Text = "Klar til å konvertere styringsfiler!"; } private void radioButtonSOSI_CheckedChanged(object sender, EventArgs e) { btnFullfør.Enabled = true; toolStripStatusLabel1.Text = "Klar til å konvertere styringsfiler!"; } } }
avinet/joddgewe
Joddgewe/Form1.cs
C#
mit
7,184
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm0 15l-5-5h3V9h4v4h3l-5 5z" }), 'AssignmentReturned');
AlloyTeam/Nuclear
components/icon/esm/assignment-returned.js
JavaScript
mit
355
(function () { 'use strict'; angular .module('app.home') .config(appRun); /* @ngInject */ function appRun($stateProvider) { $stateProvider .state('root.home', { url: '/', templateUrl: 'app/home/home.html', controller: 'Home', controllerAs: 'vm', }); } })();
hawkup/github-stars
angularjs/app/home/config.route.js
JavaScript
mit
326
using OTransport.Factory; using OTransport.Serializer.protobuf; namespace OTransport.Serializer.protobuf { public static class ObjectTransportAssemblyLine_protobufExtension { /// <summary> /// Use Protobuf Serialization to serialize objects /// </summary> /// <returns></returns> public static ObjectTransportAssemblyLine UseProtobufSerialization(this ObjectTransportAssemblyLine objectTranposrtAssemblyLine) { var protobufSerialization = new ProtobufSerializer(); objectTranposrtAssemblyLine.SetSerializer(protobufSerialization); return objectTranposrtAssemblyLine; } } }
RhynoVDS/ObjectTransport
Implementation/ObjectTransport.Serializer.protobuf/ObjectTransportAssemblyLine_protobufExtension.cs
C#
mit
682
import React from 'react'; import { Text, View, TextInput, } from 'react-native'; import newChallengeStyles from '../../styles/newChallenge/newChallengeStyles'; import mainStyles from '../../styles/main/mainStyles'; import ItemSelectView from './ItemSelectView'; const propTypes = { onChallengeUpdate: React.PropTypes.func, }; const prizeItemStyle = { marginTop: 10, labelFontSize: 22, iconFontSize: 30, iconColor: mainStyles.themeColors.textPrimary, }; class PrizeView extends React.Component { constructor(props) { super(props); this.state = { prize: null, customPrize: '', prizes: [ { label: 'Diner', style: prizeItemStyle }, { label: 'Drinks', style: prizeItemStyle }, { label: 'Gift', style: prizeItemStyle }, { label: 'Define your own', style: prizeItemStyle }, ], }; } setCustomPrize = (customPrize) => { this.setState({ customPrize }); this.props.onChallengeUpdate({ prize: customPrize }); } selectPrize = (prizeLabel) => { const prizes = this.state.prizes; prizes.forEach(prize => { if (prizeLabel === prize.label) { prize.style = { ...prizeItemStyle, iconColor: mainStyles.themeColors.primary }; } else { prize.style = { ...prizeItemStyle, opacity: 0.2 }; } }); this.setState({ prize: prizeLabel, prizes }); this.props.onChallengeUpdate({ prize: prizeLabel }); } render = () => ( <View style={newChallengeStyles.mainContainer}> <View style={newChallengeStyles.contentContainer}> <Text style={newChallengeStyles.titleFont}>Prize (optional)</Text> <View style={newChallengeStyles.itemsContainer} > {this.state.prizes.map(prize => (<ItemSelectView key={prize.label} label={prize.label} style={prize.style} onItemSelect={this.selectPrize} />) )} </View> {this.state.prize === 'Define your own' ? <View style={newChallengeStyles.settingInputContainer} > <TextInput style={newChallengeStyles.inputFont} placeholder="Birthday cake for Paul" placeholderTextColor={mainStyles.themeColors.textPrimary} onChangeText={this.setCustomPrize} value={this.state.customPrize} /> </View> : null} </View> </View> ); } PrizeView.propTypes = propTypes; export default PrizeView;
SamyZ/BoomApp
js/views/newChallenge/PrizeView.js
JavaScript
mit
2,598
/* * Copyright (c) 2012 M. M. Naseri <m.m.naseri@gmail.com> * * 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. */ package com.agileapes.powerpack.string.exception; /** * @author Mohammad Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (2012/12/3, 17:47) */ public class NoMoreTextException extends DocumentReaderException { private static final long serialVersionUID = -1822455471711418794L; public NoMoreTextException() { } public NoMoreTextException(String message) { super(message); } }
agileapes/jpowerpack
string-tools/src/main/java/com/agileapes/powerpack/string/exception/NoMoreTextException.java
Java
mit
1,068
import React, {PropTypes} from 'react'; import L from 'leaflet'; import gh from '../api/GitHubApi'; import RaisedButton from 'material-ui/RaisedButton'; const REPO_TIMESPAN = { ALLTIME: 0, THIRTYDAYS: 1, SIXTYDAYS: 2, ONEYEAR: 3 }; const defaultMapConfig = { options: { center: [ 39.7589, -84.1916 ], zoomControl: false, zoom: 4, maxZoom: 20, minZoom: 2, scrollwheel: false, infoControl: false, attributionControl: false }, tileLayer: { uri: 'http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png', options: { maxZoom: 18, id: '' } } }; class RepoUserHeatmap extends React.Component { constructor(props, context) { super(props, context); this.state = { timespan: REPO_TIMESPAN.THIRTYDAYS, data: [] }; this.initializeMap = this.initializeMap.bind(this); } componentDidMount() { this.initializeMap(); this.updateData(); gh.getTopRepos().then(data => { console.log('=== REPOS ==='); console.log(data); return gh.getContributors(data.data[0].full_name); }).then(contribs => { console.log('=== CONTRIBS ==='); console.log(contribs); return gh.getUser(contribs.data[0].login); }).then(user => { console.log('=== USER ==='); console.log(user); return gh.getRateLimit(); }).then(limit => { console.log('=== RATE LIMIT ==='); console.log(limit); }).catch(err => { console.log('ERROR:'); console.log(err); }); } componentWillUnmount() { this.map = null; } initializeMap() { if (this.map) { return; } this.map = L.map(this.mapDiv, this.props.mapOptions || defaultMapConfig.options); if (this.props.mapLayers && this.props.mapLayers.length > 0) { for (let i=0; i < this.props.mapLayers.length; i++) { this.props.mapLayers[i].addTo(this.map); } } else { L.tileLayer(defaultMapConfig.tileLayer.uri, defaultMapConfig.tileLayer.options).addTo(this.map); } } updateData() { } render() { return ( <div className="map-container"> <div className="os-map" ref={(div) => { this.mapDiv = div; }}></div> <RaisedButton label="Default" /> </div> ); } } RepoUserHeatmap.propTypes = { mapOptions: PropTypes.object, mapLayers: PropTypes.array }; export default RepoUserHeatmap;
jefferey/octoviz
src/components/views/RepoUserHeatmap.js
JavaScript
mit
2,707
import java.security.Security; import java.util.Base64; import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.engines.RijndaelEngine; import org.bouncycastle.crypto.modes.CBCBlockCipher; import org.bouncycastle.crypto.paddings.PKCS7Padding; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; public class DotNet { static byte[] buffer = new byte[] { (byte)17, (byte)185, (byte)186, (byte)161, (byte)188, (byte)43, (byte)253, (byte)224, (byte)76, (byte)24, (byte)133, (byte)9, (byte)201, (byte)173, (byte)255, (byte)152, (byte)113, (byte)171, (byte)225, (byte)163, (byte)121, (byte)177, (byte)211, (byte)18, (byte)50, (byte)50, (byte)219, (byte)190, (byte)168, (byte)138, (byte)97, (byte)197 }; static byte[] initVector = new byte[] { (byte) 8, (byte) 173, (byte) 47, (byte) 130, (byte) 199, (byte) 242, (byte) 20, (byte) 211, (byte) 63, (byte) 47, (byte) 254, (byte) 173, (byte) 163, (byte) 245, (byte) 242, (byte) 232, (byte) 11, (byte) 244, (byte) 134, (byte) 249, (byte) 44, (byte) 123, (byte) 138, (byte) 109, (byte) 155, (byte) 173, (byte) 122, (byte) 76, (byte) 93, (byte) 125, (byte) 185, (byte) 66 }; public static String decrypt(byte[] key, byte[] initVector, byte[] encrypted) { try { BlockCipher engine = new RijndaelEngine(256); CBCBlockCipher cbc = new CBCBlockCipher(engine); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(cbc, new PKCS7Padding()); cipher.init(false, new ParametersWithIV(new KeyParameter(key), initVector)); int minSize = cipher.getOutputSize(encrypted.length); byte[] outBuf = new byte[minSize]; int length1 = cipher.processBytes(encrypted, 0, encrypted.length, outBuf, 0); int length2 = cipher.doFinal(outBuf, length1); int actualLength = length1 + length2; byte[] result = new byte[actualLength]; System.arraycopy(outBuf, 0, result, 0, result.length); return new String(result); } catch (Exception ex) { ex.printStackTrace(); } return null; } public static void main(String[] args) { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); String sha64 = "SxTgWtrMjXY/dA50Kk20PkNeNLQ="; byte[] k = Base64.getDecoder().decode(sha64); System.out.println("Buffer :: "+Base64.getEncoder().encodeToString(buffer)+" --> length "+buffer.length); System.out.println("Key(Sha) :: "+Base64.getEncoder().encodeToString(k)+" --> length "+k.length); System.out.println("IV :: "+Base64.getEncoder().encodeToString(initVector)+" --> length "+initVector.length); System.out.println(decrypt(k, initVector, buffer)); } }
mseclab/AHE17
Token-Generator/src/main/java/DotNet.java
Java
mit
3,987
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("03. Printing Triangle")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("03. Printing Triangle")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c2d80a6e-c54c-4fc3-be24-ae9b7d912f09")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
delian1986/SoftUni-C-Sharp-repo
Old Courses/Programming Fundamentals Old/03. Methods/Methods/03. Printing Triangle/Properties/AssemblyInfo.cs
C#
mit
1,418
function lessThan (a, b) { return a < b } function main () { for (var i = 0; i < 10000; i++) { lessThan(1, 0x7fffffff) } for (var i = 0; i < 10000; i++) { lessThan(1, Infinity) } for (var i = 0; i < 10000; i++) { lessThan(1, 0x7fffffff) } } main()
bigeasy/hotspot
jit/less-than.js
JavaScript
mit
304
/*! * hybridify-all <https://github.com/hybridables/hybridify-all> * * Copyright (c) 2015 Charlike Mike Reagent, contributors. * Released under the MIT license. */ 'use strict' var reduce = require('object.reduce') var hybridify = require('hybridify') /** * > Hybridifies all the selected functions in an object. * * **Example:** * * ```js * var hybridifyAll = require('hybridify-all') * var fs = require('fs') * * fs = hybridifyAll(fs) * fs.readFile(__filename, 'utf8', function(err, res) { * //=> err, res * }) * .then(function(res) { * //=> res * return fs.stat(__filename) * }) * .then(function(stat) { * assert.strictEqual(stat.size, fs.statSync(__filename).size) * }) * ``` * * @name hybridifyAll * @param {Object|Function} `<source>` the source object for the async functions * @param {Object|Function} `[dest]` the destination to set all the hybridified methods * @return {Object|Function} * @api public */ module.exports = function hybridifyAll (source, dest) { if (!source) { throw new Error('hybridify-all: should have at least 1 arguments') } if (typeOf(source) !== 'function' && typeOf(source) !== 'object') { throw new TypeError('hybridify-all: expect `source` be object|function') } dest = dest || {} if (typeof source === 'function') { dest = hybridify(source) } return Object.keys(source).length ? reduce(source, function (dest, fn, key) { if (typeof fn === 'function') { dest[key] = hybridify(fn) } return dest }, dest) : dest } /** * Get correct type of value * * @param {*} `val` * @return {String} * @api private */ function typeOf (val) { if (Array.isArray(val)) { return 'array' } if (typeof val !== 'object') { return typeof val } return Object.prototype.toString(val).slice(8, -1).toLowerCase() }
hybridables/hybridify-all
index.js
JavaScript
mit
1,844
/*! p5.dom.js v0.3.3 May 10, 2017 */ /** * <p>The web is much more than just canvas and p5.dom makes it easy to interact * with other HTML5 objects, including text, hyperlink, image, input, video, * audio, and webcam.</p> * <p>There is a set of creation methods, DOM manipulation methods, and * an extended p5.Element that supports a range of HTML elements. See the * <a href="https://github.com/processing/p5.js/wiki/Beyond-the-canvas"> * beyond the canvas tutorial</a> for a full overview of how this addon works. * * <p>Methods and properties shown in black are part of the p5.js core, items in * blue are part of the p5.dom library. You will need to include an extra file * in order to access the blue functions. See the * <a href="http://p5js.org/libraries/#using-a-library">using a library</a> * section for information on how to include this library. p5.dom comes with * <a href="http://p5js.org/download">p5 complete</a> or you can download the single file * <a href="https://raw.githubusercontent.com/lmccart/p5.js/master/lib/addons/p5.dom.js"> * here</a>.</p> * <p>See <a href="https://github.com/processing/p5.js/wiki/Beyond-the-canvas">tutorial: beyond the canvas</a> * for more info on how to use this libary.</a> * * @module p5.dom * @submodule p5.dom * @for p5.dom * @main */ (function (root, factory) { if (typeof define === 'function' && define.amd) define('p5.dom', ['p5'], function (p5) { (factory(p5));}); else if (typeof exports === 'object') factory(require('../p5')); else factory(root['p5']); }(this, function (p5) { // ============================================================================= // p5 additions // ============================================================================= /** * Searches the page for an element with the given ID, class, or tag name (using the '#' or '.' * prefixes to specify an ID or class respectively, and none for a tag) and returns it as * a p5.Element. If a class or tag name is given with more than 1 element, * only the first element will be returned. * The DOM node itself can be accessed with .elt. * Returns null if none found. You can also specify a container to search within. * * @method select * @param {String} name id, class, or tag name of element to search for * @param {String} [container] id, p5.Element, or HTML element to search within * @return {Object|p5.Element|Null} p5.Element containing node found * @example * <div ><code class='norender'> * function setup() { * createCanvas(100,100); * //translates canvas 50px down * select('canvas').position(100, 100); * } * </code></div> * <div ><code class='norender'> * // these are all valid calls to select() * var a = select('#moo'); * var b = select('#blah', '#myContainer'); * var c = select('#foo', b); * var d = document.getElementById('beep'); * var e = select('p', d); * </code></div> * */ p5.prototype.select = function (e, p) { var res = null; var container = getContainer(p); if (e[0] === '.'){ e = e.slice(1); res = container.getElementsByClassName(e); if (res.length) { res = res[0]; } else { res = null; } }else if (e[0] === '#'){ e = e.slice(1); res = container.getElementById(e); }else { res = container.getElementsByTagName(e); if (res.length) { res = res[0]; } else { res = null; } } if (res) { return wrapElement(res); } else { return null; } }; /** * Searches the page for elements with the given class or tag name (using the '.' prefix * to specify a class and no prefix for a tag) and returns them as p5.Elements * in an array. * The DOM node itself can be accessed with .elt. * Returns an empty array if none found. * You can also specify a container to search within. * * @method selectAll * @param {String} name class or tag name of elements to search for * @param {String} [container] id, p5.Element, or HTML element to search within * @return {Array} Array of p5.Elements containing nodes found * @example * <div class='norender'><code> * function setup() { * createButton('btn'); * createButton('2nd btn'); * createButton('3rd btn'); * var buttons = selectAll('button'); * * for (var i = 0; i < buttons.length; i++){ * buttons[i].size(100,100); * } * } * </code></div> * <div class='norender'><code> * // these are all valid calls to selectAll() * var a = selectAll('.moo'); * var b = selectAll('div'); * var c = selectAll('button', '#myContainer'); * var d = select('#container'); * var e = selectAll('p', d); * var f = document.getElementById('beep'); * var g = select('.blah', f); * </code></div> * */ p5.prototype.selectAll = function (e, p) { var arr = []; var res; var container = getContainer(p); if (e[0] === '.'){ e = e.slice(1); res = container.getElementsByClassName(e); } else { res = container.getElementsByTagName(e); } if (res) { for (var j = 0; j < res.length; j++) { var obj = wrapElement(res[j]); arr.push(obj); } } return arr; }; /** * Helper function for select and selectAll */ function getContainer(p) { var container = document; if (typeof p === 'string' && p[0] === '#'){ p = p.slice(1); container = document.getElementById(p) || document; } else if (p instanceof p5.Element){ container = p.elt; } else if (p instanceof HTMLElement){ container = p; } return container; } /** * Helper function for getElement and getElements. */ function wrapElement(elt) { if(elt.tagName === "INPUT" && elt.type === "checkbox") { var converted = new p5.Element(elt); converted.checked = function(){ if (arguments.length === 0){ return this.elt.checked; } else if(arguments[0]) { this.elt.checked = true; } else { this.elt.checked = false; } return this; }; return converted; } else if (elt.tagName === "VIDEO" || elt.tagName === "AUDIO") { return new p5.MediaElement(elt); } else if ( elt.tagName === "SELECT" ){ return createSelect( new p5.Element(elt) ); } else { return new p5.Element(elt); } } /** * Removes all elements created by p5, except any canvas / graphics * elements created by createCanvas or createGraphics. * Event handlers are removed, and element is removed from the DOM. * @method removeElements * @example * <div class='norender'><code> * function setup() { * createCanvas(100, 100); * createDiv('this is some text'); * createP('this is a paragraph'); * } * function mousePressed() { * removeElements(); // this will remove the div and p, not canvas * } * </code></div> * */ p5.prototype.removeElements = function (e) { for (var i=0; i<this._elements.length; i++) { if (!(this._elements[i].elt instanceof HTMLCanvasElement)) { this._elements[i].remove(); } } }; /** * Helpers for create methods. */ function addElement(elt, pInst, media) { var node = pInst._userNode ? pInst._userNode : document.body; node.appendChild(elt); var c = media ? new p5.MediaElement(elt) : new p5.Element(elt); pInst._elements.push(c); return c; } /** * Creates a &lt;div&gt;&lt;/div&gt; element in the DOM with given inner HTML. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createDiv * @param {String} html inner HTML for element created * @return {Object|p5.Element} pointer to p5.Element holding created node * @example * <div class='norender'><code> * var myDiv; * function setup() { * myDiv = createDiv('this is some text'); * } * </code></div> */ /** * Creates a &lt;p&gt;&lt;/p&gt; element in the DOM with given inner HTML. Used * for paragraph length text. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createP * @param {String} html inner HTML for element created * @return {Object|p5.Element} pointer to p5.Element holding created node * @example * <div class='norender'><code> * var myP; * function setup() { * myP = createP('this is some text'); * } * </code></div> */ /** * Creates a &lt;span&gt;&lt;/span&gt; element in the DOM with given inner HTML. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createSpan * @param {String} html inner HTML for element created * @return {Object|p5.Element} pointer to p5.Element holding created node * @example * <div class='norender'><code> * var mySpan; * function setup() { * mySpan = createSpan('this is some text'); * } * </code></div> */ var tags = ['div', 'p', 'span']; tags.forEach(function(tag) { var method = 'create' + tag.charAt(0).toUpperCase() + tag.slice(1); p5.prototype[method] = function(html) { var elt = document.createElement(tag); elt.innerHTML = typeof html === undefined ? "" : html; return addElement(elt, this); } }); /** * Creates an &lt;img&gt; element in the DOM with given src and * alternate text. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createImg * @param {String} src src path or url for image * @param {String} [alt] alternate text to be used if image does not load * @param {Function} [successCallback] callback to be called once image data is loaded * @return {Object|p5.Element} pointer to p5.Element holding created node * @example * <div class='norender'><code> * var img; * function setup() { * img = createImg('http://p5js.org/img/asterisk-01.png'); * } * </code></div> */ p5.prototype.createImg = function() { var elt = document.createElement('img'); var args = arguments; var self; var setAttrs = function(){ self.width = elt.offsetWidth || elt.width; self.height = elt.offsetHeight || elt.height; if (args.length > 1 && typeof args[1] === 'function'){ self.fn = args[1]; self.fn(); }else if (args.length > 1 && typeof args[2] === 'function'){ self.fn = args[2]; self.fn(); } }; elt.src = args[0]; if (args.length > 1 && typeof args[1] === 'string'){ elt.alt = args[1]; } elt.onload = function(){ setAttrs(); } self = addElement(elt, this); return self; }; /** * Creates an &lt;a&gt;&lt;/a&gt; element in the DOM for including a hyperlink. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createA * @param {String} href url of page to link to * @param {String} html inner html of link element to display * @param {String} [target] target where new link should open, * could be _blank, _self, _parent, _top. * @return {Object|p5.Element} pointer to p5.Element holding created node * @example * <div class='norender'><code> * var myLink; * function setup() { * myLink = createA('http://p5js.org/', 'this is a link'); * } * </code></div> */ p5.prototype.createA = function(href, html, target) { var elt = document.createElement('a'); elt.href = href; elt.innerHTML = html; if (target) elt.target = target; return addElement(elt, this); }; /** INPUT **/ /** * Creates a slider &lt;input&gt;&lt;/input&gt; element in the DOM. * Use .size() to set the display length of the slider. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createSlider * @param {Number} min minimum value of the slider * @param {Number} max maximum value of the slider * @param {Number} [value] default value of the slider * @param {Number} [step] step size for each tick of the slider (if step is set to 0, the slider will move continuously from the minimum to the maximum value) * @return {Object|p5.Element} pointer to p5.Element holding created node * @example * <div><code> * var slider; * function setup() { * slider = createSlider(0, 255, 100); * slider.position(10, 10); * slider.style('width', '80px'); * } * * function draw() { * var val = slider.value(); * background(val); * } * </code></div> * * <div><code> * var slider; * function setup() { * colorMode(HSB); * slider = createSlider(0, 360, 60, 40); * slider.position(10, 10); * slider.style('width', '80px'); * } * * function draw() { * var val = slider.value(); * background(val, 100, 100, 1); * } * </code></div> */ p5.prototype.createSlider = function(min, max, value, step) { var elt = document.createElement('input'); elt.type = 'range'; elt.min = min; elt.max = max; if (step === 0) { elt.step = .000000000000000001; // smallest valid step } else if (step) { elt.step = step; } if (typeof(value) === "number") elt.value = value; return addElement(elt, this); }; /** * Creates a &lt;button&gt;&lt;/button&gt; element in the DOM. * Use .size() to set the display size of the button. * Use .mousePressed() to specify behavior on press. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createButton * @param {String} label label displayed on the button * @param {String} [value] value of the button * @return {Object|p5.Element} pointer to p5.Element holding created node * @example * <div class='norender'><code> * var button; * function setup() { * createCanvas(100, 100); * background(0); * button = createButton('click me'); * button.position(19, 19); * button.mousePressed(changeBG); * } * * function changeBG() { * var val = random(255); * background(val); * } * </code></div> */ p5.prototype.createButton = function(label, value) { var elt = document.createElement('button'); elt.innerHTML = label; if (value) elt.value = value; return addElement(elt, this); }; /** * Creates a checkbox &lt;input&gt;&lt;/input&gt; element in the DOM. * Calling .checked() on a checkbox returns if it is checked or not * * @method createCheckbox * @param {String} [label] label displayed after checkbox * @param {boolean} [value] value of the checkbox; checked is true, unchecked is false.Unchecked if no value given * @return {Object|p5.Element} pointer to p5.Element holding created node * @example * <div class='norender'><code> * var checkbox; * * function setup() { * checkbox = createCheckbox('label', false); * checkbox.changed(myCheckedEvent); * } * * function myCheckedEvent() { * if (this.checked()) { * console.log("Checking!"); * } else { * console.log("Unchecking!"); * } * } * </code></div> */ p5.prototype.createCheckbox = function() { var elt = document.createElement('div'); var checkbox = document.createElement('input'); checkbox.type = 'checkbox'; elt.appendChild(checkbox); //checkbox must be wrapped in p5.Element before label so that label appears after var self = addElement(elt, this); self.checked = function(){ var cb = self.elt.getElementsByTagName('input')[0]; if (cb) { if (arguments.length === 0){ return cb.checked; }else if(arguments[0]){ cb.checked = true; }else{ cb.checked = false; } } return self; }; this.value = function(val){ self.value = val; return this; }; if (arguments[0]){ var ran = Math.random().toString(36).slice(2); var label = document.createElement('label'); checkbox.setAttribute('id', ran); label.htmlFor = ran; self.value(arguments[0]); label.appendChild(document.createTextNode(arguments[0])); elt.appendChild(label); } if (arguments[1]){ checkbox.checked = true; } return self; }; /** * Creates a dropdown menu &lt;select&gt;&lt;/select&gt; element in the DOM. * It also helps to assign select-box methods to p5.Element when selecting existing select box * @method createSelect * @param {boolean} [multiple] true if dropdown should support multiple selections * @return {p5.Element} * @example * <div><code> * var sel; * * function setup() { * textAlign(CENTER); * background(200); * sel = createSelect(); * sel.position(10, 10); * sel.option('pear'); * sel.option('kiwi'); * sel.option('grape'); * sel.changed(mySelectEvent); * } * * function mySelectEvent() { * var item = sel.value(); * background(200); * text("it's a "+item+"!", 50, 50); * } * </code></div> */ /** * @method createSelect * @param {Object} existing DOM select element * @return {p5.Element} */ p5.prototype.createSelect = function() { var elt, self; var arg = arguments[0]; if( typeof arg === 'object' && arg.elt.nodeName === 'SELECT' ) { self = arg; elt = this.elt = arg.elt; } else { elt = document.createElement('select'); if( arg && typeof arg === 'boolean' ) { elt.setAttribute('multiple', 'true'); } self = addElement(elt, this); } self.option = function(name, value) { var index; //see if there is already an option with this name for (var i = 0; i < this.elt.length; i++) { if(this.elt[i].innerHTML == name) { index = i; break; } } //if there is an option with this name we will modify it if(index !== undefined) { //if the user passed in false then delete that option if(value === false) { this.elt.remove(index); } else { //otherwise if the name and value are the same then change both if(this.elt[index].innerHTML == this.elt[index].value) { this.elt[index].innerHTML = this.elt[index].value = value; //otherwise just change the value } else { this.elt[index].value = value; } } } //if it doesn't exist make it else { var opt = document.createElement('option'); opt.innerHTML = name; if (arguments.length > 1) opt.value = value; else opt.value = name; elt.appendChild(opt); } }; self.selected = function(value) { var arr = []; if (arguments.length > 0) { for (var i = 0; i < this.elt.length; i++) { if (value.toString() === this.elt[i].value) { this.elt.selectedIndex = i; } } return this; } else { if (arg) { for (var i = 0; i < this.elt.selectedOptions.length; i++) { arr.push(this.elt.selectedOptions[i].value); } return arr; } else { return this.elt.value; } } }; return self; }; /** * Creates a radio button &lt;input&gt;&lt;/input&gt; element in the DOM. * The .option() method can be used to set options for the radio after it is * created. The .value() method will return the currently selected option. * * @method createRadio * @param {String} [divId] the id and name of the created div and input field respectively * @return {Object|p5.Element} pointer to p5.Element holding created node * @example * <div><code> * var radio; * * function setup() { * radio = createRadio(); * radio.option("black"); * radio.option("white"); * radio.option("gray"); * radio.style('width', '60px'); * textAlign(CENTER); * fill(255, 0, 0); * } * * function draw() { * var val = radio.value(); * background(val); * text(val, width/2, height/2); * } * </code></div> * <div><code> * var radio; * * function setup() { * radio = createRadio(); * radio.option('apple', 1); * radio.option('bread', 2); * radio.option('juice', 3); * radio.style('width', '60px'); * textAlign(CENTER); * } * * function draw() { * background(200); * var val = radio.value(); * if (val) { * text('item cost is $'+val, width/2, height/2); * } * } * </code></div> */ p5.prototype.createRadio = function() { var radios = document.querySelectorAll("input[type=radio]"); var count = 0; if(radios.length > 1){ var length = radios.length; var prev=radios[0].name; var current = radios[1].name; count = 1; for(var i = 1; i < length; i++) { current = radios[i].name; if(prev != current){ count++; } prev = current; } } else if (radios.length == 1){ count = 1; } var elt = document.createElement('div'); var self = addElement(elt, this); var times = -1; self.option = function(name, value){ var opt = document.createElement('input'); opt.type = 'radio'; opt.innerHTML = name; if (arguments.length > 1) opt.value = value; else opt.value = name; opt.setAttribute('name',"defaultradio"+count); elt.appendChild(opt); if (name){ times++; var ran = Math.random().toString(36).slice(2); var label = document.createElement('label'); opt.setAttribute('id', "defaultradio"+count+"-"+times); label.htmlFor = "defaultradio"+count+"-"+times; label.appendChild(document.createTextNode(name)); elt.appendChild(label); } return opt; }; self.selected = function(){ var length = this.elt.childNodes.length; if(arguments.length == 1) { for (var i = 0; i < length; i+=2){ if(this.elt.childNodes[i].value == arguments[0]) this.elt.childNodes[i].checked = true; } return this; } else { for (var i = 0; i < length; i+=2){ if(this.elt.childNodes[i].checked == true) return this.elt.childNodes[i].value; } } }; self.value = function(){ var length = this.elt.childNodes.length; if(arguments.length == 1) { for (var i = 0; i < length; i+=2){ if(this.elt.childNodes[i].value == arguments[0]) this.elt.childNodes[i].checked = true; } return this; } else { for (var i = 0; i < length; i+=2){ if(this.elt.childNodes[i].checked == true) return this.elt.childNodes[i].value; } return ""; } }; return self }; /** * Creates an &lt;input&gt;&lt;/input&gt; element in the DOM for text input. * Use .size() to set the display length of the box. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createInput * @param {Number} [value] default value of the input box * @param {String} [type] type of text, ie text, password etc. Defaults to text * @return {Object|p5.Element} pointer to p5.Element holding created node * @example * <div class='norender'><code> * function setup(){ * var inp = createInput(''); * inp.input(myInputEvent); * } * * function myInputEvent(){ * console.log('you are typing: ', this.value()); * } * * </code></div> */ p5.prototype.createInput = function(value, type) { var elt = document.createElement('input'); elt.type = type ? type : 'text'; if (value) elt.value = value; return addElement(elt, this); }; /** * Creates an &lt;input&gt;&lt;/input&gt; element in the DOM of type 'file'. * This allows users to select local files for use in a sketch. * * @method createFileInput * @param {Function} [callback] callback function for when a file loaded * @param {String} [multiple] optional to allow multiple files selected * @return {Object|p5.Element} pointer to p5.Element holding created DOM element * @example * var input; * var img; * * function setup() { * input = createFileInput(handleFile); * input.position(0, 0); * } * * function draw() { * if (img) { * image(img, 0, 0, width, height); * } * } * * function handleFile(file) { * print(file); * if (file.type === 'image') { * img = createImg(file.data); * img.hide(); * } * } */ p5.prototype.createFileInput = function(callback, multiple) { // Is the file stuff supported? if (window.File && window.FileReader && window.FileList && window.Blob) { // Yup, we're ok and make an input file selector var elt = document.createElement('input'); elt.type = 'file'; // If we get a second argument that evaluates to true // then we are looking for multiple files if (multiple) { // Anything gets the job done elt.multiple = 'multiple'; } // Function to handle when a file is selected // We're simplifying life and assuming that we always // want to load every selected file function handleFileSelect(evt) { // These are the files var files = evt.target.files; // Load each one and trigger a callback for (var i = 0; i < files.length; i++) { var f = files[i]; var reader = new FileReader(); function makeLoader(theFile) { // Making a p5.File object var p5file = new p5.File(theFile); return function(e) { p5file.data = e.target.result; callback(p5file); }; }; reader.onload = makeLoader(f); // Text or data? // This should likely be improved if (f.type.indexOf('text') > -1) { reader.readAsText(f); } else { reader.readAsDataURL(f); } } } // Now let's handle when a file was selected elt.addEventListener('change', handleFileSelect, false); return addElement(elt, this); } else { console.log('The File APIs are not fully supported in this browser. Cannot create element.'); } }; /** VIDEO STUFF **/ function createMedia(pInst, type, src, callback) { var elt = document.createElement(type); // allow src to be empty var src = src || ''; if (typeof src === 'string') { src = [src]; } for (var i=0; i<src.length; i++) { var source = document.createElement('source'); source.src = src[i]; elt.appendChild(source); } if (typeof callback !== 'undefined') { var callbackHandler = function() { callback(); elt.removeEventListener('canplaythrough', callbackHandler); } elt.addEventListener('canplaythrough', callbackHandler); } var c = addElement(elt, pInst, true); c.loadedmetadata = false; // set width and height onload metadata elt.addEventListener('loadedmetadata', function() { c.width = elt.videoWidth; c.height = elt.videoHeight; // set elt width and height if not set if (c.elt.width === 0) c.elt.width = elt.videoWidth; if (c.elt.height === 0) c.elt.height = elt.videoHeight; c.loadedmetadata = true; }); return c; } /** * Creates an HTML5 &lt;video&gt; element in the DOM for simple playback * of audio/video. Shown by default, can be hidden with .hide() * and drawn into canvas using video(). Appends to the container * node if one is specified, otherwise appends to body. The first parameter * can be either a single string path to a video file, or an array of string * paths to different formats of the same video. This is useful for ensuring * that your video can play across different browsers, as each supports * different formats. See <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats">this * page</a> for further information about supported formats. * * @method createVideo * @param {String|Array} src path to a video file, or array of paths for * supporting different browsers * @param {Object} [callback] callback function to be called upon * 'canplaythrough' event fire, that is, when the * browser can play the media, and estimates that * enough data has been loaded to play the media * up to its end without having to stop for * further buffering of content * @return {Object|p5.Element} pointer to video p5.Element */ p5.prototype.createVideo = function(src, callback) { return createMedia(this, 'video', src, callback); }; /** AUDIO STUFF **/ /** * Creates a hidden HTML5 &lt;audio&gt; element in the DOM for simple audio * playback. Appends to the container node if one is specified, * otherwise appends to body. The first parameter * can be either a single string path to a audio file, or an array of string * paths to different formats of the same audio. This is useful for ensuring * that your audio can play across different browsers, as each supports * different formats. See <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats">this * page for further information about supported formats</a>. * * @method createAudio * @param {String|Array} src path to an audio file, or array of paths for * supporting different browsers * @param {Object} [callback] callback function to be called upon * 'canplaythrough' event fire, that is, when the * browser can play the media, and estimates that * enough data has been loaded to play the media * up to its end without having to stop for * further buffering of content * @return {Object|p5.Element} pointer to audio p5.Element */ p5.prototype.createAudio = function(src, callback) { return createMedia(this, 'audio', src, callback); }; /** CAMERA STUFF **/ p5.prototype.VIDEO = 'video'; p5.prototype.AUDIO = 'audio'; navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; /** * <p>Creates a new &lt;video&gt; element that contains the audio/video feed * from a webcam. This can be drawn onto the canvas using video().</p> * <p>More specific properties of the feed can be passing in a Constraints object. * See the * <a href="http://w3c.github.io/mediacapture-main/getusermedia.html#media-track-constraints"> W3C * spec</a> for possible properties. Note that not all of these are supported * by all browsers.</p> * <p>Security note: A new browser security specification requires that getUserMedia, * which is behind createCapture(), only works when you're running the code locally, * or on HTTPS. Learn more <a href="http://stackoverflow.com/questions/34197653/getusermedia-in-chrome-47-without-using-https">here</a> * and <a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia">here</a>.</p> * * @method createCapture * @param {String|Constant|Object} type type of capture, either VIDEO or * AUDIO if none specified, default both, * or a Constraints object * @param {Function} callback function to be called once * stream has loaded * @return {Object|p5.Element} capture video p5.Element * @example * <div class='norender'><code> * var capture; * * function setup() { * createCanvas(480, 120); * capture = createCapture(VIDEO); * } * * function draw() { * image(capture, 0, 0, width, width*capture.height/capture.width); * filter(INVERT); * } * </code></div> * <div class='norender'><code> * function setup() { * createCanvas(480, 120); * var constraints = { * video: { * mandatory: { * minWidth: 1280, * minHeight: 720 * }, * optional: [ * { maxFrameRate: 10 } * ] * }, * audio: true * }; * createCapture(constraints, function(stream) { * console.log(stream); * }); * } * </code></div> */ p5.prototype.createCapture = function() { var useVideo = true; var useAudio = true; var constraints; var cb; for (var i=0; i<arguments.length; i++) { if (arguments[i] === p5.prototype.VIDEO) { useAudio = false; } else if (arguments[i] === p5.prototype.AUDIO) { useVideo = false; } else if (typeof arguments[i] === 'object') { constraints = arguments[i]; } else if (typeof arguments[i] === 'function') { cb = arguments[i]; } } if (navigator.getUserMedia) { var elt = document.createElement('video'); if (!constraints) { constraints = {video: useVideo, audio: useAudio}; } navigator.getUserMedia(constraints, function(stream) { elt.src = window.URL.createObjectURL(stream); if (cb) { cb(stream); } }, function(e) { console.log(e); }); } else { throw 'getUserMedia not supported in this browser'; } var c = addElement(elt, this, true); c.loadedmetadata = false; // set width and height onload metadata elt.addEventListener('loadedmetadata', function() { elt.play(); if (elt.width) { c.width = elt.videoWidth = elt.width; c.height = elt.videoHeight = elt.height; } else { c.width = c.elt.width = elt.videoWidth; c.height = c.elt.height = elt.videoHeight; } c.loadedmetadata = true; }); return c; }; /** * Creates element with given tag in the DOM with given content. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createElement * @param {String} tag tag for the new element * @param {String} [content] html content to be inserted into the element * @return {Object|p5.Element} pointer to p5.Element holding created node * @example * <div class='norender'><code> * var h2 = createElement('h2','im an h2 p5.element!'); * </code></div> */ p5.prototype.createElement = function(tag, content) { var elt = document.createElement(tag); if (typeof content !== 'undefined') { elt.innerHTML = content; } return addElement(elt, this); }; // ============================================================================= // p5.Element additions // ============================================================================= /** * * Adds specified class to the element. * * @for p5.Element * @method addClass * @param {String} class name of class to add * @return {Object|p5.Element} * @example * <div class='norender'><code> * var div = createDiv('div'); * div.addClass('myClass'); * </code></div> */ p5.Element.prototype.addClass = function(c) { if (this.elt.className) { // PEND don't add class more than once //var regex = new RegExp('[^a-zA-Z\d:]?'+c+'[^a-zA-Z\d:]?'); //if (this.elt.className.search(/[^a-zA-Z\d:]?hi[^a-zA-Z\d:]?/) === -1) { this.elt.className = this.elt.className+' '+c; //} } else { this.elt.className = c; } return this; } /** * * Removes specified class from the element. * * @method removeClass * @param {String} class name of class to remove * @return {Object|p5.Element} */ p5.Element.prototype.removeClass = function(c) { var regex = new RegExp('(?:^|\\s)'+c+'(?!\\S)'); this.elt.className = this.elt.className.replace(regex, ''); this.elt.className = this.elt.className.replace(/^\s+|\s+$/g, ""); //prettify (optional) return this; } /** * * Attaches the element as a child to the parent specified. * Accepts either a string ID, DOM node, or p5.Element. * If no argument is specified, an array of children DOM nodes is returned. * * @method child * @param {String|Object|p5.Element} [child] the ID, DOM node, or p5.Element * to add to the current element * @return {p5.Element} * @example * <div class='norender'><code> * var div0 = createDiv('this is the parent'); * var div1 = createDiv('this is the child'); * div0.child(div1); // use p5.Element * </code></div> * <div class='norender'><code> * var div0 = createDiv('this is the parent'); * var div1 = createDiv('this is the child'); * div1.id('apples'); * div0.child('apples'); // use id * </code></div> * <div class='norender'><code> * var div0 = createDiv('this is the parent'); * var elt = document.getElementById('myChildDiv'); * div0.child(elt); // use element from page * </code></div> */ p5.Element.prototype.child = function(c) { if (typeof c === 'undefined'){ return this.elt.childNodes } if (typeof c === 'string') { if (c[0] === '#') { c = c.substring(1); } c = document.getElementById(c); } else if (c instanceof p5.Element) { c = c.elt; } this.elt.appendChild(c); return this; }; /** * Centers a p5 Element either vertically, horizontally, * or both, relative to its parent or according to * the body if the Element has no parent. If no argument is passed * the Element is aligned both vertically and horizontally. * * @param {String} align passing 'vertical', 'horizontal' aligns element accordingly * @return {Object|p5.Element} pointer to p5.Element * @example * <div><code> * function setup() { * var div = createDiv('').size(10,10); * div.style('background-color','orange'); * div.center(); * * } * </code></div> */ p5.Element.prototype.center = function(align) { var style = this.elt.style.display; var hidden = this.elt.style.display === 'none'; var parentHidden = this.parent().style.display === 'none'; var pos = { x : this.elt.offsetLeft, y : this.elt.offsetTop }; if (hidden) this.show(); this.elt.style.display = 'block'; this.position(0,0); if (parentHidden) this.parent().style.display = 'block'; var wOffset = Math.abs(this.parent().offsetWidth - this.elt.offsetWidth); var hOffset = Math.abs(this.parent().offsetHeight - this.elt.offsetHeight); var y = pos.y; var x = pos.x; if (align === 'both' || align === undefined){ this.position(wOffset/2, hOffset/2); }else if (align === 'horizontal'){ this.position(wOffset/2, y); }else if (align === 'vertical'){ this.position(x, hOffset/2); } this.style('display', style); if (hidden) this.hide(); if (parentHidden) this.parent().style.display = 'none'; return this; }; /** * * If an argument is given, sets the inner HTML of the element, * replacing any existing html. If true is included as a second * argument, html is appended instead of replacing existing html. * If no arguments are given, returns * the inner HTML of the element. * * @for p5.Element * @method html * @param {String} [html] the HTML to be placed inside the element * @param {boolean} [append] whether to append HTML to existing * @return {Object|p5.Element|String} * @example * <div class='norender'><code> * var div = createDiv('').size(100,100); * div.html('hi'); * </code></div> * <div class='norender'><code> * var div = createDiv('Hello ').size(100,100); * div.html('World', true); * </code></div> */ p5.Element.prototype.html = function() { if (arguments.length === 0) { return this.elt.innerHTML; } else if (arguments[1]) { this.elt.innerHTML += arguments[0]; return this; } else { this.elt.innerHTML = arguments[0]; return this; } }; /** * * Sets the position of the element relative to (0, 0) of the * window. Essentially, sets position:absolute and left and top * properties of style. If no arguments given returns the x and y position * of the element in an object. * * @method position * @param {Number} [x] x-position relative to upper left of window * @param {Number} [y] y-position relative to upper left of window * @return {Object|p5.Element} * @example * <div><code class='norender'> * function setup() { * var cnv = createCanvas(100, 100); * // positions canvas 50px to the right and 100px * // below upper left corner of the window * cnv.position(50, 100); * } * </code></div> */ p5.Element.prototype.position = function() { if (arguments.length === 0){ return { 'x' : this.elt.offsetLeft , 'y' : this.elt.offsetTop }; }else{ this.elt.style.position = 'absolute'; this.elt.style.left = arguments[0]+'px'; this.elt.style.top = arguments[1]+'px'; this.x = arguments[0]; this.y = arguments[1]; return this; } }; /* Helper method called by p5.Element.style() */ p5.Element.prototype._translate = function(){ this.elt.style.position = 'absolute'; // save out initial non-translate transform styling var transform = ''; if (this.elt.style.transform) { transform = this.elt.style.transform.replace(/translate3d\(.*\)/g, ''); transform = transform.replace(/translate[X-Z]?\(.*\)/g, ''); } if (arguments.length === 2) { this.elt.style.transform = 'translate('+arguments[0]+'px, '+arguments[1]+'px)'; } else if (arguments.length > 2) { this.elt.style.transform = 'translate3d('+arguments[0]+'px,'+arguments[1]+'px,'+arguments[2]+'px)'; if (arguments.length === 3) { this.elt.parentElement.style.perspective = '1000px'; } else { this.elt.parentElement.style.perspective = arguments[3]+'px'; } } // add any extra transform styling back on end this.elt.style.transform += transform; return this; }; /* Helper method called by p5.Element.style() */ p5.Element.prototype._rotate = function(){ // save out initial non-rotate transform styling var transform = ''; if (this.elt.style.transform) { var transform = this.elt.style.transform.replace(/rotate3d\(.*\)/g, ''); transform = transform.replace(/rotate[X-Z]?\(.*\)/g, ''); } if (arguments.length === 1){ this.elt.style.transform = 'rotate('+arguments[0]+'deg)'; }else if (arguments.length === 2){ this.elt.style.transform = 'rotate('+arguments[0]+'deg, '+arguments[1]+'deg)'; }else if (arguments.length === 3){ this.elt.style.transform = 'rotateX('+arguments[0]+'deg)'; this.elt.style.transform += 'rotateY('+arguments[1]+'deg)'; this.elt.style.transform += 'rotateZ('+arguments[2]+'deg)'; } // add remaining transform back on this.elt.style.transform += transform; return this; }; /** * Sets the given style (css) property (1st arg) of the element with the * given value (2nd arg). If a single argument is given, .style() * returns the value of the given property; however, if the single argument * is given in css syntax ('text-align:center'), .style() sets the css * appropriatly. .style() also handles 2d and 3d css transforms. If * the 1st arg is 'rotate', 'translate', or 'position', the following arguments * accept Numbers as values. ('translate', 10, 100, 50); * * @method style * @param {String} property property to be set * @param {String|Number|p5.Color} [value] value to assign to property (only String|Number for rotate/translate) * @return {String|Object|p5.Element} value of property, if no value is specified * or p5.Element * @example * <div><code class="norender"> * var myDiv = createDiv("I like pandas."); * myDiv.style("font-size", "18px"); * myDiv.style("color", "#ff0000"); * </code></div> * <div><code class="norender"> * var col = color(25,23,200,50); * var button = createButton("button"); * button.style("background-color", col); * button.position(10, 10); * </code></div> * <div><code class="norender"> * var myDiv = createDiv("I like lizards."); * myDiv.style("position", 20, 20); * myDiv.style("rotate", 45); * </code></div> * <div><code class="norender"> * var myDiv; * function setup() { * background(200); * myDiv = createDiv("I like gray."); * myDiv.position(20, 20); * } * * function draw() { * myDiv.style("font-size", mouseX+"px"); * } * </code></div> */ p5.Element.prototype.style = function(prop, val) { var self = this; if (val instanceof p5.Color) { val = 'rgba(' + val.levels[0] + ',' + val.levels[1] + ',' + val.levels[2] + ',' + val.levels[3]/255 + ')' } if (typeof val === 'undefined') { if (prop.indexOf(':') === -1) { var styles = window.getComputedStyle(self.elt); var style = styles.getPropertyValue(prop); return style; } else { var attrs = prop.split(';'); for (var i = 0; i < attrs.length; i++) { var parts = attrs[i].split(':'); if (parts[0] && parts[1]) { this.elt.style[parts[0].trim()] = parts[1].trim(); } } } } else { if (prop === 'rotate' || prop === 'translate' || prop === 'position'){ var trans = Array.prototype.shift.apply(arguments); var f = this[trans] || this['_'+trans]; f.apply(this, arguments); } else { this.elt.style[prop] = val; if (prop === 'width' || prop === 'height' || prop === 'left' || prop === 'top') { var numVal = val.replace(/\D+/g, ''); this[prop] = parseInt(numVal, 10); // pend: is this necessary? } } } return this; }; /** * * Adds a new attribute or changes the value of an existing attribute * on the specified element. If no value is specified, returns the * value of the given attribute, or null if attribute is not set. * * @method attribute * @param {String} attr attribute to set * @param {String} [value] value to assign to attribute * @return {String|Object|p5.Element} value of attribute, if no value is * specified or p5.Element * @example * <div class="norender"><code> * var myDiv = createDiv("I like pandas."); * myDiv.attribute("align", "center"); * </code></div> */ p5.Element.prototype.attribute = function(attr, value) { //handling for checkboxes and radios to ensure options get //attributes not divs if(this.elt.firstChild != null && (this.elt.firstChild.type === 'checkbox' || this.elt.firstChild.type === 'radio')) { if(typeof value === 'undefined') { return this.elt.firstChild.getAttribute(attr); } else { for(var i=0; i<this.elt.childNodes.length; i++) { this.elt.childNodes[i].setAttribute(attr, value); } } } else if (typeof value === 'undefined') { return this.elt.getAttribute(attr); } else { this.elt.setAttribute(attr, value); return this; } }; /** * * Removes an attribute on the specified element. * * @method removeAttribute * @param {String} attr attribute to remove * @return {Object|p5.Element} * * @example * <div><code> * var button; * var checkbox; * * function setup() { * checkbox = createCheckbox('enable', true); * checkbox.changed(enableButton); * button = createButton('button'); * button.position(10, 10); * } * * function enableButton() { * if( this.checked() ) { * // Re-enable the button * button.removeAttribute('disabled'); * } else { * // Disable the button * button.attribute('disabled',''); * } * } * </code></div> */ p5.Element.prototype.removeAttribute = function(attr) { if(this.elt.firstChild != null && (this.elt.firstChild.type === 'checkbox' || this.elt.firstChild.type === 'radio')) { for(var i=0; i<this.elt.childNodes.length; i++) { this.elt.childNodes[i].removeAttribute(attr); } } this.elt.removeAttribute(attr); return this; }; /** * Either returns the value of the element if no arguments * given, or sets the value of the element. * * @method value * @param {String|Number} [value] * @return {String|Object|p5.Element} value of element if no value is specified or p5.Element * @example * <div class='norender'><code> * // gets the value * var inp; * function setup() { * inp = createInput(''); * } * * function mousePressed() { * print(inp.value()); * } * </code></div> * <div class='norender'><code> * // sets the value * var inp; * function setup() { * inp = createInput('myValue'); * } * * function mousePressed() { * inp.value("myValue"); * } * </code></div> */ p5.Element.prototype.value = function() { if (arguments.length > 0) { this.elt.value = arguments[0]; return this; } else { if (this.elt.type === 'range') { return parseFloat(this.elt.value); } else return this.elt.value; } }; /** * * Shows the current element. Essentially, setting display:block for the style. * * @method show * @return {Object|p5.Element} * @example * <div class='norender'><code> * var div = createDiv('div'); * div.style("display", "none"); * div.show(); // turns display to block * </code></div> */ p5.Element.prototype.show = function() { this.elt.style.display = 'block'; return this; }; /** * Hides the current element. Essentially, setting display:none for the style. * * @method hide * @return {Object|p5.Element} * @example * <div class='norender'><code> * var div = createDiv('this is a div'); * div.hide(); * </code></div> */ p5.Element.prototype.hide = function() { this.elt.style.display = 'none'; return this; }; /** * * Sets the width and height of the element. AUTO can be used to * only adjust one dimension. If no arguments given returns the width and height * of the element in an object. * * @method size * @param {Number} [w] width of the element * @param {Number} [h] height of the element * @return {Object|p5.Element} * @example * <div class='norender'><code> * var div = createDiv('this is a div'); * div.size(100, 100); * </code></div> */ p5.Element.prototype.size = function(w, h) { if (arguments.length === 0){ return { 'width' : this.elt.offsetWidth , 'height' : this.elt.offsetHeight }; }else{ var aW = w; var aH = h; var AUTO = p5.prototype.AUTO; if (aW !== AUTO || aH !== AUTO) { if (aW === AUTO) { aW = h * this.width / this.height; } else if (aH === AUTO) { aH = w * this.height / this.width; } // set diff for cnv vs normal div if (this.elt instanceof HTMLCanvasElement) { var j = {}; var k = this.elt.getContext('2d'); for (var prop in k) { j[prop] = k[prop]; } this.elt.setAttribute('width', aW * this._pInst._pixelDensity); this.elt.setAttribute('height', aH * this._pInst._pixelDensity); this.elt.setAttribute('style', 'width:' + aW + 'px; height:' + aH + 'px'); this._pInst.scale(this._pInst._pixelDensity, this._pInst._pixelDensity); for (var prop in j) { this.elt.getContext('2d')[prop] = j[prop]; } } else { this.elt.style.width = aW+'px'; this.elt.style.height = aH+'px'; this.elt.width = aW; this.elt.height = aH; this.width = aW; this.height = aH; } this.width = this.elt.offsetWidth; this.height = this.elt.offsetHeight; if (this._pInst) { // main canvas associated with p5 instance if (this._pInst._curElement.elt === this.elt) { this._pInst._setProperty('width', this.elt.offsetWidth); this._pInst._setProperty('height', this.elt.offsetHeight); } } } return this; } }; /** * Removes the element and deregisters all listeners. * @method remove * @example * <div class='norender'><code> * var myDiv = createDiv('this is some text'); * myDiv.remove(); * </code></div> */ p5.Element.prototype.remove = function() { // deregister events for (var ev in this._events) { this.elt.removeEventListener(ev, this._events[ev]); } if (this.elt.parentNode) { this.elt.parentNode.removeChild(this.elt); } delete(this); }; // ============================================================================= // p5.MediaElement additions // ============================================================================= /** * Extends p5.Element to handle audio and video. In addition to the methods * of p5.Element, it also contains methods for controlling media. It is not * called directly, but p5.MediaElements are created by calling createVideo, * createAudio, and createCapture. * * @class p5.MediaElement * @constructor * @param {String} elt DOM node that is wrapped * @param {Object} [pInst] pointer to p5 instance */ p5.MediaElement = function(elt, pInst) { p5.Element.call(this, elt, pInst); var self = this; this.elt.crossOrigin = 'anonymous'; this._prevTime = 0; this._cueIDCounter = 0; this._cues = []; this._pixelDensity = 1; /** * Path to the media element source. * * @property src * @return {String} src */ Object.defineProperty(self, 'src', { get: function() { var firstChildSrc = self.elt.children[0].src; var srcVal = self.elt.src === window.location.href ? '' : self.elt.src; var ret = firstChildSrc === window.location.href ? srcVal : firstChildSrc; return ret; }, set: function(newValue) { for (var i = 0; i < self.elt.children.length; i++) { self.elt.removeChild(self.elt.children[i]); } var source = document.createElement('source'); source.src = newValue; elt.appendChild(source); self.elt.src = newValue; }, }); // private _onended callback, set by the method: onended(callback) self._onended = function() {}; self.elt.onended = function() { self._onended(self); } }; p5.MediaElement.prototype = Object.create(p5.Element.prototype); /** * Play an HTML5 media element. * * @method play * @return {Object|p5.Element} */ p5.MediaElement.prototype.play = function() { if (this.elt.currentTime === this.elt.duration) { this.elt.currentTime = 0; } if (this.elt.readyState > 1) { this.elt.play(); } else { // in Chrome, playback cannot resume after being stopped and must reload this.elt.load(); this.elt.play(); } return this; }; /** * Stops an HTML5 media element (sets current time to zero). * * @method stop * @return {Object|p5.Element} */ p5.MediaElement.prototype.stop = function() { this.elt.pause(); this.elt.currentTime = 0; return this; }; /** * Pauses an HTML5 media element. * * @method pause * @return {Object|p5.Element} */ p5.MediaElement.prototype.pause = function() { this.elt.pause(); return this; }; /** * Set 'loop' to true for an HTML5 media element, and starts playing. * * @method loop * @return {Object|p5.Element} */ p5.MediaElement.prototype.loop = function() { this.elt.setAttribute('loop', true); this.play(); return this; }; /** * Set 'loop' to false for an HTML5 media element. Element will stop * when it reaches the end. * * @method noLoop * @return {Object|p5.Element} */ p5.MediaElement.prototype.noLoop = function() { this.elt.setAttribute('loop', false); return this; }; /** * Set HTML5 media element to autoplay or not. * * @method autoplay * @param {Boolean} autoplay whether the element should autoplay * @return {Object|p5.Element} */ p5.MediaElement.prototype.autoplay = function(val) { this.elt.setAttribute('autoplay', val); return this; }; /** * Sets volume for this HTML5 media element. If no argument is given, * returns the current volume. * * @param {Number} [val] volume between 0.0 and 1.0 * @return {Number|p5.MediaElement} current volume or p5.MediaElement * @method volume */ p5.MediaElement.prototype.volume = function(val) { if (typeof val === 'undefined') { return this.elt.volume; } else { this.elt.volume = val; } }; /** * If no arguments are given, returns the current playback speed of the * element. The speed parameter sets the speed where 2.0 will play the * element twice as fast, 0.5 will play at half the speed, and -1 will play * the element in normal speed in reverse.(Note that not all browsers support * backward playback and even if they do, playback might not be smooth.) * * @method speed * @param {Number} [speed] speed multiplier for element playback * @return {Number|Object|p5.MediaElement} current playback speed or p5.MediaElement */ p5.MediaElement.prototype.speed = function(val) { if (typeof val === 'undefined') { return this.elt.playbackRate; } else { this.elt.playbackRate = val; } }; /** * If no arguments are given, returns the current time of the element. * If an argument is given the current time of the element is set to it. * * @method time * @param {Number} [time] time to jump to (in seconds) * @return {Number|Object|p5.MediaElement} current time (in seconds) * or p5.MediaElement */ p5.MediaElement.prototype.time = function(val) { if (typeof val === 'undefined') { return this.elt.currentTime; } else { this.elt.currentTime = val; } }; /** * Returns the duration of the HTML5 media element. * * @method duration * @return {Number} duration */ p5.MediaElement.prototype.duration = function() { return this.elt.duration; }; p5.MediaElement.prototype.pixels = []; p5.MediaElement.prototype.loadPixels = function() { if (!this.canvas) { this.canvas = document.createElement('canvas'); this.drawingContext = this.canvas.getContext('2d'); } if (this.loadedmetadata) { // wait for metadata for w/h if (this.canvas.width !== this.elt.width) { this.canvas.width = this.elt.width; this.canvas.height = this.elt.height; this.width = this.canvas.width; this.height = this.canvas.height; } this.drawingContext.drawImage(this.elt, 0, 0, this.canvas.width, this.canvas.height); p5.Renderer2D.prototype.loadPixels.call(this); } return this; } p5.MediaElement.prototype.updatePixels = function(x, y, w, h){ if (this.loadedmetadata) { // wait for metadata p5.Renderer2D.prototype.updatePixels.call(this, x, y, w, h); } return this; } p5.MediaElement.prototype.get = function(x, y, w, h){ if (this.loadedmetadata) { // wait for metadata return p5.Renderer2D.prototype.get.call(this, x, y, w, h); } else if (typeof x === 'undefined') { return new p5.Image(1, 1); } else if (w > 1) { return new p5.Image(x, y, w, h); } else { return [0, 0, 0, 255]; } }; p5.MediaElement.prototype.set = function(x, y, imgOrCol){ if (this.loadedmetadata) { // wait for metadata p5.Renderer2D.prototype.set.call(this, x, y, imgOrCol); } }; p5.MediaElement.prototype.copy = function(){ p5.Renderer2D.prototype.copy.apply(this, arguments); }; p5.MediaElement.prototype.mask = function(){ this.loadPixels(); p5.Image.prototype.mask.apply(this, arguments); }; /** * Schedule an event to be called when the audio or video * element reaches the end. If the element is looping, * this will not be called. The element is passed in * as the argument to the onended callback. * * @method onended * @param {Function} callback function to call when the * soundfile has ended. The * media element will be passed * in as the argument to the * callback. * @return {Object|p5.MediaElement} * @example * <div><code> * function setup() { * audioEl = createAudio('assets/beat.mp3'); * audioEl.showControls(true); * audioEl.onended(sayDone); * } * * function sayDone(elt) { * alert('done playing ' + elt.src ); * } * </code></div> */ p5.MediaElement.prototype.onended = function(callback) { this._onended = callback; return this; }; /*** CONNECT TO WEB AUDIO API / p5.sound.js ***/ /** * Send the audio output of this element to a specified audioNode or * p5.sound object. If no element is provided, connects to p5's master * output. That connection is established when this method is first called. * All connections are removed by the .disconnect() method. * * This method is meant to be used with the p5.sound.js addon library. * * @method connect * @param {AudioNode|p5.sound object} audioNode AudioNode from the Web Audio API, * or an object from the p5.sound library */ p5.MediaElement.prototype.connect = function(obj) { var audioContext, masterOutput; // if p5.sound exists, same audio context if (typeof p5.prototype.getAudioContext === 'function') { audioContext = p5.prototype.getAudioContext(); masterOutput = p5.soundOut.input; } else { try { audioContext = obj.context; masterOutput = audioContext.destination } catch(e) { throw 'connect() is meant to be used with Web Audio API or p5.sound.js' } } // create a Web Audio MediaElementAudioSourceNode if none already exists if (!this.audioSourceNode) { this.audioSourceNode = audioContext.createMediaElementSource(this.elt); // connect to master output when this method is first called this.audioSourceNode.connect(masterOutput); } // connect to object if provided if (obj) { if (obj.input) { this.audioSourceNode.connect(obj.input); } else { this.audioSourceNode.connect(obj); } } // otherwise connect to master output of p5.sound / AudioContext else { this.audioSourceNode.connect(masterOutput); } }; /** * Disconnect all Web Audio routing, including to master output. * This is useful if you want to re-route the output through * audio effects, for example. * * @method disconnect */ p5.MediaElement.prototype.disconnect = function() { if (this.audioSourceNode) { this.audioSourceNode.disconnect(); } else { throw 'nothing to disconnect'; } }; /*** SHOW / HIDE CONTROLS ***/ /** * Show the default MediaElement controls, as determined by the web browser. * * @method showControls */ p5.MediaElement.prototype.showControls = function() { // must set style for the element to show on the page this.elt.style['text-align'] = 'inherit'; this.elt.controls = true; }; /** * Hide the default mediaElement controls. * * @method hideControls */ p5.MediaElement.prototype.hideControls = function() { this.elt.controls = false; }; /*** SCHEDULE EVENTS ***/ /** * Schedule events to trigger every time a MediaElement * (audio/video) reaches a playback cue point. * * Accepts a callback function, a time (in seconds) at which to trigger * the callback, and an optional parameter for the callback. * * Time will be passed as the first parameter to the callback function, * and param will be the second parameter. * * * @method addCue * @param {Number} time Time in seconds, relative to this media * element's playback. For example, to trigger * an event every time playback reaches two * seconds, pass in the number 2. This will be * passed as the first parameter to * the callback function. * @param {Function} callback Name of a function that will be * called at the given time. The callback will * receive time and (optionally) param as its * two parameters. * @param {Object} [value] An object to be passed as the * second parameter to the * callback function. * @return {Number} id ID of this cue, * useful for removeCue(id) * @example * <div><code> * function setup() { * background(255,255,255); * * audioEl = createAudio('assets/beat.mp3'); * audioEl.showControls(); * * // schedule three calls to changeBackground * audioEl.addCue(0.5, changeBackground, color(255,0,0) ); * audioEl.addCue(1.0, changeBackground, color(0,255,0) ); * audioEl.addCue(2.5, changeBackground, color(0,0,255) ); * audioEl.addCue(3.0, changeBackground, color(0,255,255) ); * audioEl.addCue(4.2, changeBackground, color(255,255,0) ); * audioEl.addCue(5.0, changeBackground, color(255,255,0) ); * } * * function changeBackground(val) { * background(val); * } * </code></div> */ p5.MediaElement.prototype.addCue = function(time, callback, val) { var id = this._cueIDCounter++; var cue = new Cue(callback, time, id, val); this._cues.push(cue); if (!this.elt.ontimeupdate) { this.elt.ontimeupdate = this._onTimeUpdate.bind(this); } return id; }; /** * Remove a callback based on its ID. The ID is returned by the * addCue method. * * @method removeCue * @param {Number} id ID of the cue, as returned by addCue */ p5.MediaElement.prototype.removeCue = function(id) { for (var i = 0; i < this._cues.length; i++) { if (this._cues[i] === id) { console.log(id) this._cues.splice(i, 1); } } if (this._cues.length === 0) { this.elt.ontimeupdate = null } }; /** * Remove all of the callbacks that had originally been scheduled * via the addCue method. * * @method clearCues */ p5.MediaElement.prototype.clearCues = function() { this._cues = []; this.elt.ontimeupdate = null; }; // private method that checks for cues to be fired if events // have been scheduled using addCue(callback, time). p5.MediaElement.prototype._onTimeUpdate = function() { var playbackTime = this.time(); for (var i = 0 ; i < this._cues.length; i++) { var callbackTime = this._cues[i].time; var val = this._cues[i].val; if (this._prevTime < callbackTime && callbackTime <= playbackTime) { // pass the scheduled callbackTime as parameter to the callback this._cues[i].callback(val); } } this._prevTime = playbackTime; }; // Cue inspired by JavaScript setTimeout, and the // Tone.js Transport Timeline Event, MIT License Yotam Mann 2015 tonejs.org var Cue = function(callback, time, id, val) { this.callback = callback; this.time = time; this.id = id; this.val = val; }; // ============================================================================= // p5.File // ============================================================================= /** * Base class for a file * Using this for createFileInput * * @class p5.File * @constructor * @param {File} file File that is wrapped * @param {Object} [pInst] pointer to p5 instance */ p5.File = function(file, pInst) { /** * Underlying File object. All normal File methods can be called on this. * * @property file */ this.file = file; this._pInst = pInst; // Splitting out the file type into two components // This makes determining if image or text etc simpler var typeList = file.type.split('/'); /** * File type (image, text, etc.) * * @property type */ this.type = typeList[0]; /** * File subtype (usually the file extension jpg, png, xml, etc.) * * @property subtype */ this.subtype = typeList[1]; /** * File name * * @property name */ this.name = file.name; /** * File size * * @property size */ this.size = file.size; /** * URL string containing image data. * * @property data */ this.data = undefined; }; }));
dsii-2017-unirsm/dsii-2017-unirsm.github.io
taniasabatini/10PRINT/libraries/p5.dom.js
JavaScript
mit
70,383
<?php namespace Nur\Database; use Illuminate\Database\Eloquent\Model as EloquentModel; /** * @mixin \Illuminate\Database\Query\Builder */ class Model extends EloquentModel { /** * Create Eloquent Model. * * @param array $attributes * * @return void */ function __construct(array $attributes = []) { parent::__construct($attributes); Eloquent::getInstance()->getCapsule(); Eloquent::getInstance()->getSchema(); } }
izniburak/nur-core
src/Database/Model.php
PHP
mit
489
module Miro class DominantColors attr_accessor :src_image_path def initialize(src_image_path, image_type = nil) @src_image_path = src_image_path @image_type = image_type end def to_hex return histogram.map{ |item| item[1].html } if Miro.histogram? sorted_pixels.collect { |pixel| ChunkyPNG::Color.to_hex(pixel, false) } end def to_rgb return histogram.map { |item| item[1].to_rgb.to_a } if Miro.histogram? sorted_pixels.collect { |pixel| ChunkyPNG::Color.to_truecolor_bytes(pixel) } end def to_rgba return histogram.map { |item| item[1].css_rgba } if Miro.histogram? sorted_pixels.collect { |pixel| ChunkyPNG::Color.to_truecolor_alpha_bytes(pixel) } end def to_hsl histogram.map { |item| item[1].to_hsl.to_a } if Miro.histogram? end def to_cmyk histogram.map { |item| item[1].to_cmyk.to_a } if Miro.histogram? end def to_yiq histogram.map { |item| item[1].to_yiq.to_a } if Miro.histogram? end def by_percentage return nil if Miro.histogram? sorted_pixels pixel_count = @pixels.size sorted_pixels.collect { |pixel| @grouped_pixels[pixel].size / pixel_count.to_f } end def sorted_pixels @sorted_pixels ||= extract_colors_from_image end def histogram @histogram ||= downsample_and_histogram.sort_by { |item| item[0] }.reverse end private def downsample_and_histogram @source_image = open_source_image hstring = Cocaine::CommandLine.new(Miro.options[:image_magick_path], image_magick_params). run(:in => File.expand_path(@source_image.path), :resolution => Miro.options[:resolution], :colors => Miro.options[:color_count].to_s, :quantize => Miro.options[:quantize]) cleanup_temporary_files! parse_result(hstring) end def parse_result(hstring) hstring.scan(/(\d*):.*(#[0-9A-Fa-f]*)/).collect do |match| [match[0].to_i, Object.const_get("Color::#{Miro.options[:quantize].upcase}").from_html(match[1])] end end def extract_colors_from_image downsample_colors_and_convert_to_png! colors = sort_by_dominant_color cleanup_temporary_files! colors end def downsample_colors_and_convert_to_png! @source_image = open_source_image @downsampled_image = open_downsampled_image Cocaine::CommandLine.new(Miro.options[:image_magick_path], image_magick_params). run(:in => File.expand_path(@source_image.path), :resolution => Miro.options[:resolution], :colors => Miro.options[:color_count].to_s, :quantize => Miro.options[:quantize], :out => File.expand_path(@downsampled_image.path)) end def open_source_image return File.open(@src_image_path) unless remote_source_image? original_extension = @image_type || URI.parse(@src_image_path).path.split('.').last tempfile = Tempfile.open(["source", ".#{original_extension}"]) remote_file_data = open(@src_image_path).read tempfile.write(should_force_encoding? ? remote_file_data.force_encoding("UTF-8") : remote_file_data) tempfile.close tempfile end def should_force_encoding? Gem::Version.new(RUBY_VERSION.dup) >= Gem::Version.new('1.9') end def open_downsampled_image tempfile = Tempfile.open(["downsampled", '.png']) tempfile.binmode tempfile end def image_magick_params if Miro.histogram? "':in[0]' -resize :resolution -colors :colors -colorspace :quantize -quantize :quantize -alpha remove -format %c histogram:info:" else "':in[0]' -resize :resolution -colors :colors -colorspace :quantize -quantize :quantize :out" end end def group_pixels_by_color @pixels ||= ChunkyPNG::Image.from_file(File.expand_path(@downsampled_image.path)).pixels @grouped_pixels ||= @pixels.group_by { |pixel| pixel } end def sort_by_dominant_color group_pixels_by_color.sort_by { |k,v| v.size }.reverse.flatten.uniq end def cleanup_temporary_files! @source_image.close! if remote_source_image? @downsampled_image.close! if @downsampled_image end def remote_source_image? @src_image_path =~ /^https?:\/\// end end end
oxoooo/miro
lib/miro/dominant_colors.rb
Ruby
mit
4,361
<?php include_once('Msidcalendar_LifeCycle.php'); class Msidcalendar_Plugin extends Msidcalendar_LifeCycle { /** * See: http://plugin.michael-simpson.com/?page_id=31 * @return array of option meta data. */ public function getOptionMetaData() { // http://plugin.michael-simpson.com/?page_id=31 return array( //'_version' => array('Installed Version'), // Leave this one commented-out. Uncomment to test upgrades. 'MSIDBaseURL' => array(__('Base url to the MSI Calendar', 'my-awesome-plugin')), 'CanSeeSubmitData' => array(__('Can See Submission data', 'my-awesome-plugin'), 'Administrator', 'Editor', 'Author', 'Contributor', 'Subscriber', 'Anyone') ); } // protected function getOptionValueI18nString($optionValue) { // $i18nValue = parent::getOptionValueI18nString($optionValue); // return $i18nValue; // } protected function initOptions() { $options = $this->getOptionMetaData(); if (!empty($options)) { foreach ($options as $key => $arr) { if (is_array($arr) && count($arr > 1)) { $this->addOption($key, $arr[1]); } } $this->updateOption('MSIDBaseURL','http://msid.ca/calendar/events/json/'); } } public function getPluginDisplayName() { return 'MSIDCalendar'; } protected function getMainPluginFileName() { return 'msidcalendar.php'; } /** * See: http://plugin.michael-simpson.com/?page_id=101 * Called by install() to create any database tables if needed. * Best Practice: * (1) Prefix all table names with $wpdb->prefix * (2) make table names lower case only * @return void */ protected function installDatabaseTables() { // global $wpdb; // $tableName = $this->prefixTableName('mytable'); // $wpdb->query("CREATE TABLE IF NOT EXISTS `$tableName` ( // `id` INTEGER NOT NULL"); } /** * See: http://plugin.michael-simpson.com/?page_id=101 * Drop plugin-created tables on uninstall. * @return void */ protected function unInstallDatabaseTables() { // global $wpdb; // $tableName = $this->prefixTableName('mytable'); // $wpdb->query("DROP TABLE IF EXISTS `$tableName`"); } /** * Perform actions when upgrading from version X to version Y * See: http://plugin.michael-simpson.com/?page_id=35 * @return void */ public function upgrade() { } public function addActionsAndFilters() { // Add options administration page // http://plugin.michael-simpson.com/?page_id=47 add_action('admin_menu', array(&$this, 'addSettingsSubMenuPage')); // Example adding a script & style just for the options administration page // http://plugin.michael-simpson.com/?page_id=47 // if (strpos($_SERVER['REQUEST_URI'], $this->getSettingsSlug()) !== false) { // wp_enqueue_script('my-script', plugins_url('/js/my-script.js', __FILE__)); // wp_enqueue_style('my-style', plugins_url('/css/my-style.css', __FILE__)); // } // Add Actions & Filters // http://plugin.michael-simpson.com/?page_id=37 // Adding scripts & styles to all pages // Examples: add_action( 'wp_enqueue_scripts', array( &$this, 'register_plugin_styles' ) ); add_action( 'wp_enqueue_scripts', array( &$this, 'register_plugin_scripts' ) ); // Register short codes // http://plugin.michael-simpson.com/?page_id=39 // Register AJAX hooks // http://plugin.michael-simpson.com/?page_id=41 add_action( 'wp_ajax_fetch_events', array( &$this, 'fetch_events' ) ); add_action( 'wp_ajax_nopriv_fetch_events', array( &$this, 'fetch_events' ) );// optional // Include the Ajax library on the front end add_action( 'wp_head', array( &$this, 'add_ajax_library' ) ); } /*--------------------------------------------* * Action Functions *--------------------------------------------*/ /** * Adds the WordPress Ajax Library to the frontend. */ public function add_ajax_library() { $html = '<script type="text/javascript">'; $html .= 'var msidajaxurl = "' . admin_url( 'admin-ajax.php' ) . '"'; $html .= '</script>'; echo $html; } // end add_ajax_library /** * Registers and enqueues plugin-specific styles. */ public function register_plugin_styles() { wp_enqueue_style('jquery-ui','http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css'); wp_register_style( 'ive-read-this', plugins_url( 'ive-read-this/css/plugin.css' ) ); wp_enqueue_style( 'ive-read-this' ); } // end register_plugin_styles /** * Registers and enqueues plugin-specific scripts. */ public function register_plugin_scripts() { wp_enqueue_script('jquery-ui', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js', array('jquery'), '1.10.3'); wp_register_script( 'ive-read-this', plugins_url( 'ive-read-this/js/plugin.js' ), array( 'jquery' ) ); wp_enqueue_script( 'ive-read-this' ); } // end register_plugin_scripts public function fetch_events() { // Don't let IE cache this request header("Pragma: no-cache"); header("Cache-Control: no-cache, must-revalidate"); header("Expires: Thu, 01 Jan 1970 00:00:00 GMT"); header("Content-type: text/plain"); $start = date('Y-m-d',$_POST["start"]); $end = date('Y-m-d',$_POST["end"]); $url = 'http://msid.ca/calendar/events/json/?sustainability_month=true&start_date='.$start.'&end_date='.$end; $json = file_get_contents($url ); $obj = json_decode($json); $events = array(); foreach($obj->events as $event) { $calobj=array(); $calobj['title']= $event->summary; $calobj['id'] = $event->id; $calobj['keywords']= $event->keywords; $calobj['allDay'] = empty($event->start_time); $calobj['start'] = date('c',strtotime($event->year.'-'.$event->month.'-'.$event->day.' '.date("H:i", strtotime($event->start_time)))); $calobj['end'] = date('c',strtotime($event->year.'-'.$event->month.'-'.$event->day.' '.date("H:i", strtotime($event->end_time)))); array_push($events, $calobj); } echo json_encode($events); die(); } }
bretthamilton/msidcalendar
Msidcalendar_Plugin.php
PHP
mit
6,513
<div class="container-fluid"> <div class="page-content"> <div class="portlet-body form"> <!-- BEGIN FORM--> <form action="<?php echo base_url(); ?>User/user_dashboard/editorginfo" method="POST" role="form" class="horizontal-form"> <div class="form-body"> <h3 class="form-section">Organization Information</h3> <div class="row "> <!-- ACTIVITY TITLE --> <div class="col-md-12"> <div class="form-group"> <div class="form-group form-md-line-input"> <input type="text" class="form-control" id="title" placeholder="Enter Organization Name" name="org_name" value="<?=$org['organization_name']?>"> <label for="form_control_1">Organization Name: </label> <span class="help-block">Input Organization Name</span> </div> </div> </div> <!-- /ACTIVITY TITLE --> <!-- DESCRIPTION --> <div class="col-md-12"> <div class="form-group form-md-line-input"> <textarea class="form-control" rows="3" placeholder="Enter Acronym" name="org_abbreviation" ><?=$org['organization_abbreviation']?></textarea> <label for="form_control_1">Acronym </label> <span class="help-block">Enter Acronym for your organization</span> </div> </div> <!-- /DESCRIPTION --> <!-- GENERAL OBJECTIVES --> <div class="col-md-12"> <div class="form-group form-md-line-input"> <textarea class="form-control" rows="3" placeholder="Enter Mission" name="org_mission" ><?=$org['org_mission']?>"</textarea> <label for="form_control_1">Mission</label> <span class="help-block">What is the mission of this organization? </span> </div> </div> <!-- /GENERAL OBJECTIVES --> <!-- SPECIFIC OBJECTIVES --> <div class="col-md-12"> <div class="form-group form-md-line-input"> <textarea class="form-control" rows="3" placeholder="Enter Vision" name="org_vision" value=""><?=$org['org_vision']?></textarea> <label for="form_control_1">Vision</label> <span class="help-block">What is the vision of this organization? </span> </div> </div> <!-- /SPECIFIC OBJECTIVES --> </div> <!--/span--> </div> <ul id="list_item"> </ul> <div class="form-actions right"> <button type="submit" class="btn green"><i class="fa fa-check"></i> Save Changes</button> <button type="button" id="modalbutton1" class="btn default">Cancel</button> </div> </form> <!-- END FORM--> </div> </div> </div>
mrkjohnperalta/ITSQ
application/views/USER/user_editorginfo.php
PHP
mit
3,737
import {Server, Config} from "./server"; import * as path from "path"; /** * Load configuration file given as command line parameter */ let config: Config; if (process.argv.length > 2) { const configPath = path.join(__dirname, process.argv[2]); console.info("loading configuration file: " + configPath); config = require(configPath); }else { console.error("no configuration file provided, exiting"); process.exit(); }; const server = new Server(config); server.run();
filosofianakatemia/qne
server/src/index.ts
TypeScript
mit
482
import { createStore } from '@utils/store.utils'; import placeholderImage from '../images/placeholder.jpeg'; import { getPhotoUrl, getPrefetchedPhotoForDisplay } from './api'; import { getLocalPhotoPath, getRandomLocalPhoto } from './photos.local'; import Settings from './settings'; export const getStateObject = (force = false) => { const fetchFromServer = Settings.fetchFromServer; const newPhotoDuration = Settings.newPhotoDuration; let photoUrl; let placeholderPhotoUrl; let photoMeta; let placeholderPhotoMeta; // if allowed to fetch from server // begin with assuming we get a // prefetched photo from the api if (fetchFromServer) { photoMeta = getPrefetchedPhotoForDisplay(force ? 0 : newPhotoDuration); photoUrl = getPhotoUrl(photoMeta); } // or a locally stored photo if (!photoUrl) { photoMeta = getRandomLocalPhoto(); photoUrl = getLocalPhotoPath(photoMeta); } // or a fallback placeholder photo if (!photoUrl) { photoMeta = null; photoUrl = placeholderImage; } // get a random image as placeholder // to handle offline network scenarios placeholderPhotoMeta = getRandomLocalPhoto(); placeholderPhotoUrl = getLocalPhotoPath(placeholderPhotoMeta); return { fetchFromServer, photoUrl, photoMeta, placeholderPhotoUrl, placeholderPhotoMeta, newPhotoDuration, }; }; export default createStore();
emadalam/mesmerized
src/modules/background/utils/store.js
JavaScript
mit
1,498
using System; using System.ComponentModel; using System.Reactive.Linq; using System.Reactive.Subjects; namespace Moen.KanColle.Dentan.ViewModel { public abstract class ViewModel<T> : ModelBase, IDisposable where T : ModelBase { public T Model { get; private set; } public IConnectableObservable<string> PropertyChangedObservable { get; private set; } IDisposable r_Subscriptions; protected ViewModel(T rpModel) { Model = rpModel; PropertyChangedObservable = Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>( rpHandler => Model.PropertyChanged += rpHandler, rpHandler => Model.PropertyChanged -= rpHandler) .Select(r => r.EventArgs.PropertyName).Publish(); r_Subscriptions = PropertyChangedObservable.Connect(); } public void Dispose() { r_Subscriptions.Dispose(); } } }
KodamaSakuno/ProjectDentan
Dentan/ViewModel/ViewModel`T.cs
C#
mit
1,000
import {Component} from 'react'; import {reduxForm} from 'redux-form'; import './CreateTodoForm.styl'; class CreateTodoForm extends Component { render() { return ( <form className="create-todo-form" onSubmit={this.props.handleSubmit} autoComplete="off"> <input type="text" placeholder="Todo text..." {...this.props.fields.text}></input> <button type="submit">Create</button> </form> ); } } CreateTodoForm.propTypes = { fields: React.PropTypes.object.isRequired, handleSubmit: React.PropTypes.func.isRequired }; export default reduxForm({ form: 'CreateTodoForm', fields: ['text'] })(CreateTodoForm);
malykhinvi/generator-spa
generators/app/templates/src/pages/TodosPage/CreateTodoForm.js
JavaScript
mit
651
require 'spec_helper' describe SK::GameObjectManager do it "can create a game_object with a name" do expect(SK::GameObjectManager.new).to respond_to(:create).with(1).argument end it "can not create a game_object without a name" do expect(SK::GameObjectManager.new).to_not respond_to(:create).with(0).arguments end it "creates a new game_object when calling name" do expect(SK::GameObjectManager.new.create("my_obj").name).to eq("my_obj") end it "can remove a game_object" do manager = SK::GameObjectManager.new game_object = manager.create("obj") manager.remove(game_object) expect(manager.instance_variable_get(:@game_objects).size).to be(0) end it "starts a gameobject when created if manager alread has started" do manager = SK::GameObjectManager.new manager.start expect_any_instance_of(SK::GameObject).to receive(:start) obj = manager.create "obj" end it "generates a unique id for all new game_objects created" do manager = SK::GameObjectManager.new expect(manager.create("obj_1").id).to eq(1) expect(manager.create("obj_2").id).to eq(2) expect(manager.create("obj_3").id).to eq(3) expect(manager.create("obj_4").id).to eq(4) end it "contains the game_object after calling create" do manager = SK::GameObjectManager.new manager.create("my_obj") expect(manager.instance_variable_get(:@game_objects).size).to eq(1) end it "can be updated" do expect(SK::GameObjectManager.new).to respond_to(:update).with(1).argument end it "can be drawn with a context" do expect(SK::GameObjectManager.new).to respond_to(:draw).with(1).argument end it "starts all gameobjects when calling start" do manager = SK::GameObjectManager.new obj = manager.create("my_obj") expect(obj).to receive(:start) manager.start end it "updates all gameobjects when calling update" do manager = SK::GameObjectManager.new obj = manager.create("my_obj") expect(obj).to receive(:update).with(16.0) manager.update 16.0 end it "draws all gameobjects in order of sorting layer" do manager = SK::GameObjectManager.new foreground_object = manager.create("fg") fg_component = SK::Component.new() fg_component.layer = 1 foreground_object.add_component fg_component background_object = manager.create("bg") bg_component = SK::Component.new() bg_component.layer = 0 background_object.add_component bg_component context = "context" expect(bg_component).to receive(:draw).ordered expect(fg_component).to receive(:draw).ordered manager.draw context end it "draws all gameobjects in order of sorting layer and order in layer" do manager = SK::GameObjectManager.new foreground_object = manager.create("fg") fg_component = SK::Component.new() fg_component.layer = 1 foreground_object.add_component fg_component background_object = manager.create("bg") bg_component = SK::Component.new() bg_component.layer = 0 bg_component.order_in_layer = 2 bg_component2 = SK::Component.new() bg_component2.layer = 0 bg_component2.order_in_layer = 3 background_object.add_component bg_component background_object.add_component bg_component2 context = "context" expect(bg_component).to receive(:draw).ordered expect(bg_component2).to receive(:draw).ordered manager.draw context end end
eriksk/shirokuro
spec/shirokuro/ecs/game_object_manager_spec.rb
Ruby
mit
3,298
module DataMapper # :include:/QUICKLINKS # # = Types # Provides means of writing custom types for properties. Each type is based # on a ruby primitive and handles its own serialization and materialization, # and therefore is responsible for providing those methods. # # To see complete list of supported types, see documentation for # DataMapper::Property::TYPES # # == Defining new Types # To define a new type, subclass DataMapper::Type, pick ruby primitive, and # set the options for this type. # # class MyType < DataMapper::Type # primitive String # size 10 # end # # Following this, you will be able to use MyType as a type for any given # property. If special materialization and serialization is required, # override the class methods # # class MyType < DataMapper::Type # primitive String # size 10 # # def self.dump(value, property) # <work some magic> # end # # def self.load(value) # <work some magic> # end # end class Type PROPERTY_OPTIONS = [ :public, :protected, :private, :accessor, :reader, :writer, :lazy, :default, :nullable, :key, :serial, :field, :size, :length, :format, :index, :check, :ordinal, :auto_validation, :validates, :unique, :lock, :track ] PROPERTY_OPTION_ALIASES = { :size => [ :length ] } class << self def configure(primitive_type, options) @_primitive_type = primitive_type @_options = options def self.inherited(base) base.primitive @_primitive_type @_options.each do |k, v| base.send(k, v) end end self end # The Ruby primitive type to use as basis for this type. See # DataMapper::Property::TYPES for list of types. # # ==== Parameters # primitive<Class, nil>:: # The class for the primitive. If nil is passed in, it returns the # current primitive # # ==== Returns # Class:: if the <primitive> param is nil, return the current primitive. # # @public def primitive(primitive = nil) return @primitive if primitive.nil? @primitive = primitive end #load DataMapper::Property options PROPERTY_OPTIONS.each do |property_option| self.class_eval <<-EOS, __FILE__, __LINE__ def #{property_option}(arg = nil) return @#{property_option} if arg.nil? @#{property_option} = arg end EOS end #create property aliases PROPERTY_OPTION_ALIASES.each do |property_option, aliases| aliases.each do |ali| self.class_eval <<-EOS, __FILE__, __LINE__ alias #{ali} #{property_option} EOS end end # Gives all the options set on this type # # ==== Returns # Hash:: with all options and their values set on this type # # @public def options options = {} PROPERTY_OPTIONS.each do |method| next if (value = send(method)).nil? options[method] = value end options end end # Stub instance method for dumping # # ==== Parameters # value<Object, nil>:: # The value to dump # property<Property, nil>:: # The property the type is being used by # # ==== Returns # Object:: Dumped object # # # @public def self.dump(value, property) value end # Stub instance method for loading # # ==== Parameters # value<Object, nil>:: # The value to serialize # property<Property, nil>:: # The property the type is being used by # # ==== Returns # Object:: Serialized object. Must be the same type as the ruby primitive # # # @public def self.load(value, property) value end end # class Type def self.Type(primitive_type, options = {}) Class.new(Type).configure(primitive_type, options) end end # module DataMapper
cardmagic/dm-core
lib/data_mapper/type.rb
Ruby
mit
4,085
namespace Archient.Razor.TagHelpers { using Microsoft.AspNet.Razor.Runtime.TagHelpers; using Microsoft.AspNet.Razor.TagHelpers; [TagName("asp-if-authenticated")] [ContentBehavior(ContentBehavior.Modify)] public class AuthenticatedUserTagHelper : ConditionalDisplayTagHelperBase { protected override bool IsContentDisplayed { get { // display if authenticated return this.ViewContext.HttpContext.User.Identity.IsAuthenticated; } } } }
ericis/me
Web/src/Archient.Razor.TagHelpers/AuthenticatedUserTagHelper.cs
C#
mit
557
<?php /** Telerivet_ScheduledMessage Represents a scheduled message within Telerivet. Fields: - id (string, max 34 characters) * ID of the scheduled message * Read-only - content * Text content of the scheduled message * Read-only - rrule * Recurrence rule for recurring scheduled messages, e.g. 'FREQ=MONTHLY' or 'FREQ=WEEKLY;INTERVAL=2'; see <https://tools.ietf.org/html/rfc2445#section-4.3.10> * Read-only - timezone_id * Timezone ID used to compute times for recurring messages; see <http://en.wikipedia.org/wiki/List_of_tz_database_time_zones> * Read-only - recipients (array of objects) * List of recipients. Each recipient is an object with a string `type` property, which may be `"phone_number"`, `"group"`, or `"filter"`. If the type is `"phone_number"`, the `phone_number` property will be set to the recipient's phone number. If the type is `"group"`, the `group_id` property will be set to the ID of the group, and the `group_name` property will be set to the name of the group. If the type is `"filter"`, the `filter_type` property (string) and `filter_params` property (object) describe the filter used to send the broadcast. (API clients should not rely on a particular value or format of the `filter_type` or `filter_params` properties, as they may change without notice.) * Read-only - recipients_str * A string with a human readable description of the first few recipients (possibly truncated) * Read-only - group_id * ID of the group to send the message to (null if the recipient is an individual contact, or if there are multiple recipients) * Read-only - contact_id * ID of the contact to send the message to (null if the recipient is a group, or if there are multiple recipients) * Read-only - to_number * Phone number to send the message to (null if the recipient is a group, or if there are multiple recipients) * Read-only - route_id * ID of the phone or route the message will be sent from * Read-only - service_id (string, max 34 characters) * The service associated with this message (for voice calls, the service defines the call flow) * Read-only - audio_url * For voice calls, the URL of an MP3 file to play when the contact answers the call * Read-only - tts_lang * For voice calls, the language of the text-to-speech voice * Allowed values: en-US, en-GB, en-GB-WLS, en-AU, en-IN, da-DK, nl-NL, fr-FR, fr-CA, de-DE, is-IS, it-IT, pl-PL, pt-BR, pt-PT, ru-RU, es-ES, es-US, sv-SE * Read-only - tts_voice * For voice calls, the text-to-speech voice * Allowed values: female, male * Read-only - message_type * Type of scheduled message * Allowed values: sms, mms, ussd, call, service * Read-only - time_created (UNIX timestamp) * Time the scheduled message was created in Telerivet * Read-only - start_time (UNIX timestamp) * The time that the message will be sent (or first sent for recurring messages) * Read-only - end_time (UNIX timestamp) * Time after which a recurring message will stop (not applicable to non-recurring scheduled messages) * Read-only - prev_time (UNIX timestamp) * The most recent time that Telerivet has sent this scheduled message (null if it has never been sent) * Read-only - next_time (UNIX timestamp) * The next upcoming time that Telerivet will sent this scheduled message (null if it will not be sent again) * Read-only - occurrences (int) * Number of times this scheduled message has already been sent * Read-only - is_template (bool) * Set to true if Telerivet will render variables like [[contact.name]] in the message content, false otherwise * Read-only - track_clicks (boolean) * If true, URLs in the message content will automatically be replaced with unique short URLs * Read-only - media (array) * For text messages containing media files, this is an array of objects with the properties `url`, `type` (MIME type), `filename`, and `size` (file size in bytes). Unknown properties are null. This property is undefined for messages that do not contain media files. Note: For files uploaded via the Telerivet web app, the URL is temporary and may not be valid for more than 1 day. * Read-only - vars (associative array) * Custom variables stored for this scheduled message (copied to Message when sent) * Updatable via API - label_ids (array) * IDs of labels to add to the Message * Read-only - project_id * ID of the project this scheduled message belongs to * Read-only */ class Telerivet_ScheduledMessage extends Telerivet_Entity { /** $scheduled_msg->save() Saves any fields or custom variables that have changed for this scheduled message. */ function save() { parent::save(); } /** $scheduled_msg->delete() Cancels this scheduled message. */ function delete() { $this->_api->doRequest("DELETE", "{$this->getBaseApiPath()}"); } function getBaseApiPath() { return "/projects/{$this->project_id}/scheduled/{$this->id}"; } }
Telerivet/telerivet-php-client
lib/scheduledmessage.php
PHP
mit
6,284
import React, { useState, useRef } from 'react'; import { computeOutOffsetByIndex, computeInOffsetByIndex } from './lib/Util'; // import { SVGComponent } from './lib-hooks/svgComp-hooks'; import Spline from './lib/Spline'; import DragNode from './lib/Node'; const index = ({ data, onNodeDeselect, onNodeMove, onNodeStartMove, onNodeSelect, onNewConnector, onRemoveConnector }) => { const [dataS, setDataS] = useState(data); const [source, setSource] = useState([]); const [dragging, setDragging] = useState(false); const [mousePos, setMousePos] = useState({x: 0, y: 0}); const svgRef = useRef(); const onMouseMove = e => { let [pX, pY] = [e.clientX, e.clientY]; e.stopPropagation(); e.preventDefault(); const svgRect = svgRef.current.getBoundingClientRect(); // console.log(svgRect); setMousePos(old => { return { ...old, ...{x: pX - svgRect.left, y: pY - svgRect.top} } }); } const onMouseUp = e => { setDragging(false); } const handleNodeStart = nid => { onNodeStartMove(nid); } const handleNodeStop = (nid, pos) => { onNodeMove(nid, pos); } const handleNodeMove = (idx, pos) => { let dataT = dataS; dataT.nodes[idx].x = pos.x; dataT.nodes[idx].y = pos.y; // console.log(dataT); // console.log({...dataS,...dataT}); setDataS(old => { return { ...old, ...dataT } }); } const handleStartConnector = (nid, outputIdx) => { let newSrc = [nid, outputIdx]; setDragging(true); setSource(newSrc); // Not sure if this will work... } const handleCompleteConnector = (nid, inputIdx) => { if (dragging) { let fromNode = getNodeById(data.nodes, source[0]); let fromPinName = fromNode.fields.out[source[1]].name; let toNode = getNodeById(data.nodes, nid); let toPinName = toNode.fields.in[inputIdx].name; onNewConnector(fromNode.nid, fromPinName, toNode.nid, toPinName); } setDragging(false); } const handleRemoveConnector = connector => { if (onRemoveConnector) { onRemoveConnector(connector); } } const handleNodeSelect = nid => { if (onNodeSelect) { onNodeSelect(nid); } } const handleNodeDeselect = nid => { if (onNodeDeselect) { onNodeDeselect(nid); } } const computePinIdxfromLabel = (pins, pinLabel) => { let reval = 0; for (let pin of pins) { if (pin.name === pinLabel) { return reval; } else { reval++; } } } const getNodeById = (nodes, nid) => { let reval = 0; for(const node of nodes) { if (node.nid === nid) { return nodes[reval]; } else { reval++; } } } let newConn = null; let i = 0; // console.log(dragging); if (dragging) { let sourceNode = getNodeById(dataS.nodes, source[0]); let connectorStart = computeOutOffsetByIndex(sourceNode.x, sourceNode.y, source[1]); let connectorEnd = { x: mousePos.x, y: mousePos.y }; // console.log(mousePos); newConn = <Spline start={connectorStart} end={connectorEnd} /> } let splineIdx = 0; return ( <div className={dragging ? 'dragging' : ''} onMouseMove={onMouseMove} onMouseUp={onMouseUp} > {dataS.nodes.map(node => { // console.log(node); return <DragNode index={i++} nid={node.nid} title={node.type} inputs={node.fields.in} outputs={node.fields.out} pos={{x: node.x, y: node.y}} key={node.nid} onNodeStart={nid => handleNodeStart(nid)} onNodeStop={(nid, pos) => handleNodeStop(nid, pos)} onNodeMove={(idx, pos) => handleNodeMove(idx, pos)} onStartConnector={(nid, outputIdx) => handleStartConnector(nid, outputIdx)} onCompleteConnector={(nid, inputIdx) => handleCompleteConnector(nid, inputIdx)} onNodeSelect={nid => handleNodeSelect(nid)} onNodeDeselect={nid => handleNodeDeselect(nid)} /> })} <svg style={{position: 'absolute', height: "100%", width: "100%", zIndex: 9000}} ref={svgRef}> {data.connections.map(connector => { // console.log(data); // console.log(connector); let fromNode = getNodeById(data.nodes, connector.from_node); let toNode = getNodeById(data.nodes, connector.to_node); let splinestart = computeOutOffsetByIndex(fromNode.x, fromNode.y, computePinIdxfromLabel(fromNode.fields.out, connector.from)); let splineend = computeInOffsetByIndex(toNode.x, toNode.y, computePinIdxfromLabel(toNode.fields.in, connector.to)); return <Spline start={splinestart} end={splineend} key={splineIdx++} mousePos={mousePos} onRemove={() => handleRemoveConnector(connector)} /> })} {newConn} </svg> </div> ); } export default index;
lightsinthesky/react-node-graph
index.js
JavaScript
mit
6,053
var t = require('chai').assert; var P = require('bluebird'); var Renderer = require('../').Renderer; var view = { "name": { "first": "Michael", "last": "Jackson" }, "age": "RIP", calc: function () { return 2 + 4; }, delayed: function () { return new P(function (resolve) { setTimeout(resolve.bind(undefined, 'foo'), 100); }); } }; describe('Renderer', function () { describe('Basics features', function () { it('should render properties', function (done) { var renderer = new Renderer(); renderer.render('Hello {{name.first}} {{name.last}}', { "name": { "first": "Michael", "last": "Jackson" } }).then(function (result) { t.equal(result, 'Hello Michael Jackson'); done(); }) }); it('should render variables', function (done) { var renderer = new Renderer(); renderer.render('* {{name}} * {{age}} * {{company}} * {{{company}}} * {{&company}}{{=<% %>=}} * {{company}}<%={{ }}=%>', { "name": "Chris", "company": "<b>GitHub</b>" }).then(function (result) { t.equal(result, '* Chris * * &lt;b&gt;GitHub&lt;&#x2F;b&gt; * <b>GitHub</b> * <b>GitHub</b> * {{company}}'); done(); }) }); it('should render variables with dot notation', function (done) { var renderer = new Renderer(); renderer.render('{{name.first}} {{name.last}} {{age}}', { "name": { "first": "Michael", "last": "Jackson" }, "age": "RIP" }).then(function (result) { t.equal(result, 'Michael Jackson RIP'); done(); }) }); it('should render sections with false values or empty lists', function (done) { var renderer = new Renderer(); renderer.render('Shown. {{#person}}Never shown!{{/person}}', { "person": false }).then(function (result) { t.equal(result, 'Shown. '); done(); }) }); it('should render sections with non-empty lists', function (done) { var renderer = new Renderer(); renderer.render('{{#stooges}}<b>{{name}}</b>{{/stooges}}', { "stooges": [ {"name": "Moe"}, {"name": "Larry"}, {"name": "Curly"} ] }).then(function (result) { t.equal(result, '<b>Moe</b><b>Larry</b><b>Curly</b>'); done(); }) }); it('should render sections using . for array of strings', function (done) { var renderer = new Renderer(); renderer.render('{{#musketeers}}* {{.}}{{/musketeers}}', { "musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"] }).then(function (result) { t.equal(result, '* Athos* Aramis* Porthos* D&#39;Artagnan'); done(); }) }); it('should render function', function (done) { var renderer = new Renderer(); renderer.render('{{title}} spends {{calc}}', { title: "Joe", calc: function () { return 2 + 4; } }).then(function (result) { t.equal(result, 'Joe spends 6'); done(); }) }); it('should render function with variable as context', function (done) { var renderer = new Renderer(); renderer.render('{{#beatles}}* {{name}} {{/beatles}}', { "beatles": [ {"firstName": "John", "lastName": "Lennon"}, {"firstName": "Paul", "lastName": "McCartney"}, {"firstName": "George", "lastName": "Harrison"}, {"firstName": "Ringo", "lastName": "Starr"} ], "name": function () { return this.firstName + " " + this.lastName; } }).then(function (result) { t.equal(result, '* John Lennon * Paul McCartney * George Harrison * Ringo Starr '); done(); }) }); it('should render inverted sections', function (done) { var renderer = new Renderer(); renderer.render('{{#repos}}<b>{{name}}</b>{{/repos}}{{^repos}}No repos :({{/repos}}', { "repos": [] }).then(function (result) { t.equal(result, 'No repos :('); done(); }) }); it('should render ignore comments', function (done) { var renderer = new Renderer(); renderer.render('Today{{! ignore me }}.').then(function (result) { t.equal(result, 'Today.'); done(); }) }); it('should render partials', function (done) { var renderer = new Renderer(); renderer.render('{{#names}}{{> user}}{{/names}}', { names: [{ name: 'Athos' }, { name: 'Porthos' }] }, { user: 'Hello {{name}}.' }).then(function (result) { t.equal(result, 'Hello Athos.Hello Porthos.'); done(); }) }); }); describe('Promise functions', function () { it('should render with promise functions', function (done) { var renderer = new Renderer(); renderer.render('3+5={{#add}}[3,5]{{/add}}', { add: function (a, b) { return new P(function (resolve) { setTimeout(function () { resolve(a + b); }, 100); }) } }).then(function (result) { t.equal(result, '3+5=8'); done(); }); }); }); describe('Custom view', function () { function View() { this.buffer = []; this.text = function (text) { this.buffer.push(text); return this; }; this.write = function (i) { this.buffer.push(i); return this; }; } it('should render with custom view', function (done) { var view = new View(); var renderer = new Renderer(); renderer.render('The number is:{{#write}}1{{/write}}', view).then(function (result) { t.notOk(result); t.deepEqual(view.buffer, ['The number is:', 1]); done(); }) }); }); }) ;
taoyuan/mustem
test/renderer.test.js
JavaScript
mit
5,908
import { Component ,OnInit} from '@angular/core'; import {GlobalService} from '../_globals/global.service'; import {PermissionService} from './permission.service'; import {ContentTypeService} from '../content_types/content_type.service'; import {Permission} from './permission'; @Component({ selector: 'permission-index', templateUrl: './permission.component.html', providers:[PermissionService,ContentTypeService], //styleUrls: ['./.component.css'] }) export class PermissionListComponent implements OnInit { constructor(private globalService:GlobalService, private permissionService:PermissionService, private contentTypeService:ContentTypeService){} //set permissions:Permission[]; permission=new Permission(); selectedPermission=null; contentTypes=null; //needed for pagination pagination:any; onPagination(results:any){ //get results paginated from pagination component this.permissions=results; } ngOnInit(){ this.listContentTypes(); // this.listPermissions(); } private onSelectPermission(g){ this.selectedPermission=g; } protected getContentType(content_type_id){ //get from listed content types let ct=this.contentTypes.filter(ct=>ct.id===content_type_id)[0]; //console.log(this.contentTypes.filter(ct=>ct.id===content_type_id)); return ct.app_label+'.'+ct.model; } public listPermissions(){ this.permissionService.getAll().subscribe( response=>(this.permissions=response.data.results,this.pagination=response.data.pagination,this.globalService.displayResponseMessage(response)),//success error=>(this.globalService.displayResponseMessage(error)),//failure ()=>{}//complete );//success,failure,complete } private createPermission(){ console.log(this.permission); this.permissionService.create(this.permission).subscribe( response=>(this.globalService.hideModal("#createPermissionModal"),this.listPermissions()),//success error=>(this.globalService.displayResponseMessage(error)),//failure ()=>{}//complete );//success,failure,complete; } private editPermission(){ this.permissionService.edit(this.selectedPermission).subscribe( response=>(this.globalService.hideModal("#editPermissionModal"),this.globalService.displayResponseMessage(response)),//success error=>(this.globalService.displayResponseMessage(error)),//failure ()=>{}//complete );//success,failure,complete; } private deletePermission(){ this.permissionService.delete(this.selectedPermission).subscribe( response=>(this.globalService.hideModal("#deletePermissionModal"),this.listPermissions()),//success error=>(this.globalService.displayResponseMessage(error)),//failure ()=>{}//complete );//success,failure,complete; } public listContentTypes(){ //also list permissions after content types has loaded this.contentTypeService.getAll().subscribe( response=>(this.contentTypes=response.data.results,this.listPermissions()),//success error=>(this.globalService.displayResponseMessage(error)),//failure ()=>{}//complete );//success,failure,complete } }
morfat/angular-quickstart
src/app/permissions/permission.component.ts
TypeScript
mit
3,259
using Treefrog.Extensibility; using Treefrog.Framework.Model; using Treefrog.Plugins.Tiles.Layers; using Treefrog.Presentation; using Treefrog.Presentation.Layers; using Treefrog.Render.Layers; namespace Treefrog.Plugins.Tiles { public static class Registration { // Layer Presenter Creation [LevelLayerPresenterExport(LayerType = typeof(TileLayer), TargetType = typeof(TileLayerPresenter))] public static LevelLayerPresenter CreateTileLayerPresenter1 (Layer layer, ILayerContext context) { return new TileLayerPresenter(context, layer as TileLayer); } [LevelLayerPresenterExport(LayerType = typeof(TileGridLayer), TargetType = typeof(TileGridLayerPresenter))] public static LevelLayerPresenter CreateTileLayerPresenter2 (Layer layer, ILayerContext context) { return new TileGridLayerPresenter(context, layer as TileGridLayer); } [LevelLayerPresenterExport(LayerType = typeof(MultiTileGridLayer), TargetType = typeof(TileGridLayerPresenter))] public static LevelLayerPresenter CreateTileLayerPresenter3 (Layer layer, ILayerContext context) { return new TileGridLayerPresenter(context, layer as TileGridLayer); } // Layer Creation [LayerFromPresenterExport(SourceType = typeof(TileGridLayerPresenter), TargetType = typeof(MultiTileGridLayer))] public static Layer CreateTileLayer (LayerPresenter layer, string name) { return new MultiTileGridLayer(name, (layer as TileGridLayerPresenter).Layer as MultiTileGridLayer); } // Canvas Layer Creation [CanvasLayerExport(LayerType = typeof(TileLayerPresenter), TargetType = typeof(LevelRenderLayer))] public static CanvasLayer CreateTileCanvasLayer1 (LayerPresenter layer) { return new LevelRenderLayer(layer as LevelLayerPresenter); } [CanvasLayerExport(LayerType = typeof(TileSetLayerPresenter), TargetType = typeof(TileSetRenderLayer))] public static CanvasLayer CreateTileCanvasLayer2 (LayerPresenter layer) { return new TileSetRenderLayer(layer as TileSetLayerPresenter); } [CanvasLayerExport(LayerType = typeof(TileGridLayerPresenter), TargetType = typeof(LevelRenderLayer))] public static CanvasLayer CreateTileCanvasLayer3 (LayerPresenter layer) { return new LevelRenderLayer(layer as LevelLayerPresenter); } } }
jaquadro/Treefrog
Treefrog/Plugins/Tile/Registration.cs
C#
mit
2,521
import collections import re import urlparse class DSN(collections.MutableMapping): ''' Hold the results of a parsed dsn. This is very similar to urlparse.ParseResult tuple. http://docs.python.org/2/library/urlparse.html#results-of-urlparse-and-urlsplit It exposes the following attributes: scheme schemes -- if your scheme has +'s in it, then this will contain a list of schemes split by + path paths -- the path segment split by /, so "/foo/bar" would be ["foo", "bar"] host -- same as hostname (I just like host better) hostname hostloc -- host:port username password netloc query -- a dict of the query string query_str -- the raw query string port fragment ''' DSN_REGEXP = re.compile(r'^\S+://\S+') FIELDS = ('scheme', 'netloc', 'path', 'params', 'query', 'fragment') def __init__(self, dsn, **defaults): ''' Parse a dsn to parts similar to urlparse. This is a nuts function that can serve as a good basis to parsing a custom dsn :param dsn: the dsn to parse :type dsn: str :param defaults: any values you want to have defaults for if they aren't in the dsn :type defaults: dict ''' assert self.DSN_REGEXP.match(dsn), \ "{} is invalid, only full dsn urls (scheme://host...) allowed".format(dsn) first_colon = dsn.find(':') scheme = dsn[0:first_colon] dsn_url = dsn[first_colon+1:] url = urlparse.urlparse(dsn_url) options = {} if url.query: for k, kv in urlparse.parse_qs(url.query, True, True).iteritems(): if len(kv) > 1: options[k] = kv else: options[k] = kv[0] self.scheme = scheme self.hostname = url.hostname self.path = url.path self.params = url.params self.query = options self.fragment = url.fragment self.username = url.username self.password = url.password self.port = url.port self.query_str = url.query for k, v in defaults.iteritems(): self.set_default(k, v) def __iter__(self): for f in self.FIELDS: yield getattr(self, f, '') def __len__(self): return len(iter(self)) def __getitem__(self, field): return getattr(self, field, None) def __setitem__(self, field, value): setattr(self, field, value) def __delitem__(self, field): delattr(self, field) @property def schemes(self): '''the scheme, split by plus signs''' return self.scheme.split('+') @property def netloc(self): '''return username:password@hostname:port''' s = '' prefix = '' if self.username: s += self.username prefix = '@' if self.password: s += ":{}".format(self.password) prefix = '@' s += "{}{}".format(prefix, self.hostloc) return s @property def paths(self): '''the path attribute split by /''' return filter(None, self.path.split('/')) @property def host(self): '''the hostname, but I like host better''' return self.hostname @property def hostloc(self): '''return host:port''' hostloc = self.hostname if self.port: hostloc = '{}:{}'.format(hostloc, self.port) return hostloc def set_default(self, key, value): ''' Set a default value for key. This is different than dict's setdefault because it will set default either if the key doesn't exist, or if the value at the key evaluates to False, so an empty string or a None will value will be updated. :param key: the item to update :type key: str :param value: the items new value if key has a current value that evaluates to False ''' if not getattr(self, key, None): setattr(self, key, value) def get_url(self): '''return the dsn back into url form''' return urlparse.urlunparse(( self.scheme, self.netloc, self.path, self.params, self.query_str, self.fragment, )) def copy(self): return DSN(self.get_url()) def __str__(self): return self.get_url()
mylokin/servy
servy/utils/dsntool.py
Python
mit
4,496
package org.ebaloo.itkeeps.core.domain.vertex; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.ebaloo.itkeeps.api.enumeration.enAclAdmin; import org.ebaloo.itkeeps.api.enumeration.enAclData; import org.ebaloo.itkeeps.api.model.jAclGroup; import org.ebaloo.itkeeps.api.model.jBaseLight; import org.ebaloo.itkeeps.core.database.annotation.DatabaseVertrex; import org.ebaloo.itkeeps.core.domain.edge.DirectionType; import org.ebaloo.itkeeps.core.domain.edge.notraverse.eAclNoTraverse; import com.tinkerpop.blueprints.impls.orient.OrientBaseGraph; /** * * */ @DatabaseVertrex() final class vAclGroup extends vBase { vAclGroup() { super(); } /* * CHILD */ vAclGroup(final jAclGroup j) { super(j); try { this.update(j); } catch (Exception e) { this.delete(); throw e; } } final jBaseLight getChild() { vAclGroup child = this.getEdge(vAclGroup.class, DirectionType.CHILD, false, eAclNoTraverse.class); return child == null ? null : getJBaseLight(child); } /* * PARENTS */ final void setChild(final jBaseLight group) { vAclGroup child = get(this.getGraph(), vAclGroup.class, group, false); setEdges(this.getGraph(), vAclGroup.class, this, vAclGroup.class, child, DirectionType.CHILD, eAclNoTraverse.class, false); } final List<jBaseLight> getParents() { return this.getEdges( vAclGroup.class, DirectionType.PARENT, false, eAclNoTraverse.class).stream().map(vBase::getJBaseLight).collect(Collectors.toList()); } /* * ACL ADMIN */ final void setParents(List<jBaseLight> list) { if (list == null) list = new ArrayList<>(); // Optimization OrientBaseGraph graph = this.getGraph(); setEdges( graph, vAclGroup.class, this, vAclGroup.class, list.stream().map(e -> get(graph, vAclGroup.class, e, false)).collect(Collectors.toList()), DirectionType.PARENT, eAclNoTraverse.class, false); } final List<enAclAdmin> getAclAdmin() { return this.getEdges( vAclAdmin.class, DirectionType.PARENT, true, eAclNoTraverse.class) .stream().map(e -> enAclAdmin.valueOf(e.getName())).collect(Collectors.toList()); } /* * ACL DATA */ final void setAclAdmin(List<enAclAdmin> list) { if(list == null) list = new ArrayList<>(); // Optimization OrientBaseGraph graph = this.getGraph(); setEdges( graph, vAclGroup.class, this, vAclAdmin.class, list.stream().map(e -> vAclAdmin.get(graph, vAclAdmin.class, e.name())).collect(Collectors.toList()), DirectionType.PARENT, eAclNoTraverse.class, false); } final List<enAclData> getAclData() { return this.getEdges( vAclData.class, DirectionType.PARENT, true, eAclNoTraverse.class) .stream().map(e -> enAclData.valueOf(e.getName())).collect(Collectors.toList()); } // API final void setAclData(List<enAclData> list) { if(list == null) list = new ArrayList<>(); // Optimization OrientBaseGraph graph = this.getGraph(); setEdges( graph, vAclGroup.class, this, vAclData.class, list.stream().map(e -> vAclData.get(graph, vAclData.class, e.name())).collect(Collectors.toList()), DirectionType.PARENT, eAclNoTraverse.class, false); } final jAclGroup read() { jAclGroup j = new jAclGroup(); this.readBase(j); j.setAclAdmin(this.getAclAdmin()); j.setAclData(this.getAclData()); j.setChild(this.getChild()); j.setParents(this.getParents()); return j; } /* public static final jAclGroup create(Rid requesteurRid, jAclGroup j) { SecurityAcl sAcl = SecurityFactory.getSecurityAcl(requesteurRid, Rid.NULL); if(!sAcl.isRoleRoot()) throw ExceptionPermission.NOT_ROOT; vAclGroup aclGroup = new vAclGroup(j); return vAclGroup.read(requesteurRid, aclGroup.getId()); } */ /* public static final jAclGroup delete(Rid requesteurRid, Rid guid) { SecurityAcl sAcl = SecurityFactory.getSecurityAcl(requesteurRid, Rid.NULL); if(!sAcl.isRoleRoot()) throw ExceptionPermission.NOT_ROOT; vAclGroup aclGroup = vAclGroup.get(null, vAclGroup.class, guid, false); jAclGroup j = aclGroup.read(); aclGroup.delete(); return j; } */ /* public static final jAclGroup read(Rid requesteurRid, Rid guid) { SecurityAcl sAcl = SecurityFactory.getSecurityAcl(requesteurRid, Rid.NULL); if(!sAcl.isRoleRoot()) throw ExceptionPermission.NOT_ROOT; vAclGroup aclGroup = vAclGroup.get(null, vAclGroup.class, guid, false); return aclGroup.read(); } */ /* public static final jAclGroup update(Rid requesteurRid, jAclGroup j) { SecurityAcl sAcl = SecurityFactory.getSecurityAcl(requesteurRid, Rid.NULL); if(!sAcl.isRoleRoot()) throw ExceptionPermission.NOT_ROOT; vAclGroup aclGroup = vAclGroup.get(null, vAclGroup.class, j.getId(), false); aclGroup.checkVersion(j); aclGroup.update(j); return vAclGroup.read(requesteurRid, j.getId()); } */ final void update(jAclGroup j) { this.setAclAdmin(j.getAclAdmin()); this.setAclData(j.getAclData()); this.setParents(j.getParents()); this.setChild(j.getChild()); } /* public static final List<jAclGroup> readAll(Rid requesteurRid) { SecurityAcl sAcl = SecurityFactory.getSecurityAcl(requesteurRid, Rid.NULL); if(!sAcl.isRoleRoot()) throw ExceptionPermission.NOT_ROOT; List<jAclGroup> list = vAclGroup.getAllBase(null, vAclGroup.class, false).stream().map(e -> e.read()).collect(Collectors.toList()); return list; } */ }
e-baloo/it-keeps
it-keeps-core/src/main/java/org/ebaloo/itkeeps/core/domain/vertex/vAclGroup.java
Java
mit
6,089
import { expect } from 'chai'; import 'mocha'; import { Integer, TestContext } from '../../..'; import { makeInteger } from './make-integer'; describe('make-integer', () => { it('should handle single digits', () => { const ctx = new TestContext("test"); const delayedValue = makeInteger("5"); const value = delayedValue(ctx) as Integer; expect(ctx.callCount).to.equal(0); expect(value.value).to.equal(5); expect(value.pretties).to.equal("5"); expect(value.dice()).to.equal(0); expect(value.depth()).to.equal(1); }); it('should handle multiple digits', () => { const ctx = new TestContext("test"); const delayedValue = makeInteger("189465"); const value = delayedValue(ctx) as Integer; expect(ctx.callCount).to.equal(0); expect(value.value).to.equal(189465);; expect(value.pretties).to.equal("189465"); expect(value.dice()).to.equal(0); expect(value.depth()).to.equal(1); }); it('should handle negative numbers', () => { const ctx = new TestContext("test"); const delayedValue = makeInteger("-189465"); const value = delayedValue(ctx) as Integer; expect(ctx.callCount).to.equal(0); expect(value.value).to.equal(-189465); expect(value.pretties).to.equal("-189465"); expect(value.dice()).to.equal(0); expect(value.depth()).to.equal(1); }); });
lemtzas/rollem-discord
packages/language/src/rollem-language-2/evaluators/unary/make-integer.spec.ts
TypeScript
mit
1,351
<?php /** * This file is part of GSSimpleOcr. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @copyright Copyright (c) 2014 Gordon Schmidt * @license MIT */ namespace GSSimpleOcr\Service; use GSImage\Entity\Image; use GSOcr\Service\OcrServiceInterface; use GSSimpleOcr\Exception; use GSSimpleOcr\Entity\Font; use GSSimpleOcr\Entity\BWImage; /** * This class provides a simple OCR service. * * @author Gordon Schmidt <schmidt.gordon@web.de> */ class SimpleOcrService implements OcrServiceInterface { const MODE_GLYPHS = 0; const MODE_LINES = 1; const MODE_WORDS = 2; const MODE_ALL = 3; const MODE_TEXT = 4; /** * Maximum variation in the y for 2 glyphs to be on the same line * @var int */ protected $maxYVariation = 1; /** * Maximum variation in the x for 2 glyphs to be in the same word * @var int */ protected $maxXVariation = 2; /** * Seperator for 2 glyphs * @var string */ protected $glyphSeperator = ''; /** * Seperator for 2 words * @var string */ protected $wordSeperator = ' '; /** * Seperator for 2 lines * @var string */ protected $lineSeperator = PHP_EOL; /** * List of fonts * @var array */ protected $fonts = array(); /** * Set config to ocr service * * @param array $config */ public function setConfig($config) { if (isset($config['fonts'])) { $this->setFonts($config['fonts']); } if (isset($config['maxYVariation'])) { $this->maxYVariation = $config['maxYVariation']; } if (isset($config['maxXVariation'])) { $this->maxXVariation = $config['maxXVariation']; } } /** * Recognize image * * @param string $image * @param array $options * @return string */ public function recognize($image, $options) { if (isset($options['threshold'])) { $threshold = $options['threshold']; } else { $threshold = 127; } if (isset($options['mode'])) { $mode = $options['mode']; } else { $mode = self::MODE_TEXT; } $image = new Image($image); $bwImage = new BWImage($image, $threshold); if (isset($options['rotate']) && in_array($options['rotate'], array(-90, 90, 180, 270))) { $bwImage->rotate($options['rotate']); } return $this->workflow($bwImage, $mode, array( 'recognizeGlyphs', 'recognizeLines', 'recognizeWords', 'generateTexts', )); } /** * Perform workflow of given steps * * @param mixed $input * @param int $mode * @param array $steps * @return mixed */ protected function workflow($input, $mode, $steps) { if (empty($steps)) { //output only text return $input['text']; } //array_assoc_shift list($stepMode) = array_keys($steps); $stepMethod = $steps[$stepMode]; unset($steps[$stepMode]); //execute workflow step $input = $this->$stepMethod($input); //stop if mode is reached if ($mode == $stepMode) { return $input; } //recursive call return $this->workflow($input, $mode, $steps); } /** * Recognize glyphs of known fonts in black and white image * * @param GSSimpleOcr\Entity\BWImage $image * @param int GSSimpleOcr\Entity\BWImage $image * @return array */ protected function recognizeGlyphs(BWImage $image) { $chars = array(); foreach ($this->fonts as $font) { $glyphs = $font->getGlyphs(); foreach ($glyphs as $c => $glyph) { $results = $image->findSubImage($glyph); if (is_array($results)) { $w = $glyph->getWidth(); $h = $glyph->getHeight(); foreach ($results as $result) { $chars[] = array('text' => $c, 'x' => $result['x'], 'y' => $result['y'], 'w' => $w, 'h' => $h); } } } } return array('glyphs' => $chars); } /** * Recognize lines in data array * * @param array $data */ protected function recognizeLines($data) { $glyphs = $data['glyphs']; $this->sortByKey('y', $glyphs); $last = array(array_shift($glyphs)); $lines = array(); foreach ($glyphs as $glyph) { if ($this->maxYVariation >= abs($last[0]['y'] - $glyph['y'])) { $last[] = $glyph; } else { $lines[] = array('glyphs' => $last); $last = array($glyph); } } if (!empty($last)) { $lines[] = array('glyphs' => $last); } return array('lines' => $lines); } /** * Recognize words in char array * * @param array $data */ protected function recognizeWords($data) { foreach ($data['lines'] as &$line) { $glyphs = $line['glyphs']; $this->sortByKey('x', $glyphs); $latest = array_shift($glyphs); $last = array($latest); $words = array(); foreach ($glyphs as $glyph) { if (($this->maxXVariation + $latest['w']) > abs($glyph['x'] - $latest['x'])) { $latest = $glyph; $last[] = $latest; } else { $latest = $glyph; $words[] = array('glyphs' => $last); $last = array($latest); } } if (!empty($last)) { $words[] = array('glyphs' => $last); } $line = array('words' => $words); } return $data; } /** * Generate texts from data array * * @param array $data */ protected function generateTexts($data) { foreach ($data['lines'] as &$line) { foreach ($line['words'] as &$word) { $word['text'] = $this->implodeByKey($this->glyphSeperator, 'text', $word['glyphs']); } $line['text'] = $this->implodeByKey($this->wordSeperator, 'text', $line['words']); } $data['text'] = $this->implodeByKey($this->lineSeperator, 'text', $data['lines']); return $data; } /** * Set Fonts to simple ocr service * * @param array $fonts * @return self */ protected function setFonts($fonts) { $this->fonts = array(); foreach ($fonts as $font) { if ($font instanceof Font) { $this->fonts[] = $font; } else { $this->fonts[] = new Font($font); } } return $this; } /** * Order data by given key * * @param string $key * @param array &$data * @return array */ protected function sortByKey($key, &$data) { return usort($data, $this->generateSorter($key)); } /** * Generate a sort function for given key * * @param string $key * @return function */ protected function generateSorter($key) { return function ($a, $b) use ($key) { if ($a[$key] == $b[$key]) { return 0; } return ($a[$key] < $b[$key]) ? -1 : 1; }; } /** * Implode data by given key * * @param string $seperator * @param string $key * @param array $data * @return function */ protected function implodeByKey($seperator, $key, $data) { $values = array(); foreach ($data as $value) { $values[] = $value[$key]; } return implode($seperator, $values); } }
GordonSchmidt/GSSimpleOcr
src/GSSimpleOcr/Service/SimpleOcrService.php
PHP
mit
8,111
package com.vexus2.jenkins.chatwork.jenkinschatworkplugin.api; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.annotate.JsonProperty; @JsonIgnoreProperties(ignoreUnknown=true) public class Room { @JsonProperty("room_id") public String roomId; @JsonProperty("name") public String name; @JsonProperty("type") public String type; @Override public int hashCode(){ return new HashCodeBuilder() .append(name) .append(roomId) .append(type) .toHashCode(); } @Override public boolean equals(final Object obj){ if(obj instanceof Room){ final Room other = (Room) obj; return new EqualsBuilder() .append(name, other.name) .append(roomId, other.roomId) .append(type, other.type) .isEquals(); } else{ return false; } } }
jenkinsci/chatwork-plugin
src/main/java/com/vexus2/jenkins/chatwork/jenkinschatworkplugin/api/Room.java
Java
mit
992
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors.server.controller'), Task = mongoose.model('Task'), Project = mongoose.model('Project'), Person = mongoose.model('Person'), _ = require('lodash'); /** * Create a Task */ var person, project; exports.createTask = function(req, res) { var task = new Task(req.body); task.user = req.user; Person.findById(req.body.personId).exec(function(err, person_object) { person = person_object; Project.findById(req.body.projectId).exec(function(err, project_object) { project = project_object; task.projectName = project.name; task.personName = person.name; task.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { person.tasks.push(task); person.save(); project.tasks.push(task); project.save(); res.jsonp(task); } }); }); }); }; /** * Show the current Task */ exports.readTask = function(req, res) { res.jsonp(req.task); }; /** * Update a Task */ exports.updateTask = function(req, res) { var task = req.task; task = _.extend(task, req.body); task.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(task); } }); }; /** * Delete an Task */ exports.deleteTask = function(req, res) { var task = req.task; Project.findById(req.task.project).exec(function(err, project) { if (project && project.tasks) { var i = project.tasks.indexOf(task._id); project.tasks.splice(i, 1); project.save(); } }); Person.findById(req.task.person).exec(function(err, person) { if (person && person.tasks) { var i = person.tasks.indexOf(task._id); person.tasks.splice(i, 1); person.save(); } }); task.remove(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(task); } }); }; /** * List of Tasks */ exports.listTasks = function(req, res) { Task.find({'user':req.user._id}).sort('-created').populate('person', 'name').populate('project', 'name').exec(function(err, tasks) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(tasks); } }); }; /** * Task middleware */ exports.taskByID = function(req, res, next, id) { Task.findById(id).populate('user', 'username').exec(function(err, task) { if (err) return next(err); if (!task) return next(new Error('Failed to load Task ' + id)); req.task = task; next(); }); }; /** * Task authorization middleware */ exports.hasAuthorization = function(req, res, next) { if (req.task.user.id !== req.user.id) { return res.status(403).send('User is not authorized'); } next(); };
andela-ajayeoba/Calendarize
app/controllers/tasks.server.controller.js
JavaScript
mit
3,108
import { useCallback, useState, useEffect } from 'react'; import { KeyStore } from './keystore'; import type { Accounts, Hooks as HooksType } from './../types'; export const Hooks = { useKeyStore: () => { const [accounts, setAccounts] = useState<Accounts>(); const [error, setError] = useState<string>(); useEffect(() => { async function getAccounts() { try { setAccounts(await KeyStore.getAccounts()); } catch (err: any) { setError(err); } } getAccounts(); }, []); const newAccount = useCallback((passphrase: string) => { async function addAccount() { try { await KeyStore.newAccount(passphrase); setAccounts(await KeyStore.getAccounts()); } catch (err: any) { setError(err); } } addAccount(); }, []); return { accounts, error, newAccount }; }, useEthereumClient: () => {}, } as HooksType;
YsnKsy/react-native-geth
src/packages/hooks.tsx
TypeScript
mit
960
package net.ihiroky.reservoir.coder; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; /** * Created on 12/10/04, 19:26 * * @author Hiroki Itoh */ public class ByteBufferOutputStream extends OutputStream { ByteBuffer byteBuffer; ByteBufferOutputStream(int initialCapacity) { byteBuffer = ByteBuffer.allocate(initialCapacity); } private void ensureCapacity(int minimumIncrement) { int c = byteBuffer.capacity(); int newSize = c / 2 * 3; if (newSize < c + minimumIncrement) { newSize = c + minimumIncrement; } ByteBuffer t = ByteBuffer.allocate(newSize); byteBuffer.flip(); t.put(byteBuffer); byteBuffer = t; } @Override public void write(int b) throws IOException { if (!byteBuffer.hasRemaining()) { ensureCapacity(1); } byteBuffer.put((byte) b); } @Override public void write(byte[] bytes, int offset, int length) { if (byteBuffer.remaining() < length) { ensureCapacity(length); } byteBuffer.put(bytes, offset, length); } @Override public void close() { byteBuffer.flip(); } }
ihiroky/reservoir
src/main/java/net/ihiroky/reservoir/coder/ByteBufferOutputStream.java
Java
mit
1,244
// angular.module is a global place for creating, registering and retrieving Angular modules // 'directory' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' // 'directory.services' is found in services.js // 'directory.controllers' is found in controllers.js angular.module('directory', ['ionic', 'directory.controllers', 'ionic.contrib.ui.cards']) .config(function ($stateProvider, $urlRouterProvider) { // Ionic uses AngularUI Router which uses the concept of states // Learn more here: https://github.com/angular-ui/ui-router // Set up the various states which the app can be in. // Each state's controller can be found in controllers.js $stateProvider .state('landing', { url: '/landing', templateUrl: 'templates/index.html', controller: 'FbCtrl' }) .state('profilec', { url: '/createProfile', templateUrl: 'templates/profilec.html', controller: 'ProfileCtrl' }) .state('matches', { url: '/matches', templateUrl: 'templates/matches.html', controller: 'TestCtrl' }) .state('food', { url: '/restaurants', templateUrl: 'templates/restaurants.html', controller: 'RecCtrl' }) .state('chat', { url: '/chat', templateUrl: 'templates/chat.html', controller: 'ChatCtrl' }) .state('home', { url: '/home', templateUrl: 'templates/home.html', controller: 'DocCtrl' }) .state('stats', { url: '/stats', templateUrl: 'templates/stats.html', controller: 'DocCtrl' }) .state('graphs', { url: '/graphs', templateUrl: 'templates/graphs.html', controller: 'GraphCtrl' }) .state('doc-index', { url: '/docs', templateUrl: 'templates/doc-index.html', controller: 'DocCtrl' }) .state('doc-detail', { url: '/doclist/:doclistId', templateUrl: 'templates/doc-detail.html', controller: 'DocCtrl' }); /*.state('employee-index', { url: '/employees', templateUrl: 'templates/employee-index.html', controller: 'EmployeeIndexCtrl' }) .state('employee-detail', { url: '/employee/:employeeId', templateUrl: 'templates/employee-detail.html', controller: 'EmployeeDetailCtrl' }) .state('employee-reports', { url: '/employee/:employeeId/reports', templateUrl: 'templates/employee-reports.html', controller: 'EmployeeReportsCtrl' }); */ // if none of the above states are matched, use this as the fallback $urlRouterProvider.otherwise('landing'); });
zzeleznick/zzeleznick.github.io
hackerlove/main/www/js/app.js
JavaScript
mit
3,330
const fs = require('fs'); class Loader { static extend (name, loader) { return { name, loader }; } static get (name, options) { const item = options.loaders.find((loader) => name === loader.name); if (!item) { throw new Error(`Missing loader for ${name}`); } return item.loader; } static getFileContent (filename, options) { return fs.readFileSync(filename, options).toString(); } constructor (options) { this.options = options; } /* istanbul ignore next */ /* eslint-disable-next-line class-methods-use-this */ load () { throw new Error('Cannot call abstract Loader.load() method'); } emitTemplate (source) { this.options.source.template = source || ''; return Promise.resolve(); } emitScript (source) { this.options.source.script = source || ''; return Promise.resolve(); } emitErrors (errors) { this.options.source.errors.push(...errors); return Promise.resolve(); } pipe (name, source) { const LoaderClass = Loader.get(name, this.options); return new LoaderClass(this.options).load(source); } } module.exports = Loader;
vuedoc/parser
lib/Loader.js
JavaScript
mit
1,150
package org.ayo.ui.sample.material; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.content.Context; import android.support.design.widget.CoordinatorLayout; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.view.View; import org.ayo.animate.yoyo.Techniques; import org.ayo.animate.yoyo.YoYo; import org.ayo.view.widget.TitleBar; /** * FloatingActionBar会跟着ScrollView缩小 */ public class ScaleTitlebarBehavior extends CoordinatorLayout.Behavior<TitleBar> { public ScaleTitlebarBehavior(Context context, AttributeSet attrs) { super(); } @Override public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, TitleBar child, View directTargetChild, View target, int nestedScrollAxes) { return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL || super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes); } @Override public void onNestedScroll(CoordinatorLayout coordinatorLayout, final TitleBar child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) { super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed); if (dyConsumed > 0 && child.getVisibility() == View.VISIBLE) { //child.setVisibility(View.GONE); YoYo.with(Techniques.ZoomOut).duration(300).listen(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { child.setVisibility(View.GONE); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }).playOn(child); } else if (dyConsumed < 0 && child.getVisibility() != View.VISIBLE) { YoYo.with(Techniques.ZoomIn).duration(300).listen(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { child.setVisibility(View.VISIBLE); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }).playOn(child); } } }
cowthan/Ayo2022
Ayo/app/src/main/java/org/ayo/ui/sample/material/ScaleTitlebarBehavior.java
Java
mit
2,886
/* * The MIT License * * Copyright 2019 Intuit Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.intuit.karate.job; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.function.Predicate; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; /** * * @author pthomas3 */ public class JobUtils { public static void zip(File src, File dest) { try { src = src.getCanonicalFile(); FileOutputStream fos = new FileOutputStream(dest); ZipOutputStream zipOut = new ZipOutputStream(fos); zip(src, "", zipOut, 0); zipOut.close(); fos.close(); } catch (IOException e) { throw new RuntimeException(e); } } private static void zip(File fileToZip, String fileName, ZipOutputStream zipOut, int level) throws IOException { if (fileToZip.isHidden()) { return; } if (fileToZip.isDirectory()) { String entryName = fileName; zipOut.putNextEntry(new ZipEntry(entryName + "/")); zipOut.closeEntry(); File[] children = fileToZip.listFiles(); for (File childFile : children) { String childFileName = childFile.getName(); // TODO improve ? if (childFileName.equals("target") || childFileName.equals("build")) { continue; } if (level != 0) { childFileName = entryName + "/" + childFileName; } zip(childFile, childFileName, zipOut, level + 1); } return; } ZipEntry zipEntry = new ZipEntry(fileName); zipOut.putNextEntry(zipEntry); FileInputStream fis = new FileInputStream(fileToZip); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zipOut.write(bytes, 0, length); } fis.close(); } public static void unzip(File src, File dest) { try { byte[] buffer = new byte[1024]; ZipInputStream zis = new ZipInputStream(new FileInputStream(src)); ZipEntry zipEntry = zis.getNextEntry(); while (zipEntry != null) { File newFile = createFile(dest, zipEntry); if (zipEntry.isDirectory()) { newFile.mkdirs(); } else { File parentFile = newFile.getParentFile(); if (parentFile != null && !parentFile.exists()) { parentFile.mkdirs(); } FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); } zipEntry = zis.getNextEntry(); } zis.closeEntry(); zis.close(); } catch (IOException e) { throw new RuntimeException(e); } } private static File createFile(File destinationDir, ZipEntry zipEntry) throws IOException { File destFile = new File(destinationDir, zipEntry.getName()); String destDirPath = destinationDir.getCanonicalPath(); String destFilePath = destFile.getCanonicalPath(); if (!destFilePath.startsWith(destDirPath)) { throw new IOException("entry outside target dir: " + zipEntry.getName()); } return destFile; } public static File getFirstFileMatching(File parent, Predicate<String> predicate) { File[] files = parent.listFiles((f, n) -> predicate.test(n)); return files == null || files.length == 0 ? null : files[0]; } }
intuit/karate
karate-core/src/main/java/com/intuit/karate/job/JobUtils.java
Java
mit
5,009
const storage = require("./storage"); const recognition = require("./recognition"); async function labelPictures(bucketName) { const bucket = await storage.getOrCreateBucket(bucketName); const fileNames = await storage.ls(bucket); for (const file of fileNames) { console.log(`Retrieve labels for file ${file.name}`); try { const labels = await recognition.getLabels(file.metadata.mediaLink); const metadata = { metadata: { labels: JSON.stringify(labels) } }; console.log(`Set metadata for file ${file.name}`); await storage.setMetadata(file, metadata); } catch (ex) { console.warn("Failed to set metadata for file ${file.name}", ex); } } } async function main(bucketName) { try { await labelPictures(bucketName); } catch (error) { console.error(error); } } if (process.argv.length < 3) { throw new Error("Please specify a bucket name"); } main(process.argv[2]);
zack17/klio-picture-labeler
labler.js
JavaScript
mit
1,072
require "magnitude" describe Magnitude::Registry do context "#register" do it "registers a unit and returns an instance" do result = subject.register(:length, name: "meter", abbr: :m) expect(result).to be_kind_of(Magnitude::Unit) expect(result.name).to eq("meter") end end context "#fetch" do before{ subject.register :mass, name: "Pound", abbr: :lb } it "finds unit by abbreviation" do result = subject.fetch(:lb) expect(result).to be_kind_of(Magnitude::Unit) expect(result.name).to eq("Pound") end it "finds unit by name" do result = subject.fetch("Pound") expect(result).to be_kind_of(Magnitude::Unit) expect(result.name).to eq("Pound") end it "finds unit by plural name" do result = subject.fetch("Pounds") expect(result).to be_kind_of(Magnitude::Unit) expect(result.name).to eq("Pound") end it "finds unit by lower cased name" do result = subject.fetch("pound") expect(result).to be_kind_of(Magnitude::Unit) expect(result.name).to eq("Pound") end it "finds unit by lower cased name" do result = subject.fetch("pounds") expect(result).to be_kind_of(Magnitude::Unit) expect(result.name).to eq("Pound") end it "raises unknown unit error" do action = ->{ subject.fetch(:foo) } expect(&action).to raise_error(Magnitude::UnknownUnitError, "unknown unit: foo") end it "raises unknown type error" do action = ->{ subject.fetch(:foo, type: :bar) } expect(&action).to raise_error(Magnitude::UnknownTypeError, "unknown type: bar") end context "ambiguous unit" do before{ subject.register :force, name: "Pound", abbr: :lb } it "raises ambiguous error" do action = ->{ subject.fetch(:lb) } expect(&action).to raise_error(Magnitude::AmbiguousUnitError, "ambiguous unit: lb. Possible types: mass, force") end end end end
rwz/magnitude
spec/registry_spec.rb
Ruby
mit
1,972
import Ember from 'ember'; export default Ember.Controller.extend({ resume: Ember.inject.controller(), actions: { scrollToElem: function(selector) { this.get('resume').send('scrollToElem', selector); }, selectTemplate: function(template) { this.get('resume').send('selectTemplate', template); }, selectPalette: function(palette) { this.get('resume').send('selectPalette', palette); } } });
iorrah/you-rockstar
app/controllers/resume/index.js
JavaScript
mit
439
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\XMPPlus; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class MinorModelAgeDisclosure extends AbstractTag { protected $Id = 'MinorModelAgeDisclosure'; protected $Name = 'MinorModelAgeDisclosure'; protected $FullName = 'XMP::plus'; protected $GroupName = 'XMP-plus'; protected $g0 = 'XMP'; protected $g1 = 'XMP-plus'; protected $g2 = 'Author'; protected $Type = 'string'; protected $Writable = true; protected $Description = 'Minor Model Age Disclosure'; protected $Values = array( 'AG-A15' => array( 'Id' => 'AG-A15', 'Label' => 'Age 15', ), 'AG-A16' => array( 'Id' => 'AG-A16', 'Label' => 'Age 16', ), 'AG-A17' => array( 'Id' => 'AG-A17', 'Label' => 'Age 17', ), 'AG-A18' => array( 'Id' => 'AG-A18', 'Label' => 'Age 18', ), 'AG-A19' => array( 'Id' => 'AG-A19', 'Label' => 'Age 19', ), 'AG-A20' => array( 'Id' => 'AG-A20', 'Label' => 'Age 20', ), 'AG-A21' => array( 'Id' => 'AG-A21', 'Label' => 'Age 21', ), 'AG-A22' => array( 'Id' => 'AG-A22', 'Label' => 'Age 22', ), 'AG-A23' => array( 'Id' => 'AG-A23', 'Label' => 'Age 23', ), 'AG-A24' => array( 'Id' => 'AG-A24', 'Label' => 'Age 24', ), 'AG-A25' => array( 'Id' => 'AG-A25', 'Label' => 'Age 25 or Over', ), 'AG-U14' => array( 'Id' => 'AG-U14', 'Label' => 'Age 14 or Under', ), 'AG-UNK' => array( 'Id' => 'AG-UNK', 'Label' => 'Age Unknown', ), ); }
bburnichon/PHPExiftool
lib/PHPExiftool/Driver/Tag/XMPPlus/MinorModelAgeDisclosure.php
PHP
mit
2,220
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Feb 24 12:49:36 2017 @author: drsmith """ import os from .globals import FdpError def canonicalMachineName(machine=''): aliases = {'nstxu': ['nstx', 'nstxu', 'nstx-u'], 'diiid': ['diiid', 'diii-d', 'd3d'], 'cmod': ['cmod', 'c-mod']} for key, value in aliases.items(): if machine.lower() in value: return key # invalid machine name raise FdpError('"{}" is not a valid machine name\n'.format(machine)) MDS_SERVERS = { 'nstxu': {'hostname': 'skylark.pppl.gov', 'port': '8000'}, 'diiid': {'hostname': 'atlas.gat.com', 'port': '8000'} } EVENT_SERVERS = { 'nstxu': {'hostname': 'skylark.pppl.gov', 'port': '8000'}, 'diiid': {'hostname': 'atlas.gat.com', 'port': '8000'}, 'ltx': {'hostname': 'lithos.pppl.gov', 'port': '8000'} } LOGBOOK_CREDENTIALS = { 'nstxu': {'server': 'sql2008.pppl.gov', 'instance': None, 'username': None, 'password': None, 'database': None, 'port': '62917', 'table': 'entries', 'loginfile': os.path.join(os.getenv('HOME'), 'nstxlogs.sybase_login') } }
Fusion-Data-Platform/fdp
fdp/lib/datasources.py
Python
mit
1,353
process.env.NODE_ENV = 'test'; const chai = require('chai'); const chaiHttp = require('chai-http'); const should = chai.should(); const CostCalculator = require("../libs/costcalculator"); describe('Calculate Cost', () => { describe("Book Meeting Room", () => { it("it should calcuate cost for meeting room for 30m", async (done) => { try { let result = await CostCalculator("5bd7283ebfc02163c7b4d5d7", new Date("2020-01-01T09:00:00"), new Date("2020-01-01T09:30:00")); result.should.equal(2.8); done(); } catch(err) { done(err); } }); }); });
10layer/jexpress
test/costcalculator.js
JavaScript
mit
675
<?php /** * Created by PhpStorm. * User: GuoHao * Date: 2016/1/10 * Time: 14:32 */ class BeauticianRestModel extends BaseModel { public function setTable() { $this->table = 'beautician_rest'; } public function rules() { $validate = new ValidateUtil(); $validate->required('rest_day'); $validate->required('start_time'); $validate->required('end_time'); $validate->required('ps'); $validate->required('beautician_id'); return $validate; } }
guohao214/xinya
application/models/BeauticianRestModel.php
PHP
mit
561
package com.java.group34; import java.util.ArrayList; /** * Created by dell-pc on 2017/9/11. */ public class NewsPictures { private Value[] value; private static class Value { String contentUrl; } public ArrayList<String> getFirstNthPictures(int n) { ArrayList<String> ans=new ArrayList<String>(); System.out.println(value.length); for(int i=0;i<n&&i<value.length;++i) ans.add(value[i].contentUrl); return ans; } }
bennyguo/AssemblyNews
app/src/main/java/com/java/group34/NewsPictures.java
Java
mit
500
module.exports = { // Token you get from discord "token": "", // Prefix before your commands "prefix": "", // Port for webserver (Not working) "port": 8080, // Mongodb stuff "mongodb": { // Mongodb uri "uri": "" }, // Channel IDs "channelIDs": { // Where to announce the events in ACCF "events": "", // Where to announce online towns "onlineTowns": "", // Where to log the logs "logs": "" } }
rey2952/RoverBot
config.js
JavaScript
mit
455
Object.prototype.getKeyByValue = function( value ) { for( var prop in this ) { if( this.hasOwnProperty( prop ) ) { if( this[ prop ] === value ) return prop; } } }
tametheboardgame/tametheboardgame.github.io
CrushTheCrown/tools.js
JavaScript
mit
217
require('./ramda-mori')
fractalPlatform/Fractal.js
tests/index.js
JavaScript
mit
24
<?php use Squarely\Setup; use Squarely\Wrapper; ?> <?php get_template_part('templates/head'); ?> <body <?php body_class('main-body'); ?>> <!--[if IE]> <div class="alert alert-warning"> <?php _e('You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.', 'squarely'); ?> </div> <![endif]--> <?php do_action('get_header'); get_template_part('templates/header'); ?> <div class="wrapper" role="document" style="margin-top: 110px;"> <main> <?php include Wrapper\template_path(); ?> </main><!-- /.main --> </div><!-- /.wrap --> <?php do_action('get_footer'); get_template_part('templates/footer'); wp_footer(); ?> </body> </html>
jessicahawkins3344/SquarelyV.1
base-template-home.php
PHP
mit
810
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ach" version="2.0"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About CoinsBazar Core</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;CoinsBazar Core&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../utilitydialog.cpp" line="+29"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The CoinsBazar Core developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+30"/> <source>Double-click to edit address or label</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;New</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Copy the currently selected address to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Copy</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>C&amp;lose</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="+74"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="-41"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-27"/> <source>&amp;Delete</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="-30"/> <source>Choose the address to send coins to</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Choose the address to receive coins with</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>C&amp;hoose</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Sending addresses</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Receiving addresses</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>These are your CoinsBazar addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>These are your CoinsBazar addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+194"/> <source>Export Address List</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Exporting Failed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>There was an error trying to save the address list to %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+168"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>(no label)</source> <translation type="unfinished"/> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+40"/> <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 type="unfinished"/> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR BITCOINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation type="unfinished"/> </message> <message> <location line="-56"/> <source>CoinsBazar will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation type="unfinished"/> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation type="unfinished"/> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>CoinsBazarGUI</name> <message> <location filename="../bitcoingui.cpp" line="+295"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+335"/> <source>Synchronizing with network...</source> <translation type="unfinished"/> </message> <message> <location line="-407"/> <source>&amp;Overview</source> <translation type="unfinished"/> </message> <message> <location line="-137"/> <source>Node</source> <translation type="unfinished"/> </message> <message> <location line="+138"/> <source>Show general overview of wallet</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>E&amp;xit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Quit application</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show information about CoinsBazar</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+2"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Sending addresses...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Receiving addresses...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Open &amp;URI...</source> <translation type="unfinished"/> </message> <message> <location line="+325"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-405"/> <source>Send coins to a CoinsBazar address</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Modify configuration options for CoinsBazar</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="+430"/> <source>CoinsBazar</source> <translation type="unfinished"/> </message> <message> <location line="-643"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+146"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <location line="+2"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your CoinsBazar addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified CoinsBazar addresses</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>&amp;File</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Settings</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Help</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Tabs toolbar</source> <translation type="unfinished"/> </message> <message> <location line="-284"/> <location line="+376"/> <source>[testnet]</source> <translation type="unfinished"/> </message> <message> <location line="-401"/> <source>CoinsBazar Core</source> <translation type="unfinished"/> </message> <message> <location line="+163"/> <source>Request payments (generates QR codes and bitcoin: URIs)</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <location line="+2"/> <source>&amp;About CoinsBazar Core</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Show the list of used sending addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Show the list of used receiving addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Open a bitcoin: URI or payment request</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show the CoinsBazar Core help message to get a list with possible CoinsBazar command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+159"/> <location line="+5"/> <source>CoinsBazar client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+142"/> <source>%n active connection(s) to CoinsBazar network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+23"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="-85"/> <source>Up to date</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Catching up...</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Sent transaction</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+438"/> <source>A fatal error occurred. CoinsBazar can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+119"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control Address Selection</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+63"/> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>List mode</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Priority</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="+42"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock unspent</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Unlock unspent</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+323"/> <source>highest</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>higher</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>low</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lower</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lowest</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>(%1 locked)</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>none</source> <translation type="unfinished"/> </message> <message> <location line="+140"/> <source>Dust</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is greater than 1000 bytes.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+5"/> <source>This means a fee of at least %1 per kB is required.</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>Can vary +/- 1 byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions with higher priority are more likely to get included into a block.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the priority is smaller than &quot;medium&quot;.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This label turns red, if any recipient receives an amount smaller than %1.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+4"/> <source>This means a fee of at least %1 is required.</source> <translation type="unfinished"/> </message> <message> <location line="-3"/> <source>Amounts below 0.546 times the minimum relay fee are shown as dust.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>This label turns red, if the change is smaller than %1.</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <location line="+66"/> <source>(no label)</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The label associated with this address list entry</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>The address associated with this address list entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>&amp;Address</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+28"/> <source>New receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>New sending address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid CoinsBazar address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>FreespaceChecker</name> <message> <location filename="../intro.cpp" line="+65"/> <source>A new data directory will be created.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>name</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Path already exists, and is not a directory.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Cannot create data directory here.</source> <translation type="unfinished"/> </message> </context> <context> <name>HelpMessageDialog</name> <message> <location filename="../forms/helpmessagedialog.ui" line="+19"/> <source>CoinsBazar Core - Command-line options</source> <translation type="unfinished"/> </message> <message> <location filename="../utilitydialog.cpp" line="+38"/> <source>CoinsBazar Core</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Choose data directory on startup (default: 0)</source> <translation type="unfinished"/> </message> </context> <context> <name>Intro</name> <message> <location filename="../forms/intro.ui" line="+14"/> <source>Welcome</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Welcome to CoinsBazar Core.</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>As this is the first time the program is launched, you can choose where CoinsBazar Core will store its data.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>CoinsBazar Core will download and store a copy of the CoinsBazar 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> <location line="+10"/> <source>Use the default data directory</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use a custom data directory:</source> <translation type="unfinished"/> </message> <message> <location filename="../intro.cpp" line="+85"/> <source>CoinsBazar</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Specified data directory &quot;%1&quot; can not be created.</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>GB of free space available</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>(of %1GB needed)</source> <translation type="unfinished"/> </message> </context> <context> <name>OpenURIDialog</name> <message> <location filename="../forms/openuridialog.ui" line="+14"/> <source>Open URI</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Open payment request from URI or file</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>URI:</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Select payment request file</source> <translation type="unfinished"/> </message> <message> <location filename="../openuridialog.cpp" line="+47"/> <source>Select payment request file to open</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start CoinsBazar after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start CoinsBazar on system login</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Size of &amp;database cache</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>MB</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Number of script &amp;verification threads</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+58"/> <source>Connect to the CoinsBazar network through a SOCKS proxy.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy (default proxy):</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source> <translation type="unfinished"/> </message> <message> <location line="+224"/> <source>Active command-line options that override above options:</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="-323"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the CoinsBazar client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting CoinsBazar.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show CoinsBazar addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only)</source> <translation type="unfinished"/> </message> <message> <location line="+136"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+67"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source>none</source> <translation type="unfinished"/> </message> <message> <location line="+75"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+29"/> <source>Client restart required to activate changes.</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Client will be shutdown, do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <source>This change would require a client restart.</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the CoinsBazar network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-155"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-83"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Confirmed:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <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> <location line="+16"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Total:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+120"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+403"/> <location line="+13"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>URI can not be parsed! This can be caused by an invalid CoinsBazar address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+96"/> <source>Requested payment amount of %1 is too small (considered dust).</source> <translation type="unfinished"/> </message> <message> <location line="-221"/> <location line="+212"/> <location line="+13"/> <location line="+95"/> <location line="+18"/> <location line="+16"/> <source>Payment request error</source> <translation type="unfinished"/> </message> <message> <location line="-353"/> <source>Cannot start bitcoin: click-to-pay handler</source> <translation type="unfinished"/> </message> <message> <location line="+58"/> <source>Net manager warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Your active proxy doesn&apos;t support SOCKS5, which is required for payment requests via proxy.</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>Payment request fetch URL is invalid: %1</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Payment request file handling</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <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> <location line="+73"/> <source>Unverified payment requests to custom payment scripts are unsupported.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Refund from %1</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Error communicating with %1: %2</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Payment request can not be parsed or processed!</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Bad response from server %1</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <source>Payment acknowledged</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Network request error</source> <translation type="unfinished"/> </message> </context> <context> <name>QObject</name> <message> <location filename="../bitcoin.cpp" line="+71"/> <location line="+11"/> <source>CoinsBazar</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Specified data directory &quot;%1&quot; does not exist.</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Error: Invalid combination of -regtest and -testnet.</source> <translation type="unfinished"/> </message> </context> <context> <name>QRImageWidget</name> <message> <location filename="../receiverequestdialog.cpp" line="+36"/> <source>&amp;Save Image...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Copy Image</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Image (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+23"/> <location line="+36"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+359"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-223"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>General</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Name</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="+72"/> <source>&amp;Network Traffic</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Clear</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Totals</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>In:</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <source>Out:</source> <translation type="unfinished"/> </message> <message> <location line="-521"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="+206"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the CoinsBazar debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the CoinsBazar RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> <message> <location line="+122"/> <source>%1 B</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 KB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 MB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 GB</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>%1 m</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>%1 h</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 h %2 m</source> <translation type="unfinished"/> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <location filename="../forms/receivecoinsdialog.ui" line="+83"/> <source>&amp;Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location line="-34"/> <source>&amp;Message:</source> <translation type="unfinished"/> </message> <message> <location line="-17"/> <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> <location line="+3"/> <source>R&amp;euse an existing receiving address (not recommended)</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>An optional label to associate with the new receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <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 CoinsBazar network.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use this form to request payments. All fields are &lt;b&gt;optional&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Clear all fields of the form.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Request payment</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Requested payments</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Show the selected request (does the same as double clicking an entry)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Show</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Remove the selected entries from the list</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Remove</source> <translation type="unfinished"/> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <location filename="../forms/receiverequestdialog.ui" line="+29"/> <source>QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>Copy &amp;URI</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Copy &amp;Address</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Save Image...</source> <translation type="unfinished"/> </message> <message> <location filename="../receiverequestdialog.cpp" line="+56"/> <source>Request payment to %1</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Payment information</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>URI</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <location filename="../recentrequeststablemodel.cpp" line="+24"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+38"/> <source>(no label)</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>(no message)</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+381"/> <location line="+80"/> <source>Send Coins</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <location line="+89"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <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> <location line="+3"/> <source>Custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+115"/> <source>Send to multiple recipients at once</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Clear all fields of the form.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Confirm the send action</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-228"/> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <location line="+5"/> <location line="+5"/> <location line="+4"/> <source>%1 to %2</source> <translation type="unfinished"/> </message> <message> <location line="-136"/> <source>Enter a CoinsBazar address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+170"/> <source>Total Amount %1 (= %2)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>or</source> <translation type="unfinished"/> </message> <message> <location line="+202"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <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 type="unfinished"/> </message> <message> <location line="+112"/> <source>Warning: Invalid CoinsBazar address</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>(no label)</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Warning: Unknown change address</source> <translation type="unfinished"/> </message> <message> <location line="-366"/> <source>Are you sure you want to send?</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>added as transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+170"/> <source>Payment request expired</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Invalid payment address %1</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+131"/> <location line="+521"/> <location line="+536"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location line="-1152"/> <source>Pay &amp;To:</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+30"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="+57"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Choose previously used address</source> <translation type="unfinished"/> </message> <message> <location line="-40"/> <source>This is a normal payment.</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <location line="+524"/> <location line="+536"/> <source>Remove this entry</source> <translation type="unfinished"/> </message> <message> <location line="-1008"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>A message that was attached to the CoinsBazar URI which will be stored with the transaction for your reference. Note: This message will not be sent over the CoinsBazar network.</source> <translation type="unfinished"/> </message> <message> <location line="+958"/> <source>This is a verified payment request.</source> <translation type="unfinished"/> </message> <message> <location line="-991"/> <source>Enter a label for this address to add it to the list of used addresses</source> <translation type="unfinished"/> </message> <message> <location line="+459"/> <source>This is an unverified payment request.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <location line="+532"/> <source>Pay To:</source> <translation type="unfinished"/> </message> <message> <location line="-498"/> <location line="+536"/> <source>Memo:</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a CoinsBazar address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> </context> <context> <name>ShutdownWindow</name> <message> <location filename="../utilitydialog.cpp" line="+48"/> <source>CoinsBazar Core is shutting down...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do not shut down the computer until this window disappears.</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose previously used address</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this CoinsBazar address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified CoinsBazar address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+29"/> <location line="+3"/> <source>Enter a CoinsBazar address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter CoinsBazar signature</source> <translation type="unfinished"/> </message> <message> <location line="+84"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+28"/> <source>CoinsBazar Core</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>The CoinsBazar Core developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation type="unfinished"/> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <location filename="../trafficgraphwidget.cpp" line="+79"/> <source>KB/s</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+28"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+53"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-125"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+53"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-62"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <location line="+9"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="-7"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Merchant</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <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> <location line="+8"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-232"/> <source>, has not been successfully broadcast yet</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+234"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+16"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="-22"/> <location line="+25"/> <source>Confirmed (%1 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="-22"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+62"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Received from</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation type="unfinished"/> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+57"/> <location line="+16"/> <source>All</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <source>Today</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This week</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Last month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This year</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Range...</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>To yourself</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Other</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter address or label to search</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Min amount</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+142"/> <source>Export Transaction History</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Exporting Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the transaction history to %1.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Exporting Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The transaction history was successfully saved to %1.</source> <translation type="unfinished"/> </message> <message> <location line="-22"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>ID</source> <translation type="unfinished"/> </message> <message> <location line="+107"/> <source>Range:</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>to</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletFrame</name> <message> <location filename="../walletframe.cpp" line="+26"/> <source>No wallet has been loaded.</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+245"/> <source>Send Coins</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+43"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+181"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to %1.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>The wallet data was successfully saved to %1.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+221"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="-54"/> <source>List commands</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Get help for a command</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Options:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Specify configuration file (default: bitcoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Specify pid file (default: bitcoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="-26"/> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="-51"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+84"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-148"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-36"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-118"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-95"/> <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;CoinsBazar Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <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> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. CoinsBazar is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <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> <location line="+4"/> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <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> <location line="+5"/> <source>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <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> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong CoinsBazar will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <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> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&lt;category&gt; can be:</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>CoinsBazar Core Daemon</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>CoinsBazar RPC client version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Connect through SOCKS proxy</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Connect to JSON-RPC on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do not load the wallet and disable wallet RPC calls</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Fee per kB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>If &lt;category&gt; is not supplied, output all debugging information.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -onion address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Prepend debug output with timestamp (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>RPC client options:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Select SOCKS version for -proxy (4 or 5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send command to CoinsBazar server</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Set maximum block size in bytes (default: %d)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Start CoinsBazar server</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Usage (deprecated, use bitcoin-cli):</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wait for RPC server to start</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet %s resides outside data directory %s</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Wallet options:</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>You need to rebuild the database using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="-79"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-105"/> <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> <location line="+14"/> <source>Output debugging information (default: 0, supplying &lt;category&gt; is optional)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+89"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>SSL options: (see the CoinsBazar Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-58"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-70"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="-132"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+161"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="-24"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+38"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-30"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>This help message</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-107"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <source>Loading addresses...</source> <translation type="unfinished"/> </message> <message> <location line="-37"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of CoinsBazar</source> <translation type="unfinished"/> </message> <message> <location line="+98"/> <source>Wallet needed to be rewritten: restart CoinsBazar to complete</source> <translation type="unfinished"/> </message> <message> <location line="-100"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-101"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation type="unfinished"/> </message> <message> <location line="-62"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="-32"/> <source>Unable to bind to %s on this computer. CoinsBazar is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+95"/> <source>Loading wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-56"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+67"/> <source>Rescanning...</source> <translation type="unfinished"/> </message> <message> <location line="-58"/> <source>Done loading</source> <translation type="unfinished"/> </message> <message> <location line="+85"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="-35"/> <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>
aqavi-paracha/coinsbazar
src/qt/locale/bitcoin_ach.ts
TypeScript
mit
130,916
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; namespace DND.AspNetCore.Web.Models.ManageViewModels { public class IndexViewModel { public bool HasPassword { get; set; } public IList<UserLoginInfo> Logins { get; set; } public string PhoneNumber { get; set; } public bool TwoFactor { get; set; } public bool BrowserRemembered { get; set; } } }
davidikin45/DigitalNomadDave
DND.AspNetCore.Web/Models/ManageViewModels/IndexViewModel.cs
C#
mit
490
/** * Programmer: Minhas Kamal (BSSE0509,IIT,DU) * Date: 30-Mar-2014 **/ #include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; #define X 3 struct node{ int value; int depth; node *previous; node *next[X]; } nullNode; int main(){ ///input array int arrayLength=1; for(int i=0; i<X; i++){ arrayLength = arrayLength * 2; } int array[arrayLength]; for(int i=0; i<arrayLength; i++){ array[i]=rand()%100; printf("%d \n", array[i]);///test } ///initialize null node nullNode.value=-1; nullNode.depth=0; nullNode.previous=NULL; for(int i=0; i<X; i++){ nullNode.next[i]=NULL; } ///constructing binomial tree bool similarityFound=true; node binomialTree[arrayLength]; for(int i=0; i<arrayLength; i++){ ///initialization binomialTree[i].value = array[i]; binomialTree[i].depth = 0; binomialTree[i].previous = &nullNode; for(int j=0; j<X; j++){ binomialTree[i].next[j] =NULL; } nullNode.next[nullNode.depth]=&binomialTree[i]; nullNode.depth++; ///finding & merging similar trees int newNode=i; while(1){ similarityFound=false; int j; for(j=0; j<nullNode.depth-1; j++){ if(nullNode.next[j]->depth==binomialTree[newNode].depth) similarityFound=true; } if(similarityFound){ if(binomialTree[j].value < binomialTree[newNode].value){ binomialTree[j].next[binomialTree[j].depth]=&binomialTree[newNode]; binomialTree[newNode].previous=&binomialTree[j]; newNode=j; binomialTree[j].depth++; } else{ binomialTree[newNode].next[binomialTree[newNode].depth]=&binomialTree[j]; binomialTree[j].previous=&binomialTree[newNode]; newNode=newNode; binomialTree[newNode].depth++; } nullNode.depth--; nullNode.next[nullNode.depth]=&binomialTree[newNode]; }else{ break; } } } ///traversing for(int i=0; i<arrayLength; i++){ cout << &binomialTree[i] << "\t" << binomialTree[i].value << "\t"; cout << binomialTree[i].depth << "\t" << binomialTree[i].previous << "\t"; for(int j=0; j<X; j++){ cout << binomialTree[i].next[j] << "\t"; } cout << endl; } return 0; }
MinhasKamal/AlgorithmImplementations
dataStructures/tree/BinomialTree.cpp
C++
mit
2,759
<?php namespace PlaceFinder\APIBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('place_finder_api'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
yoannrenard/place-finder
src/PlaceFinder/APIBundle/DependencyInjection/Configuration.php
PHP
mit
886
/*istanbul ignore next*/'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var _request2 = require('request'); var _request3 = _interopRequireDefault(_request2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * A set of utlity methods. * @abstract */ var EgoJSUtils = (function () { function EgoJSUtils() { _classCallCheck(this, EgoJSUtils); } _createClass(EgoJSUtils, null, [{ key: '_fullfilledPromise', /** * Returns an already fullfilled promise with a given value. * @param {bollean} success - Whether to call `resolve` or `reject`. * @param {*} response - The object to resolve or reject. * @return {Promise<*,*>} * @private * @ignore */ value: function _fullfilledPromise(success, response) { return new Promise(function (resolve, reject) { if (success) { resolve(response); } else { reject(response); } }); } /** * Returns an already rejected promise. * @example * EgoJSUtils.rejectedPromise('error message').catch((e) => { * // It will log 'error message' * console.log(e); * }); * * @param {*} response - The object to send to the `.catch` method. * @return {Promise<null, *>} This promise won't call `.then` but `.catch` directly. */ }, { key: 'rejectedPromise', value: function rejectedPromise(response) { return this._fullfilledPromise(false, response); } /** * Returns an already resolved promise. * @example * EgoJSUtils.rejectedPromise('hello world').then((message) => { * // It will log 'hello world' * console.log(message); * }); * * @param {*} response - The object to send to the `.then` method. * @return {Promise<*, null>} This promise won't call `.catch`. */ }, { key: 'resolvedPromise', value: function resolvedPromise(response) { return this._fullfilledPromise(true, response); } /** * It will merge a given list of Objects into a new one. It works recursively, so any "sub * objects" will also be merged. This method returns a new Object, so none of the targets will * be modified. * @example * const a = { * b: 'c', * d: { * e: 'f', * g: { * h: ['i'], * }, * }, * j: 'k', * }; * const b = { * j: 'key', * d: { * g: { * h: ['x', 'y', 'z'], * l: 'm', * }, * }, * }; * // The result will be * // { * // b: 'c', * // d: { * // e: 'f', * // g: { * // h: ['x', 'y', 'z'], * // l: 'm', * // }, * // }, * // j: 'key', * // } * ._mergeObjects(a, b); * * @param {...Object} objects - The list of objects to merge. * @return {Object} A new object with the merged properties. */ }, { key: 'mergeObjects', value: function mergeObjects() { /*istanbul ignore next*/ var _this = this; var result = {}; /*istanbul ignore next*/ for (var _len = arguments.length, objects = Array(_len), _key = 0; _key < _len; _key++) { objects[_key] = arguments[_key]; } objects.forEach(function (obj) { if (typeof obj !== 'undefined') { Object.keys(obj).forEach(function (objKey) { var current = obj[objKey]; var target = result[objKey]; if (typeof target !== 'undefined' && current.constructor === Object && target.constructor === Object) { result[objKey] = /*istanbul ignore next*/_this.mergeObjects(target, current); } else { result[objKey] = current; } }, /*istanbul ignore next*/_this); } }, this); return result; } /** * Wraps a Request call into a Promise. * @example * request({uri: 'https://homer0.com/rosario'}) * .then((response) => doSomething(response)) * .catch((err) => handleErrors(err)); * * @param {Object} data The request settings. The same you would use with request(). * @return {Promise<Object, Error>} It will be resolved or rejected depending on the response. */ }, { key: 'request', value: function request(data) { return new Promise(function (resolve, reject) { /*istanbul ignore next*/(0, _request3.default)(data, function (err, httpResponse, body) { if (err) { reject(err); } else { resolve(body); } }); }); } }]); return EgoJSUtils; })(); /*istanbul ignore next*/exports.default = EgoJSUtils;
homer0/egojs
dist/utils.js
JavaScript
mit
6,397
// shexmap-simple - Simple ShEx2 validator for HTML. // Copyright 2017 Eric Prud'hommeux // Release under MIT License. const ShEx = ShExWebApp; // @@ rename globally const ShExJsUrl = 'https://github.com/shexSpec/shex.js' const RdfJs = N3js; const ShExApi = ShEx.Api({ fetch: window.fetch.bind(window), rdfjs: RdfJs, jsonld: null }) const MapModule = ShEx.Map({rdfjs: RdfJs, Validator: ShEx.Validator}); ShEx.ShapeMap.start = ShEx.Validator.start const SharedForTests = {} // an object to share state with a test harness const START_SHAPE_LABEL = "START"; const START_SHAPE_INDEX_ENTRY = "- start -"; // specificially not a JSON-LD @id form. const INPUTAREA_TIMEOUT = 250; const NO_MANIFEST_LOADED = "no manifest loaded"; const LOG_PROGRESS = false; const DefaultBase = location.origin + location.pathname; const Caches = {}; Caches.inputSchema = makeSchemaCache($("#inputSchema textarea.schema")); Caches.inputData = makeTurtleCache($("#inputData textarea")); Caches.manifest = makeManifestCache($("#manifestDrop")); Caches.extension = makeExtensionCache($("#extensionDrop")); Caches.shapeMap = makeShapeMapCache($("#textMap")); // @@ rename to #shapeMap Caches.bindings = makeJSONCache($("#bindings1 textarea")); Caches.statics = makeJSONCache($("#staticVars textarea")); Caches.outputSchema = makeSchemaCache($("#outputSchema textarea")); // let ShExRSchema; // defined in calling page const ParseTriplePattern = (function () { const uri = "<[^>]*>|[a-zA-Z0-9_-]*:[a-zA-Z0-9_-]*"; const literal = "((?:" + "'(?:[^'\\\\]|\\\\')*'" + "|" + "\"(?:[^\"\\\\]|\\\\\")*\"" + "|" + "'''(?:(?:'|'')?[^'\\\\]|\\\\')*'''" + "|" + "\"\"\"(?:(?:\"|\"\")?[^\"\\\\]|\\\\\")*\"\"\"" + ")" + "(?:@[a-zA-Z-]+|\\^\\^(?:" + uri + "))?)"; const uriOrKey = uri + "|FOCUS|_"; // const termOrKey = uri + "|" + literal + "|FOCUS|_"; return "(\\s*{\\s*)("+ uriOrKey+")?(\\s*)("+ uri+"|a)?(\\s*)("+ uriOrKey+"|" + literal + ")?(\\s*)(})?(\\s*)"; })(); const Getables = [ {queryStringParm: "schema", location: Caches.inputSchema.selection, cache: Caches.inputSchema}, {queryStringParm: "data", location: Caches.inputData.selection, cache: Caches.inputData }, {queryStringParm: "manifest", location: Caches.manifest.selection, cache: Caches.manifest , fail: e => $("#manifestDrop li").text(NO_MANIFEST_LOADED)}, {queryStringParm: "extension", location: Caches.extension.selection, cache: Caches.extension }, {queryStringParm: "shape-map", location: $("#textMap"), cache: Caches.shapeMap }, {queryStringParm: "bindings", location: Caches.bindings.selection, cache: Caches.bindings }, {queryStringParm: "statics", location: Caches.statics.selection, cache: Caches.statics }, {queryStringParm: "outSchema", location: Caches.outputSchema.selection,cache: Caches.outputSchema}, ]; const QueryParams = Getables.concat([ {queryStringParm: "interface", location: $("#interface"), deflt: "human" }, {queryStringParm: "success", location: $("#success"), deflt: "proof" }, {queryStringParm: "regexpEngine", location: $("#regexpEngine"), deflt: "eval-threaded-nerr" }, ]); // utility functions function parseTurtle (text, meta, base) { const ret = new RdfJs.Store(); RdfJs.Parser._resetBlankNodePrefix(); const parser = new RdfJs.Parser({baseIRI: base, format: "text/turtle" }); const quads = parser.parse(text); if (quads !== undefined) ret.addQuads(quads); meta.base = parser._base; meta.prefixes = parser._prefixes; return ret; } const shexParser = ShEx.Parser.construct(DefaultBase, null, {index: true}); function parseShEx (text, meta, base) { shexParser._setOptions({duplicateShape: $("#duplicateShape").val()}); shexParser._setBase(base); const ret = shexParser.parse(text); // ret = ShEx.Util.canonicalize(ret, DefaultBase); meta.base = ret._base; // base set above. meta.prefixes = ret._prefixes || {}; // @@ revisit after separating shexj from meta and indexes return ret; } function sum (s) { // cheap way to identify identical strings return s.replace(/\s/g, "").split("").reduce(function (a,b){ a = ((a<<5) - a) + b.charCodeAt(0); return a&a },0); } // <n3.js-specific> function rdflib_termToLex (node, resolver) { if (node === "http://www.w3.org/1999/02/22-rdf-syntax-ns#type") return "a"; if (node === ShEx.Validator.start) return START_SHAPE_LABEL; if (node === resolver._base) return "<>"; if (node.indexOf(resolver._base) === 0/* && ['#', '?'].indexOf(node.substr(resolver._base.length)) !== -1 */) return "<" + node.substr(resolver._base.length) + ">"; if (node.indexOf(resolver._basePath) === 0 && ['#', '?', '/', '\\'].indexOf(node.substr(resolver._basePath.length)) === -1) return "<" + node.substr(resolver._basePath.length) + ">"; return ShEx.ShExTerm.intermalTermToTurtle(node, resolver.meta.base, resolver.meta.prefixes); } function rdflib_lexToTerm (lex, resolver) { return lex === START_SHAPE_LABEL ? ShEx.Validator.start : lex === "a" ? "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" : new RdfJs.Lexer().tokenize(lex + " ") // need " " to parse "chat"@en .map(token => { const left = token.type === "typeIRI" ? "^^" : token.type === "langcode" ? "@" : token.type === "type" ? "^^" + resolver.meta.prefixes[token.prefix] : token.type === "prefixed" ? resolver.meta.prefixes[token.prefix] : token.type === "blank" ? "_:" : ""; const right = token.type === "IRI" || token.type === "typeIRI" ? resolver._resolveAbsoluteIRI(token) : token.value; return left + right; }).join(""); return lex === ShEx.Validator.start ? lex : lex[0] === "<" ? lex.substr(1, lex.length - 2) : lex; } // </n3.js-specific> // caches for textarea parsers function _makeCache (selection) { let _dirty = true; const ret = { selection: selection, parsed: null, // a Promise meta: { prefixes: {}, base: DefaultBase }, dirty: function (newVal) { const ret = _dirty; _dirty = newVal; return ret; }, get: function () { return selection.val(); }, set: async function (text, base) { _dirty = true; selection.val(text); this.meta.base = base; if (base !== DefaultBase) { this.url = base; // @@crappyHack1 -- parms should differntiate: // working base: base for URL resolution. // loaded base: place where you can GET current doc. // Note that Caches.manifest.set takes a 3rd parm. } }, refresh: async function () { if (!_dirty) return this.parsed; this.parsed = await this.parse(selection.val(), this.meta.base); await this.parsed; _dirty = false; return this.parsed; }, asyncGet: async function (url) { url = new URL(url, window.location).href const _cache = this; let resp try { resp = await fetch(url, {headers: { accept: 'text/shex,text/turtle,*/*;q=0.9, test/html;q=0.8', cache: 'no-cache' }}) } catch (e) { throw Error("unable to fetch <" + url + ">: " + '\n' + e.message); } if (!resp.ok) throw Error("fetch <" + url + "> got error response " + resp.status + ": " + resp.statusText); const data = await resp.text(); _cache.meta.base = url; try { await _cache.set(data, url, undefined, resp.headers.get('content-type')); } catch (e) { throw Error("error setting " + this.queryStringParm + " with <" + url + ">: " + '\n' + e.message); } $("#loadForm").dialog("close"); toggleControls(); return { url: url, data: data }; }, url: undefined // only set if inputarea caches some web resource. }; ret.meta.termToLex = function (trm) { return rdflib_termToLex(trm, new IRIResolver(ret.meta)); }; ret.meta.lexToTerm = function (lex) { return rdflib_lexToTerm(lex, new IRIResolver(ret.meta)); }; return ret; } function makeSchemaCache (selection) { const ret = _makeCache(selection); let graph = null; ret.language = null; ret.parse = async function (text, base) { const isJSON = text.match(/^\s*\{/); graph = isJSON ? null : tryN3(text); this.language = isJSON ? "ShExJ" : graph ? "ShExR" : "ShExC"; $("#results .status").text("parsing "+this.language+" schema...").show(); const schema = isJSON ? ShEx.Util.ShExJtoAS(JSON.parse(text)) : graph ? parseShExR() : parseShEx(text, ret.meta, base); $("#results .status").hide(); markEditMapDirty(); // ShapeMap validity may have changed. return schema; function tryN3 (text) { try { if (text.match(/^\s*$/)) return null; const db = parseTurtle (text, ret.meta, DefaultBase); // interpret empty schema as ShExC if (db.getQuads().length === 0) return null; return db; } catch (e) { return null; } } function parseShExR () { const graphParser = ShEx.Validator.construct( parseShEx(ShExRSchema, {}, base), // !! do something useful with the meta parm (prefixes and base) ShEx.Util.rdfjsDB(graph), {} ); const schemaRoot = graph.getQuads(null, ShEx.Util.RDF.type, "http://www.w3.org/ns/shex#Schema")[0].subject; // !!check const val = graphParser.validate(schemaRoot, ShEx.Validator.start); // start shape return ShEx.Util.ShExJtoAS(ShEx.Util.ShExRtoShExJ(ShEx.Util.valuesToSchema(ShEx.Util.valToValues(val)))); } }; ret.getItems = async function () { const obj = await this.refresh(); const start = "start" in obj ? [START_SHAPE_LABEL] : []; const rest = "shapes" in obj ? obj.shapes.map(se => Caches.inputSchema.meta.termToLex(se.id)) : []; return start.concat(rest); }; return ret; } function makeTurtleCache (selection) { const ret = _makeCache(selection); ret.parse = async function (text, base) { const res = ShEx.Util.rdfjsDB(parseTurtle(text, ret.meta, base)); markEditMapDirty(); // ShapeMap validity may have changed. return res; }; ret.getItems = async function () { const data = await this.refresh(); return data.getQuads().map(t => { return Caches.inputData.meta.termToLex(t.subject); // !!check }); }; return ret; } function makeManifestCache (selection) { const ret = _makeCache(selection); ret.set = async function (textOrObj, url, source) { $("#inputSchema .manifest li").remove(); $("#inputData .passes li, #inputData .fails li").remove(); if (typeof textOrObj !== "object") { if (url !== DefaultBase) { this.url = url; // @@crappyHack1 -- parms should differntiate: } try { // exceptions pass through to caller (asyncGet) textOrObj = JSON.parse(textOrObj); } catch (e) { $("#inputSchema .manifest").append($("<li/>").text(NO_MANIFEST_LOADED)); const throwMe = Error(e + '\n' + textOrObj); throwMe.action = 'load manifest' throw throwMe // @@DELME(2017-12-29) // transform deprecated examples.js structure // textOrObj = eval(textOrObj).reduce(function (acc, schema) { // function x (data, status) { // return { // schemaLabel: schema.name, // schema: schema.schema, // dataLabel: data.name, // data: data.data, // queryMap: data.queryMap, // outputSchema: data.outputSchema, // outputShape: data.outputShape, // staticVars: data.staticVars, // createRoot: data.createRoot, // status: status // }; // } // return acc.concat( // schema.passes.map(data => x(data, "conformant")), // schema.fails.map(data => x(data, "nonconformant")) // ); // }, []); } } if (!Array.isArray(textOrObj)) textOrObj = [textOrObj]; const demos = textOrObj.reduce((acc, elt) => { if ("action" in elt) { // compatibility with test suite structure. const action = elt.action; let schemaLabel = action.schema.substr(action.schema.lastIndexOf('/')+1); let dataLabel = elt["@id"]; let match = null; const emptyGraph = "-- empty graph --"; if ("comment" in elt) { if ((match = elt.comment.match(/^(.*?) \/ { (.*?) }$/))) { schemaLabel = match[1]; dataLabel = match[2] || emptyGraph; } else if ((match = elt.comment.match(/^(.*?) on { (.*?) }$/))) { schemaLabel = match[1]; dataLabel = match[2] || emptyGraph; } else if ((match = elt.comment.match(/^(.*?) as { (.*?) }$/))) { schemaLabel = match[2]; dataLabel = match[1] || emptyGraph; } } const queryMap = "map" in action ? null : ldToTurtle(action.focus, Caches.inputData.meta.termToLex) + "@" + ("shape" in action ? ldToTurtle(action.shape, Caches.inputSchema.meta.termToLex) : START_SHAPE_LABEL); const queryMapURL = "map" in action ? action.map : null; elt = Object.assign( { schemaLabel: schemaLabel, schemaURL: action.schema || url, // dataLabel: "comment" in elt ? elt.comment : (queryMap || dataURL), dataLabel: dataLabel, dataURL: action.data || DefaultBase }, (queryMap ? { queryMap: queryMap } : { queryMapURL: queryMapURL }), { status: elt["@type"] === "sht:ValidationFailure" ? "nonconformant" : "conformant" } ); if ("termResolver" in action || "termResolverURL" in action) { elt.meta = action.termResolver; elt.metaURL = action.termResolverURL || DefaultBase; } } ["schemaURL", "dataURL", "queryMapURL"].forEach(parm => { if (parm in elt) { elt[parm] = new URL(elt[parm], new URL(url, DefaultBase).href).href; } else { delete elt[parm]; } }); return acc.concat(elt); }, []); await prepareManifest(demos, url); $("#manifestDrop").show(); // may have been hidden if no manifest loaded. }; ret.parse = async function (text, base) { throw Error("should not try to parse manifest cache"); }; ret.getItems = async function () { throw Error("should not try to get manifest cache items"); }; return ret; function maybeGET(obj, base, key, accept) { // !!not used if (obj[key] != null) { // Take the passed data, guess base if not provided. if (!(key + "URL" in obj)) obj[key + "URL"] = base; obj[key] = Promise.resolve(obj[key]); } else if (key + "URL" in obj) { // absolutize the URL obj[key + "URL"] = ret.meta.lexToTerm("<"+obj[key + "URL"]+">"); // Load the remote resource. obj[key] = new Promise((resolve, reject) => { $.ajax({ accepts: { mycustomtype: accept }, url: ret.meta.lexToTerm("<"+obj[key + "URL"]+">"), dataType: "text" }).then(text => { resolve(text); }).fail(e => { results.append($("<pre/>").text( "Error " + e.status + " " + e.statusText + " on GET " + obj[key + "URL"] ).addClass("error")); reject(e); }); }); } else { // Ignore this parameter. obj[key] = Promise.resolve(obj[key]); } } } function makeExtensionCache (selection) { const ret = _makeCache(selection); ret.set = async function (code, url, source, mediaType) { this.url = url; // @@crappyHack1 -- parms should differntiate: try { // exceptions pass through to caller (asyncGet) // const resp = await fetch('http://localhost/checkouts/shexSpec/extensions/Eval/') // const text = await resp.text(); if (mediaType.startsWith('text/html')) return this.grepHtmlIndexForPackage(code, url, source) const extension = Function(`"use strict"; const module = {exports: {}}; ${code} return module.exports; `)() const name = extension.name; const id = "extension_" + name; // Delete any old li associated with this extension. const old = $(`.extensionControl[data-url="${extension.url}"]`) if (old.length) { results.append($("<div/>").append( $("<span/>").text(`removing old ${old.attr('data-name')} extension`) )); old.parent().remove(); } // Create a new li. const elt = $("<li/>", { class: "menuItem", title: extension.description }).append( $("<input/>", { type: "checkbox", checked: "checked", class: "extensionControl", id: id, "data-name": name, "data-url": extension.url }), $("<label/>", { for: id }).append( $("<a/>", {href: extension.url, text: name}) ) ); elt.insertBefore("#load-extension-button"); $("#" + id).data("code", extension); Caches.extension.url = url; // @@ cheesy hack that only works to remember one extension URL results.append($("<div/>").append( $("<span/>").text(`extension ${name} loaded from <${url}>`) )); } catch (e) { // $("#inputSchema .extension").append($("<li/>").text(NO_EXTENSION_LOADED)); const throwMe = Error(e + '\n' + code); throwMe.action = 'load extension' throw throwMe } // $("#extensionDrop").show(); // may have been hidden if no extension loaded. }; /* Poke around in HTML for a PACKAGE link in <table class="implementations"> <td property="code:softwareAgent" resource="https://github.com/shexSpec/shex.js">shexjs</td> <td><a property="shex:package" href="PACKAGE"/>...</td>... </table> */ ret.grepHtmlIndexForPackage = async function (code, url, source) { const jq = $(code); const impls = $(jq.find('table.implementations')) if (impls.length !== 1) { results.append($("<div/>").append( $("<span/>").text("unparsable extension index at " + url) ).addClass("error")); return; } const tr = $(impls).find(`tr td[resource="${ShExJsUrl}"]`).parent() if (tr.length !== 1) { results.append($("<div/>").append( $("<span/>").text("no entry for shexjs in index HTML at " + url) ).addClass("error")); return; } const href = tr.find('[property="shex:package"]').attr('href') if (!href) { results.append($("<div/>").append( $("<span/>").text("no package for shexjs in index HTML at " + url) ).addClass("error")); return; } const refd = await fetch(href); if (!refd.ok) { results.append($("<div/>").append( $("<span/>").text(`error fetching implementation: ${refd.status} (${refd.statusText}) for URL <${href}>`) ).addClass("error")); } else { code = await refd.text(); await this.set(code, url, source, refd.headers.get('content-type')); } }; ret.parse = async function (text, base) { throw Error("should not try to parse extension cache"); }; ret.getItems = async function () { throw Error("should not try to get extension cache items"); }; return ret; } function ldToTurtle (ld, termToLex) { return typeof ld === "object" ? lit(ld) : termToLex(ld); function lit (o) { let ret = "\""+o["@value"].replace(/["\r\n\t]/g, (c) => { return {'"': "\\\"", "\r": "\\r", "\n": "\\n", "\t": "\\t"}[c]; }) +"\""; if ("@type" in o) ret += "^^<" + o["@type"] + ">"; if ("@language" in o) ret += "@" + o["@language"]; return ret; } } function makeShapeMapCache (selection) { const ret = _makeCache(selection); ret.parse = async function (text) { removeEditMapPair(null); $("#textMap").val(text); copyTextMapToEditMap(); await copyEditMapToFixedMap(); }; // ret.parse = function (text, base) { }; ret.getItems = async function () { throw Error("should not try to get manifest cache items"); }; return ret; } function makeJSONCache(selection) { const ret = _makeCache(selection); ret.parse = async function (text) { return Promise.resolve(JSON.parse(text)); }; return ret; } // controls for manifest buttons async function paintManifest (selector, list, func, listItems, side) { $(selector).empty(); await Promise.all(list.map(async entry => { // build button disabled and with leading "..." to indicate that it's being loaded const button = $("<button/>").text("..." + entry.label.substr(3)).attr("disabled", "disabled"); const li = $("<li/>").append(button); $(selector).append(li); if (entry.text === undefined) { entry.text = await fetchOK(entry.url).catch(responseOrError => { // leave a message in the schema or data block return "# " + renderErrorMessage( responseOrError instanceof Error ? { url: entry.url, status: -1, statusText: responseOrError.message } : responseOrError, side); }) textLoaded(); } else { textLoaded(); } function textLoaded () { li.on("click", async () => { SharedForTests.promise = func(entry.name, entry, li, listItems, side); }); listItems[side][sum(entry.text)] = li; // enable and get rid of the "..." in the label now that it's loaded button.text(entry.label).removeAttr("disabled"); } })) setTextAreaHandlers(listItems); } function fetchOK (url) { return fetch(url).then(responseOrError => { if (!responseOrError.ok) { throw responseOrError; } return responseOrError.text() }); } function renderErrorMessage (response, what) { const message = "failed to load " + "queryMap" + " from <" + response.url + ">, got: " + response.status + " " + response.statusText; results.append($("<pre/>").text(message).addClass("error")); return message; } async function clearData () { // Clear out data textarea. await Caches.inputData.set("", DefaultBase); $("#inputData .status").text(" "); // Clear out every form of ShapeMap. $("#textMap").val("").removeClass("error"); makeFreshEditMap(); $("#fixedMap").empty(); results.clear(); } async function clearAll () { $("#results .status").hide(); await Caches.inputSchema.set("", DefaultBase); $(".inputShape").val(""); $("#inputSchema .status").text(" "); $("#inputSchema li.selected").removeClass("selected"); clearData(); $("#inputData .passes, #inputData .fails").hide(); $("#inputData .passes p:first").text(""); $("#inputData .fails p:first").text(""); $("#inputData .passes ul, #inputData .fails ul").empty(); } async function pickSchema (name, schemaTest, elt, listItems, side) { if ($(elt).hasClass("selected")) { await clearAll(); } else { await Caches.inputSchema.set(schemaTest.text, new URL((schemaTest.url || ""), DefaultBase).href); Caches.inputSchema.url = undefined; // @@ crappyHack1 $("#inputSchema .status").text(name); clearData(); const headings = { "passes": "Passing:", "fails": "Failing:", "indeterminant": "Data:" }; await Promise.all(Object.keys(headings).map(async function (key) { if (key in schemaTest) { $("#inputData ." + key + "").show(); $("#inputData ." + key + " p:first").text(headings[key]); await paintManifest("#inputData ." + key + " ul", schemaTest[key], pickData, listItems, "inputData"); } else { $("#inputData ." + key + " ul").empty(); } })); $("#inputSchema li.selected").removeClass("selected"); $(elt).addClass("selected"); try { await Caches.inputSchema.refresh(); } catch (e) { failMessage(e, "parsing schema"); } } } async function pickData (name, dataTest, elt, listItems, side) { clearData(); if ($(elt).hasClass("selected")) { $(elt).removeClass("selected"); } else { // Update data pane. await Caches.inputData.set(dataTest.text, new URL((dataTest.url || ""), DefaultBase).href); Caches.inputData.url = undefined; // @@ crappyHack1 $("#inputData .status").text(name); $("#inputData li.selected").removeClass("selected"); $(elt).addClass("selected"); try { await Caches.inputData.refresh(); } catch (e) { failMessage(e, "parsing data"); } // Update ShapeMap pane. removeEditMapPair(null); if (dataTest.entry.queryMap !== undefined) { await queryMapLoaded(dataTest.entry.queryMap); } else if (dataTest.entry.queryMapURL !== undefined) { try { const resp = await fetchOK(dataTest.entry.queryMapURL) queryMapLoaded(resp); } catch (e) { renderErrorMessage(e, "queryMap"); } } else { results.append($("<div/>").text("No queryMap or queryMapURL supplied in manifest").addClass("warning")); } async function queryMapLoaded (text) { dataTest.entry.queryMap = text; try { $("#textMap").val(JSON.parse(dataTest.entry.queryMap).map(entry => `<${entry.node}>@<${entry.shape}>`).join(",\n")); } catch (e) { $("#textMap").val(dataTest.entry.queryMap); } await copyTextMapToEditMap(); Caches.outputSchema.set(dataTest.entry.outputSchema, dataTest.outputSchemaUrl); $("#outputSchema .status").text(name); Caches.statics.set(JSON.stringify(dataTest.entry.staticVars, null, " ")); $("#staticVars .status").text(name); $("#outputShape").val(dataTest.entry.outputShape); // targetSchema.start in Map-test $("#createRoot").val(dataTest.entry.createRoot); // createRoot in Map-test // callValidator(); } } } // Control results area content. const results = (function () { const resultsElt = document.querySelector("#results div"); const resultsSel = $("#results div"); return { replace: function (text) { return resultsSel.text(text); }, append: function (text) { return resultsSel.append(text); }, clear: function () { resultsSel.removeClass("passes fails error"); $("#results .status").text("").hide(); $("#shapeMap-tabs").removeAttr("title"); return resultsSel.text(""); }, start: function () { resultsSel.removeClass("passes fails error"); $("#results").addClass("running"); }, finish: function () { $("#results").removeClass("running"); const height = resultsSel.height(); resultsSel.height(1); resultsSel.animate({height:height}, 100); }, text: function () { return $(resultsElt).text(); } }; })(); let LastFailTime = 0; // Validation UI function disableResultsAndValidate (evt) { if (new Date().getTime() - LastFailTime < 100) { results.append( $("<div/>").addClass("warning").append( $("<h2/>").text("see shape map errors above"), $("<button/>").text("validate (ctl-enter)").on("click", disableResultsAndValidate), " again to continue." ) ); return; // return if < 100ms since last error. } results.clear(); results.start(); SharedForTests.promise = new Promise((resolve, reject) => { setTimeout(async function () { const errors = await copyEditMapToTextMap() // will update if #editMap is dirty if (errors.length === 0) resolve(await callValidator()) }, 0); }) } function hasFocusNode () { return $(".focus").map((idx, elt) => { return $(elt).val(); }).get().some(str => { return str.length > 0; }); } let Mapper = null async function callValidator (done) { $("#fixedMap .pair").removeClass("passes fails"); $("#results .status").hide(); let currentAction = "parsing input schema"; try { await Caches.inputSchema.refresh(); // @@ throw away parser stack? $("#schemaDialect").text(Caches.inputSchema.language); if (hasFocusNode()) { currentAction = "parsing input data"; $("#results .status").text("parsing data...").show(); const inputData = await Caches.inputData.refresh(); // need prefixes for ShapeMap // $("#shapeMap-tabs").tabs("option", "active", 2); // select fixedMap currentAction = "parsing shape map"; const fixedMap = fixedShapeMapToTerms($("#fixedMap tr").map((idx, tr) => { return { node: Caches.inputData.meta.lexToTerm($(tr).find("input.focus").val()), shape: Caches.inputSchema.meta.lexToTerm($(tr).find("input.inputShape").val()) }; }).get()); currentAction = "creating validator"; $("#results .status").text("creating validator...").show(); // const dataURL = "data:text/json," + // JSON.stringify( // ShEx.Util.AStoShExJ( // ShEx.Util.canonicalize( // Caches.inputSchema.refresh()))); const alreadLoaded = { schema: await Caches.inputSchema.refresh(), url: Caches.inputSchema.url || DefaultBase }; // shex-node loads IMPORTs and tests the schema for structural faults. try { const loaded = await ShExApi.load([alreadLoaded], [], [], []); let time; const validator = ShEx.Validator.construct( loaded.schema, inputData, { results: "api", regexModule: ShEx[$("#regexpEngine").val()] }); $(".extensionControl:checked").each(function () { $(this).data("code").register(validator, ShEx); }) Mapper = MapModule.register(validator, ShEx); currentAction = "validating"; $("#results .status").text("validating...").show(); time = new Date(); const ret = validator.validate(fixedMap, LOG_PROGRESS ? makeConsoleTracker() : null); time = new Date() - time; $("#shapeMap-tabs").attr("title", "last validation: " + time + " ms") // const dated = Object.assign({ _when: new Date().toISOString() }, ret); $("#results .status").text("rendering results...").show(); await Promise.all(ret.map(renderEntry)); // for debugging values and schema formats: // try { // const x = ShExUtil.valToValues(ret); // // const x = ShExUtil.ShExJtoAS(valuesToSchema(valToValues(ret))); // res = results.replace(JSON.stringify(x, null, " ")); // const y = ShExUtil.valuesToSchema(x); // res = results.append(JSON.stringify(y, null, " ")); // } catch (e) { // console.dir(e); // } finishRendering(); return { validationResults: ret }; // for tester or whoever is awaiting this promise } catch (e) { $("#results .status").text("validation errors:").show(); failMessage(e, currentAction); console.error(e); // dump details to console. return { validationError: e }; } } else { const outputLanguage = Caches.inputSchema.language === "ShExJ" ? "ShExC" : "ShExJ"; $("#results .status"). text("parsed "+Caches.inputSchema.language+" schema, generated "+outputLanguage+" "). append($("<button>(copy to input)</button>"). css("border-radius", ".5em"). on("click", async function () { await Caches.inputSchema.set($("#results div").text(), DefaultBase); })). append(":"). show(); let parsedSchema; if (Caches.inputSchema.language === "ShExJ") { const opts = { simplifyParentheses: false, base: Caches.inputSchema.meta.base, prefixes: Caches.inputSchema.meta.prefixes } new ShEx.Writer(opts).writeSchema(Caches.inputSchema.parsed, (error, text) => { if (error) { $("#results .status").text("unwritable ShExJ schema:\n" + error).show(); // res.addClass("error"); } else { results.append($("<pre/>").text(text).addClass("passes")); } }); } else { const pre = $("<pre/>"); pre.text(JSON.stringify(ShEx.Util.AStoShExJ(ShEx.Util.canonicalize(Caches.inputSchema.parsed)), null, " ")).addClass("passes"); results.append(pre); } results.finish(); return { transformation: { from: Caches.inputSchema.language, to: outputLanguage } } } } catch (e) { failMessage(e, currentAction); console.error(e); // dump details to console. return { inputError: e }; } function makeConsoleTracker () { function padding (depth) { return (new Array(depth + 1)).join(" "); } // AKA " ".repeat(depth) function sm (node, shape) { return `${Caches.inputData.meta.termToLex(node)}@${Caches.inputSchema.meta.termToLex(shape)}`; } const logger = { recurse: x => { console.log(`${padding(logger.depth)}↻ ${sm(x.node, x.shape)}`); return x; }, known: x => { console.log(`${padding(logger.depth)}↵ ${sm(x.node, x.shape)}`); return x; }, enter: (point, label) => { console.log(`${padding(logger.depth)}→ ${sm(point, label)}`); ++logger.depth; }, exit: (point, label, ret) => { --logger.depth; console.log(`${padding(logger.depth)}← ${sm(point, label)}`); }, depth: 0 }; return logger; } } async function renderEntry (entry) { const fails = entry.status === "nonconformant"; // locate FixedMap entry const shapeString = entry.shape === ShEx.Validator.start ? START_SHAPE_INDEX_ENTRY : entry.shape; const fixedMapEntry = $("#fixedMap .pair"+ "[data-node='"+entry.node+"']"+ "[data-shape='"+shapeString+"']"); const klass = (fails ^ fixedMapEntry.find(".shapeMap-joiner").hasClass("nonconformant")) ? "fails" : "passes"; const resultStr = fails ? "✗" : "✓"; let elt = null; if (!fails) { if ($("#success").val() === "query" || $("#success").val() === "remainder") { const proofStore = new RdfJs.Store(); ShEx.Util.getProofGraph(entry.appinfo, proofStore, RdfJs.DataFactory); entry.graph = proofStore.getQuads(); } if ($("#success").val() === "remainder") { const remainder = new RdfJs.Store(); remainder.addQuads((await Caches.inputData.refresh()).getQuads()); entry.graph.forEach(q => remainder.removeQuad(q)); entry.graph = remainder.getQuads(); } } if (entry.graph) { const wr = new RdfJs.Writer(Caches.inputData.meta); wr.addQuads(entry.graph); wr.end((error, results) => { if (error) throw error; entry.turtle = "" + "# node: " + entry.node + "\n" + "# shape: " + entry.shape + "\n" + results.trim(); elt = $("<pre/>").text(entry.turtle).addClass(klass); }); delete entry.graph; } else { let renderMe = entry switch ($("#interface").val()) { case "human": elt = $("<div class='human'/>").append( $("<span/>").text(resultStr), $("<span/>").text( `${Caches.inputData.meta.termToLex(entry.node)}@${fails ? "!" : ""}${Caches.inputSchema.meta.termToLex(entry.shape)}` )).addClass(klass); if (fails) elt.append($("<pre>").text(ShEx.Util.errsToSimple(entry.appinfo).join("\n"))); break; case "minimal": if (fails) entry.reason = ShEx.Util.errsToSimple(entry.appinfo).join("\n"); renderMe = Object.keys(entry).reduce((acc, key) => { if (key !== "appinfo") acc[key] = entry[key]; return acc }, {}); // falling through to default covers the appinfo case default: elt = $("<pre/>").text(JSON.stringify(renderMe, null, " ")).addClass(klass); } } results.append(elt); // update the FixedMap fixedMapEntry.addClass(klass).find("a").text(resultStr); const nodeLex = fixedMapEntry.find("input.focus").val(); const shapeLex = fixedMapEntry.find("input.inputShape").val(); const anchor = encodeURIComponent(nodeLex) + "@" + encodeURIComponent(shapeLex); elt.attr("id", anchor); fixedMapEntry.find("a").attr("href", "#" + anchor); fixedMapEntry.attr("title", entry.elapsed + " ms") if (entry.status === "conformant") { const resultBindings = ShEx.Util.valToExtension(entry.appinfo, MapModule.url); await Caches.bindings.set(JSON.stringify(resultBindings, null, " ")); } else { await Caches.bindings.set("{}"); } } function finishRendering (done) { $("#results .status").text("rendering results...").show(); // Add commas to JSON results. if ($("#interface").val() !== "human") $("#results div *").each((idx, elt) => { if (idx === 0) $(elt).prepend("["); $(elt).append(idx === $("#results div *").length - 1 ? "]" : ","); }); $("#results .status").hide(); // for debugging values and schema formats: // try { // const x = ShEx.Util.valToValues(ret); // // const x = ShEx.Util.ShExJtoAS(valuesToSchema(valToValues(ret))); // res = results.replace(JSON.stringify(x, null, " ")); // const y = ShEx.Util.valuesToSchema(x); // res = results.append(JSON.stringify(y, null, " ")); // } catch (e) { // console.dir(e); // } results.finish(); } function failMessage (e, action, text) { $("#results .status").empty().text("Errors encountered:").show() const div = $("<div/>").addClass("error"); div.append($("<h3/>").text("error " + action + ":\n")); div.append($("<pre/>").text(e.message)); if (text) div.append($("<pre/>").text(text)); results.append(div); LastFailTime = new Date().getTime(); } async function materialize () { SharedForTests.promise = materializeAsync() } async function materializeAsync () { if (Caches.bindings.get().trim().length === 0) { results.replace("You must validate data against a ShExMap schema to populate mappings bindings."). removeClass("passes fails").addClass("error"); return null; } results.start(); const parsing = "output schema"; try { const outputSchemaText = Caches.outputSchema.selection.val(); const outputSchemaIsJSON = outputSchemaText.match(/^\s*\{/); const outputSchema = await Caches.outputSchema.refresh(); // const resultBindings = Object.assign( // await Caches.statics.refresh(), // await Caches.bindings.refresh() // ); function _dup (obj) { return JSON.parse(JSON.stringify(obj)); } const resultBindings = _dup(await Caches.bindings.refresh()); if (Caches.statics.get().trim().length === 0) await Caches.statics.set("{ }"); const _t = await Caches.statics.refresh(); if (_t && Object.keys(_t) > 0) { if (!Array.isArray(resultBindings)) resultBindings = [resultBindings]; resultBindings.unshift(_t); } // const trivialMaterializer = Mapper.trivialMaterializer(outputSchema); const outputShapeMap = fixedShapeMapToTerms([{ node: Caches.inputData.meta.lexToTerm($("#createRoot").val()), shape: Caches.outputSchema.meta.lexToTerm($("#outputShape").val()) // resolve with Caches.outputSchema }]); const binder = Mapper.binder(resultBindings); await Caches.bindings.set(JSON.stringify(resultBindings, null, " ")); // const outputGraph = trivialMaterializer.materialize(binder, lexToTerm($("#createRoot").val()), outputShape); // binder = Mapper.binder(resultBindings); const generatedGraph = new RdfJs.Store(); $("#results div").empty(); $("#results .status").text("materializing data...").show(); outputShapeMap.forEach(pair => { try { const materializer = MapModule.materializer.construct(outputSchema, Mapper, {}); const res = materializer.validate(binder, pair.node, pair.shape); if ("errors" in res) { renderEntry( { node: pair.node, shape: pair.shape, status: "errors" in res ? "nonconformant" : "conformant", appinfo: res, elapsed: -1 }) // $("#results .status").text("validation errors:").show(); // $("#results .status").text("synthesis errors:").show(); // failMessage(e, currentAction); } else { // console.log("g:", ShEx.Util.valToTurtle(res)); generatedGraph.addQuads(ShEx.Util.valToN3js(res, RdfJs.DataFactory)); } } catch (e) { console.dir(e); } }); finishRendering(); $("#results .status").text("materialization results").show(); const writer = new RdfJs.Writer({ prefixes: Caches.outputSchema.parsed._prefixes }); writer.addQuads(generatedGraph.getQuads()); writer.end(function (error, result) { results.append( $("<div/>", {class: "passes"}).append( $("<span/>", {class: "shapeMap"}).append( "# ", $("<span/>", {class: "data"}).text($("#createRoot").val()), $("<span/>", {class: "valStatus"}).text("@"), $("<span/>", {class: "schema"}).text($("#outputShape").val()), ), $("<pre/>").text(result) ) ) // results.append($("<pre/>").text(result)); }); results.finish(); return { materializationResults: generatedGraph }; } catch (e) { results.replace("error parsing " + parsing + ":\n" + e). removeClass("passes fails").addClass("error"); // results.finish(); return null; } } function addEmptyEditMapPair (evt) { addEditMapPairs(null, $(evt.target).parent().parent()); markEditMapDirty(); return false; } function addEditMapPairs (pairs, target) { (pairs || [{node: {type: "empty"}}]).forEach(pair => { const nodeType = (typeof pair.node !== "object" || "@value" in pair.node) ? "node" : pair.node.type; let skip = false; let node, shape; switch (nodeType) { case "empty": node = shape = ""; break; case "node": node = ldToTurtle(pair.node, Caches.inputData.meta.termToLex); shape = startOrLdToTurtle(pair.shape); break; case "TriplePattern": node = renderTP(pair.node); shape = startOrLdToTurtle(pair.shape); break; case "Extension": failMessage(Error("unsupported extension: <" + pair.node.language + ">"), "parsing Query Map", pair.node.lexical); skip = true; // skip this entry. break; default: results.append($("<div/>").append( $("<span/>").text("unrecognized ShapeMap:"), $("<pre/>").text(JSON.stringify(pair)) ).addClass("error")); skip = true; // skip this entry. break; } if (!skip) { const spanElt = $("<tr/>", {class: "pair"}); const focusElt = $("<textarea/>", { rows: '1', type: 'text', class: 'data focus' }).text(node).on("change", markEditMapDirty); const joinerElt = $("<span>", { class: 'shapeMap-joiner' }).append("@").addClass(pair.status); joinerElt.append( $("<input>", {style: "border: none; width: .2em;", readonly: "readonly"}).val(pair.status === "nonconformant" ? "!" : " ").on("click", function (evt) { const status = $(this).parent().hasClass("nonconformant") ? "conformant" : "nonconformant"; $(this).parent().removeClass("conformant nonconformant"); $(this).parent().addClass(status); $(this).val(status === "nonconformant" ? "!" : ""); markEditMapDirty(); evt.preventDefault(); }) ); // if (pair.status === "nonconformant") { // joinerElt.append("!"); // } const shapeElt = $("<input/>", { type: 'text', value: shape, class: 'schema inputShape' }).on("change", markEditMapDirty); const addElt = $("<button/>", { class: "addPair", title: "add a node/shape pair"}).text("+"); const removeElt = $("<button/>", { class: "removePair", title: "remove this node/shape pair"}).text("-"); addElt.on("click", addEmptyEditMapPair); removeElt.on("click", removeEditMapPair); spanElt.append([focusElt, joinerElt, shapeElt, addElt, removeElt].map(elt => { return $("<td/>").append(elt); })); if (target) { target.after(spanElt); } else { $("#editMap").append(spanElt); } } }); if ($("#editMap .removePair").length === 1) $("#editMap .removePair").css("visibility", "hidden"); else $("#editMap .removePair").css("visibility", "visible"); $("#editMap .pair").each(idx => { addContextMenus("#editMap .pair:nth("+idx+") .focus", Caches.inputData); addContextMenus(".pair:nth("+idx+") .inputShape", Caches.inputSchema); }); return false; function renderTP (tp) { const ret = ["subject", "predicate", "object"].map(k => { const ld = tp[k]; if (ld === ShEx.ShapeMap.focus) return "FOCUS"; if (!ld) // ?? ShEx.Uti.any return "_"; return ldToTurtle(ld, Caches.inputData.meta.termToLex); }); return "{" + ret.join(" ") + "}"; } function startOrLdToTurtle (term) { return term === ShEx.Validator.start ? START_SHAPE_LABEL : ldToTurtle(term, Caches.inputSchema.meta.termToLex); } } function removeEditMapPair (evt) { markEditMapDirty(); if (evt) { $(evt.target).parent().parent().remove(); } else { $("#editMap .pair").remove(); } if ($("#editMap .removePair").length === 1) $("#editMap .removePair").css("visibility", "hidden"); return false; } function prepareControls () { $("#menu-button").on("click", toggleControls); $("#interface").on("change", setInterface); $("#success").on("change", setInterface); $("#regexpEngine").on("change", toggleControls); $("#validate").on("click", disableResultsAndValidate); $("#clear").on("click", clearAll); $("#materialize").on("click", materialize); $("#download-results-button").on("click", downloadResults); $("#loadForm").dialog({ autoOpen: false, modal: true, buttons: { "GET": function (evt, ui) { results.clear(); const target = Getables.find(g => g.queryStringParm === $("#loadForm span.whatToLoad").text()); const url = $("#loadInput").val(); const tips = $(".validateTips"); function updateTips (t) { tips .text( t ) .addClass( "ui-state-highlight" ); setTimeout(function() { tips.removeClass( "ui-state-highlight", 1500 ); }, 500 ); } if (url.length < 5) { $("#loadInput").addClass("ui-state-error"); updateTips("URL \"" + url + "\" is way too short."); return; } tips.removeClass("ui-state-highlight").text(); SharedForTests.promise = target.cache.asyncGet(url).catch(function (e) { updateTips(e.message); }); }, "Cancel": function() { $("#loadInput").removeClass("ui-state-error"); $("#loadForm").dialog("close"); toggleControls(); } }, close: function() { $("#loadInput").removeClass("ui-state-error"); $("#loadForm").dialog("close"); toggleControls(); } }); Getables.forEach(target => { const type = target.queryStringParm $("#load-"+type+"-button").click(evt => { const prefillURL = target.url ? target.url : target.cache.meta.base && target.cache.meta.base !== DefaultBase ? target.cache.meta.base : ""; $("#loadInput").val(prefillURL); $("#loadForm").attr("class", type).find("span.whatToLoad").text(type); $("#loadForm").dialog("open"); }); }); $("#about").dialog({ autoOpen: false, modal: true, width: "50%", buttons: { "Dismiss": dismissModal }, close: dismissModal }); $("#about-button").click(evt => { $("#about").dialog("open"); }); $("#shapeMap-tabs").tabs({ activate: async function (event, ui) { if (ui.oldPanel.get(0) === $("#editMap-tab").get(0)) await copyEditMapToTextMap(); else if (ui.oldPanel.get(0) === $("#textMap").get(0)) await copyTextMapToEditMap() } }); $("#textMap").on("change", evt => { results.clear(); SharedForTests.promise = copyTextMapToEditMap(); }); Caches.inputData.selection.on("change", dataInputHandler); // input + paste? // $("#copyEditMapToFixedMap").on("click", copyEditMapToFixedMap); // may add this button to tutorial function dismissModal (evt) { // $.unblockUI(); $("#about").dialog("close"); toggleControls(); return true; } // Prepare file uploads $("input.inputfile").each((idx, elt) => { $(elt).on("change", function (evt) { const reader = new FileReader(); reader.onload = function(evt) { if(evt.target.readyState != 2) return; if(evt.target.error) { alert("Error while reading file"); return; } $($(elt).attr("data-target")).val(evt.target.result); }; reader.readAsText(evt.target.files[0]); }); }); } async function dataInputHandler (evt) { const active = $('#shapeMap-tabs ul li.ui-tabs-active a').attr('href'); if (active === "#editMap-tab") return await copyEditMapToTextMap(); else // if (active === "#textMap") return await copyTextMapToEditMap(); } async function toggleControls (evt) { // don't use `return false` 'cause the browser doesn't wait around for a promise before looking at return false to decide the event is handled if (evt) evt.preventDefault(); const revealing = evt && $("#controls").css("display") !== "flex"; $("#controls").css("display", revealing ? "flex" : "none"); toggleControlsArrow(revealing ? "up" : "down"); if (revealing) { let target = evt.target; while (target.tagName !== "BUTTON") target = target.parentElement; if ($("#menuForm").css("position") === "absolute") { $("#controls"). css("top", 0). css("left", $("#menu-button").css("margin-left")); } else { const bottonBBox = target.getBoundingClientRect(); const controlsBBox = $("#menuForm").get(0).getBoundingClientRect(); const left = bottonBBox.right - bottonBBox.width; // - controlsBBox.width; $("#controls").css("top", bottonBBox.bottom).css("left", left); } $("#permalink a").removeAttr("href"); // can't click until ready const permalink = await getPermalink(); $("#permalink a").attr("href", permalink); } } function toggleControlsArrow (which) { // jQuery can't find() a prefixed attribute (xlink:href); fall back to DOM: if (document.getElementById("menu-button") === null) return; const down = $(document.getElementById("menu-button"). querySelectorAll('use[*|href="#down-arrow"]')); const up = $(document.getElementById("menu-button"). querySelectorAll('use[*|href="#up-arrow"]')); switch (which) { case "down": down.show(); up.hide(); break; case "up": down.hide(); up.show(); break; default: throw Error("toggleControlsArrow expected [up|down], got \"" + which + "\""); } } function setInterface (evt) { toggleControls(); customizeInterface(); } function downloadResults (evt) { const typed = [ { type: "text/plain", name: "results.txt" }, { type: "application/json", name: "results.json" } ][$("#interface").val() === "appinfo" ? 1 : 0]; const blob = new Blob([results.text()], {type: typed.type}); $("#download-results-button") .attr("href", window.URL.createObjectURL(blob)) .attr("download", typed.name); toggleControls(); console.log(results.text()); } /** * * location.search: e.g. "?schema=asdf&data=qwer&shape-map=ab%5Ecd%5E%5E_ef%5Egh" */ const parseQueryString = function(query) { if (query[0]==='?') query=query.substr(1); // optional leading '?' const map = {}; query.replace(/([^&,=]+)=?([^&,]*)(?:[&,]+|$)/g, function(match, key, value) { key=decodeURIComponent(key);value=decodeURIComponent(value); (map[key] = map[key] || []).push(value); }); return map; }; function markEditMapDirty () { $("#editMap").attr("data-dirty", true); } function markEditMapClean () { $("#editMap").attr("data-dirty", false); } /** getShapeMap -- zip a node list and a shape list into a ShapeMap * use {Caches.inputData,Caches.inputSchema}.meta.{prefix,base} to complete IRIs * @return array of encountered errors */ async function copyEditMapToFixedMap () { $("#fixedMap tbody").empty(); // empty out the fixed map. const fixedMapTab = $("#shapeMap-tabs").find('[href="#fixedMap-tab"]'); const restoreText = fixedMapTab.text(); fixedMapTab.text("resolving Fixed Map").addClass("running"); $("#fixedMap .pair").remove(); // clear out existing edit map (make optional?) const nodeShapePromises = $("#editMap .pair").get().reduce((acc, queryPair) => { $(queryPair).find(".error").removeClass("error"); // remove previous error markers const node = $(queryPair).find(".focus").val(); const shape = $(queryPair).find(".inputShape").val(); const status = $(queryPair).find(".shapeMap-joiner").hasClass("nonconformant") ? "nonconformant" : "conformant"; if (!node || !shape) return acc; const smparser = ShEx.ShapeMapParser.construct( Caches.shapeMap.meta.base, Caches.inputSchema.meta, Caches.inputData.meta); const nodes = []; try { const sm = smparser.parse(node + '@' + shape)[0]; const added = typeof sm.node === "string" || "@value" in sm.node ? Promise.resolve({nodes: [node], shape: shape, status: status}) : getQuads(sm.node.subject, sm.node.predicate, sm.node.object) .then(nodes => Promise.resolve({nodes: nodes, shape: shape, status: status})); return acc.concat(added); } catch (e) { // find which cell was broken try { smparser.parse(node + '@' + "START"); } catch (e) { $(queryPair).find(".focus").addClass("error"); } try { smparser.parse("<>" + '@' + shape); } catch (e) { $(queryPair).find(".inputShape").addClass("error"); } failMessage(e, "parsing Edit Map", node + '@' + shape); nodes = Promise.resolve([]); // skip this entry return acc; } }, []); const pairs = await Promise.all(nodeShapePromises) pairs.reduce((acc, pair) => { pair.nodes.forEach(node => { const nodeTerm = Caches.inputData.meta.lexToTerm(node + " "); // for langcode lookahead let shapeTerm = Caches.inputSchema.meta.lexToTerm(pair.shape); if (shapeTerm === ShEx.Validator.start) shapeTerm = START_SHAPE_INDEX_ENTRY; const key = nodeTerm + "|" + shapeTerm; if (key in acc) return; const spanElt = createEntry(node, nodeTerm, pair.shape, shapeTerm, pair.status); acc[key] = spanElt; // just needs the key so far. }); return acc; }, {}) // scroll inputs to right $("#fixedMap input").each((idx, focusElt) => { focusElt.scrollLeft = focusElt.scrollWidth; }); fixedMapTab.text(restoreText).removeClass("running"); return []; // no errors async function getQuads (s, p, o) { const get = s === ShEx.ShapeMap.focus ? "subject" : "object"; return (await Caches.inputData.refresh()).getQuads(mine(s), mine(p), mine(o)).map(t => { return Caches.inputData.meta.termToLex(t[get]);// !!check }); function mine (term) { return term === ShEx.ShapeMap.focus || term === ShEx.ShapeMap.wildcard ? null : term; } } function createEntry (node, nodeTerm, shape, shapeTerm, status) { const spanElt = $("<tr/>", {class: "pair" ,"data-node": nodeTerm ,"data-shape": shapeTerm }); const focusElt = $("<input/>", { type: 'text', value: node, class: 'data focus', disabled: "disabled" }); const joinerElt = $("<span>", { class: 'shapeMap-joiner' }).append("@").addClass(status); if (status === "nonconformant") { joinerElt.addClass("negated"); joinerElt.append("!"); } const shapeElt = $("<input/>", { type: 'text', value: shape, class: 'schema inputShape', disabled: "disabled" }); const removeElt = $("<button/>", { class: "removePair", title: "remove this node/shape pair"}).text("-"); removeElt.on("click", evt => { // Remove related result. let href, result; if ((href = $(evt.target).closest("tr").find("a").attr("href")) && (result = document.getElementById(href.substr(1)))) $(result).remove(); // Remove FixedMap entry. $(evt.target).closest("tr").remove(); }); spanElt.append([focusElt, joinerElt, shapeElt, removeElt, $("<a/>")].map(elt => { return $("<td/>").append(elt); })); $("#fixedMap").append(spanElt); return spanElt; } } function lexifyFirstColumn (row) { // !!not used return Caches.inputData.meta.termToLex(row[0]); // row[0] is the first column. } /** * @return list of errors encountered */ async function copyEditMapToTextMap () { if ($("#editMap").attr("data-dirty") === "true") { const text = $("#editMap .pair").get().reduce((acc, queryPair) => { const node = $(queryPair).find(".focus").val(); const shape = $(queryPair).find(".inputShape").val(); if (!node || !shape) return acc; const status = $(queryPair).find(".shapeMap-joiner").hasClass("nonconformant") ? "!" : ""; return acc.concat([node+"@"+status+shape]); }, []).join(",\n"); $("#textMap").empty().val(text); const ret = await copyEditMapToFixedMap(); markEditMapClean(); return ret; } else { return []; // no errors } } /** * Parse query map to populate #editMap and #fixedMap. * @returns list of errors. ([] means everything was good.) */ async function copyTextMapToEditMap () { $("#textMap").removeClass("error"); const shapeMap = $("#textMap").val(); results.clear(); try { await Caches.inputSchema.refresh(); await Caches.inputData.refresh(); const smparser = ShEx.ShapeMapParser.construct( Caches.shapeMap.meta.base, Caches.inputSchema.meta, Caches.inputData.meta); const sm = smparser.parse(shapeMap); removeEditMapPair(null); addEditMapPairs(sm.length ? sm : null); const ret = await copyEditMapToFixedMap(); markEditMapClean(); results.clear(); return ret; } catch (e) { $("#textMap").addClass("error"); failMessage(e, "parsing Query Map"); makeFreshEditMap() return [e]; } } function makeFreshEditMap () { removeEditMapPair(null); addEditMapPairs(null, null); markEditMapClean(); return []; } /** fixedShapeMapToTerms -- map ShapeMap to API terms * @@TODO: add to ShExValidator so API accepts ShapeMap */ function fixedShapeMapToTerms (shapeMap) { return shapeMap; /*.map(pair => { return {node: Caches.inputData.meta.lexToTerm(pair.node + " "), shape: Caches.inputSchema.meta.lexToTerm(pair.shape)}; });*/ } /** * Load URL search parameters */ async function loadSearchParameters () { // don't overwrite if we arrived here from going back and forth in history if (Caches.inputSchema.selection.val() !== "" || Caches.inputData.selection.val() !== "") return Promise.resolve(); const iface = parseQueryString(location.search); toggleControlsArrow("down"); $(".manifest li").text("no manifest schemas loaded"); if ("examples" in iface) { // deprecated ?examples= interface iface.manifestURL = iface.examples; delete iface.examples; } if (!("manifest" in iface) && !("manifestURL" in iface)) { iface.manifestURL = ["../examples/manifest.json"]; } if ("output-map" in iface) parseShapeMap("output-map", function (node, shape) { // only works for one n/s pair $("#createNode").val(node); $("#outputShape").val(shape); }); // Load all known query parameters. Save load results into array like: /* [ [ "data", { "skipped": "skipped" } ], [ "manifest", { "fromUrl": { "url": "http://...", "data": "..." } } ], ] */ const loadedAsArray = await Promise.all(QueryParams.map(async input => { const label = input.queryStringParm; const parm = label; if (parm + "URL" in iface) { const url = iface[parm + "URL"][0]; if (url.length > 0) { // manifest= loads no manifest // !!! set anyways in asyncGet? input.cache.url = url; // all fooURL query parms are caches. try { const got = await input.cache.asyncGet(url) return [label, {fromUrl: got}] } catch(e) { if ("fail" in input) { input.fail(e); } else { input.location.val(e.message); } results.append($("<pre/>").text(e).addClass("error")); return [label, { loadFailure: e instanceof Error ? e : Error(e) }]; }; } } else if (parm in iface) { const prepend = input.location.prop("tagName") === "TEXTAREA" ? input.location.val() : ""; const value = prepend + iface[parm].join(""); const origValue = input.location.val(); try { if ("cache" in input) { await input.cache.set(value, location.href); } else { input.location.val(prepend + value); if (input.location.val() === null) throw Error(`Unable to set value to ${prepend + value}`) } return [label, { literal: value }] } catch (e) { input.location.val(origValue); if ("fail" in input) { input.fail(e); } results.append($("<pre/>").text( "error setting " + label + ":\n" + e + "\n" + value ).addClass("error")); return [label, { failure: e }] } } else if ("deflt" in input) { input.location.val(input.deflt); return [label, { deflt: "deflt" }]; // flag that it was a default } return [label, { skipped: "skipped" }] })) // convert loaded array into Object: /* { "data": { "skipped": "skipped" }, "manifest": { "fromUrl": { "url": "http://...", "data": "..." } }, } */ const loaded = loadedAsArray.reduce((acc, fromArray) => { acc[fromArray[0]] = fromArray[1] return acc }, {}) // Parse the shape-map using the prefixes and base. const shapeMapErrors = $("#textMap").val().trim().length > 0 ? copyTextMapToEditMap() : makeFreshEditMap(); customizeInterface(); $("body").keydown(async function (e) { // keydown because we need to preventDefault const code = e.keyCode || e.charCode; // standards anyone? if (e.ctrlKey && (code === 10 || code === 13)) { // ctrl-enter // const at = $(":focus"); const smErrors = await dataInputHandler(); if (smErrors.length === 0) $("#validate")/*.focus()*/.click(); // at.focus(); return false; // same as e.preventDefault(); } else if (e.ctrlKey && e.key === "\\") { $("#materialize").click(); return false; // same as e.preventDefault(); } else if (e.ctrlKey && e.key === "[") { bindingsToTable() return false; // same as e.preventDefault(); } else if (e.ctrlKey && e.key === "]") { tableToBindings() return false; // same as e.preventDefault(); } else { return true; } }); addContextMenus("#focus0", Caches.inputData); addContextMenus("#inputShape0", Caches.inputSchema); addContextMenus("#outputShape", Caches.outputSchema); if ("schemaURL" in iface || // some schema is non-empty ("schema" in iface && iface.schema.reduce((r, elt) => { return r+elt.length; }, 0)) && shapeMapErrors.length === 0) { return callValidator(); } return loaded; } function setTextAreaHandlers (listItems) { const textAreaCaches = ["inputSchema", "inputData", "shapeMap"] const timeouts = Object.keys(Caches).reduce((acc, k) => { acc[k] = undefined; return acc; }, {}); Object.keys(Caches).forEach(function (cache) { Caches[cache].selection.keyup(function (e) { // keyup to capture backspace const code = e.keyCode || e.charCode; // if (!(e.ctrlKey)) { // results.clear(); // } if (!(e.ctrlKey && (code === 10 || code === 13))) { later(e.target, cache, Caches[cache]); } }); }); function later (target, side, cache) { cache.dirty(true); if (timeouts[side]) clearTimeout(timeouts[side]); timeouts[side] = setTimeout(() => { timeouts[side] = undefined; const curSum = sum($(target).val()); if (curSum in listItems[side]) listItems[side][curSum].addClass("selected"); else $("#"+side+" .selected").removeClass("selected"); delete cache.url; }, INPUTAREA_TIMEOUT); } } /** * update location with a current values of some inputs */ async function getPermalink () { let parms = []; await copyEditMapToTextMap(); parms = parms.concat(QueryParams.reduce((acc, input) => { let parm = input.queryStringParm; let val = input.location.val(); if (input.cache && input.cache.url && // Specifically avoid loading from DefaultBase?schema=blah // because that will load the HTML page. !input.cache.url.startsWith(DefaultBase)) { parm += "URL"; val = input.cache.url; } return val.length > 0 ? acc.concat(parm + "=" + encodeURIComponent(val)) : acc; }, [])); const s = parms.join("&"); return location.origin + location.pathname + "?" + s; } function customizeInterface () { if ($("#interface").val() === "minimal") { $("#inputSchema .status").html("schema (<span id=\"schemaDialect\">ShEx</span>)").show(); $("#inputData .status").html("data (<span id=\"dataDialect\">Turtle</span>)").show(); $("#actions").parent().children().not("#actions").hide(); $("#title img, #title h1").hide(); $("#menuForm").css("position", "absolute").css( "left", $("#inputSchema .status").get(0).getBoundingClientRect().width - $("#menuForm").get(0).getBoundingClientRect().width ); $("#controls").css("position", "relative"); } else { $("#inputSchema .status").html("schema (<span id=\"schemaDialect\">ShEx</span>)").hide(); $("#inputData .status").html("data (<span id=\"dataDialect\">Turtle</span>)").hide(); $("#actions").parent().children().not("#actions").show(); $("#title img, #title h1").show(); $("#menuForm").removeAttr("style"); $("#controls").css("position", "absolute"); } } /** * Prepare drag and drop into text areas */ async function prepareDragAndDrop () { QueryParams.filter(q => { return "cache" in q; }).map(q => { return { location: q.location, targets: [{ ext: "", // Will match any file media: "", // or media type. target: q.cache }] }; }).concat([ {location: $("body"), targets: [ {media: "application/json", target: Caches.manifest}, {ext: ".shex", media: "text/shex", target: Caches.inputSchema}, {ext: ".ttl", media: "text/turtle", target: Caches.inputData}, {ext: ".json", media: "application/json", target: Caches.manifest}, {ext: ".smap", media: "text/plain", target: Caches.shapeMap}]} ]).forEach(desc => { const droparea = desc.location; // kudos to http://html5demos.com/dnd-upload desc.location. on("drag dragstart dragend dragover dragenter dragleave drop", function (e) { e.preventDefault(); e.stopPropagation(); }). on("dragover dragenter", (evt) => { desc.location.addClass("hover"); }). on("dragend dragleave drop", (evt) => { desc.location.removeClass("hover"); }). on("drop", (evt) => { evt.preventDefault(); droparea.removeClass("droppable"); $("#results .status").removeClass("error"); results.clear(); let xfer = evt.originalEvent.dataTransfer; const prefTypes = [ {type: "files"}, {type: "application/json"}, {type: "text/uri-list"}, {type: "text/plain"} ]; const promises = []; if (prefTypes.find(l => { if (l.type.indexOf("/") === -1) { if (l.type in xfer && xfer[l.type].length > 0) { $("#results .status").text("handling "+xfer[l.type].length+" files...").show(); promises.push(readfiles(xfer[l.type], desc.targets)); return true; } } else { if (xfer.getData(l.type)) { const val = xfer.getData(l.type); $("#results .status").text("handling "+l.type+"...").show(); if (l.type === "application/json") { if (desc.location.get(0) === $("body").get(0)) { let parsed = JSON.parse(val); if (!(Array.isArray(parsed))) { parsed = [parsed]; } parsed.map(elt => { const action = "action" in elt ? elt.action: elt; action.schemaURL = action.schema; delete action.schema; action.dataURL = action.data; delete action.data; }); promises.push(Caches.manifest.set(parsed, DefaultBase, "drag and drop")); } else { promises.push(inject(desc.targets, DefaultBase, val, l.type)); } } else if (l.type === "text/uri-list") { $.ajax({ accepts: { mycustomtype: 'text/shex,text/turtle,*/*' }, url: val, dataType: "text" }).fail(function (jqXHR, textStatus) { const error = jqXHR.statusText === "OK" ? textStatus : jqXHR.statusText; results.append($("<pre/>").text("GET <" + val + "> failed: " + error)); }).done(function (data, status, jqXhr) { try { promises.push(inject(desc.targets, val, data, (jqXhr.getResponseHeader("Content-Type") || "unknown-media-type").split(/[ ;,]/)[0])); $("#loadForm").dialog("close"); toggleControls(); } catch (e) { results.append($("<pre/>").text("unable to evaluate <" + val + ">: " + (e.stack || e))); } }); } else if (l.type === "text/plain") { promises.push(inject(desc.targets, DefaultBase, val, l.type)); } $("#results .status").text("").hide(); // desc.targets.text(xfer.getData(l.type)); return true; async function inject (targets, url, data, mediaType) { const target = targets.length === 1 ? targets[0].target : targets.reduce((ret, elt) => { return ret ? ret : mediaType === elt.media ? elt.target : null; }, null); if (target) { const appendTo = $("#append").is(":checked") ? target.get() : ""; await target.set(appendTo + data, url, 'drag and drop', mediaType); } else { results.append("don't know what to do with " + mediaType + "\n"); } } } } return false; }) === undefined) results.append($("<pre/>").text( "drag and drop not recognized:\n" + JSON.stringify({ dropEffect: xfer.dropEffect, effectAllowed: xfer.effectAllowed, files: xfer.files.length, items: [].slice.call(xfer.items).map(i => { return {kind: i.kind, type: i.type}; }) }, null, 2) )); SharedForTests.promise = Promise.all(promises); }); }); /*async*/ function readfiles(files, targets) { // returns promise but doesn't use await const formData = new FormData(); let successes = 0; const promises = []; for (let i = 0; i < files.length; i++) { const file = files[i], name = file.name; const target = targets.reduce((ret, elt) => { return ret ? ret : name.endsWith(elt.ext) ? elt.target : null; }, null); if (target) { promises.push(new Promise((resolve, reject) => { formData.append("file", file); const reader = new FileReader(); reader.onload = (function (target) { return async function (event) { const appendTo = $("#append").is(":checked") ? target.get() : ""; await target.set(appendTo + event.target.result, DefaultBase); ++successes; resolve() }; })(target); reader.readAsText(file); })) } else { results.append("don't know what to do with " + name + "\n"); } } return Promise.all(promises).then(() => { $("#results .status").text("loaded "+successes+" files.").show(); }) } } async function prepareManifest (demoList, base) { const listItems = Object.keys(Caches).reduce((acc, k) => { acc[k] = {}; return acc; }, {}); const nesting = demoList.reduce(function (acc, elt) { const key = elt.schemaLabel + "|" + elt.schema; if (!(key in acc)) { // first entry with this schema acc[key] = { label: elt.schemaLabel, text: elt.schema, url: elt.schemaURL || (elt.schema ? base : undefined) }; } else { // nth entry with this schema } if ("dataLabel" in elt) { const dataEntry = { label: elt.dataLabel, text: elt.data, url: elt.dataURL || (elt.data ? base : undefined), outputSchemaUrl: elt.outputSchemaURL || (elt.outputSchema ? base : undefined), entry: elt }; const target = elt.status === "nonconformant" ? "fails" : elt.status === "conformant" ? "passes" : "indeterminant"; if (!(target in acc[key])) { // first entry with this data acc[key][target] = [dataEntry]; } else { // n'th entry with this data acc[key][target].push(dataEntry); } } else { // this is a schema-only example } return acc; }, {}); const nestingAsList = Object.keys(nesting).map(e => nesting[e]); await paintManifest("#inputSchema .manifest ul", nestingAsList, pickSchema, listItems, "inputSchema"); } function addContextMenus (inputSelector, cache) { // !!! terribly stateful; only one context menu at a time! const DATA_HANDLE = 'runCallbackThingie' let terms = null, nodeLex = null, target, scrollLeft, m, addSpace = ""; $(inputSelector).on('contextmenu', rightClickHandler) $.contextMenu({ trigger: 'none', selector: inputSelector, build: function($trigger, e) { // return callback set by the mouseup handler return $trigger.data(DATA_HANDLE)(); } }); async function buildMenuItemsPromise (elt, evt) { if (elt.hasClass("data")) { nodeLex = elt.val(); const shapeLex = elt.parent().parent().find(".schema").val() // Would like to use SMParser but that means users can't fix bad SMs. /* const sm = smparser.parse(nodeLex + '@START')[0]; const m = typeof sm.node === "string" || "@value" in sm.node ? null : tpToM(sm.node); */ m = nodeLex.match(RegExp("^"+ParseTriplePattern+"$")); if (m) { target = evt.target; const selStart = target.selectionStart; scrollLeft = target.scrollLeft; terms = [0, 1, 2].reduce((acc, ord) => { if (m[(ord+1)*2-1] !== undefined) { const at = acc.start + m[(ord+1)*2-1].length; const len = m[(ord+1)*2] ? m[(ord+1)*2].length : 0; return { start: at + len, tz: acc.tz.concat([[at, len]]), match: acc.match === null && at + len >= selStart ? ord : acc.match }; } else { return acc; } }, {start: 0, tz: [], match: null }); function norm (tz) { return tz.map(t => { return t.startsWith('!') ? "- " + t.substr(1) + " -" : Caches.inputData.meta.termToLex(t); // !!check }); } const queryMapKeywords = ["FOCUS", "_"]; const getTermsFunctions = [ () => { return queryMapKeywords.concat(norm(store.getSubjects())); }, () => { return norm(store.getPredicates()); }, () => { return queryMapKeywords.concat(norm(store.getObjects())); }, ]; const store = await Caches.inputData.refresh(); if (terms.match === null) return false; // prevent contextMenu from whining about an empty list return listToCTHash(getTermsFunctions[terms.match]()) } } terms = nodeLex = null; try { return listToCTHash(await cache.getItems()) } catch (e) { failMessage(e, cache === Caches.inputSchema ? "parsing schema" : "parsing data"); let items = {}; const failContent = "no choices found"; items[failContent] = failContent; return items } // hack to emulate regex parsing product /* function tpToM (tp) { return [nodeLex, '{', lex(tp.subject), " ", lex(tp.predicate), " ", lex(tp.object), "", "}", ""]; function lex (node) { return node === ShEx.ShapeMap.focus ? "FOCUS" : node === null ? "_" : Caches.inputData.meta.termToLex(node); } } */ } function rightClickHandler (e) { e.preventDefault(); const $this = $(this); $this.off('contextmenu', rightClickHandler); // when the items are ready, const p = buildMenuItemsPromise($this, e) p.then(items => { // store a callback on the trigger $this.data(DATA_HANDLE, function () { return { callback: menuCallback, items: items }; }); const _offset = $this.offset(); $this.contextMenu({ x: _offset.left + 10, y: _offset.top + 10 }) $this.on('contextmenu', rightClickHandler) }); } function menuCallback (key, options) { markEditMapDirty(); if (options.items[key].ignore) { // ignore the event } else if (terms) { const term = terms.tz[terms.match]; let val = nodeLex.substr(0, term[0]) + key + addSpace + nodeLex.substr(term[0] + term[1]); if (terms.match === 2 && !m[9]) val = val + "}"; else if (term[0] + term[1] === nodeLex.length) val = val + " "; $(options.selector).val(val); // target.scrollLeft = scrollLeft + val.length - nodeLex.length; target.scrollLeft = target.scrollWidth; } else { $(options.selector).val(key); } } function listToCTHash (items) { return items.reduce((acc, item) => { acc[item] = { name: item } return acc }, {}) } } function bindingsToTable () { let d = JSON.parse($("#bindings1 textarea").val()) let div = $("<div/>").css("overflow", "auto").css("border", "thin solid red") div.css("width", $("#bindings1 textarea").width()+10) div.css("height", $("#bindings1 textarea").height()+12) $("#bindings1 textarea").hide() let thead = $("<thead/>") let tbody = $("<tbody/>") let table = $("<table>").append(thead, tbody) $("#bindings1").append(div.append(table)) let vars = []; function varsIn (a) { return a.forEach(elt => { if (Array.isArray(elt)) { varsIn(elt) } else { let tr = $("<tr/>") let cols = [] Object.keys(elt).forEach(k => { if (vars.indexOf(k) === -1) vars.push(k) let i = vars.indexOf(k) cols[i] = elt[k] }) // tr.append(cols.map(c => $("<td/>").text(c))) for (let colI = 0; colI < cols.length; ++colI) tr.append($("<td/>").text(cols[colI] ? Caches.inputData.meta.termToLex(n3ify(cols[colI])) : "").css("background-color", "#f7f7f7")) tbody.append(tr) } }) } varsIn(Array.isArray(d) ? d : [d]) vars.forEach(v => { thead.append($("<th/>").css("font-size", "small").text(v.substr(v.lastIndexOf("#")+1, 999))) }) } function tableToBindings () { $("#bindings1 div").remove() $("#bindings1 textarea").show() } prepareControls(); const dndPromise = prepareDragAndDrop(); // async 'cause it calls Cache.X.set("") const loads = loadSearchParameters(); const ready = Promise.all([ dndPromise, loads ]); if ('_testCallback' in window) { SharedForTests.promise = ready.then(ab => ({drop: ab[0], loads: ab[1]})); window._testCallback(SharedForTests); } ready.then(resolves => { if (!('_testCallback' in window)) console.log('search parameters:', resolves[1]); // Update UI to say we're done loading everything? }, e => { // Drop catch on the floor presuming thrower updated the UI. }); function n3ify (ldterm) { if (typeof ldterm !== "object") return ldterm; const ret = "\"" + ldterm.value + "\""; if ("language" in ldterm) return ret + "@" + ldterm.language; if ("type" in ldterm) return ret + "^^" + ldterm.type; return ret; }
shexSpec/shex.js
packages/extension-map/doc/shexmap-simple.js
JavaScript
mit
82,436
var Branch = function (origin, baseRadius, baseSegment, maxSegments, depth, tree) { this.gid = Math.round(Math.random() * maxSegments); this.topPoint = origin; this.radius = baseRadius; this.maxSegments = maxSegments; this.lenghtSubbranch = tree.genes.pSubBranch !== 0 ? Math.floor(maxSegments * tree.genes.pSubBranch) : 0; this.segmentLenght = baseSegment; this.depth = depth; //current position of the branch in chain this.tree = tree; this.segments = 0; //always start in 0 //Directions are represented as a Vector3 where dirx*i+diry*j+dirz*k and //each dir is the magnitude that can go from 0 to 1 and multiplies the max segment lenght //Starting direction is UP this.direction = { x: 0, y: 1, z: 0 }; this.material = new THREE.MeshLambertMaterial({ color: Math.floor(Math.random()*16777215),//tree.genes.color, side: 2, shading: THREE.FlatShading }); }; /** * Conceptually grows and renders the branch * @param {THREE.Scene} scene The scene to which the branch belongs */ Branch.prototype.grow = function (scene) { var thisBranch = this; //calculate new direction, our drawing space is a 200x200x200 cube var newX = newPos('x'); var newY = newPos('y'); var newZ = newPos('z'); if (newY < 0 || newY > 300 ){ // newZ < -100 || newZ > 100 || // newX < -100 || newX > 100) { randomizeDir(); return true; } else { //direction is ok and branch is going to grow thisBranch.segments += 1; } var destination = new THREE.Vector3(newX, newY, newZ); var lcurve = new THREE.LineCurve3(this.topPoint, destination); var geometry = new THREE.TubeGeometry( lcurve, //path thisBranch.tree.genes.segmentLenght, //segments thisBranch.radius, //radius 8, //radiusSegments true //opened, muuuch more efficient but not so nice ); // modify next segment's radius thisBranch.radius = thisBranch.radius * thisBranch.tree.genes.radiusDimP; var tube = new THREE.Mesh(geometry, this.material); scene.add(tube); this.topPoint = destination; randomizeDir(); //Helper functions. function randomizeDir() { //we want our dir to be from -1 to thisBranch.direction.x = (thisBranch.tree.mtwister.random() * 2) - 1; thisBranch.direction.y = (thisBranch.tree.mtwister.random() * 2) - 1; thisBranch.direction.z = (thisBranch.tree.mtwister.random() * 2) - 1; } function newPos(dimension) { return thisBranch.topPoint[dimension] + (thisBranch.direction[dimension] * thisBranch.segmentLenght); } //calculate segment lenght for new segment thisBranch.segmentLenght = thisBranch.segmentLenght * thisBranch.tree.genes.segmentLenghtDim; if (thisBranch.lenghtSubbranch !== 0 && thisBranch.segments % thisBranch.lenghtSubbranch === 0) { thisBranch.tree.spawnBranch(thisBranch.topPoint, thisBranch.radius, thisBranch.segmentLenght, this.maxSegments, this.depth); } //check if we can kill branch if (thisBranch.radius <= thisBranch.tree.genes.minRadius) { return false; //kill branch } //Kill if we have reached the max number of segments if (thisBranch.segments > thisBranch.maxSegments) { return false; } else { return true; } };
tupini07/Brownian-Shrubs
js/Branch.js
JavaScript
mit
3,324
/// <reference path="../../config/config.ts" /> /// <reference path="../interfaces/directives/IDirective.ts" /> declare var angular:any; //Directive responsible for manipulating left (top) menu icons area when available size change module Directives { 'use strict'; export class LeftMenuAutosize implements Directives.IDirective { private static Timeout:any; private static Window:any; private Scope:any; private Element:any; private Promise:any; private WindowDimensions:any; private MenuDimensions:any; //@ngInject public static DirectiveOptions($timeout:any, $window:any):any { LeftMenuAutosize.Timeout = $timeout; LeftMenuAutosize.Window = $window; return { restrict: 'A', scope: { expandIconSize: '=', iconSize: '=', iconCount: '=' }, replace: false, link: function ($scope:any, $linkElement:any, $linkAttributes:any):void { var instance:Directives.IDirective = new LeftMenuAutosize(); instance.Link($scope, $linkElement, $linkAttributes); } }; } public Link($scope:any, $linkElement:any, $linkAttributes:any):void { this.Scope = $scope; this.Element = $linkElement; this.SizeChanged(); $scope.$watch('iconCount', this.SizeChanged.bind(this)); angular.element(LeftMenuAutosize.Window).on('resize', this.SizeChanged.bind(this)); this.BindExpandButton(); } private SizeChanged():void { LeftMenuAutosize.Timeout.cancel(this.Promise); this.Promise = LeftMenuAutosize.Timeout(this.SetIconsVisibility.bind(this), 0, false); } private MeasureDimensions():void { this.WindowDimensions = { width: LeftMenuAutosize.Window.innerWidth, height: LeftMenuAutosize.Window.innerHeight }; this.MenuDimensions = { width: this.Element[0].offsetWidth, height: this.Element[0].offsetHeight }; this.MenuDimensions.primaryDimensionSize = Math.max(this.MenuDimensions.width, this.MenuDimensions.height); this.MenuDimensions.primaryDimension = this.MenuDimensions.height > this.MenuDimensions.width ? 'height' : 'width'; this.MenuDimensions.secondaryDimension = this.MenuDimensions.primaryDimension === 'height' ? 'width' : 'height'; } private SetIconsVisibility():void { //Collapse menu if (this.Element.hasClass('expanded')) { this.ExpandCollapseMenu(null, true); } //Assume that everything can fit this.Element.removeClass('collapsed'); var elementChildren:any[] = this.Element.children(); angular.forEach(elementChildren, function (item:any, key:number):void { angular.element(item).removeClass('collapsed'); }); //Measure space this.MeasureDimensions(); var availableSpace:number = this.MenuDimensions.primaryDimensionSize; var everythingCanFit:boolean = (this.Scope.iconCount || 0) * this.Scope.iconSize <= availableSpace; if (!everythingCanFit) { //Enable collapse-expand of panel this.Element.addClass('collapsed'); //Hide records that cannot fit var canFitNumber:number = Math.floor((availableSpace - this.Scope.expandIconSize) / this.Scope.iconSize); angular.forEach(elementChildren, function (item:any, key:number):void { if (item.className !== 'menuEntityExpand' && key >= canFitNumber) { angular.element(item).addClass('collapsed'); } }); } } private BindExpandButton():void { var toggle:any = this.Element[0].querySelector('.menuEntityExpand'); toggle.onclick = this.ExpandCollapseMenu.bind(this); toggle.onblur = this.ExpandCollapseMenu.bind(this); } private ExpandCollapseMenu(event:any, collapse:boolean):void { var _this:LeftMenuAutosize = this; var isExpanded:boolean = this.Element.hasClass('expanded'); var shouldCollapse:boolean = collapse !== null ? collapse : isExpanded; if (event.type === 'blur') { shouldCollapse = true; } //Toggle if (shouldCollapse) { //Collapse setTimeout(function ():void { _this.Element.addClass('collapsed'); _this.Element.removeClass('expanded'); _this.Element.css(_this.MenuDimensions.primaryDimension, ''); _this.Element.css(_this.MenuDimensions.secondaryDimension, ''); _this.Element.css('max-' + _this.MenuDimensions.secondaryDimension, ''); }, 200); } else { //Calculate required size var totalCount:number = this.Scope.iconCount + 1; var primaryDimensionFitCount:number = Math.floor((this.MenuDimensions.primaryDimensionSize - this.Scope.expandIconSize) / this.Scope.iconSize); var requiredSecondaryDimensionFitCount:number = Math.ceil(totalCount / primaryDimensionFitCount); var requiredSecondaryDimensionSize:number = Math.min(requiredSecondaryDimensionFitCount * this.Scope.iconSize, this.WindowDimensions[this.MenuDimensions.secondaryDimension] - this.Scope.iconSize); var secondaryDimensionRealFitCount:number = Math.floor(requiredSecondaryDimensionSize / this.Scope.iconSize); var primaryDimensionReconciledFitCount:number = Math.ceil(totalCount / secondaryDimensionRealFitCount); var primaryDimensionReconciledSize:number = Math.min(primaryDimensionReconciledFitCount * this.Scope.iconSize, this.WindowDimensions[this.MenuDimensions.primaryDimension] - this.Scope.iconSize); //Expand this.Element.removeClass('collapsed'); this.Element.addClass('expanded'); this.Element.css(this.MenuDimensions.primaryDimension, primaryDimensionReconciledSize + 'px'); this.Element.css(this.MenuDimensions.secondaryDimension, requiredSecondaryDimensionSize + 'px'); this.Element.css('max-' + this.MenuDimensions.secondaryDimension, requiredSecondaryDimensionSize + 'px'); } } } }
tsimeunovic/BerryForms
client/angular/directives/leftMenuAutosize.ts
TypeScript
mit
6,839
package org.craft.client.render.blocks; import java.util.*; import java.util.Map.Entry; import com.google.common.collect.*; import org.craft.blocks.*; import org.craft.blocks.states.*; import org.craft.client.*; import org.craft.client.models.*; import org.craft.client.render.*; import org.craft.client.render.texture.TextureIcon; import org.craft.client.render.texture.TextureMap; import org.craft.maths.*; import org.craft.utils.*; import org.craft.world.*; public class BlockModelRenderer extends AbstractBlockRenderer { private HashMap<BlockVariant, HashMap<String, TextureIcon>> icons; private List<BlockVariant> blockVariants; private static Quaternion rotationQuaternion; /** * Creates a new renderer for given block variants */ public BlockModelRenderer(List<BlockVariant> list) { this.blockVariants = list; icons = Maps.newHashMap(); for(BlockVariant v : list) icons.put(v, new HashMap<String, TextureIcon>()); if(rotationQuaternion == null) rotationQuaternion = new Quaternion(); } @Override public void render(RenderEngine engine, OffsettedOpenGLBuffer buffer, World w, Block b, int x, int y, int z) { if(!b.shouldRender()) return; Chunk chunk = null; if(w != null) chunk = w.getChunk(x, y, z); BlockVariant variant = null; float lightValue = 1f; if(chunk == null) variant = blockVariants.get(0); else { variant = getVariant(w, b, x, y, z); lightValue = chunk.getLightValue(w, x, y, z); } if(variant == null) variant = blockVariants.get(0); Model blockModel = variant.getModels().get(w == null ? 0 : w.getRNG().nextInt(variant.getModels().size())); // TODO: random model ? for(int i = 0; i < blockModel.getElementsCount(); i++ ) { ModelElement element = blockModel.getElement(i); if(element.hasRotation()) { Vector3 axis = Vector3.xAxis; if(element.getRotationAxis() == null) ; else if(element.getRotationAxis().equalsIgnoreCase("y")) axis = Vector3.yAxis; else if(element.getRotationAxis().equalsIgnoreCase("z")) axis = Vector3.zAxis; rotationQuaternion.init(axis, (float) Math.toRadians(element.getRotationAngle())); } Set<Entry<String, ModelFace>> entries = element.getFaces().entrySet(); Vector3 startPos = element.getFrom(); Vector3 size = element.getTo().sub(startPos); for(Entry<String, ModelFace> entry : entries) { Vector3 faceStart = Vector3.NULL; Vector3 faceSize = Vector3.NULL; TextureIcon icon = getTexture(blockModel, variant, entry.getValue().getTexture()); boolean flip = false; EnumSide cullface = EnumSide.fromString(entry.getValue().getCullface()); EnumSide side = EnumSide.fromString(entry.getKey()); if(side != null) { if(entry.getValue().hideIfSameAdjacent() && w.getBlockNextTo(x, y, z, side) == b) { continue; } } if(cullface != EnumSide.UNDEFINED) { Block next = Blocks.air; if(w != null) next = w.getBlockNextTo(x, y, z, cullface); if(next.isSideOpaque(w, x, y, z, cullface.opposite())) { continue; } } if(entry.getKey().equals("up")) { faceStart = Vector3.get(startPos.getX(), startPos.getY() + size.getY(), startPos.getZ()); faceSize = Vector3.get(size.getX(), 0, size.getZ()); flip = true; } else if(entry.getKey().equals("down")) { faceStart = Vector3.get(startPos.getX(), startPos.getY(), startPos.getZ()); faceSize = Vector3.get(size.getX(), 0, size.getZ()); flip = true; } else if(entry.getKey().equals("west")) { faceStart = Vector3.get(startPos.getX(), startPos.getY(), startPos.getZ()); faceSize = Vector3.get(0, size.getY(), size.getZ()); } else if(entry.getKey().equals("east")) { faceStart = Vector3.get(startPos.getX() + size.getX(), startPos.getY(), startPos.getZ()); faceSize = Vector3.get(0, size.getY(), size.getZ()); } else if(entry.getKey().equals("north")) { faceStart = Vector3.get(startPos.getX(), startPos.getY(), startPos.getZ()); faceSize = Vector3.get(size.getX(), size.getY(), 0); } else if(entry.getKey().equals("south")) { faceStart = Vector3.get(startPos.getX(), startPos.getY(), startPos.getZ() + size.getZ()); faceSize = Vector3.get(size.getX(), size.getY(), 0); } else { continue; } renderFace(lightValue, buffer, x, y, z, icon, faceStart, faceSize, flip, entry.getValue().getMinUV(), entry.getValue().getMaxUV(), element.getRotationOrigin(), rotationQuaternion, element.shouldRescale()); faceSize.dispose(); faceStart.dispose(); } size.dispose(); } } /** * Returns most revelant variant depending on block states values at (x,y,z) */ private BlockVariant getVariant(World w, Block b, int x, int y, int z) { BlockVariant variant = null; variantLoop: for(BlockVariant v : blockVariants) { if(v.getBlockStates() == null && variant == null) { variant = v; } else if(v.getBlockStates().isEmpty() && variant == null) { variant = v; } else { for(int i = 0; i < v.getBlockStates().size(); i++ ) { BlockState state = v.getBlockStates().get(i); IBlockStateValue value = v.getBlockStateValues().get(i); if(w.getBlockState(x, y, z, state) != value) { continue variantLoop; } } if(variant != null) { if(variant.getBlockStates().size() <= v.getBlockStates().size()) { variant = v; } else if(variant.getBlockStates().size() > v.getBlockStates().size()) continue variantLoop; } else { variant = v; } } } return variant; } /** * Gets TextureIcon from texture variable found in json model file */ private TextureIcon getTexture(Model blockModel, BlockVariant variant, String texture) { if(texture == null) return null; if(!icons.get(variant).containsKey(texture)) { if(texture.startsWith("#")) { TextureIcon icon = getTexture(blockModel, variant, blockModel.getTexturePath(texture.substring(1))); icons.get(variant).put(texture, icon); } else { TextureMap blockMap = OurCraft.getOurCraft().getRenderEngine().blocksAndItemsMap; icons.get(variant).put(texture, blockMap.get(texture + ".png")); } } return icons.get(variant).get(texture); } @Override public boolean shouldRenderInPass(EnumRenderPass currentPass, World w, Block b, int x, int y, int z) { BlockVariant variant = getVariant(w, b, x, y, z); if(variant == null) return false; return currentPass == variant.getPass(); } }
OurCraft/OurCraft
src/main/java/org/craft/client/render/blocks/BlockModelRenderer.java
Java
mit
8,599
// Copyright 2015 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.Windows.Forms; namespace NodeEditor { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { var engine = new GUILayer.EngineDevice(); GC.KeepAlive(engine); var catalog = new TypeCatalog( typeof(ShaderPatcherLayer.Manager), typeof(ShaderFragmentArchive.Archive), typeof(NodeEditorCore.ShaderFragmentArchiveModel), typeof(NodeEditorCore.ModelConversion), typeof(NodeEditorCore.ShaderFragmentNodeCreator), typeof(NodeEditorCore.DiagramDocument), typeof(ExampleForm) ); using (var container = new CompositionContainer(catalog)) { container.ComposeExportedValue<ExportProvider>(container); container.ComposeExportedValue<CompositionContainer>(container); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(container.GetExport<ExampleForm>().Value); } engine.Dispose(); } } }
xlgames-inc/XLE
Tools/NodeEditor/Program.cs
C#
mit
1,542
# encoding: utf-8 module Eij class Translator def initialize(key) @src = File.dirname(__FILE__) + "/func.sh" @func = File.dirname(__FILE__) + "/../../data/kanjidicks.txt" @col = %x{bash -lic 'echo $COLUMNS'} @msg = key @res = Hash.new { |h,k| h[k] = Hash.new(&h.default_proc) } ch_reset end def ch_reset @ch = 'a' end def exit_msg(res) "Results: #{res}. Search query too vague!\n" end def jap @msg = %x{bash -lic 'source #{@src}; jj #{@msg}'} format_jp end def to_eng @msg = %x{bash -lic 'source #{@src}; je #{@msg}'} format_jp end def to_jap if @msg.contains_cjk? jap else @msg = %x{bash -lic "source #{@src}; ej #{@msg}"} format_jp end end def grab_item(key) ch_reset if @res[key].size > 1 @msg = @res[key].map do |x| "#{x[0]}#{x[1]}" end @msg = @msg.join else @msg = @res[key][1] end end def grab_char(ch) @msg = @msg[ch.to_i-1].strip + "\n" end def grab_split(i) @msg = @msg.split(' ')[i.to_i-1].strip + "\n" end def grab_inner_item(key, i) ch_reset @msg = @res[key][i.to_i].strip + "\n" end def out @msg = %x{source #{@src}; fmt_msg "#{@msg}"} print @msg.strip + "\n" end def format_jp @msg = @msg.gsub(":@;", "\n") @msg.strip! @msg = @msg.gsub(" \n", "") divs = @msg.split(/\n/) prim = divs[1..-1] prim_list = [] offset = 0 if prim.count > 52 print exit_msg prim.count exit end prim.each_with_index do |str, index| @ch = 'A' if @ch.ord == 123 chm = "{#{@ch}} " if !str.include? "-->" prim_list[index] = "#{chm.colorize(index-offset)}#{str}" indx = 0 str.split(/\d\./).each do |split| if split.split.size > 0 indx += 1 @res[@ch][indx] = "#{split}" end end @ch = @ch.ord.next.chr else prim_list[index] = "#{str}" offset += 1 end end prim_merge = prim_list.join("\n") prim_merge += "\n" @msg.sub!(@msg, prim_merge) end def print_num_lines lst = {} @msg.split("\n").each_with_index do |str, index| if index > 0 print "#{(index).to_s.rjust(2).colorize(index)}#{str}\n" lst[(index).to_s] = str.split(" ")[0] end end print "#: " begin @msg = lst[gets.strip] rescue Exception => e exit end lookup end def lookup @msg = %x{bash -ic 'source #{@src}; dfind #{@msg.strip} #{@func}'} divs = @msg.split(":;!;") @msg = divs[0] @msg = @msg.gsub(":@;", "\n") @msg.strip! if @msg.include? "No matches found:" print exit_msg 0 exit elsif @msg.include? "Disambiguation required:" print "Disambiguation required:\n" print_num_lines else @msg += "\n" lookup_prims divs[1] if divs[1].size > 0 lookup_jukugo divs[2] if divs[2].size > 0 lookup_usedin divs[3] if divs[3].size > 0 end end def lookup_prims(div) prim_list = [] div.split("+").each_with_index do |str, index| chm = ":#{index+1}:" prim_list[index] = chm.colorize(index) + str.strip @res[@ch][index+1] = " " + str.strip + " " end prim_merge = prim_list.join(", ") @msg.sub!(div, "\n{#{@ch}} ".blue + prim_merge) end def lookup_jukugo(div) prim_list = [] @ch = @ch.ord.next.chr offset = 0 div.split("\n").each_with_index do |str, index| chm = "{#{@ch}} " if str[0].to_s.contains_cjk? prim_list[index] = "#{chm.colorize(index-offset)}#{str}" @res[@ch][1] = str.strip @ch = @ch.ord.next.chr else prim_list[index] = str offset += 1 end end prim_merge = prim_list.join("\n") @msg.sub!(div, prim_merge) end def lookup_usedin(div) prim_list = [] offset = 0 strsizetotal = 0 div.split("\n").each_with_index do |str, index| if @ch[-1] == 'z' @ch[0,0] = '1' @ch[-1] = 'a' end chm = "{#{@ch}}" if str == "USED IN:" prim_list[index] = "\n" + str.strip + "\n" offset += 1 elsif str.strip.size > 0 if strsizetotal + str.size + @ch.size >= @col.to_i/2 newl = "\n" strsizetotal = 0 end prim_list[index] = "#{chm.colorize(index-offset)}#{str.strip}#{newl}" @res[@ch][1] = str.strip strsizetotal += str.size @ch[-1] = @ch[-1].ord.next.chr end end prim_merge = prim_list.join("") prim_merge.gsub!(", , ", "") @msg.sub!(div, prim_merge) end end end
jollywho/eij
lib/eij/translator.rb
Ruby
mit
5,026
using System; using System.Collections.Generic; using System.Linq; using Moq; using NUnit.Framework; using Ploeh.AutoFixture; using RememBeer.Models.Contracts; using RememBeer.Models.Dtos; using RememBeer.Models.Factories; using RememBeer.Services.RankingStrategies; using RememBeer.Tests.Utils; namespace RememBeer.Tests.Services.RankingStrategies.DoubleOverallScoreStrategyTests { [TestFixture] public class GetBeerRank_Should : TestClassBase { [Test] public void ThrowArgumentNullException_WhenReviewsArgumentIsNull() { // Arrange var factory = new Mock<IModelFactory>(); var beer = new Mock<IBeer>(); var strategy = new DoubleOverallScoreStrategy(factory.Object); // Act & Assert Assert.Throws<ArgumentNullException>(() => strategy.GetBeerRank(null, beer.Object)); } [Test] public void ThrowArgumentNullException_WhenBeerArgumentIsNull() { // Arrange var factory = new Mock<IModelFactory>(); var reviews = new Mock<IEnumerable<IBeerReview>>(); var strategy = new DoubleOverallScoreStrategy(factory.Object); // Act & Assert Assert.Throws<ArgumentNullException>(() => strategy.GetBeerRank(reviews.Object, null)); } [Test] public void ThrowArgumentException_WhenReviewsAreEmpty() { // Arrange var factory = new Mock<IModelFactory>(); var beer = new Mock<IBeer>(); var reviews = new List<IBeerReview>(); var strategy = new DoubleOverallScoreStrategy(factory.Object); // Act & Assert Assert.Throws<ArgumentException>(() => strategy.GetBeerRank(reviews, beer.Object)); } [Test] public void CallFactoryCreateBeerRankMethod_WithCorrectParamsOnce() { // Arrange var overallScore = this.Fixture.Create<int>(); var tasteScore = this.Fixture.Create<int>(); var smellScore = this.Fixture.Create<int>(); var looksScore = this.Fixture.Create<int>(); var factory = new Mock<IModelFactory>(); var mockedReview = new Mock<IBeerReview>(); mockedReview.Setup(r => r.Overall).Returns(overallScore); mockedReview.Setup(r => r.Taste).Returns(tasteScore); mockedReview.Setup(r => r.Smell).Returns(smellScore); mockedReview.Setup(r => r.Look).Returns(looksScore); var mockedReview2 = new Mock<IBeerReview>(); mockedReview.Setup(r => r.Overall).Returns(overallScore + this.Fixture.Create<int>()); mockedReview.Setup(r => r.Taste).Returns(tasteScore + this.Fixture.Create<int>()); mockedReview.Setup(r => r.Smell).Returns(smellScore + this.Fixture.Create<int>()); mockedReview.Setup(r => r.Look).Returns(looksScore + this.Fixture.Create<int>()); var beer = new Mock<IBeer>(); var reviews = new List<IBeerReview>() { mockedReview.Object, mockedReview2.Object }; var expectedAggregateScore = reviews.Sum(beerReview => (decimal)(2 * beerReview.Overall + beerReview.Look + beerReview.Smell + beerReview.Taste) / 5) / reviews.Count; var expectedOverall = (decimal)reviews.Sum(r => r.Overall) / reviews.Count; var expectedTaste = (decimal)reviews.Sum(r => r.Taste) / reviews.Count; var expectedSmell = (decimal)reviews.Sum(r => r.Smell) / reviews.Count; var expectedLook = (decimal)reviews.Sum(r => r.Look) / reviews.Count; var strategy = new DoubleOverallScoreStrategy(factory.Object); // Act var result = strategy.GetBeerRank(reviews, beer.Object); // Assert factory.Verify( f => f.CreateBeerRank(expectedOverall, expectedTaste, expectedLook, expectedSmell, beer.Object, expectedAggregateScore, reviews.Count), Times.Once); } [Test] public void ReturnResultFromFactory() { // Arrange var expectedRank = new Mock<IBeerRank>(); var overallScore = this.Fixture.Create<int>(); var tasteScore = this.Fixture.Create<int>(); var smellScore = this.Fixture.Create<int>(); var looksScore = this.Fixture.Create<int>(); var expectedAggregateScore = (decimal)((overallScore * 2) + tasteScore + smellScore + looksScore) / 5; var mockedReview = new Mock<IBeerReview>(); mockedReview.Setup(r => r.Overall).Returns(overallScore); mockedReview.Setup(r => r.Taste).Returns(tasteScore); mockedReview.Setup(r => r.Smell).Returns(smellScore); mockedReview.Setup(r => r.Look).Returns(looksScore); var beer = new Mock<IBeer>(); var reviews = new List<IBeerReview>() { mockedReview.Object }; var factory = new Mock<IModelFactory>(); factory.Setup( f => f.CreateBeerRank(overallScore, tasteScore, looksScore, smellScore, beer.Object, expectedAggregateScore, 1)) .Returns(expectedRank.Object); var strategy = new DoubleOverallScoreStrategy(factory.Object); // Act var result = strategy.GetBeerRank(reviews, beer.Object); // Assert Assert.IsNotNull(result); Assert.AreSame(expectedRank.Object, result); } } }
J0hnyBG/RememBeerMeMvc
src/RememBeer.Tests/Services/RankingStrategies/DoubleOverallScoreStrategyTests/GetBeerRank_Should.cs
C#
mit
6,676
using CreativeMinds.CQS.Commands; using NForum.Core.Dtos; using NForum.Datastores; using NForum.Domain; using NForum.Infrastructure; using System; using System.Security.Principal; namespace NForum.CQS.Commands.Topics { public class CreateTopicCommandHandler : CommandWithStatusHandler<CreateTopicCommand> { protected readonly IForumDatastore forums; protected readonly ITopicDatastore topics; protected readonly IPrincipal principal; public CreateTopicCommandHandler(IForumDatastore forums, ITopicDatastore topics, ITaskDatastore taskDatastore, IPrincipal principal) : base(taskDatastore) { this.forums = forums; this.topics = topics; this.principal = principal; } public override void Execute(CreateTopicCommand command) { // Nothing special to do here, permissions have been checked and parameters validated! IForumDto forum = this.forums.ReadById(command.ForumId); if (forum == null) { // TODO: throw new ArgumentException("Parent forum not found!"); } Topic t = new Topic(new Forum(forum), command.Subject, command.Content, command.Type, command.State); ITopicDto newTopic = this.topics.Create(t); this.SetTaskStatus(command.TaskId, newTopic.Id, "Topic"); } } }
steentottrup/NForum
src/NForum/CQS/Commands/Topics/CreateTopicCommandHandler.cs
C#
mit
1,229
<?php namespace js4php5; /** * Blatantly stolen from Yii2 for debug use, as it's much better than var_dump() or print_r() (but not as good as * the one included in some other frameworks). */ class VarDumper { private static $_output; private static $_depth; private static $_objects; /** * Displays a variable. * This method achieves the similar functionality as var_dump and print_r * but is more robust when handling complex objects such as Yii controllers. * @param mixed $var variable to be dumped * @param integer $depth maximum depth that the dumper should go into the variable. Defaults to 10. * @param boolean $highlight whether the result should be syntax-highlighted */ public static function dump($var, $label = '', $depth = 10, $highlight = true) { echo static::dumpAsString($var, $label, $depth, $highlight); } /** * Dumps a variable in terms of a string. * This method achieves the similar functionality as var_dump and print_r * but is more robust when handling complex objects such as Yii controllers. * @param mixed $var variable to be dumped * @param integer $depth maximum depth that the dumper should go into the variable. Defaults to 10. * @param boolean $highlight whether the result should be syntax-highlighted * @return string the string representation of the variable */ public static function dumpAsString($var, $label = '', $depth = 10, $highlight = true) { self::$_output = ''; self::$_objects = []; self::$_depth = $depth; self::dumpInternal($var, 0); if ($highlight) { $result = highlight_string("<?php\n" . self::$_output, true); // self::$_output = preg_replace('/&lt;\\?php<br \\/>/', '', $result, 1); self::$_output = preg_replace('/&lt;\\?php<br \\/>/', ($label ? $label . ' = ' : ''), $result, 1); } return self::$_output; } /** * @param mixed $var variable to be dumped * @param integer $level depth level */ private static function dumpInternal($var, $level) { switch (gettype($var)) { case 'boolean': self::$_output .= $var ? 'true' : 'false'; break; case 'integer': self::$_output .= "$var"; break; case 'double': self::$_output .= "$var"; break; case 'string': self::$_output .= "'" . addslashes($var) . "'"; break; case 'resource': self::$_output .= '{resource}'; break; case 'NULL': self::$_output .= "null"; break; case 'unknown type': self::$_output .= '{unknown}'; break; case 'array': if (self::$_depth <= $level) { self::$_output .= '[...]'; } elseif (empty($var)) { self::$_output .= '[]'; } else { $keys = array_keys($var); $spaces = str_repeat(' ', $level * 4); self::$_output .= '['; foreach ($keys as $key) { self::$_output .= "\n" . $spaces . ' '; self::dumpInternal($key, 0); self::$_output .= ' => '; self::dumpInternal($var[$key], $level + 1); } self::$_output .= "\n" . $spaces . ']'; } break; case 'object': if (($id = array_search($var, self::$_objects, true)) !== false) { self::$_output .= get_class($var) . '#' . ($id + 1) . '(...)'; } elseif (self::$_depth <= $level) { self::$_output .= get_class($var) . '(...)'; } else { $id = array_push(self::$_objects, $var); $className = get_class($var); $spaces = str_repeat(' ', $level * 4); self::$_output .= "$className#$id\n" . $spaces . '('; foreach ((array) $var as $key => $value) { $keyDisplay = strtr(trim($key), "\0", ':'); self::$_output .= "\n" . $spaces . " [$keyDisplay] => "; self::dumpInternal($value, $level + 1); } self::$_output .= "\n" . $spaces . ')'; } break; } } /** * Exports a variable as a string representation. * * The string is a valid PHP expression that can be evaluated by PHP parser * and the evaluation result will give back the variable value. * * This method is similar to `var_export()`. The main difference is that * it generates more compact string representation using short array syntax. * * It also handles objects by using the PHP functions serialize() and unserialize(). * * PHP 5.4 or above is required to parse the exported value. * * @param mixed $var the variable to be exported. * @return string a string representation of the variable */ public static function export($var) { self::$_output = ''; self::exportInternal($var, 0); return self::$_output; } /** * @param mixed $var variable to be exported * @param integer $level depth level */ private static function exportInternal($var, $level) { switch (gettype($var)) { case 'NULL': self::$_output .= 'null'; break; case 'array': if (empty($var)) { self::$_output .= '[]'; } else { $keys = array_keys($var); $outputKeys = ($keys !== range(0, sizeof($var) - 1)); $spaces = str_repeat(' ', $level * 4); self::$_output .= '['; foreach ($keys as $key) { self::$_output .= "\n" . $spaces . ' '; if ($outputKeys) { self::exportInternal($key, 0); self::$_output .= ' => '; } self::exportInternal($var[$key], $level + 1); self::$_output .= ','; } self::$_output .= "\n" . $spaces . ']'; } break; case 'object': self::$_output .= 'unserialize(' . var_export(serialize($var), true) . ')'; break; default: self::$_output .= var_export($var, true); } } }
hiltonjanfield/js4php5
VarDumper.php
PHP
mit
6,924
/** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 1999-2015, QOS.ch. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ package ch.qos.logback.core.pattern.color; import static ch.qos.logback.core.pattern.color.ANSIConstants.*; /** * Encloses a given set of converter output in gray using the appropriate ANSI * escape codes. * * @param <E> * @author Ceki G&uuml;lc&uuml; * @since 1.0.5 */ public class GrayCompositeConverter<E> extends ForegroundCompositeConverterBase<E> { @Override protected String getForegroundColorCode(E event) { return BOLD + BLACK_FG; } }
cscfa/bartleby
library/logBack/logback-1.1.3/logback-core/src/main/java/ch/qos/logback/core/pattern/color/GrayCompositeConverter.java
Java
mit
970
<?php namespace OroCRM\Bundle\ContactBundle\Tests\Unit\Twig; use OroCRM\Bundle\ContactBundle\Twig\SocialUrlExtension; use OroCRM\Bundle\ContactBundle\Model\Social; class SocialUrlExtensionTest extends \PHPUnit_Framework_TestCase { /** * @var SocialUrlExtension */ protected $twigExtension; /** * @var \PHPUnit_Framework_MockObject_MockObject */ protected $urlFormatter; protected function setUp() { $this->urlFormatter = $this->getMockBuilder('OroCRM\Bundle\ContactBundle\Formatter\SocialUrlFormatter') ->setMethods(array('getSocialUrl')) ->disableOriginalConstructor() ->getMock(); $this->twigExtension = new SocialUrlExtension($this->urlFormatter); } protected function tearDown() { unset($this->urlFormatter); unset($this->twigExtension); } public function testGetFunctions() { $expectedFunctions = array( 'oro_social_url' => 'getSocialUrl', ); $actualFunctions = array(); /** @var \Twig_SimpleFunction $function */ foreach ($this->twigExtension->getFunctions() as $function) { $this->assertInstanceOf('\Twig_SimpleFunction', $function); $callable = $function->getCallable(); $this->assertArrayHasKey(1, $callable); $actualFunctions[$function->getName()] = $callable[1]; } $this->assertEquals($expectedFunctions, $actualFunctions); } /** * @param string $expectedUrl * @param string $socialType * @param string $username * @dataProvider socialUrlDataProvider */ public function testGetSocialUrl($expectedUrl, $socialType, $username) { if ($socialType && $username) { $this->urlFormatter->expects($this->once()) ->method('getSocialUrl') ->with($socialType, $username) ->will( $this->returnCallback( function ($socialType, $username) { return 'http://' . $socialType . '/' . $username; } ) ); } else { $this->urlFormatter->expects($this->never()) ->method('getSocialUrl'); } $this->assertEquals($expectedUrl, $this->twigExtension->getSocialUrl($socialType, $username)); } /** * @return array */ public function socialUrlDataProvider() { return array( 'no type' => array( 'expectedUrl' => '#', 'socialType' => null, 'username' => 'me', ), 'no username' => array( 'expectedUrl' => '#', 'socialType' => Social::TWITTER, 'username' => null, ), 'valid data' => array( 'expectedUrl' => 'http://' . Social::TWITTER . '/me', 'socialType' => Social::TWITTER, 'username' => 'me', ), ); } }
MarkThink/OROCRM
vendor/oro/crm/src/OroCRM/Bundle/ContactBundle/Tests/Unit/Twig/SocialUrlExtensionTest.php
PHP
mit
3,113
<?php /** * @author rugk * @copyright Copyright (c) 2015-2016 rugk * @license MIT */ // set end of line $eol = PHP_EOL; if (php_sapi_name() != 'cli') { $eol .= '<br>'; } //list all functions $functions = get_extension_funcs('libsodium'); foreach ($functions as $func) { echo $func . $eol; } echo $eol;
rugk/threema-msgapi-webui
debug/libsodium_functions.php
PHP
mit
317
require 'doorkeeper/oauth/assertion_access_token_request' module Doorkeeper module Request class Assertion def self.build(server) new(server) end attr_reader :server def initialize(server) @server = server end def request @request ||= OAuth::AssertionAccessTokenRequest.new(server, Doorkeeper.configuration) end def authorize request.authorize end end end end
kioru/doorkeeper-jwt_assertion
lib/doorkeeper/request/assertion.rb
Ruby
mit
416
//process.argv.forEach(function (val, index, array) { console.log(index + ': ' + val); }); var fs = require('fs'); (function () { function slugify(text) { text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, ''); text = text.replace(/-/gi, "_"); text = text.replace(/\s/gi, "-"); return text; } var DocGen = { filesArr: null, files: {}, functions: [], nbLoaded: 0, init: function (files) { this.filesArr = files; }, start: function () { for (var i=0, len=this.filesArr.length; i<len; i++) { var file = this.filesArr[i]; this.processFile(file); } }, fileLoaded: function() { this.nbLoaded++; if (this.nbLoaded == this.filesArr.length) { this.exportHtml(); } }, getSignatures: function (m) { var sig = null; var signatures = []; var rSig = /\\*\s?(@sig\s.*)\n/gi; while (sig = rSig.exec(m)) { var params = []; var rParam = /(\w+):(\w+)/gi; while (param = rParam.exec(sig[1])) { var name = param[1]; var type = param[2]; params.push({ name: name, type: type }); } if (params.length >= 1) { ret = params.pop(); } signatures.push({ params: params, ret: ret}); } return signatures; }, extractInfos: function (m) { var self = this; var fun = m[2]; var rFun = /['|"]?([a-zA-Z0-9._-]+)['|"]?\s?:\s?function\s?\(.*\)\s?{/gi; var isFun = rFun.exec(fun); if (!isFun) { rFun = /socket\.on\(['|"]([a-zA-Z0-9._-]+)['|"]\s?,\s?function\s?\(.*\)\s?{/gi; isFun = rFun.exec(fun); } if (isFun) { var comment = m[1]; var name = isFun[1]; var sigs = self.getSignatures(comment); var desc = (/\*\s(.*?)\n/gi).exec(m[1])[1]; var f = { name: name, description: desc, sigs: sigs }; return f; } return null; }, processFile: function (file) { var self = this; // Get the file in a buffer fs.readFile(file, function(err, data) { var buf = data.toString('binary'); var functions = []; // Get all long comment ( /** ) var rgx = new RegExp("/\\*\\*\n([a-zA-Z0-9 -_\n\t]*)\\*/\n(.*)\n", "gi"); while (m = rgx.exec(buf)) { info = self.extractInfos(m); if (info) { functions.push(info); } } self.files[file] = { functions: functions }; self.fileLoaded(); }); }, sortFunctions: function (fun1, fun2) { var name1 = fun1.name.toLowerCase(); var name2 = fun2.name.toLowerCase(); if (name1 < name2) { return -1; } else if (name1 > name2) { return 1; } else { return 0; } }, exportHtml: function() { for (var fileName in this.files) { var file = this.files[fileName]; file.functions.sort(this.sortFunctions); console.log(fileName, file.functions.length); var html = '<!DOCTYPE html>\n' + '<html>\n' + '<head>\n' + ' <title></title>\n' + ' <link rel="stylesheet" href="css/reset.css" type="text/css" media="screen" charset="utf-8" />\n' + ' <link rel="stylesheet" href="css/style.css" type="text/css" media="screen" charset="utf-8" />\n' + //' <script src="js/scripts.js" type="text/javascript"></script>' + '</head>\n' + '<body>\n' + '\n' + '<div class="menu" id="menu">\n' + ' <h1>Files</h1>\n' + ' <ul>\n'; for (var f in this.files) { html += ' <li><a href="'+f+'.html">'+f+'</a></li>\n'; } html += ' </ul>\n' + ' <h1>Functions</h1>\n' + ' <ul>\n'; for (var i=0, len=file.functions.length; i<len; i++) { html += ' <li><a href="#'+slugify(file.functions[i].name)+'">'+file.functions[i].name+'</a></li>\n'; } html += ' </ul>\n' html += '</div>\n' + '<div id="page">\n' + ' <div class="content">\n'; for (var i=0, len=file.functions.length; i<len; i++) { var fn = file.functions[i]; if (fn.sigs.length > 0) { html += '<h3><a name="'+slugify(fn.name)+'">'+fn.name+'</a></h3>\n'; html += '<span class="signature">\n'; for (var s=0, len2=fn.sigs.length; s<len2; s++) { var sig = fn.sigs[s]; html += '<span class="name">'+fn.name+'</span> ( '; for (var p=0, len3=sig.params.length; p<len3; p++) { var param = sig.params[p]; html += '<span class="param">'+param.name+'</span>:<span class="type">'+param.type+'</span>, '; } html = html.substr(0, html.length-2); html += ' ) : <span class="param">'+sig.ret.name+'</span>:<span class="type">'+sig.ret.type+'</span><br />'; } html = html.substr(0, html.length-6); html += '</span>\n'; html += '<p>'+fn.description+'</p>'; } } html += ' </div>\n' + '</div>\n' + '\n' + '</body>\n' '</html>'; fs.writeFile('doc/'+fileName+'.html', html); } } }; var files = ['sockets.js', 'database_operations.js']; DocGen.init(files); DocGen.start(); })();
alaingilbert/ttdashboard
server/gatherer/parser.js
JavaScript
mit
5,796
require 'rest_client' module WebHook # Makes a http request to the target endpoint passing contents as data def self.send_message(endpoint, content) # TODO: # - Make webrequest # - If success return success # - If error, return error response = RestClient.post endpoint, content.to_json, :content_type => :json return response.code, response end def self.prune_devices # Checks failed endpoints # removes "dead" endpoints end end
WiretapServer/wiretap-server
helpers/webhook.rb
Ruby
mit
480
# -*- coding:utf-8 -*- # This code is automatically transpiled by Saklient Translator import six from ..client import Client from .model import Model from ..resources.resource import Resource from ..resources.licenseinfo import LicenseInfo from ...util import Util import saklient str = six.text_type # module saklient.cloud.models.model_licenseinfo class Model_LicenseInfo(Model): ## ライセンス種別情報を検索するための機能を備えたクラス。 ## @private # @return {str} def _api_path(self): return "/product/license" ## @private # @return {str} def _root_key(self): return "LicenseInfo" ## @private # @return {str} def _root_key_m(self): return "LicenseInfo" ## @private # @return {str} def _class_name(self): return "LicenseInfo" ## @private # @param {any} obj # @param {bool} wrapped=False # @return {saklient.cloud.resources.resource.Resource} def _create_resource_impl(self, obj, wrapped=False): Util.validate_type(wrapped, "bool") return LicenseInfo(self._client, obj, wrapped) ## 次に取得するリストの開始オフセットを指定します。 # # @param {int} offset オフセット # @return {saklient.cloud.models.model_licenseinfo.Model_LicenseInfo} this def offset(self, offset): Util.validate_type(offset, "int") return self._offset(offset) ## 次に取得するリストの上限レコード数を指定します。 # # @param {int} count 上限レコード数 # @return {saklient.cloud.models.model_licenseinfo.Model_LicenseInfo} this def limit(self, count): Util.validate_type(count, "int") return self._limit(count) ## Web APIのフィルタリング設定を直接指定します。 # # @param {str} key キー # @param {any} value 値 # @param {bool} multiple=False valueに配列を与え、OR条件で完全一致検索する場合にtrueを指定します。通常、valueはスカラ値であいまい検索されます。 # @return {saklient.cloud.models.model_licenseinfo.Model_LicenseInfo} def filter_by(self, key, value, multiple=False): Util.validate_type(key, "str") Util.validate_type(multiple, "bool") return self._filter_by(key, value, multiple) ## 次のリクエストのために設定されているステートをすべて破棄します。 # # @return {saklient.cloud.models.model_licenseinfo.Model_LicenseInfo} this def reset(self): return self._reset() ## 指定したIDを持つ唯一のリソースを取得します。 # # @param {str} id # @return {saklient.cloud.resources.licenseinfo.LicenseInfo} リソースオブジェクト def get_by_id(self, id): Util.validate_type(id, "str") return self._get_by_id(id) ## リソースの検索リクエストを実行し、結果をリストで取得します。 # # @return {saklient.cloud.resources.licenseinfo.LicenseInfo[]} リソースオブジェクトの配列 def find(self): return self._find() ## 指定した文字列を名前に含むリソースに絞り込みます。 # # 大文字・小文字は区別されません。 # 半角スペースで区切られた複数の文字列は、それらをすべて含むことが条件とみなされます。 # # @todo Implement test case # @param {str} name # @return {saklient.cloud.models.model_licenseinfo.Model_LicenseInfo} def with_name_like(self, name): Util.validate_type(name, "str") return self._with_name_like(name) ## 名前でソートします。 # # @todo Implement test case # @param {bool} reverse=False # @return {saklient.cloud.models.model_licenseinfo.Model_LicenseInfo} def sort_by_name(self, reverse=False): Util.validate_type(reverse, "bool") return self._sort_by_name(reverse) ## @ignore # @param {saklient.cloud.client.Client} client def __init__(self, client): super(Model_LicenseInfo, self).__init__(client) Util.validate_type(client, "saklient.cloud.client.Client")
sakura-internet/saklient.python
saklient/cloud/models/model_licenseinfo.py
Python
mit
4,306
'use strict'; exports.name = '/activation';
longlh/di-linker
test/data/activation.js
JavaScript
mit
45
<?php use Symfony\Component\Routing\RequestContext; use Symfony\Component\Routing\Exception\RouteNotFoundException; /** * appdevUrlGenerator * * This class has been auto-generated * by the Symfony Routing Component. */ class appdevUrlGenerator extends Symfony\Component\Routing\Generator\UrlGenerator { static private $declaredRouteNames = array( '_wdt' => true, '_profiler_search' => true, '_profiler_purge' => true, '_profiler_import' => true, '_profiler_export' => true, '_profiler_search_results' => true, '_profiler' => true, '_configurator_home' => true, '_configurator_step' => true, '_configurator_final' => true, 'Creditunions' => true, 'Creditunions_show' => true, 'Creditunions_new' => true, 'Creditunions_create' => true, 'Creditunions_edit' => true, 'Creditunions_update' => true, 'Creditunions_delete' => true, 'Customers' => true, 'Customers_show' => true, 'Customers_new' => true, 'Customers_create' => true, 'Customers_edit' => true, 'Customers_update' => true, 'Customers_delete' => true, 'creditunion_frontend_default_index' => true, 'creditunion_frontend_default_contact' => true, 'Depositsandloans' => true, 'Depositsandloans_show' => true, 'Depositsandloans_new' => true, 'Depositsandloans_create' => true, 'Depositsandloans_edit' => true, 'Depositsandloans_update' => true, 'Depositsandloans_delete' => true, 'Price' => true, 'Price_show' => true, 'Price_new' => true, 'Price_create' => true, 'Price_edit' => true, 'Price_update' => true, 'Price_delete' => true, 'creditunion_frontend_welcome_index' => true, 'worker' => true, 'worker_show' => true, 'worker_new' => true, 'worker_create' => true, 'worker_edit' => true, 'worker_update' => true, 'worker_delete' => true, ); /** * Constructor. */ public function __construct(RequestContext $context) { $this->context = $context; } public function generate($name, $parameters = array(), $absolute = false) { if (!isset(self::$declaredRouteNames[$name])) { throw new RouteNotFoundException(sprintf('Route "%s" does not exist.', $name)); } $escapedName = str_replace('.', '__', $name); list($variables, $defaults, $requirements, $tokens) = $this->{'get'.$escapedName.'RouteInfo'}(); return $this->doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $absolute); } private function get_wdtRouteInfo() { return array(array ( 0 => 'token',), array ( '_controller' => 'Symfony\\Bundle\\WebProfilerBundle\\Controller\\ProfilerController::toolbarAction',), array (), array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'token', ), 1 => array ( 0 => 'text', 1 => '/_wdt', ),)); } private function get_profiler_searchRouteInfo() { return array(array (), array ( '_controller' => 'Symfony\\Bundle\\WebProfilerBundle\\Controller\\ProfilerController::searchAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/_profiler/search', ),)); } private function get_profiler_purgeRouteInfo() { return array(array (), array ( '_controller' => 'Symfony\\Bundle\\WebProfilerBundle\\Controller\\ProfilerController::purgeAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/_profiler/purge', ),)); } private function get_profiler_importRouteInfo() { return array(array (), array ( '_controller' => 'Symfony\\Bundle\\WebProfilerBundle\\Controller\\ProfilerController::importAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/_profiler/import', ),)); } private function get_profiler_exportRouteInfo() { return array(array ( 0 => 'token',), array ( '_controller' => 'Symfony\\Bundle\\WebProfilerBundle\\Controller\\ProfilerController::exportAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '.txt', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/\\.]+?', 3 => 'token', ), 2 => array ( 0 => 'text', 1 => '/_profiler/export', ),)); } private function get_profiler_search_resultsRouteInfo() { return array(array ( 0 => 'token',), array ( '_controller' => 'Symfony\\Bundle\\WebProfilerBundle\\Controller\\ProfilerController::searchResultsAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/search/results', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'token', ), 2 => array ( 0 => 'text', 1 => '/_profiler', ),)); } private function get_profilerRouteInfo() { return array(array ( 0 => 'token',), array ( '_controller' => 'Symfony\\Bundle\\WebProfilerBundle\\Controller\\ProfilerController::panelAction',), array (), array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'token', ), 1 => array ( 0 => 'text', 1 => '/_profiler', ),)); } private function get_configurator_homeRouteInfo() { return array(array (), array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::checkAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/_configurator/', ),)); } private function get_configurator_stepRouteInfo() { return array(array ( 0 => 'index',), array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::stepAction',), array (), array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'index', ), 1 => array ( 0 => 'text', 1 => '/_configurator/step', ),)); } private function get_configurator_finalRouteInfo() { return array(array (), array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::finalAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/_configurator/final', ),)); } private function getCreditunionsRouteInfo() { return array(array (), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\CreditunionsController::indexAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/Creditunions/', ),)); } private function getCreditunions_showRouteInfo() { return array(array ( 0 => 'id',), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\CreditunionsController::showAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/show', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/Creditunions', ),)); } private function getCreditunions_newRouteInfo() { return array(array (), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\CreditunionsController::newAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/Creditunions/new', ),)); } private function getCreditunions_createRouteInfo() { return array(array (), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\CreditunionsController::createAction',), array ( '_method' => 'post',), array ( 0 => array ( 0 => 'text', 1 => '/Creditunions/create', ),)); } private function getCreditunions_editRouteInfo() { return array(array ( 0 => 'id',), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\CreditunionsController::editAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/edit', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/Creditunions', ),)); } private function getCreditunions_updateRouteInfo() { return array(array ( 0 => 'id',), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\CreditunionsController::updateAction',), array ( '_method' => 'post',), array ( 0 => array ( 0 => 'text', 1 => '/update', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/Creditunions', ),)); } private function getCreditunions_deleteRouteInfo() { return array(array ( 0 => 'id',), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\CreditunionsController::deleteAction',), array ( '_method' => 'post',), array ( 0 => array ( 0 => 'text', 1 => '/delete', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/Creditunions', ),)); } private function getCustomersRouteInfo() { return array(array (), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\CustomersController::indexAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/Customers/', ),)); } private function getCustomers_showRouteInfo() { return array(array ( 0 => 'id',), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\CustomersController::showAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/show', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/Customers', ),)); } private function getCustomers_newRouteInfo() { return array(array (), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\CustomersController::newAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/Customers/new', ),)); } private function getCustomers_createRouteInfo() { return array(array (), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\CustomersController::createAction',), array ( '_method' => 'post',), array ( 0 => array ( 0 => 'text', 1 => '/Customers/create', ),)); } private function getCustomers_editRouteInfo() { return array(array ( 0 => 'id',), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\CustomersController::editAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/edit', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/Customers', ),)); } private function getCustomers_updateRouteInfo() { return array(array ( 0 => 'id',), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\CustomersController::updateAction',), array ( '_method' => 'post',), array ( 0 => array ( 0 => 'text', 1 => '/update', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/Customers', ),)); } private function getCustomers_deleteRouteInfo() { return array(array ( 0 => 'id',), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\CustomersController::deleteAction',), array ( '_method' => 'post',), array ( 0 => array ( 0 => 'text', 1 => '/delete', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/Customers', ),)); } private function getcreditunion_frontend_default_indexRouteInfo() { return array(array ( 0 => 'name',), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\DefaultController::indexAction',), array (), array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'name', ), 1 => array ( 0 => 'text', 1 => '/hello', ),)); } private function getcreditunion_frontend_default_contactRouteInfo() { return array(array (), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\DefaultController::contact',), array (), array ( 0 => array ( 0 => 'text', 1 => '/contact', ),)); } private function getDepositsandloansRouteInfo() { return array(array (), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\DepositsandloansController::indexAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/Depositsandloans/', ),)); } private function getDepositsandloans_showRouteInfo() { return array(array ( 0 => 'id',), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\DepositsandloansController::showAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/show', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/Depositsandloans', ),)); } private function getDepositsandloans_newRouteInfo() { return array(array (), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\DepositsandloansController::newAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/Depositsandloans/new', ),)); } private function getDepositsandloans_createRouteInfo() { return array(array (), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\DepositsandloansController::createAction',), array ( '_method' => 'post',), array ( 0 => array ( 0 => 'text', 1 => '/Depositsandloans/create', ),)); } private function getDepositsandloans_editRouteInfo() { return array(array ( 0 => 'id',), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\DepositsandloansController::editAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/edit', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/Depositsandloans', ),)); } private function getDepositsandloans_updateRouteInfo() { return array(array ( 0 => 'id',), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\DepositsandloansController::updateAction',), array ( '_method' => 'post',), array ( 0 => array ( 0 => 'text', 1 => '/update', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/Depositsandloans', ),)); } private function getDepositsandloans_deleteRouteInfo() { return array(array ( 0 => 'id',), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\DepositsandloansController::deleteAction',), array ( '_method' => 'post',), array ( 0 => array ( 0 => 'text', 1 => '/delete', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/Depositsandloans', ),)); } private function getPriceRouteInfo() { return array(array (), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\PricelistController::indexAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/Price/', ),)); } private function getPrice_showRouteInfo() { return array(array ( 0 => 'id',), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\PricelistController::showAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/show', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/Price', ),)); } private function getPrice_newRouteInfo() { return array(array (), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\PricelistController::newAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/Price/new', ),)); } private function getPrice_createRouteInfo() { return array(array (), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\PricelistController::createAction',), array ( '_method' => 'post',), array ( 0 => array ( 0 => 'text', 1 => '/Price/create', ),)); } private function getPrice_editRouteInfo() { return array(array ( 0 => 'id',), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\PricelistController::editAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/edit', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/Price', ),)); } private function getPrice_updateRouteInfo() { return array(array ( 0 => 'id',), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\PricelistController::updateAction',), array ( '_method' => 'post',), array ( 0 => array ( 0 => 'text', 1 => '/update', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/Price', ),)); } private function getPrice_deleteRouteInfo() { return array(array ( 0 => 'id',), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\PricelistController::deleteAction',), array ( '_method' => 'post',), array ( 0 => array ( 0 => 'text', 1 => '/delete', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/Price', ),)); } private function getcreditunion_frontend_welcome_indexRouteInfo() { return array(array (), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\WelcomeController::indexAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/', ),)); } private function getworkerRouteInfo() { return array(array (), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\WorkerController::indexAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/Worker/', ),)); } private function getworker_showRouteInfo() { return array(array ( 0 => 'id',), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\WorkerController::showAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/show', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/Worker', ),)); } private function getworker_newRouteInfo() { return array(array (), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\WorkerController::newAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/Worker/new', ),)); } private function getworker_createRouteInfo() { return array(array (), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\WorkerController::createAction',), array ( '_method' => 'post',), array ( 0 => array ( 0 => 'text', 1 => '/Worker/create', ),)); } private function getworker_editRouteInfo() { return array(array ( 0 => 'id',), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\WorkerController::editAction',), array (), array ( 0 => array ( 0 => 'text', 1 => '/edit', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/Worker', ),)); } private function getworker_updateRouteInfo() { return array(array ( 0 => 'id',), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\WorkerController::updateAction',), array ( '_method' => 'post',), array ( 0 => array ( 0 => 'text', 1 => '/update', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/Worker', ),)); } private function getworker_deleteRouteInfo() { return array(array ( 0 => 'id',), array ( '_controller' => 'CreditUnion\\FrontendBundle\\Controller\\WorkerController::deleteAction',), array ( '_method' => 'post',), array ( 0 => array ( 0 => 'text', 1 => '/delete', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]+?', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/Worker', ),)); } }
JKord/CreditUnionSoftwareDb
app/cache/dev/appdevUrlGenerator.php
PHP
mit
20,470
const _ = require('lodash') const Joi = require('joi') module.exports = { name: 'href', params: { href: Joi.array().items( Joi.string(), Joi.func().ref() ).min(1) }, setup (params) { params.href = [''].concat(params.href) this._flags.href = params.href }, validate (params, value, state, options) { let parts = value.split('/').slice(1) if (!parts.every((p) => _.size(p) > 0)) { return this.createError('link.href', { v: value }, state, options) } else { return value } } }
hrithikp/joi-link
lib/rule.js
JavaScript
mit
545
using System; using System.Windows.Input; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using Neo.Gui.Base.Dialogs.Interfaces; using Neo.Gui.Base.Dialogs.Results.Wallets; using Neo.Gui.Base.Managers.Interfaces; using Neo.Gui.Base.Services.Interfaces; namespace Neo.Gui.ViewModels.Wallets { public class OpenWalletViewModel : ViewModelBase, IDialogViewModel<OpenWalletDialogResult> { #region Private Fields private readonly IFileDialogService fileDialogService; private string walletPath; private string password; #endregion #region Constructor public OpenWalletViewModel( IFileManager fileManager, IFileDialogService fileDialogService, ISettingsManager settingsManager) { this.fileDialogService = fileDialogService; if (fileManager.FileExists(settingsManager.LastWalletPath)) { this.WalletPath = settingsManager.LastWalletPath; } } #endregion #region Public Properties public string WalletPath { get => this.walletPath; set { if (this.walletPath == value) return; this.walletPath = value; RaisePropertyChanged(); // Update dependent property RaisePropertyChanged(nameof(this.ConfirmEnabled)); } } public bool ConfirmEnabled { get { if (string.IsNullOrEmpty(this.WalletPath) || string.IsNullOrEmpty(this.password)) { return false; } return true; } } public ICommand GetWalletPathCommand => new RelayCommand(this.GetWalletPath); public ICommand ConfirmCommand => new RelayCommand(this.Confirm); #endregion #region IDialogViewModel implementation public event EventHandler Close; public event EventHandler<OpenWalletDialogResult> SetDialogResultAndClose; public OpenWalletDialogResult DialogResult { get; private set; } #endregion #region Public Methods public void UpdatePassword(string updatedPassword) { this.password = updatedPassword; // Update dependent property RaisePropertyChanged(nameof(this.ConfirmEnabled)); } #endregion #region Private Methods private void GetWalletPath() { // TODO Localise file filter text var path = this.fileDialogService.OpenFileDialog("NEP-6 Wallet|*.json|SQLite Wallet|*.db3"); if (string.IsNullOrEmpty(path)) return; this.WalletPath = path; } private void Confirm() { if (!this.ConfirmEnabled) return; if (this.SetDialogResultAndClose == null) return; var dialogResult = new OpenWalletDialogResult( this.WalletPath, this.password); this.SetDialogResultAndClose(this, dialogResult); } #endregion } }
jlgaffney/neo-gui-wpf
Neo.Gui.ViewModels/Wallets/OpenWalletViewModel.cs
C#
mit
3,211
// Mucking with different levels let currentLevel = { cells: undefined, dims: undefined }; if (0) { currentLevel.cells = level; currentLevel.dims = level_dims; } else { currentLevel.cells = LEVEL_ONE; currentLevel.dims = LEVEL_ONE_DIMS; } // Return a reference to the (logical) cell's unique object const _getCellReference = (i, j, k = 1) => { if (i < 0 || j < 0) { return undefined; } if (i >= currentLevel.dims.i || j >= currentLevel.dims.j) { return undefined; } return currentLevel.cells[i + j * (currentLevel.dims.j)]; }; /** * The drawing grid used to represent the editable regions of the level. * [i, j] refer to logical coordinates. [w, h] represent the number of pixels * per grid division on the target 2D rendering surface. */ const grid = { i: 20, j: 20, w: undefined, h: undefined, }; // Translate party front/back/left/right to N/S/E/W const XLATE_UCS2PARTY = { n: { f: 'n', b: 's', r: 'e', l: 'w' }, s: { f: 's', b: 'n', r: 'w', l: 'e' }, e: { f: 'e', b: 'w', r: 's', l: 'n' }, w: { f: 'w', b: 'e', r: 'n', l: 's' } }; // JavaScript divmod is boned const divMod = (n, d) => { return n - d * Math.floor(n / d); }; // Give an [i, j] coordinate and wrap it if exceeds grid dimensions const gridWrap = (i, j) => { return [divMod(i, grid.i), divMod(j, grid.j)]; };
petertorelli/OldSchoolRPG
js/globals.js
JavaScript
mit
1,316
var fastn = require('fastn')({ _generic: require('fastn/genericComponent'), list: require('fastn/listComponent'), templater: require('fastn/templaterComponent'), text: require('fastn/textComponent'), ratingControl: require('./ratingControlComponent') }); module.exports = function(settings){ return fastn('ratingControl', settings).attach().render(); };
shotlom/rating-control-component
index.js
JavaScript
mit
378
import os import logging from jsub.util import safe_mkdir from jsub.util import safe_rmdir class Submit(object): def __init__(self, manager, task_id, sub_ids=None, dry_run=False, resubmit=False): self.__manager = manager self.__task = self.__manager.load_task(task_id) self.__sub_ids = sub_ids self.__dry_run = dry_run self.__resubmit = resubmit self.__logger = logging.getLogger('JSUB') if self.__sub_ids==None: self.__sub_ids=range(len(self.__task.data['jobvar'])) self.__initialize_manager() def __initialize_manager(self): self.__config_mgr = self.__manager.load_config_manager() self.__backend_mgr = self.__manager.load_backend_manager() self.__bootstrap_mgr = self.__manager.load_bootstrap_manager() self.__navigator_mgr = self.__manager.load_navigator_manager() self.__context_mgr = self.__manager.load_context_manager() self.__action_mgr = self.__manager.load_action_manager() self.__launcher_mgr = self.__manager.load_launcher_manager() def handle(self): run_root = self.__backend_mgr.get_run_root(self.__task.data['backend'], self.__task.data['id']) main_root = os.path.join(run_root, 'main') safe_rmdir(main_root) safe_mkdir(main_root) self.__create_input(main_root) self.__create_context(main_root) self.__create_action(main_root) self.__create_navigator(main_root) self.__create_bootstrap(main_root) launcher_param = self.__create_launcher(run_root) self.__submit(launcher_param) def __create_input(self, main_root): content = self.__manager.load_content() input_dir = os.path.join(main_root,'input') try: content.get(self.__task.data['id'], 'input', os.path.join(main_root, 'input')) except: safe_mkdir(input_dir) def __create_context(self, main_root): context_dir = os.path.join(main_root, 'context') safe_mkdir(context_dir) action_default = {} for unit, param in self.__task.data['workflow'].items(): action_default[unit] = self.__action_mgr.default_config(param['type']) navigators = self.__config_mgr.navigator() context_format = self.__navigator_mgr.context_format(navigators) self.__context_mgr.create_context_file(self.__task.data, action_default, context_format, context_dir) def __create_action(self, main_root): action_dir = os.path.join(main_root, 'action') safe_mkdir(action_dir) actions = set() for unit, param in self.__task.data['workflow'].items(): actions.add(param['type']) self.__action_mgr.create_actions(actions, action_dir) def __create_navigator(self, main_root): navigator_dir = os.path.join(main_root, 'navigator') safe_mkdir(navigator_dir) navigators = self.__config_mgr.navigator() self.__navigator_mgr.create_navigators(navigators, navigator_dir) def __create_bootstrap(self, main_root): bootstrap_dir = os.path.join(main_root, 'bootstrap') safe_mkdir(bootstrap_dir) bootstrap = self.__config_mgr.bootstrap() self.__bootstrap_mgr.create_bootstrap(bootstrap, bootstrap_dir) def __create_launcher(self, run_root): launcher = self.__task.data['backend']['launcher'] return self.__launcher_mgr.create_launcher(launcher, run_root) def __submit(self, launcher_param): if self.__dry_run: return if self.__resubmit==False: if self.__task.data.get('backend_job_ids') or self.__task.data.get('backend_task_id'): self.__logger.info('This task has already been submitted to backend, rerun the command with "-r" option if you wish to delete current jobs and resubmit the task.') return else: self.__logger.info('Removing submitted jobs on backend before resubmission.') task_id = self.__task.data.get('backend_task_id') #remove previously generated files in job folder job_ids = self.__task.data.get('backend_job_ids') run_root = self.__backend_mgr.get_run_root(self.__task.data['backend'], self.__task.data['id']) job_root=os.path.join(run_root,'subjobs') safe_rmdir(job_root) if task_id: self.__backend_mgr.delete_task(self.__task.data['backend'],backend_task_id = task_id) elif job_ids: self.__backend_mgr.delete_jobs(self.__task.data['backend'],backend_job_ids = job_ids) result = self.__backend_mgr.submit(self.__task.data['backend'], self.__task.data['id'], launcher_param, sub_ids = self.__sub_ids) if not type(result) is dict: result = {} if 'backend_job_ids' in result: njobs = len(result['backend_job_ids']) else: njobs = len(result) if njobs>0: self.__logger.info('%d jobs successfully submitted to backend.'%(njobs)) self.__task.data.setdefault('backend_job_ids',{}) backend_job_ids=result.get('backend_job_ids',{}) backend_task_id=result.get('backend_task_id',0) self.__task.data['backend_job_ids'].update(backend_job_ids) self.__task.data['backend_task_id']=backend_task_id self.__task.data['status'] = 'Submitted' task_pool = self.__manager.load_task_pool() task_pool.save(self.__task) self.__logger.debug(result)
jsubpy/jsub
jsub/operation/submit.py
Python
mit
4,925
<?php namespace rg\injektor; class InjectionLoopException extends InjectionException { }
researchgate/injektor
src/rg/injektor/InjectionLoopException.php
PHP
mit
91
#!/usr/bin/env node 'use strict'; var assert = require('assert'); var depRep = require('../../lib/depRep'); var oldJson = require('../fixtures/old.json'); var newJson = require('../fixtures/new.json'); var unsupported = require('../fixtures/unsupported.json'); function key(number, dev) { var prefix = "/dependencies/"; if (dev) prefix = "/devDependencies/"; return prefix + number; } describe('Compare', function () { // describe('#report()', function () { // it('should generate a proper report for dependencies', function () { // depRep // .report(oldJson, newJson) // .then(function () { // assert.equal(analyze[key(1)].status, "major"); // assert.equal(report[key(2)].status, null); // assert.equal(report[key(3)], null); // assert.equal(report[key(4)].status, null); // assert.equal(report[key(5)].status, null); // assert.equal(report[key(6)], null); // assert.equal(report[key(7)].status, null); // assert.equal(report[key(8)].status, "minor"); // assert.equal(report[key(9)].status, "major"); // done(); // }); // }); // }); // // describe('#report()', function () { // it('should generate a proper report for devDependencies', function () { // depRep // .report(oldJson, newJson) // .then(function () { // assert.equal(report[key(1, true)].status, "major"); // assert.equal(report[key(2, true)].status, null); // assert.equal(report[key(3, true)], null); // assert.equal(report[key(4, true)].status, null); // assert.equal(report[key(5, true)].status, null); // assert.equal(report[key(6, true)], null); // assert.equal(report[key(7, true)].status, null); // assert.equal(report[key(8, true)].status, "minor"); // assert.equal(report[key(9, true)].status, "major"); // done(); // }); // }); // }); });
kevin-smets/dep-rep
test/specs/depRepSpec.js
JavaScript
mit
2,302