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 |
|---|---|---|---|---|---|
using System.Collections;
public class BooleanKeypadShim : ComponentSolverShim
{
public BooleanKeypadShim(TwitchModule module)
: base(module, "BooleanKeypad")
{
ModInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType(), "Use '!{0} press 2 4' to press buttons 2 and 4. | Buttons are indexed 1-4 in reading order.");
}
protected override IEnumerator RespondToCommandShimmed(string inputCommand)
{
inputCommand = inputCommand.ToLowerInvariant().Trim().Replace("press", "solve").Replace("submit", "solve");
IEnumerator command = RespondToCommandUnshimmed(inputCommand.ToLowerInvariant().Trim());
while (command.MoveNext())
yield return command.Current;
}
}
| samfun123/KtaneTwitchPlays | TwitchPlaysAssembly/Src/ComponentSolvers/Modded/Shims/BooleanKeypadShim.cs | C# | mit | 679 |
'use strict';
angular
.module('facebookMe', [
])
;
| codealchemist/insight | app/facebook-me/facebook-me.js | JavaScript | mit | 55 |
package com.recursivechaos.boredgames.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.data.annotation.Id;
/**
* Created by Andrew Bell 5/28/2015
* www.recursivechaos.com
* andrew@recursivechaos.com
* Licensed under MIT License 2015. See license.txt for details.
*/
public class Game {
@Id
@JsonIgnore
private String id;
private String title;
private String description;
public Game() {
}
public Game(String id) {
this.id = id;
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| AndrewBell/boredgames-mongo | src/main/java/com/recursivechaos/boredgames/domain/Game.java | Java | mit | 888 |
// Code generated by protoc-gen-go.
// source: meta.proto
// DO NOT EDIT!
/*
Package internal is a generated protocol buffer package.
It is generated from these files:
meta.proto
It has these top-level messages:
Series
Tag
MeasurementFields
Field
*/
package from090
import proto "github.com/golang/protobuf/proto"
import math "math"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = math.Inf
type Series struct {
Key *string `protobuf:"bytes,1,req" json:"Key,omitempty"`
Tags []*Tag `protobuf:"bytes,2,rep" json:"Tags,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (m *Series) Reset() { *m = Series{} }
func (m *Series) String() string { return proto.CompactTextString(m) }
func (*Series) ProtoMessage() {}
func (m *Series) GetKey() string {
if m != nil && m.Key != nil {
return *m.Key
}
return ""
}
func (m *Series) GetTags() []*Tag {
if m != nil {
return m.Tags
}
return nil
}
type Tag struct {
Key *string `protobuf:"bytes,1,req" json:"Key,omitempty"`
Value *string `protobuf:"bytes,2,req" json:"Value,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (m *Tag) Reset() { *m = Tag{} }
func (m *Tag) String() string { return proto.CompactTextString(m) }
func (*Tag) ProtoMessage() {}
func (m *Tag) GetKey() string {
if m != nil && m.Key != nil {
return *m.Key
}
return ""
}
func (m *Tag) GetValue() string {
if m != nil && m.Value != nil {
return *m.Value
}
return ""
}
type MeasurementFields struct {
Fields []*Field `protobuf:"bytes,1,rep" json:"Fields,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (m *MeasurementFields) Reset() { *m = MeasurementFields{} }
func (m *MeasurementFields) String() string { return proto.CompactTextString(m) }
func (*MeasurementFields) ProtoMessage() {}
func (m *MeasurementFields) GetFields() []*Field {
if m != nil {
return m.Fields
}
return nil
}
type Field struct {
ID *int32 `protobuf:"varint,1,req" json:"ID,omitempty"`
Name *string `protobuf:"bytes,2,req" json:"Name,omitempty"`
Type *int32 `protobuf:"varint,3,req" json:"Type,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (m *Field) Reset() { *m = Field{} }
func (m *Field) String() string { return proto.CompactTextString(m) }
func (*Field) ProtoMessage() {}
func (m *Field) GetID() int32 {
if m != nil && m.ID != nil {
return *m.ID
}
return 0
}
func (m *Field) GetName() string {
if m != nil && m.Name != nil {
return *m.Name
}
return ""
}
func (m *Field) GetType() int32 {
if m != nil && m.Type != nil {
return *m.Type
}
return 0
}
func init() {
}
| vladlopes/influxdb-migrate | from090/store.pb.go | GO | mit | 2,750 |
# frozen_string_literal: true
# An InternalId is a strictly monotone sequence of integers
# generated for a given scope and usage.
#
# The monotone sequence may be broken if an ID is explicitly provided
# to `.track_greatest_and_save!` or `#track_greatest`.
#
# For example, issues use their project to scope internal ids:
# In that sense, scope is "project" and usage is "issues".
# Generated internal ids for an issue are unique per project.
#
# See InternalId#usage enum for available usages.
#
# In order to leverage InternalId for other usages, the idea is to
# * Add `usage` value to enum
# * (Optionally) add columns to `internal_ids` if needed for scope.
class InternalId < ApplicationRecord
belongs_to :project
belongs_to :namespace
enum usage: { issues: 0, merge_requests: 1, deployments: 2, milestones: 3, epics: 4, ci_pipelines: 5 }
validates :usage, presence: true
REQUIRED_SCHEMA_VERSION = 20180305095250
# Increments #last_value and saves the record
#
# The operation locks the record and gathers a `ROW SHARE` lock (in PostgreSQL).
# As such, the increment is atomic and safe to be called concurrently.
def increment_and_save!
update_and_save { self.last_value = (last_value || 0) + 1 }
end
# Increments #last_value with new_value if it is greater than the current,
# and saves the record
#
# The operation locks the record and gathers a `ROW SHARE` lock (in PostgreSQL).
# As such, the increment is atomic and safe to be called concurrently.
def track_greatest_and_save!(new_value)
update_and_save { self.last_value = [last_value || 0, new_value].max }
end
private
def update_and_save(&block)
lock!
yield
save!
last_value
end
class << self
def track_greatest(subject, scope, usage, new_value, init)
return new_value unless available?
InternalIdGenerator.new(subject, scope, usage)
.track_greatest(init, new_value)
end
def generate_next(subject, scope, usage, init)
# Shortcut if `internal_ids` table is not available (yet)
# This can be the case in other (unrelated) migration specs
return (init.call(subject) || 0) + 1 unless available?
InternalIdGenerator.new(subject, scope, usage)
.generate(init)
end
def reset(subject, scope, usage, value)
return false unless available?
InternalIdGenerator.new(subject, scope, usage)
.reset(value)
end
# Flushing records is generally safe in a sense that those
# records are going to be re-created when needed.
#
# A filter condition has to be provided to not accidentally flush
# records for all projects.
def flush_records!(filter)
raise ArgumentError, "filter cannot be empty" if filter.blank?
where(filter).delete_all
end
def available?
return true unless Rails.env.test?
Gitlab::SafeRequestStore.fetch(:internal_ids_available_flag) do
ActiveRecord::Migrator.current_version >= REQUIRED_SCHEMA_VERSION
end
end
# Flushes cached information about schema
def reset_column_information
Gitlab::SafeRequestStore[:internal_ids_available_flag] = nil
super
end
end
class InternalIdGenerator
# Generate next internal id for a given scope and usage.
#
# For currently supported usages, see #usage enum.
#
# The method implements a locking scheme that has the following properties:
# 1) Generated sequence of internal ids is unique per (scope and usage)
# 2) The method is thread-safe and may be used in concurrent threads/processes.
# 3) The generated sequence is gapless.
# 4) In the absence of a record in the internal_ids table, one will be created
# and last_value will be calculated on the fly.
#
# subject: The instance we're generating an internal id for. Gets passed to init if called.
# scope: Attributes that define the scope for id generation.
# usage: Symbol to define the usage of the internal id, see InternalId.usages
attr_reader :subject, :scope, :scope_attrs, :usage
def initialize(subject, scope, usage)
@subject = subject
@scope = scope
@usage = usage
raise ArgumentError, 'Scope is not well-defined, need at least one column for scope (given: 0)' if scope.empty?
unless InternalId.usages.has_key?(usage.to_s)
raise ArgumentError, "Usage '#{usage}' is unknown. Supported values are #{InternalId.usages.keys} from InternalId.usages"
end
end
# Generates next internal id and returns it
# init: Block that gets called to initialize InternalId record if not present
# Make sure to not throw exceptions in the absence of records (if this is expected).
def generate(init)
subject.transaction do
# Create a record in internal_ids if one does not yet exist
# and increment its last value
#
# Note this will acquire a ROW SHARE lock on the InternalId record
(lookup || create_record(init)).increment_and_save!
end
end
# Reset tries to rewind to `value-1`. This will only succeed,
# if `value` stored in database is equal to `last_value`.
# value: The expected last_value to decrement
def reset(value)
return false unless value
updated =
InternalId
.where(**scope, usage: usage_value)
.where(last_value: value)
.update_all('last_value = last_value - 1')
updated > 0
end
# Create a record in internal_ids if one does not yet exist
# and set its new_value if it is higher than the current last_value
#
# Note this will acquire a ROW SHARE lock on the InternalId record
def track_greatest(init, new_value)
subject.transaction do
(lookup || create_record(init)).track_greatest_and_save!(new_value)
end
end
private
# Retrieve InternalId record for (project, usage) combination, if it exists
def lookup
InternalId.find_by(**scope, usage: usage_value)
end
def usage_value
@usage_value ||= InternalId.usages[usage.to_s]
end
# Create InternalId record for (scope, usage) combination, if it doesn't exist
#
# We blindly insert without synchronization. If another process
# was faster in doing this, we'll realize once we hit the unique key constraint
# violation. We can safely roll-back the nested transaction and perform
# a lookup instead to retrieve the record.
def create_record(init)
subject.transaction(requires_new: true) do
InternalId.create!(
**scope,
usage: usage_value,
last_value: init.call(subject) || 0
)
end
rescue ActiveRecord::RecordNotUnique
lookup
end
end
end
| iiet/iiet-git | app/models/internal_id.rb | Ruby | mit | 6,777 |
RSpec.describe Unidom::Certificate::China::IdentificationNumberValidator, type: :validator do
valid_values = %w{
231024198506186916
231024198506188110
231024198506185470
231024198506182851
231024198506187193
}
invalid_values = %w{
231024198506186917
231024198506188111
231024198506185471
231024198506182852
231024198506187194
}
it_behaves_like 'ActiveModel::EachValidator', valid_values, invalid_values
end
| topbitdu/unidom-certificate-china | lib/rspec/validators/unidom/certificate/china/identification_number_validator_spec.rb | Ruby | mit | 484 |
using OpenQA.Selenium;
namespace Vzhzhzh.SeleniumWrapper.Examples.Proprietary.Pages.Operator.Shared
{
public abstract class SubForm : PageElement
{
protected SubForm(DriverHolder driver)
: base(driver)
{
}
public virtual IWebElement SaveButton
{
get { return Driver.Find(ByNg.Click("saveAndShowNextPart")); }
}
public abstract void Clear();
public abstract bool IsOpened();
public void Fill()
{
Clear();
FillFields();
}
public virtual void Refill()
{
Clear();
FillFields();
}
protected abstract void FillFields();
public virtual void Save()
{
SaveButton.SendKeys(Keys.Enter);
}
}
} | vzhzhzh/Vzhzhzh.SeleniumWrapper | Vzhzhzh.SeleniumWrapper.Examples/Proprietary/Pages/Operator/Shared/SubForm.cs | C# | mit | 829 |
package edu.harvard.fas.rbrady.tpteam.tpbridge.hibernate;
// Generated Nov 10, 2006 5:22:58 PM by Hibernate Tools 3.2.0.beta8
import java.util.HashSet;
import java.util.Set;
/**
* TestType generated by hbm2java
*/
public class TestType implements java.io.Serializable {
// Fields
private static final long serialVersionUID = 1L;
private int id;
private String name;
private Set<Test> tests = new HashSet<Test>(0);
// Constructors
/** default constructor */
public TestType() {
}
/** minimal constructor */
public TestType(int id) {
this.id = id;
}
/** full constructor */
public TestType(int id, String name, Set<Test> tests) {
this.id = id;
this.name = name;
this.tests = tests;
}
// Property accessors
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Set<Test> getTests() {
return this.tests;
}
public void setTests(Set<Test> tests) {
this.tests = tests;
}
}
| bobbrady/tpteam | tpbridge/src/edu/harvard/fas/rbrady/tpteam/tpbridge/hibernate/TestType.java | Java | mit | 1,142 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class Destination(Model):
"""Capture storage details for capture description.
:param name: Name for capture destination
:type name: str
:param storage_account_resource_id: Resource id of the storage account to
be used to create the blobs
:type storage_account_resource_id: str
:param blob_container: Blob container Name
:type blob_container: str
:param archive_name_format: Blob naming convention for archive, e.g.
{Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}.
Here all the parameters (Namespace,EventHub .. etc) are mandatory
irrespective of order
:type archive_name_format: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'storage_account_resource_id': {'key': 'properties.storageAccountResourceId', 'type': 'str'},
'blob_container': {'key': 'properties.blobContainer', 'type': 'str'},
'archive_name_format': {'key': 'properties.archiveNameFormat', 'type': 'str'},
}
def __init__(self, name=None, storage_account_resource_id=None, blob_container=None, archive_name_format=None):
self.name = name
self.storage_account_resource_id = storage_account_resource_id
self.blob_container = blob_container
self.archive_name_format = archive_name_format
| AutorestCI/azure-sdk-for-python | azure-mgmt-servicebus/azure/mgmt/servicebus/models/destination.py | Python | mit | 1,856 |
<?php
// Add new input type "border width"
if ( function_exists('smile_add_input_type'))
{
smile_add_input_type('margin' , 'margin_settings_field' );
}
add_action( 'admin_enqueue_scripts', 'enqueue_margin_param_scripts' );
function enqueue_margin_param_scripts( $hook ){
$cp_page = strpos( $hook, 'plug_page');
$data = get_option( 'convert_plug_debug' );
if( $cp_page == 7 && isset( $_GET['style-view'] ) && $_GET['style-view'] == "edit" ){
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'jquery-ui-core' );
wp_enqueue_script( 'margin-script', plugins_url( 'js/margin.js', __FILE__ ), array('jquery') );
wp_enqueue_style( 'jquery-ui' );
if( isset( $data['cp-dev-mode'] ) && $data['cp-dev-mode'] == '1' ) {
wp_enqueue_style( 'margin-style', plugins_url( 'css/margin.css', __FILE__ ) );
}
}
}
/**
* Function to handle new input type "border width"
*
* @param $settings - settings provided when using the input type "border"
* @param $value - holds the default / updated value
* @return string/html - html output generated by the function
*/
function margin_settings_field($name, $settings, $value)
{
$input_name = $name;
$type = isset($settings['type']) ? $settings['type'] : '';
$class = isset($settings['class']) ? $settings['class'] : '';
$output = '<p><textarea id="margin-code" class="content form-control smile-input smile-'.$type.' '.$input_name.' '.$type.' '.$class.'" name="' . $input_name . '" rows="6" cols="6">'.$value.'</textarea></p>';
$pairs = explode("|", $value );
$settings = array();
if( is_array( $pairs ) && !empty( $pairs ) && count( $pairs ) > 1 ) {
foreach( $pairs as $pair ){
$values = explode(":", $pair);
$settings[$values[0]] = $values[1];
}
}
$all_sides = isset( $settings['all_sides'] ) ? $settings['all_sides'] : 1;
$top = isset( $settings['top'] ) ? $settings['top'] : 1;
$left = isset( $settings['left'] ) ? $settings['left'] : 1;
$right = isset( $settings['right'] ) ? $settings['right'] : 1;
$bottom = isset( $settings['bottom'] ) ? $settings['bottom'] : 1;
ob_start();
echo $output;
?>
<div class="box">
<div class="holder">
<div class="frame">
<div class="setting-block all-sides">
<div class="row">
<label for="margin"><?php _e( "All Sides", "smile" ); ?></label>
<label class="align-right" for="margin-all_sides">px</label>
<div class="text-1">
<input id="margin-all_sides" type="text" value="<?php echo $all_sides; ?>">
</div>
</div>
<div id="slider-margin-all_sides" class="slider-bar large ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all"><a class="ui-slider-handle ui-state-default ui-corner-all" href="#" style="left: 0%;"></a><span class="range-quantity" ></span></div>
</div>
<div class="setting-block">
<div class="row">
<label for="top"><?php _e( "Top", "smile" ); ?></label>
<label class="align-right" for="top">px</label>
<div class="text-1">
<input id="margin-top" type="text" value="<?php echo $top; ?>">
</div>
</div>
<div id="slider-margin-top" class="slider-bar large ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all"><a class="ui-slider-handle ui-state-default ui-corner-all" href="#"></a><span class="range-quantity" ></span></div>
<div class="row mtop15">
<label for="margin-left"><?php _e( "Left", "smile" ); ?></label>
<label class="align-right" for="left">px</label>
<div class="text-1">
<input id="margin-left" type="text" value="<?php echo $left; ?>">
</div>
</div>
<div id="slider-margin-left" class="slider-bar large ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all"><a class="ui-slider-handle ui-state-default ui-corner-all" href="#"></a><span class="range-quantity" ></span></div>
<div class="row mtop15">
<label for="right"><?php _e( "Right", "smile" ); ?></label>
<label class="align-right" for="right">px</label>
<div class="text-1">
<input id="margin-right" type="text" value="<?php echo $right; ?>">
</div>
</div>
<div id="slider-margin-right" class="slider-bar large ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all"><a class="ui-slider-handle ui-state-default ui-corner-all" href="#"></a><span class="range-quantity" ></span></div>
<div class="row mtop15">
<label for="bottom"><?php _e( "Bottom", "smile" ); ?></label>
<label class="align-right" for="bottom">px</label>
<div class="text-1">
<input id="margin-bottom" type="text" value="<?php echo $bottom; ?>">
</div>
</div>
<div id="slider-margin-bottom" class="slider-bar large ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all"><a class="ui-slider-handle ui-state-default ui-corner-all" href="#"></a><span class="range-quantity" ></span></div>
</div>
</div>
</div>
</div>
<?php
return ob_get_clean();
} | 20steps/alexa | web/wp-content/plugins/framework/lib/fields/margin/margin.php | PHP | mit | 5,319 |
/**
* interact.js v1.1.2
*
* Copyright (c) 2012, 2013, 2014 Taye Adeyemi <dev@taye.me>
* Open source under the MIT License.
* https://raw.github.com/taye/interact.js/master/LICENSE
*/
(function () {
'use strict';
var document = window.document,
SVGElement = window.SVGElement || blank,
SVGSVGElement = window.SVGSVGElement || blank,
SVGElementInstance = window.SVGElementInstance || blank,
HTMLElement = window.HTMLElement || window.Element,
PointerEvent = (window.PointerEvent || window.MSPointerEvent),
pEventTypes,
hypot = Math.hypot || function (x, y) { return Math.sqrt(x * x + y * y); },
tmpXY = {}, // reduce object creation in getXY()
documents = [], // all documents being listened to
interactables = [], // all set interactables
interactions = [], // all interactions
dynamicDrop = false,
// {
// type: {
// selectors: ['selector', ...],
// contexts : [document, ...],
// listeners: [[listener, useCapture], ...]
// }
// }
delegatedEvents = {},
defaultOptions = {
draggable : false,
dragAxis : 'xy',
dropzone : false,
accept : null,
dropOverlap : 'pointer',
resizable : false,
squareResize: false,
resizeAxis : 'xy',
gesturable : false,
// no more than this number of actions can target the Interactable
dragMax : 1,
resizeMax : 1,
gestureMax: 1,
// no more than this number of actions can target the same
// element of this Interactable simultaneously
dragMaxPerElement : 1,
resizeMaxPerElement : 1,
gestureMaxPerElement: 1,
pointerMoveTolerance: 1,
actionChecker: null,
styleCursor: true,
preventDefault: 'auto',
// aww snap
snap: {
mode : 'grid',
endOnly : false,
actions : ['drag'],
range : Infinity,
grid : { x: 100, y: 100 },
gridOffset : { x: 0, y: 0 },
anchors : [],
paths : [],
elementOrigin: null,
arrayTypes : /^anchors$|^paths$|^actions$/,
objectTypes : /^grid$|^gridOffset$|^elementOrigin$/,
stringTypes : /^mode$/,
numberTypes : /^range$/,
boolTypes : /^endOnly$/
},
snapEnabled: false,
restrict: {
drag: null,
resize: null,
gesture: null,
endOnly: false
},
restrictEnabled: false,
autoScroll: {
container : null, // the item that is scrolled (Window or HTMLElement)
margin : 60,
speed : 300, // the scroll speed in pixels per second
numberTypes : /^margin$|^speed$/
},
autoScrollEnabled: false,
inertia: {
resistance : 10, // the lambda in exponential decay
minSpeed : 100, // target speed must be above this for inertia to start
endSpeed : 10, // the speed at which inertia is slow enough to stop
allowResume : true, // allow resuming an action in inertia phase
zeroResumeDelta : false, // if an action is resumed after launch, set dx/dy to 0
smoothEndDuration: 300, // animate to snap/restrict endOnly if there's no inertia
actions : ['drag', 'resize'], // allow inertia on these actions. gesture might not work
numberTypes: /^resistance$|^minSpeed$|^endSpeed$|^smoothEndDuration$/,
arrayTypes : /^actions$/,
boolTypes : /^(allowResume|zeroResumeDelta)$/
},
inertiaEnabled: false,
origin : { x: 0, y: 0 },
deltaSource : 'page',
},
// Things related to autoScroll
autoScroll = {
interaction: null,
i: null, // the handle returned by window.setInterval
x: 0, y: 0, // Direction each pulse is to scroll in
// scroll the window by the values in scroll.x/y
scroll: function () {
var options = autoScroll.interaction.target.options.autoScroll,
container = options.container || getWindow(autoScroll.interaction.element),
now = new Date().getTime(),
// change in time in seconds
dt = (now - autoScroll.prevTime) / 1000,
// displacement
s = options.speed * dt;
if (s >= 1) {
if (isWindow(container)) {
container.scrollBy(autoScroll.x * s, autoScroll.y * s);
}
else if (container) {
container.scrollLeft += autoScroll.x * s;
container.scrollTop += autoScroll.y * s;
}
autoScroll.prevTime = now;
}
if (autoScroll.isScrolling) {
cancelFrame(autoScroll.i);
autoScroll.i = reqFrame(autoScroll.scroll);
}
},
edgeMove: function (event) {
var interaction,
target,
doAutoscroll = false;
for (var i = 0; i < interactions.length; i++) {
interaction = interactions[i];
target = interaction.target;
if (target && target.options.autoScrollEnabled
&& (interaction.dragging || interaction.resizing)) {
doAutoscroll = true;
break;
}
}
if (!doAutoscroll) { return; }
var top,
right,
bottom,
left,
options = target.options.autoScroll,
container = options.container || getWindow(interaction.element);
if (isWindow(container)) {
left = event.clientX < autoScroll.margin;
top = event.clientY < autoScroll.margin;
right = event.clientX > container.innerWidth - autoScroll.margin;
bottom = event.clientY > container.innerHeight - autoScroll.margin;
}
else {
var rect = getElementRect(container);
left = event.clientX < rect.left + autoScroll.margin;
top = event.clientY < rect.top + autoScroll.margin;
right = event.clientX > rect.right - autoScroll.margin;
bottom = event.clientY > rect.bottom - autoScroll.margin;
}
autoScroll.x = (right ? 1: left? -1: 0);
autoScroll.y = (bottom? 1: top? -1: 0);
if (!autoScroll.isScrolling) {
// set the autoScroll properties to those of the target
autoScroll.margin = options.margin;
autoScroll.speed = options.speed;
autoScroll.start(interaction);
}
},
isScrolling: false,
prevTime: 0,
start: function (interaction) {
autoScroll.isScrolling = true;
cancelFrame(autoScroll.i);
autoScroll.interaction = interaction;
autoScroll.prevTime = new Date().getTime();
autoScroll.i = reqFrame(autoScroll.scroll);
},
stop: function () {
autoScroll.isScrolling = false;
cancelFrame(autoScroll.i);
}
},
// Does the browser support touch input?
supportsTouch = (('ontouchstart' in window) || window.DocumentTouch && document instanceof window.DocumentTouch),
// Does the browser support PointerEvents
supportsPointerEvent = !!PointerEvent,
// Less Precision with touch input
margin = supportsTouch || supportsPointerEvent? 20: 10,
// for ignoring browser's simulated mouse events
prevTouchTime = 0,
// Allow this many interactions to happen simultaneously
maxInteractions = 1,
actionCursors = {
drag : 'move',
resizex : 'e-resize',
resizey : 's-resize',
resizexy: 'se-resize',
gesture : ''
},
actionIsEnabled = {
drag : true,
resize : true,
gesture: true
},
// because Webkit and Opera still use 'mousewheel' event type
wheelEvent = 'onmousewheel' in document? 'mousewheel': 'wheel',
eventTypes = [
'dragstart',
'dragmove',
'draginertiastart',
'dragend',
'dragenter',
'dragleave',
'dropactivate',
'dropdeactivate',
'dropmove',
'drop',
'resizestart',
'resizemove',
'resizeinertiastart',
'resizeend',
'gesturestart',
'gesturemove',
'gestureinertiastart',
'gestureend',
'down',
'move',
'up',
'cancel',
'tap',
'doubletap',
'hold'
],
globalEvents = {},
// Opera Mobile must be handled differently
isOperaMobile = navigator.appName == 'Opera' &&
supportsTouch &&
navigator.userAgent.match('Presto'),
// scrolling doesn't change the result of
// getBoundingClientRect/getClientRects on iOS <=7 but it does on iOS 8
isIOS7orLower = (/iP(hone|od|ad)/.test(navigator.platform)
&& /OS [1-7][^\d]/.test(navigator.appVersion)),
// prefix matchesSelector
prefixedMatchesSelector = 'matchesSelector' in Element.prototype?
'matchesSelector': 'webkitMatchesSelector' in Element.prototype?
'webkitMatchesSelector': 'mozMatchesSelector' in Element.prototype?
'mozMatchesSelector': 'oMatchesSelector' in Element.prototype?
'oMatchesSelector': 'msMatchesSelector',
// will be polyfill function if browser is IE8
ie8MatchesSelector,
// native requestAnimationFrame or polyfill
reqFrame = window.requestAnimationFrame,
cancelFrame = window.cancelAnimationFrame,
// Events wrapper
events = (function () {
var useAttachEvent = ('attachEvent' in window) && !('addEventListener' in window),
addEvent = useAttachEvent? 'attachEvent': 'addEventListener',
removeEvent = useAttachEvent? 'detachEvent': 'removeEventListener',
on = useAttachEvent? 'on': '',
elements = [],
targets = [],
attachedListeners = [];
function add (element, type, listener, useCapture) {
var elementIndex = indexOf(elements, element),
target = targets[elementIndex];
if (!target) {
target = {
events: {},
typeCount: 0
};
elementIndex = elements.push(element) - 1;
targets.push(target);
attachedListeners.push((useAttachEvent ? {
supplied: [],
wrapped : [],
useCount: []
} : null));
}
if (!target.events[type]) {
target.events[type] = [];
target.typeCount++;
}
if (!contains(target.events[type], listener)) {
var ret;
if (useAttachEvent) {
var listeners = attachedListeners[elementIndex],
listenerIndex = indexOf(listeners.supplied, listener);
var wrapped = listeners.wrapped[listenerIndex] || function (event) {
if (!event.immediatePropagationStopped) {
event.target = event.srcElement;
event.currentTarget = element;
event.preventDefault = event.preventDefault || preventDef;
event.stopPropagation = event.stopPropagation || stopProp;
event.stopImmediatePropagation = event.stopImmediatePropagation || stopImmProp;
if (/mouse|click/.test(event.type)) {
event.pageX = event.clientX + element.ownerDdocument.documentElement.scrollLeft;
event.pageY = event.clientY + element.ownerDdocument.documentElement.scrollTop;
}
listener(event);
}
};
ret = element[addEvent](on + type, wrapped, Boolean(useCapture));
if (listenerIndex === -1) {
listeners.supplied.push(listener);
listeners.wrapped.push(wrapped);
listeners.useCount.push(1);
}
else {
listeners.useCount[listenerIndex]++;
}
}
else {
ret = element[addEvent](type, listener, useCapture || false);
}
target.events[type].push(listener);
return ret;
}
}
function remove (element, type, listener, useCapture) {
var i,
elementIndex = indexOf(elements, element),
target = targets[elementIndex],
listeners,
listenerIndex,
wrapped = listener;
if (!target || !target.events) {
return;
}
if (useAttachEvent) {
listeners = attachedListeners[elementIndex];
listenerIndex = indexOf(listeners.supplied, listener);
wrapped = listeners.wrapped[listenerIndex];
}
if (type === 'all') {
for (type in target.events) {
if (target.events.hasOwnProperty(type)) {
remove(element, type, 'all');
}
}
return;
}
if (target.events[type]) {
var len = target.events[type].length;
if (listener === 'all') {
for (i = 0; i < len; i++) {
remove(element, type, target.events[type][i], Boolean(useCapture));
}
} else {
for (i = 0; i < len; i++) {
if (target.events[type][i] === listener) {
element[removeEvent](on + type, wrapped, useCapture || false);
target.events[type].splice(i, 1);
if (useAttachEvent && listeners) {
listeners.useCount[listenerIndex]--;
if (listeners.useCount[listenerIndex] === 0) {
listeners.supplied.splice(listenerIndex, 1);
listeners.wrapped.splice(listenerIndex, 1);
listeners.useCount.splice(listenerIndex, 1);
}
}
break;
}
}
}
if (target.events[type] && target.events[type].length === 0) {
target.events[type] = null;
target.typeCount--;
}
}
if (!target.typeCount) {
targets.splice(elementIndex);
elements.splice(elementIndex);
attachedListeners.splice(elementIndex);
}
}
function preventDef () {
this.returnValue = false;
}
function stopProp () {
this.cancelBubble = true;
}
function stopImmProp () {
this.cancelBubble = true;
this.immediatePropagationStopped = true;
}
return {
add: add,
remove: remove,
useAttachEvent: useAttachEvent,
_elements: elements,
_targets: targets,
_attachedListeners: attachedListeners
};
}());
function blank () {}
function isElement (o) {
if (!o || (typeof o !== 'object')) { return false; }
var _window = getWindow(o) || window;
return (/object|function/.test(typeof _window.Element)
? o instanceof _window.Element //DOM2
: o.nodeType === 1 && typeof o.nodeName === "string");
}
function isWindow (thing) { return !!(thing && thing.Window) && (thing instanceof thing.Window); }
function isArray (thing) {
return isObject(thing)
&& (typeof thing.length !== undefined)
&& isFunction(thing.splice);
}
function isObject (thing) { return !!thing && (typeof thing === 'object'); }
function isFunction (thing) { return typeof thing === 'function'; }
function isNumber (thing) { return typeof thing === 'number' ; }
function isBool (thing) { return typeof thing === 'boolean' ; }
function isString (thing) { return typeof thing === 'string' ; }
function trySelector (value) {
if (!isString(value)) { return false; }
// an exception will be raised if it is invalid
document.querySelector(value);
return true;
}
function extend (dest, source) {
for (var prop in source) {
dest[prop] = source[prop];
}
return dest;
}
function copyCoords (dest, src) {
dest.page = dest.page || {};
dest.page.x = src.page.x;
dest.page.y = src.page.y;
dest.client = dest.client || {};
dest.client.x = src.client.x;
dest.client.y = src.client.y;
dest.timeStamp = src.timeStamp;
}
function setEventXY (targetObj, pointer, interaction) {
if (!pointer) {
if (interaction.pointerIds.length > 1) {
pointer = touchAverage(interaction.pointers);
}
else {
pointer = interaction.pointers[0];
}
}
getPageXY(pointer, tmpXY, interaction);
targetObj.page.x = tmpXY.x;
targetObj.page.y = tmpXY.y;
getClientXY(pointer, tmpXY, interaction);
targetObj.client.x = tmpXY.x;
targetObj.client.y = tmpXY.y;
targetObj.timeStamp = new Date().getTime();
}
function setEventDeltas (targetObj, prev, cur) {
targetObj.page.x = cur.page.x - prev.page.x;
targetObj.page.y = cur.page.y - prev.page.y;
targetObj.client.x = cur.client.x - prev.client.x;
targetObj.client.y = cur.client.y - prev.client.y;
targetObj.timeStamp = new Date().getTime() - prev.timeStamp;
// set pointer velocity
var dt = Math.max(targetObj.timeStamp / 1000, 0.001);
targetObj.page.speed = hypot(targetObj.page.x, targetObj.page.y) / dt;
targetObj.page.vx = targetObj.page.x / dt;
targetObj.page.vy = targetObj.page.y / dt;
targetObj.client.speed = hypot(targetObj.client.x, targetObj.page.y) / dt;
targetObj.client.vx = targetObj.client.x / dt;
targetObj.client.vy = targetObj.client.y / dt;
}
// Get specified X/Y coords for mouse or event.touches[0]
function getXY (type, pointer, xy) {
xy = xy || {};
type = type || 'page';
xy.x = pointer[type + 'X'];
xy.y = pointer[type + 'Y'];
return xy;
}
function getPageXY (pointer, page, interaction) {
page = page || {};
if (pointer instanceof InteractEvent) {
if (/inertiastart/.test(pointer.type)) {
interaction = interaction || pointer.interaction;
extend(page, interaction.inertiaStatus.upCoords.page);
page.x += interaction.inertiaStatus.sx;
page.y += interaction.inertiaStatus.sy;
}
else {
page.x = pointer.pageX;
page.y = pointer.pageY;
}
}
// Opera Mobile handles the viewport and scrolling oddly
else if (isOperaMobile) {
getXY('screen', pointer, page);
page.x += window.scrollX;
page.y += window.scrollY;
}
else {
getXY('page', pointer, page);
}
return page;
}
function getClientXY (pointer, client, interaction) {
client = client || {};
if (pointer instanceof InteractEvent) {
if (/inertiastart/.test(pointer.type)) {
extend(client, interaction.inertiaStatus.upCoords.client);
client.x += interaction.inertiaStatus.sx;
client.y += interaction.inertiaStatus.sy;
}
else {
client.x = pointer.clientX;
client.y = pointer.clientY;
}
}
else {
// Opera Mobile handles the viewport and scrolling oddly
getXY(isOperaMobile? 'screen': 'client', pointer, client);
}
return client;
}
function getScrollXY (win) {
win = win || window;
return {
x: win.scrollX || win.document.documentElement.scrollLeft,
y: win.scrollY || win.document.documentElement.scrollTop
};
}
function getPointerId (pointer) {
return isNumber(pointer.pointerId)? pointer.pointerId : pointer.identifier;
}
function getActualElement (element) {
return (element instanceof SVGElementInstance
? element.correspondingUseElement
: element);
}
function getWindow (node) {
if (isWindow(node)) {
return node;
}
var rootNode = (node.ownerDocument || node);
return rootNode.defaultView || rootNode.parentWindow;
}
function getElementRect (element) {
var scroll = isIOS7orLower
? { x: 0, y: 0 }
: getScrollXY(getWindow(element)),
clientRect = (element instanceof SVGElement)?
element.getBoundingClientRect():
element.getClientRects()[0];
return clientRect && {
left : clientRect.left + scroll.x,
right : clientRect.right + scroll.x,
top : clientRect.top + scroll.y,
bottom: clientRect.bottom + scroll.y,
width : clientRect.width || clientRect.right - clientRect.left,
height: clientRect.heigh || clientRect.bottom - clientRect.top
};
}
function getTouchPair (event) {
var touches = [];
// array of touches is supplied
if (isArray(event)) {
touches[0] = event[0];
touches[1] = event[1];
}
// an event
else {
if (event.type === 'touchend') {
if (event.touches.length === 1) {
touches[0] = event.touches[0];
touches[1] = event.changedTouches[0];
}
else if (event.touches.length === 0) {
touches[0] = event.changedTouches[0];
touches[1] = event.changedTouches[1];
}
}
else {
touches[0] = event.touches[0];
touches[1] = event.touches[1];
}
}
return touches;
}
function touchAverage (event) {
var touches = getTouchPair(event);
return {
pageX: (touches[0].pageX + touches[1].pageX) / 2,
pageY: (touches[0].pageY + touches[1].pageY) / 2,
clientX: (touches[0].clientX + touches[1].clientX) / 2,
clientY: (touches[0].clientY + touches[1].clientY) / 2
};
}
function touchBBox (event) {
if (!event.length && !(event.touches && event.touches.length > 1)) {
return;
}
var touches = getTouchPair(event),
minX = Math.min(touches[0].pageX, touches[1].pageX),
minY = Math.min(touches[0].pageY, touches[1].pageY),
maxX = Math.max(touches[0].pageX, touches[1].pageX),
maxY = Math.max(touches[0].pageY, touches[1].pageY);
return {
x: minX,
y: minY,
left: minX,
top: minY,
width: maxX - minX,
height: maxY - minY
};
}
function touchDistance (event, deltaSource) {
deltaSource = deltaSource || defaultOptions.deltaSource;
var sourceX = deltaSource + 'X',
sourceY = deltaSource + 'Y',
touches = getTouchPair(event);
var dx = touches[0][sourceX] - touches[1][sourceX],
dy = touches[0][sourceY] - touches[1][sourceY];
return hypot(dx, dy);
}
function touchAngle (event, prevAngle, deltaSource) {
deltaSource = deltaSource || defaultOptions.deltaSource;
var sourceX = deltaSource + 'X',
sourceY = deltaSource + 'Y',
touches = getTouchPair(event),
dx = touches[0][sourceX] - touches[1][sourceX],
dy = touches[0][sourceY] - touches[1][sourceY],
angle = 180 * Math.atan(dy / dx) / Math.PI;
if (isNumber(prevAngle)) {
var dr = angle - prevAngle,
drClamped = dr % 360;
if (drClamped > 315) {
angle -= 360 + (angle / 360)|0 * 360;
}
else if (drClamped > 135) {
angle -= 180 + (angle / 360)|0 * 360;
}
else if (drClamped < -315) {
angle += 360 + (angle / 360)|0 * 360;
}
else if (drClamped < -135) {
angle += 180 + (angle / 360)|0 * 360;
}
}
return angle;
}
function getOriginXY (interactable, element) {
var origin = interactable
? interactable.options.origin
: defaultOptions.origin;
if (origin === 'parent') {
origin = element.parentNode;
}
else if (origin === 'self') {
origin = interactable.getRect(element);
}
else if (trySelector(origin)) {
origin = closest(element, origin) || { x: 0, y: 0 };
}
if (isFunction(origin)) {
origin = origin(interactable && element);
}
if (isElement(origin)) {
origin = getElementRect(origin);
}
origin.x = ('x' in origin)? origin.x : origin.left;
origin.y = ('y' in origin)? origin.y : origin.top;
return origin;
}
// http://stackoverflow.com/a/5634528/2280888
function _getQBezierValue(t, p1, p2, p3) {
var iT = 1 - t;
return iT * iT * p1 + 2 * iT * t * p2 + t * t * p3;
}
function getQuadraticCurvePoint(startX, startY, cpX, cpY, endX, endY, position) {
return {
x: _getQBezierValue(position, startX, cpX, endX),
y: _getQBezierValue(position, startY, cpY, endY)
};
}
// http://gizma.com/easing/
function easeOutQuad (t, b, c, d) {
t /= d;
return -c * t*(t-2) + b;
}
function nodeContains (parent, child) {
while ((child = child.parentNode)) {
if (child === parent) {
return true;
}
}
return false;
}
function closest (child, selector) {
var parent = child.parentNode;
while (isElement(parent)) {
if (matchesSelector(parent, selector)) { return parent; }
parent = parent.parentNode;
}
return null;
}
function inContext (interactable, element) {
return interactable._context === element.ownerDocument
|| nodeContains(interactable._context, element);
}
function testIgnore (interactable, interactableElement, element) {
var ignoreFrom = interactable.options.ignoreFrom;
if (!ignoreFrom
// limit test to the interactable's element and its children
|| !isElement(element) || element === interactableElement.parentNode) {
return false;
}
if (isString(ignoreFrom)) {
return matchesSelector(element, ignoreFrom) || testIgnore(interactable, element.parentNode);
}
else if (isElement(ignoreFrom)) {
return element === ignoreFrom || nodeContains(ignoreFrom, element);
}
return false;
}
function testAllow (interactable, interactableElement, element) {
var allowFrom = interactable.options.allowFrom;
if (!allowFrom) { return true; }
// limit test to the interactable's element and its children
if (!isElement(element) || element === interactableElement.parentNode) {
return false;
}
if (isString(allowFrom)) {
return matchesSelector(element, allowFrom) || testAllow(interactable, element.parentNode);
}
else if (isElement(allowFrom)) {
return element === allowFrom || nodeContains(allowFrom, element);
}
return false;
}
function checkAxis (axis, interactable) {
if (!interactable) { return false; }
var thisAxis = interactable.options.dragAxis;
return (axis === 'xy' || thisAxis === 'xy' || thisAxis === axis);
}
function checkSnap (interactable, action) {
var options = interactable.options;
if (/^resize/.test(action)) {
action = 'resize';
}
return action !== 'gesture' && options.snapEnabled && contains(options.snap.actions, action);
}
function checkRestrict (interactable, action) {
var options = interactable.options;
if (/^resize/.test(action)) {
action = 'resize';
}
return options.restrictEnabled && options.restrict[action];
}
function withinInteractionLimit (interactable, element, action) {
action = /resize/.test(action)? 'resize': action;
var options = interactable.options,
maxActions = options[action + 'Max'],
maxPerElement = options[action + 'MaxPerElement'],
activeInteractions = 0,
targetCount = 0,
targetElementCount = 0;
for (var i = 0, len = interactions.length; i < len; i++) {
var interaction = interactions[i],
otherAction = /resize/.test(interaction.prepared)? 'resize': interaction.prepared,
active = interaction.interacting();
if (!active) { continue; }
activeInteractions++;
if (activeInteractions >= maxInteractions) {
return false;
}
if (interaction.target !== interactable) { continue; }
targetCount += (otherAction === action)|0;
if (targetCount >= maxActions) {
return false;
}
if (interaction.element === element) {
targetElementCount++;
if (otherAction !== action || targetElementCount >= maxPerElement) {
return false;
}
}
}
return maxInteractions > 0;
}
// Test for the element that's "above" all other qualifiers
function indexOfDeepestElement (elements) {
var dropzone,
deepestZone = elements[0],
index = deepestZone? 0: -1,
parent,
deepestZoneParents = [],
dropzoneParents = [],
child,
i,
n;
for (i = 1; i < elements.length; i++) {
dropzone = elements[i];
// an element might belong to multiple selector dropzones
if (!dropzone || dropzone === deepestZone) {
continue;
}
if (!deepestZone) {
deepestZone = dropzone;
index = i;
continue;
}
// check if the deepest or current are document.documentElement or document.rootElement
// - if the current dropzone is, do nothing and continue
if (dropzone.parentNode === dropzone.ownerDocument) {
continue;
}
// - if deepest is, update with the current dropzone and continue to next
else if (deepestZone.parentNode === dropzone.ownerDocument) {
deepestZone = dropzone;
index = i;
continue;
}
if (!deepestZoneParents.length) {
parent = deepestZone;
while (parent.parentNode && parent.parentNode !== parent.ownerDocument) {
deepestZoneParents.unshift(parent);
parent = parent.parentNode;
}
}
// if this element is an svg element and the current deepest is
// an HTMLElement
if (deepestZone instanceof HTMLElement
&& dropzone instanceof SVGElement
&& !(dropzone instanceof SVGSVGElement)) {
if (dropzone === deepestZone.parentNode) {
continue;
}
parent = dropzone.ownerSVGElement;
}
else {
parent = dropzone;
}
dropzoneParents = [];
while (parent.parentNode !== parent.ownerDocument) {
dropzoneParents.unshift(parent);
parent = parent.parentNode;
}
n = 0;
// get (position of last common ancestor) + 1
while (dropzoneParents[n] && dropzoneParents[n] === deepestZoneParents[n]) {
n++;
}
var parents = [
dropzoneParents[n - 1],
dropzoneParents[n],
deepestZoneParents[n]
];
child = parents[0].lastChild;
while (child) {
if (child === parents[1]) {
deepestZone = dropzone;
index = i;
deepestZoneParents = [];
break;
}
else if (child === parents[2]) {
break;
}
child = child.previousSibling;
}
}
return index;
}
function Interaction () {
this.target = null; // current interactable being interacted with
this.element = null; // the target element of the interactable
this.dropTarget = null; // the dropzone a drag target might be dropped into
this.dropElement = null; // the element at the time of checking
this.prevDropTarget = null; // the dropzone that was recently dragged away from
this.prevDropElement = null; // the element at the time of checking
this.prepared = null; // Action that's ready to be fired on next move event
this.matches = []; // all selectors that are matched by target element
this.matchElements = []; // corresponding elements
this.inertiaStatus = {
active : false,
smoothEnd : false,
startEvent: null,
upCoords: {},
xe: 0, ye: 0,
sx: 0, sy: 0,
t0: 0,
vx0: 0, vys: 0,
duration: 0,
resumeDx: 0,
resumeDy: 0,
lambda_v0: 0,
one_ve_v0: 0,
i : null
};
if (isFunction(Function.prototype.bind)) {
this.boundInertiaFrame = this.inertiaFrame.bind(this);
this.boundSmoothEndFrame = this.smoothEndFrame.bind(this);
}
else {
var that = this;
this.boundInertiaFrame = function () { return that.inertiaFrame(); };
this.boundSmoothEndFrame = function () { return that.smoothEndFrame(); };
}
this.activeDrops = {
dropzones: [], // the dropzones that are mentioned below
elements : [], // elements of dropzones that accept the target draggable
rects : [] // the rects of the elements mentioned above
};
// keep track of added pointers
this.pointers = [];
this.pointerIds = [];
this.downTargets = [];
this.downTimes = [];
this.holdTimers = [];
// Previous native pointer move event coordinates
this.prevCoords = {
page : { x: 0, y: 0 },
client : { x: 0, y: 0 },
timeStamp: 0
};
// current native pointer move event coordinates
this.curCoords = {
page : { x: 0, y: 0 },
client : { x: 0, y: 0 },
timeStamp: 0
};
// Starting InteractEvent pointer coordinates
this.startCoords = {
page : { x: 0, y: 0 },
client : { x: 0, y: 0 },
timeStamp: 0
};
// Change in coordinates and time of the pointer
this.pointerDelta = {
page : { x: 0, y: 0, vx: 0, vy: 0, speed: 0 },
client : { x: 0, y: 0, vx: 0, vy: 0, speed: 0 },
timeStamp: 0
};
this.downEvent = null; // pointerdown/mousedown/touchstart event
this.downPointer = {};
this.prevEvent = null; // previous action event
this.tapTime = 0; // time of the most recent tap event
this.prevTap = null;
this.startOffset = { left: 0, right: 0, top: 0, bottom: 0 };
this.restrictOffset = { left: 0, right: 0, top: 0, bottom: 0 };
this.snapOffset = { x: 0, y: 0};
this.gesture = {
start: { x: 0, y: 0 },
startDistance: 0, // distance between two touches of touchStart
prevDistance : 0,
distance : 0,
scale: 1, // gesture.distance / gesture.startDistance
startAngle: 0, // angle of line joining two touches
prevAngle : 0 // angle of the previous gesture event
};
this.snapStatus = {
x : 0, y : 0,
dx : 0, dy : 0,
realX : 0, realY : 0,
snappedX: 0, snappedY: 0,
anchors : [],
paths : [],
locked : false,
changed : false
};
this.restrictStatus = {
dx : 0, dy : 0,
restrictedX: 0, restrictedY: 0,
snap : null,
restricted : false,
changed : false
};
this.restrictStatus.snap = this.snapStatus;
this.pointerIsDown = false;
this.pointerWasMoved = false;
this.gesturing = false;
this.dragging = false;
this.resizing = false;
this.resizeAxes = 'xy';
this.mouse = false;
interactions.push(this);
}
Interaction.prototype = {
getPageXY : function (pointer, xy) { return getPageXY(pointer, xy, this); },
getClientXY: function (pointer, xy) { return getClientXY(pointer, xy, this); },
setEventXY : function (target, ptr) { return setEventXY(target, ptr, this); },
pointerOver: function (pointer, event, eventTarget) {
if (this.prepared || !this.mouse) { return; }
var curMatches = [],
curMatchElements = [],
prevTargetElement = this.element;
this.addPointer(pointer);
if (this.target
&& (testIgnore(this.target, this.element, eventTarget)
|| !testAllow(this.target, this.element, eventTarget)
|| !withinInteractionLimit(this.target, this.element, this.prepared))) {
// if the eventTarget should be ignored or shouldn't be allowed
// clear the previous target
this.target = null;
this.element = null;
this.matches = [];
this.matchElements = [];
}
var elementInteractable = interactables.get(eventTarget),
elementAction = (elementInteractable
&& !testIgnore(elementInteractable, eventTarget, eventTarget)
&& testAllow(elementInteractable, eventTarget, eventTarget)
&& validateAction(
elementInteractable.getAction(pointer, this, eventTarget),
elementInteractable));
elementAction = elementInteractable && withinInteractionLimit(elementInteractable, eventTarget, elementAction)
? elementAction
: null;
function pushCurMatches (interactable, selector) {
if (interactable
&& inContext(interactable, eventTarget)
&& !testIgnore(interactable, eventTarget, eventTarget)
&& testAllow(interactable, eventTarget, eventTarget)
&& matchesSelector(eventTarget, selector)) {
curMatches.push(interactable);
curMatchElements.push(eventTarget);
}
}
if (elementAction) {
this.target = elementInteractable;
this.element = eventTarget;
this.matches = [];
this.matchElements = [];
}
else {
interactables.forEachSelector(pushCurMatches);
if (this.validateSelector(pointer, curMatches, curMatchElements)) {
this.matches = curMatches;
this.matchElements = curMatchElements;
this.pointerHover(pointer, event, this.matches, this.matchElements);
events.add(eventTarget,
PointerEvent? pEventTypes.move : 'mousemove',
listeners.pointerHover);
}
else if (this.target) {
if (nodeContains(prevTargetElement, eventTarget)) {
this.pointerHover(pointer, event, this.matches, this.matchElements);
events.add(this.element,
PointerEvent? pEventTypes.move : 'mousemove',
listeners.pointerHover);
}
else {
this.target = null;
this.element = null;
this.matches = [];
this.matchElements = [];
}
}
}
},
// Check what action would be performed on pointerMove target if a mouse
// button were pressed and change the cursor accordingly
pointerHover: function (pointer, event, eventTarget, curEventTarget, matches, matchElements) {
var target = this.target;
if (!this.prepared && this.mouse) {
var action;
// update pointer coords for defaultActionChecker to use
this.setEventXY(this.curCoords, pointer);
if (matches) {
action = this.validateSelector(pointer, matches, matchElements);
}
else if (target) {
action = validateAction(target.getAction(this.pointers[0], this, this.element), this.target);
}
if (target && target.options.styleCursor) {
if (action) {
target._doc.documentElement.style.cursor = actionCursors[action];
}
else {
target._doc.documentElement.style.cursor = '';
}
}
}
else if (this.prepared) {
this.checkAndPreventDefault(event, target, this.element);
}
},
pointerOut: function (pointer, event, eventTarget) {
if (this.prepared) { return; }
// Remove temporary event listeners for selector Interactables
if (!interactables.get(eventTarget)) {
events.remove(eventTarget,
PointerEvent? pEventTypes.move : 'mousemove',
listeners.pointerHover);
}
if (this.target && this.target.options.styleCursor && !this.interacting()) {
this.target._doc.documentElement.style.cursor = '';
}
},
selectorDown: function (pointer, event, eventTarget, curEventTarget) {
var that = this,
element = eventTarget,
pointerIndex = this.addPointer(pointer),
action;
this.collectEventTargets(pointer, event, eventTarget, 'down');
this.holdTimers[pointerIndex] = window.setTimeout(function () {
that.pointerHold(pointer, event, eventTarget, curEventTarget);
}, 600);
this.pointerIsDown = true;
// Check if the down event hits the current inertia target
if (this.inertiaStatus.active && this.target.selector) {
// climb up the DOM tree from the event target
while (element && element !== element.ownerDocument) {
// if this element is the current inertia target element
if (element === this.element
// and the prospective action is the same as the ongoing one
&& validateAction(this.target.getAction(pointer, this, this.element), this.target) === this.prepared) {
// stop inertia so that the next move will be a normal one
cancelFrame(this.inertiaStatus.i);
this.inertiaStatus.active = false;
return;
}
element = element.parentNode;
}
}
// do nothing if interacting
if (this.interacting()) {
return;
}
function pushMatches (interactable, selector, context) {
var elements = ie8MatchesSelector
? context.querySelectorAll(selector)
: undefined;
if (inContext(interactable, element)
&& !testIgnore(interactable, element, eventTarget)
&& testAllow(interactable, element, eventTarget)
&& matchesSelector(element, selector, elements)) {
that.matches.push(interactable);
that.matchElements.push(element);
}
}
// update pointer coords for defaultActionChecker to use
this.setEventXY(this.curCoords, pointer);
if (this.matches.length && this.mouse) {
action = this.validateSelector(pointer, this.matches, this.matchElements);
}
else {
while (element && element !== element.ownerDocument && !action) {
this.matches = [];
this.matchElements = [];
interactables.forEachSelector(pushMatches);
action = this.validateSelector(pointer, this.matches, this.matchElements);
element = element.parentNode;
}
}
if (action) {
this.prepared = action;
return this.pointerDown(pointer, event, eventTarget, curEventTarget, action);
}
else {
// do these now since pointerDown isn't being called from here
this.downTimes[pointerIndex] = new Date().getTime();
this.downTargets[pointerIndex] = eventTarget;
this.downEvent = event;
extend(this.downPointer, pointer);
copyCoords(this.prevCoords, this.curCoords);
this.pointerWasMoved = false;
}
},
// Determine action to be performed on next pointerMove and add appropriate
// style and event Listeners
pointerDown: function (pointer, event, eventTarget, curEventTarget, forceAction) {
if (!forceAction && !this.inertiaStatus.active && this.pointerWasMoved && this.prepared) {
this.checkAndPreventDefault(event, this.target, this.element);
return;
}
this.pointerIsDown = true;
var pointerIndex = this.addPointer(pointer),
action;
// If it is the second touch of a multi-touch gesture, keep the target
// the same if a target was set by the first touch
// Otherwise, set the target if there is no action prepared
if ((this.pointerIds.length < 2 && !this.target) || !this.prepared) {
var interactable = interactables.get(curEventTarget);
if (interactable
&& !testIgnore(interactable, curEventTarget, eventTarget)
&& testAllow(interactable, curEventTarget, eventTarget)
&& (action = validateAction(forceAction || interactable.getAction(pointer, this), interactable, eventTarget))
&& withinInteractionLimit(interactable, curEventTarget, action)) {
this.target = interactable;
this.element = curEventTarget;
}
}
var target = this.target,
options = target && target.options;
if (target && !this.interacting()) {
action = action || validateAction(forceAction || target.getAction(pointer, this), target, this.element);
this.setEventXY(this.startCoords);
if (!action) { return; }
if (options.styleCursor) {
target._doc.documentElement.style.cursor = actionCursors[action];
}
this.resizeAxes = action === 'resizexy'?
'xy':
action === 'resizex'?
'x':
action === 'resizey'?
'y':
'';
if (action === 'gesture' && this.pointerIds.length < 2) {
action = null;
}
this.prepared = action;
this.snapStatus.snappedX = this.snapStatus.snappedY =
this.restrictStatus.restrictedX = this.restrictStatus.restrictedY = NaN;
this.downTimes[pointerIndex] = new Date().getTime();
this.downTargets[pointerIndex] = eventTarget;
this.downEvent = event;
extend(this.downPointer, pointer);
this.setEventXY(this.prevCoords);
this.pointerWasMoved = false;
this.checkAndPreventDefault(event, target, this.element);
}
// if inertia is active try to resume action
else if (this.inertiaStatus.active
&& curEventTarget === this.element
&& validateAction(target.getAction(pointer, this, this.element), target) === this.prepared) {
cancelFrame(this.inertiaStatus.i);
this.inertiaStatus.active = false;
this.checkAndPreventDefault(event, target, this.element);
}
},
pointerMove: function (pointer, event, eventTarget, curEventTarget, preEnd) {
this.recordPointer(pointer);
this.setEventXY(this.curCoords, (pointer instanceof InteractEvent)
? this.inertiaStatus.startEvent
: undefined);
var duplicateMove = (this.curCoords.page.x === this.prevCoords.page.x
&& this.curCoords.page.y === this.prevCoords.page.y
&& this.curCoords.client.x === this.prevCoords.client.x
&& this.curCoords.client.y === this.prevCoords.client.y);
var dx, dy,
pointerIndex = this.mouse? 0 : indexOf(this.pointerIds, getPointerId(pointer));
// register movement greater than pointerMoveTolerance
if (this.pointerIsDown && !this.pointerWasMoved) {
dx = this.curCoords.client.x - this.startCoords.client.x;
dy = this.curCoords.client.y - this.startCoords.client.y;
this.pointerWasMoved = hypot(dx, dy) > defaultOptions.pointerMoveTolerance;
}
if (!duplicateMove && (!this.pointerIsDown || this.pointerWasMoved)) {
if (this.pointerIsDown) {
window.clearTimeout(this.holdTimers[pointerIndex]);
}
this.collectEventTargets(pointer, event, eventTarget, 'move');
}
if (!this.pointerIsDown) { return; }
if (duplicateMove && this.pointerWasMoved && !preEnd) {
this.checkAndPreventDefault(event, this.target, this.element);
return;
}
// set pointer coordinate, time changes and speeds
setEventDeltas(this.pointerDelta, this.prevCoords, this.curCoords);
if (!this.prepared) { return; }
if (this.pointerWasMoved
// ignore movement while inertia is active
&& (!this.inertiaStatus.active || (pointer instanceof InteractEvent && /inertiastart/.test(pointer.type)))) {
// if just starting an action, calculate the pointer speed now
if (!this.interacting()) {
setEventDeltas(this.pointerDelta, this.prevCoords, this.curCoords);
// check if a drag is in the correct axis
if (this.prepared === 'drag') {
var absX = Math.abs(dx),
absY = Math.abs(dy),
targetAxis = this.target.options.dragAxis,
axis = (absX > absY ? 'x' : absX < absY ? 'y' : 'xy');
// if the movement isn't in the axis of the interactable
if (axis !== 'xy' && targetAxis !== 'xy' && targetAxis !== axis) {
// cancel the prepared action
this.prepared = null;
// then try to get a drag from another ineractable
var element = eventTarget;
// check element interactables
while (element && element !== element.ownerDocument) {
var elementInteractable = interactables.get(element);
if (elementInteractable
&& elementInteractable !== this.target
&& elementInteractable.getAction(this.downPointer, this, element) === 'drag'
&& checkAxis(axis, elementInteractable)) {
this.prepared = 'drag';
this.target = elementInteractable;
this.element = element;
break;
}
element = element.parentNode;
}
// if there's no drag from element interactables,
// check the selector interactables
if (!this.prepared) {
var getDraggable = function (interactable, selector, context) {
var elements = ie8MatchesSelector
? context.querySelectorAll(selector)
: undefined;
if (interactable === this.target) { return; }
if (inContext(interactable, eventTarget)
&& !testIgnore(interactable, element, eventTarget)
&& testAllow(interactable, element, eventTarget)
&& matchesSelector(element, selector, elements)
&& interactable.getAction(this.downPointer, this, element) === 'drag'
&& checkAxis(axis, interactable)
&& withinInteractionLimit(interactable, element, 'drag')) {
return interactable;
}
};
element = eventTarget;
while (element && element !== element.ownerDocument) {
var selectorInteractable = interactables.forEachSelector(getDraggable);
if (selectorInteractable) {
this.prepared = 'drag';
this.target = selectorInteractable;
this.element = element;
break;
}
element = element.parentNode;
}
}
}
}
}
var starting = !!this.prepared && !this.interacting();
if (starting && !withinInteractionLimit(this.target, this.element, this.prepared)) {
this.stop();
return;
}
if (this.prepared && this.target) {
var target = this.target,
shouldMove = true,
shouldSnap = checkSnap(target, this.prepared) && (!target.options.snap.endOnly || preEnd),
shouldRestrict = checkRestrict(target, this.prepared) && (!target.options.restrict.endOnly || preEnd);
if (starting) {
var rect = target.getRect(this.element),
snap = target.options.snap,
restrict = target.options.restrict,
width, height;
if (rect) {
this.startOffset.left = this.startCoords.page.x - rect.left;
this.startOffset.top = this.startCoords.page.y - rect.top;
this.startOffset.right = rect.right - this.startCoords.page.x;
this.startOffset.bottom = rect.bottom - this.startCoords.page.y;
if ('width' in rect) { width = rect.width; }
else { width = rect.right - rect.left; }
if ('height' in rect) { height = rect.height; }
else { height = rect.bottom - rect.top; }
}
else {
this.startOffset.left = this.startOffset.top = this.startOffset.right = this.startOffset.bottom = 0;
}
if (rect && snap.elementOrigin) {
this.snapOffset.x = this.startOffset.left - (width * snap.elementOrigin.x);
this.snapOffset.y = this.startOffset.top - (height * snap.elementOrigin.y);
}
else {
this.snapOffset.x = this.snapOffset.y = 0;
}
if (rect && restrict.elementRect) {
this.restrictOffset.left = this.startOffset.left - (width * restrict.elementRect.left);
this.restrictOffset.top = this.startOffset.top - (height * restrict.elementRect.top);
this.restrictOffset.right = this.startOffset.right - (width * (1 - restrict.elementRect.right));
this.restrictOffset.bottom = this.startOffset.bottom - (height * (1 - restrict.elementRect.bottom));
}
else {
this.restrictOffset.left = this.restrictOffset.top = this.restrictOffset.right = this.restrictOffset.bottom = 0;
}
}
var snapCoords = starting? this.startCoords.page : this.curCoords.page;
if (shouldSnap ) { this.setSnapping (snapCoords); } else { this.snapStatus .locked = false; }
if (shouldRestrict) { this.setRestriction(snapCoords); } else { this.restrictStatus.restricted = false; }
if (shouldSnap && this.snapStatus.locked && !this.snapStatus.changed) {
shouldMove = shouldRestrict && this.restrictStatus.restricted && this.restrictStatus.changed;
}
else if (shouldRestrict && this.restrictStatus.restricted && !this.restrictStatus.changed) {
shouldMove = false;
}
// move if snapping or restriction doesn't prevent it
if (shouldMove) {
var action = /resize/.test(this.prepared)? 'resize': this.prepared;
if (starting) {
var dragStartEvent = this[action + 'Start'](this.downEvent);
this.prevEvent = dragStartEvent;
// reset active dropzones
this.activeDrops.dropzones = [];
this.activeDrops.elements = [];
this.activeDrops.rects = [];
if (!this.dynamicDrop) {
this.setActiveDrops(this.element);
}
var dropEvents = this.getDropEvents(event, dragStartEvent);
if (dropEvents.activate) {
this.fireActiveDrops(dropEvents.activate);
}
snapCoords = this.curCoords.page;
// set snapping and restriction for the move event
if (shouldSnap ) { this.setSnapping (snapCoords); }
if (shouldRestrict) { this.setRestriction(snapCoords); }
}
this.prevEvent = this[action + 'Move'](event);
}
this.checkAndPreventDefault(event, this.target, this.element);
}
}
copyCoords(this.prevCoords, this.curCoords);
if (this.dragging || this.resizing) {
autoScroll.edgeMove(event);
}
},
dragStart: function (event) {
var dragEvent = new InteractEvent(this, event, 'drag', 'start', this.element);
this.dragging = true;
this.target.fire(dragEvent);
return dragEvent;
},
dragMove: function (event) {
var target = this.target,
dragEvent = new InteractEvent(this, event, 'drag', 'move', this.element),
draggableElement = this.element,
drop = this.getDrop(dragEvent, draggableElement);
this.dropTarget = drop.dropzone;
this.dropElement = drop.element;
var dropEvents = this.getDropEvents(event, dragEvent);
target.fire(dragEvent);
if (dropEvents.leave) { this.prevDropTarget.fire(dropEvents.leave); }
if (dropEvents.enter) { this.dropTarget.fire(dropEvents.enter); }
if (dropEvents.move ) { this.dropTarget.fire(dropEvents.move ); }
this.prevDropTarget = this.dropTarget;
this.prevDropElement = this.dropElement;
return dragEvent;
},
resizeStart: function (event) {
var resizeEvent = new InteractEvent(this, event, 'resize', 'start', this.element);
this.target.fire(resizeEvent);
this.resizing = true;
return resizeEvent;
},
resizeMove: function (event) {
var resizeEvent = new InteractEvent(this, event, 'resize', 'move', this.element);
this.target.fire(resizeEvent);
return resizeEvent;
},
gestureStart: function (event) {
var gestureEvent = new InteractEvent(this, event, 'gesture', 'start', this.element);
gestureEvent.ds = 0;
this.gesture.startDistance = this.gesture.prevDistance = gestureEvent.distance;
this.gesture.startAngle = this.gesture.prevAngle = gestureEvent.angle;
this.gesture.scale = 1;
this.gesturing = true;
this.target.fire(gestureEvent);
return gestureEvent;
},
gestureMove: function (event) {
if (!this.pointerIds.length) {
return this.prevEvent;
}
var gestureEvent;
gestureEvent = new InteractEvent(this, event, 'gesture', 'move', this.element);
gestureEvent.ds = gestureEvent.scale - this.gesture.scale;
this.target.fire(gestureEvent);
this.gesture.prevAngle = gestureEvent.angle;
this.gesture.prevDistance = gestureEvent.distance;
if (gestureEvent.scale !== Infinity &&
gestureEvent.scale !== null &&
gestureEvent.scale !== undefined &&
!isNaN(gestureEvent.scale)) {
this.gesture.scale = gestureEvent.scale;
}
return gestureEvent;
},
pointerHold: function (pointer, event, eventTarget) {
this.collectEventTargets(pointer, event, eventTarget, 'hold');
},
pointerUp: function (pointer, event, eventTarget, curEventTarget) {
var pointerIndex = this.mouse? 0 : indexOf(this.pointerIds, getPointerId(pointer));
window.clearTimeout(this.holdTimers[pointerIndex]);
this.collectEventTargets(pointer, event, eventTarget, 'up' );
this.collectEventTargets(pointer, event, eventTarget, 'tap');
this.pointerEnd(pointer, event, eventTarget, curEventTarget);
this.removePointer(pointer);
},
pointerCancel: function (pointer, event, eventTarget, curEventTarget) {
var pointerIndex = this.mouse? 0 : indexOf(this.pointerIds, getPointerId(pointer));
window.clearTimeout(this.holdTimers[pointerIndex]);
this.collectEventTargets(pointer, event, eventTarget, 'cancel');
this.pointerEnd(pointer, event, eventTarget, curEventTarget);
},
// End interact move events and stop auto-scroll unless inertia is enabled
pointerEnd: function (pointer, event, eventTarget, curEventTarget) {
var endEvent,
target = this.target,
options = target && target.options,
inertiaOptions = options && options.inertia,
inertiaStatus = this.inertiaStatus;
if (this.interacting()) {
if (inertiaStatus.active) { return; }
var pointerSpeed,
now = new Date().getTime(),
inertiaPossible = false,
inertia = false,
smoothEnd = false,
endSnap = checkSnap(target, this.prepared) && options.snap.endOnly,
endRestrict = checkRestrict(target, this.prepared) && options.restrict.endOnly,
dx = 0,
dy = 0,
startEvent;
if (this.dragging) {
if (options.dragAxis === 'x' ) { pointerSpeed = Math.abs(this.pointerDelta.client.vx); }
else if (options.dragAxis === 'y' ) { pointerSpeed = Math.abs(this.pointerDelta.client.vy); }
else /*options.dragAxis === 'xy'*/{ pointerSpeed = this.pointerDelta.client.speed; }
}
// check if inertia should be started
inertiaPossible = (options.inertiaEnabled
&& this.prepared !== 'gesture'
&& contains(inertiaOptions.actions, this.prepared)
&& event !== inertiaStatus.startEvent);
inertia = (inertiaPossible
&& (now - this.curCoords.timeStamp) < 50
&& pointerSpeed > inertiaOptions.minSpeed
&& pointerSpeed > inertiaOptions.endSpeed);
if (inertiaPossible && !inertia && (endSnap || endRestrict)) {
var snapRestrict = {};
snapRestrict.snap = snapRestrict.restrict = snapRestrict;
if (endSnap) {
this.setSnapping(this.curCoords.page, snapRestrict);
if (snapRestrict.locked) {
dx += snapRestrict.dx;
dy += snapRestrict.dy;
}
}
if (endRestrict) {
this.setRestriction(this.curCoords.page, snapRestrict);
if (snapRestrict.restricted) {
dx += snapRestrict.dx;
dy += snapRestrict.dy;
}
}
if (dx || dy) {
smoothEnd = true;
}
}
if (inertia || smoothEnd) {
copyCoords(inertiaStatus.upCoords, this.curCoords);
this.pointers[0] = inertiaStatus.startEvent = startEvent =
new InteractEvent(this, event, this.prepared, 'inertiastart', this.element);
inertiaStatus.t0 = now;
target.fire(inertiaStatus.startEvent);
if (inertia) {
inertiaStatus.vx0 = this.pointerDelta.client.vx;
inertiaStatus.vy0 = this.pointerDelta.client.vy;
inertiaStatus.v0 = pointerSpeed;
this.calcInertia(inertiaStatus);
var page = extend({}, this.curCoords.page),
origin = getOriginXY(target, this.element),
statusObject;
page.x = page.x + inertiaStatus.xe - origin.x;
page.y = page.y + inertiaStatus.ye - origin.y;
statusObject = {
useStatusXY: true,
x: page.x,
y: page.y,
dx: 0,
dy: 0,
snap: null
};
statusObject.snap = statusObject;
dx = dy = 0;
if (endSnap) {
var snap = this.setSnapping(this.curCoords.page, statusObject);
if (snap.locked) {
dx += snap.dx;
dy += snap.dy;
}
}
if (endRestrict) {
var restrict = this.setRestriction(this.curCoords.page, statusObject);
if (restrict.restricted) {
dx += restrict.dx;
dy += restrict.dy;
}
}
inertiaStatus.modifiedXe += dx;
inertiaStatus.modifiedYe += dy;
inertiaStatus.i = reqFrame(this.boundInertiaFrame);
}
else {
inertiaStatus.smoothEnd = true;
inertiaStatus.xe = dx;
inertiaStatus.ye = dy;
inertiaStatus.sx = inertiaStatus.sy = 0;
inertiaStatus.i = reqFrame(this.boundSmoothEndFrame);
}
inertiaStatus.active = true;
return;
}
if (endSnap || endRestrict) {
// fire a move event at the snapped coordinates
this.pointerMove(pointer, event, eventTarget, curEventTarget, true);
}
}
if (this.dragging) {
endEvent = new InteractEvent(this, event, 'drag', 'end', this.element);
var draggableElement = this.element,
drop = this.getDrop(endEvent, draggableElement);
this.dropTarget = drop.dropzone;
this.dropElement = drop.element;
var dropEvents = this.getDropEvents(event, endEvent);
if (dropEvents.leave) { this.prevDropTarget.fire(dropEvents.leave); }
if (dropEvents.enter) { this.dropTarget.fire(dropEvents.enter); }
if (dropEvents.drop ) { this.dropTarget.fire(dropEvents.drop ); }
if (dropEvents.deactivate) {
this.fireActiveDrops(dropEvents.deactivate);
}
target.fire(endEvent);
}
else if (this.resizing) {
endEvent = new InteractEvent(this, event, 'resize', 'end', this.element);
target.fire(endEvent);
}
else if (this.gesturing) {
endEvent = new InteractEvent(this, event, 'gesture', 'end', this.element);
target.fire(endEvent);
}
this.stop(event);
},
collectDrops: function (element) {
var drops = [],
elements = [],
i;
element = element || this.element;
// collect all dropzones and their elements which qualify for a drop
for (i = 0; i < interactables.length; i++) {
if (!interactables[i].options.dropzone) { continue; }
var current = interactables[i];
// test the draggable element against the dropzone's accept setting
if ((isElement(current.options.accept) && current.options.accept !== element)
|| (isString(current.options.accept)
&& !matchesSelector(element, current.options.accept))) {
continue;
}
// query for new elements if necessary
var dropElements = current.selector? current._context.querySelectorAll(current.selector) : [current._element];
for (var j = 0, len = dropElements.length; j < len; j++) {
var currentElement = dropElements[j];
if (currentElement === element) {
continue;
}
drops.push(current);
elements.push(currentElement);
}
}
return {
dropzones: drops,
elements: elements
};
},
fireActiveDrops: function (event) {
var i,
current,
currentElement,
prevElement;
// loop through all active dropzones and trigger event
for (i = 0; i < this.activeDrops.dropzones.length; i++) {
current = this.activeDrops.dropzones[i];
currentElement = this.activeDrops.elements [i];
// prevent trigger of duplicate events on same element
if (currentElement !== prevElement) {
// set current element as event target
event.target = currentElement;
current.fire(event);
}
prevElement = currentElement;
}
},
// Collect a new set of possible drops and save them in activeDrops.
// setActiveDrops should always be called when a drag has just started or a
// drag event happens while dynamicDrop is true
setActiveDrops: function (dragElement) {
// get dropzones and their elements that could receive the draggable
var possibleDrops = this.collectDrops(dragElement, true);
this.activeDrops.dropzones = possibleDrops.dropzones;
this.activeDrops.elements = possibleDrops.elements;
this.activeDrops.rects = [];
for (var i = 0; i < this.activeDrops.dropzones.length; i++) {
this.activeDrops.rects[i] = this.activeDrops.dropzones[i].getRect(this.activeDrops.elements[i]);
}
},
getDrop: function (event, dragElement) {
var validDrops = [];
if (dynamicDrop) {
this.setActiveDrops(dragElement);
}
// collect all dropzones and their elements which qualify for a drop
for (var j = 0; j < this.activeDrops.dropzones.length; j++) {
var current = this.activeDrops.dropzones[j],
currentElement = this.activeDrops.elements [j],
rect = this.activeDrops.rects [j];
validDrops.push(current.dropCheck(this.pointers[0], this.target, dragElement, currentElement, rect)
? currentElement
: null);
}
// get the most appropriate dropzone based on DOM depth and order
var dropIndex = indexOfDeepestElement(validDrops),
dropzone = this.activeDrops.dropzones[dropIndex] || null,
element = this.activeDrops.elements [dropIndex] || null;
return {
dropzone: dropzone,
element: element
};
},
getDropEvents: function (pointerEvent, dragEvent) {
var dragLeaveEvent = null,
dragEnterEvent = null,
dropActivateEvent = null,
dropDeactivateEvent = null,
dropMoveEvent = null,
dropEvent = null;
if (this.dropElement !== this.prevDropElement) {
// if there was a prevDropTarget, create a dragleave event
if (this.prevDropTarget) {
dragLeaveEvent = new InteractEvent(this, pointerEvent, 'drag', 'leave', this.prevDropElement, dragEvent.target);
dragLeaveEvent.draggable = dragEvent.interactable;
dragEvent.dragLeave = this.prevDropElement;
dragEvent.prevDropzone = this.prevDropTarget;
}
// if the dropTarget is not null, create a dragenter event
if (this.dropTarget) {
dragEnterEvent = new InteractEvent(this, pointerEvent, 'drag', 'enter', this.dropElement, dragEvent.target);
dragEnterEvent.draggable = dragEvent.interactable;
dragEvent.dragEnter = this.dropElement;
dragEvent.dropzone = this.dropTarget;
}
}
if (dragEvent.type === 'dragend' && this.dropTarget) {
dropEvent = new InteractEvent(this, pointerEvent, 'drop', null, this.dropElement, dragEvent.target);
dropEvent.draggable = dragEvent.interactable;
dragEvent.dropzone = this.dropTarget;
}
if (dragEvent.type === 'dragstart') {
dropActivateEvent = new InteractEvent(this, pointerEvent, 'drop', 'activate', this.element, dragEvent.target);
dropActivateEvent.draggable = dragEvent.interactable;
}
if (dragEvent.type === 'dragend') {
dropDeactivateEvent = new InteractEvent(this, pointerEvent, 'drop', 'deactivate', this.element, dragEvent.target);
dropDeactivateEvent.draggable = dragEvent.interactable;
}
if (dragEvent.type === 'dragmove' && this.dropTarget) {
dropMoveEvent = {
target : this.dropElement,
relatedTarget: dragEvent.target,
draggable : dragEvent.interactable,
dragmove : dragEvent,
type : 'dropmove',
timeStamp : dragEvent.timeStamp
};
dragEvent.dropzone = this.dropTarget;
}
return {
enter : dragEnterEvent,
leave : dragLeaveEvent,
activate : dropActivateEvent,
deactivate : dropDeactivateEvent,
move : dropMoveEvent,
drop : dropEvent
};
},
currentAction: function () {
return (this.dragging && 'drag') || (this.resizing && 'resize') || (this.gesturing && 'gesture') || null;
},
interacting: function () {
return this.dragging || this.resizing || this.gesturing;
},
clearTargets: function () {
if (this.target && !this.target.selector) {
this.target = this.element = null;
}
this.dropTarget = this.dropElement = this.prevDropTarget = this.prevDropElement = null;
},
stop: function (event) {
if (this.interacting()) {
autoScroll.stop();
this.matches = [];
this.matchElements = [];
var target = this.target;
if (target.options.styleCursor) {
target._doc.documentElement.style.cursor = '';
}
// prevent Default only if were previously interacting
if (event && isFunction(event.preventDefault)) {
this.checkAndPreventDefault(event, target, this.element);
}
if (this.dragging) {
this.activeDrops.dropzones = this.activeDrops.elements = this.activeDrops.rects = null;
}
this.clearTargets();
}
this.pointerIsDown = this.snapStatus.locked = this.dragging = this.resizing = this.gesturing = false;
this.prepared = this.prevEvent = null;
this.inertiaStatus.resumeDx = this.inertiaStatus.resumeDy = 0;
this.pointerIds .splice(0);
this.pointers .splice(0);
this.downTargets.splice(0);
this.downTimes .splice(0);
this.holdTimers .splice(0);
// delete interaction if it's not the only one
if (interactions.length > 1) {
interactions.splice(indexOf(interactions, this), 1);
}
},
inertiaFrame: function () {
var inertiaStatus = this.inertiaStatus,
options = this.target.options.inertia,
lambda = options.resistance,
t = new Date().getTime() / 1000 - inertiaStatus.t0;
if (t < inertiaStatus.te) {
var progress = 1 - (Math.exp(-lambda * t) - inertiaStatus.lambda_v0) / inertiaStatus.one_ve_v0;
if (inertiaStatus.modifiedXe === inertiaStatus.xe && inertiaStatus.modifiedYe === inertiaStatus.ye) {
inertiaStatus.sx = inertiaStatus.xe * progress;
inertiaStatus.sy = inertiaStatus.ye * progress;
}
else {
var quadPoint = getQuadraticCurvePoint(
0, 0,
inertiaStatus.xe, inertiaStatus.ye,
inertiaStatus.modifiedXe, inertiaStatus.modifiedYe,
progress);
inertiaStatus.sx = quadPoint.x;
inertiaStatus.sy = quadPoint.y;
}
this.pointerMove(inertiaStatus.startEvent, inertiaStatus.startEvent);
inertiaStatus.i = reqFrame(this.boundInertiaFrame);
}
else {
inertiaStatus.sx = inertiaStatus.modifiedXe;
inertiaStatus.sy = inertiaStatus.modifiedYe;
this.pointerMove(inertiaStatus.startEvent, inertiaStatus.startEvent);
inertiaStatus.active = false;
this.pointerEnd(inertiaStatus.startEvent, inertiaStatus.startEvent);
}
},
smoothEndFrame: function () {
var inertiaStatus = this.inertiaStatus,
t = new Date().getTime() - inertiaStatus.t0,
duration = this.target.options.inertia.smoothEndDuration;
if (t < duration) {
inertiaStatus.sx = easeOutQuad(t, 0, inertiaStatus.xe, duration);
inertiaStatus.sy = easeOutQuad(t, 0, inertiaStatus.ye, duration);
this.pointerMove(inertiaStatus.startEvent, inertiaStatus.startEvent);
inertiaStatus.i = reqFrame(this.boundSmoothEndFrame);
}
else {
inertiaStatus.sx = inertiaStatus.xe;
inertiaStatus.sy = inertiaStatus.ye;
this.pointerMove(inertiaStatus.startEvent, inertiaStatus.startEvent);
inertiaStatus.active = false;
inertiaStatus.smoothEnd = false;
this.pointerEnd(inertiaStatus.startEvent, inertiaStatus.startEvent);
}
},
addPointer: function (pointer) {
var id = getPointerId(pointer),
index = this.mouse? 0 : indexOf(this.pointerIds, id);
if (index === -1) {
index = this.pointerIds.length;
this.pointerIds.push(id);
}
this.pointers[index] = pointer;
return index;
},
removePointer: function (pointer) {
var id = getPointerId(pointer),
index = this.mouse? 0 : indexOf(this.pointerIds, id);
if (index === -1) { return; }
this.pointerIds .splice(index, 1);
this.pointers .splice(index, 1);
this.downTargets.splice(index, 1);
this.downTimes .splice(index, 1);
this.holdTimers .splice(index, 1);
},
recordPointer: function (pointer) {
// Do not update pointers while inertia is active.
// The inertia start event should be this.pointers[0]
if (this.inertiaStatus.active) { return; }
var index = this.mouse? 0: indexOf(this.pointerIds, getPointerId(pointer));
if (index === -1) { return; }
this.pointers[index] = pointer;
},
collectEventTargets: function (pointer, event, eventTarget, eventType) {
var pointerIndex = this.mouse? 0 : indexOf(this.pointerIds, getPointerId(pointer));
// do not fire a tap event if the pointer was moved before being lifted
if (eventType === 'tap' && (this.pointerWasMoved
// or if the pointerup target is different to the pointerdown target
|| !(this.downTargets[pointerIndex] && this.downTargets[pointerIndex] === eventTarget))) {
return;
}
var targets = [],
elements = [],
element = eventTarget;
function collectSelectors (interactable, selector, context) {
var els = ie8MatchesSelector
? context.querySelectorAll(selector)
: undefined;
if (interactable._iEvents[eventType]
&& isElement(element)
&& inContext(interactable, element)
&& !testIgnore(interactable, element, eventTarget)
&& testAllow(interactable, element, eventTarget)
&& matchesSelector(element, selector, els)) {
targets.push(interactable);
elements.push(element);
}
}
while (element) {
if (interact.isSet(element) && interact(element)._iEvents[eventType]) {
targets.push(interact(element));
elements.push(element);
}
interactables.forEachSelector(collectSelectors);
element = element.parentNode;
}
if (targets.length) {
this.firePointers(pointer, event, targets, elements, eventType);
}
},
firePointers: function (pointer, event, targets, elements, eventType) {
var pointerIndex = this.mouse? 0 : indexOf(getPointerId(pointer)),
pointerEvent = {},
i,
// for tap events
interval, dbl;
extend(pointerEvent, event);
if (event !== pointer) {
extend(pointerEvent, pointer);
}
pointerEvent.preventDefault = preventOriginalDefault;
pointerEvent.stopPropagation = InteractEvent.prototype.stopPropagation;
pointerEvent.stopImmediatePropagation = InteractEvent.prototype.stopImmediatePropagation;
pointerEvent.interaction = this;
pointerEvent.timeStamp = new Date().getTime();
pointerEvent.originalEvent = event;
pointerEvent.type = eventType;
pointerEvent.pointerId = getPointerId(pointer);
pointerEvent.pointerType = this.mouse? 'mouse' : !supportsPointerEvent? 'touch'
: isString(pointer.pointerType)
? pointer.pointerType
: [,,'touch', 'pen', 'mouse'][pointer.pointerType];
if (eventType === 'tap') {
pointerEvent.dt = pointerEvent.timeStamp - this.downTimes[pointerIndex];
interval = pointerEvent.timeStamp - this.tapTime;
dbl = (this.prevTap && this.prevTap.type !== 'doubletap'
&& this.prevTap.target === pointerEvent.target
&& interval < 500);
this.tapTime = pointerEvent.timeStamp;
}
for (i = 0; i < targets.length; i++) {
pointerEvent.currentTarget = elements[i];
pointerEvent.interactable = targets[i];
targets[i].fire(pointerEvent);
if (pointerEvent.immediatePropagationStopped
||(pointerEvent.propagationStopped && elements[i + 1] !== pointerEvent.currentTarget)) {
break;
}
}
if (dbl) {
var doubleTap = {};
extend(doubleTap, pointerEvent);
doubleTap.dt = interval;
doubleTap.type = 'doubletap';
for (i = 0; i < targets.length; i++) {
doubleTap.currentTarget = elements[i];
doubleTap.interactable = targets[i];
targets[i].fire(doubleTap);
if (doubleTap.immediatePropagationStopped
||(doubleTap.propagationStopped && elements[i + 1] !== doubleTap.currentTarget)) {
break;
}
}
this.prevTap = doubleTap;
}
else if (eventType === 'tap') {
this.prevTap = pointerEvent;
}
},
validateSelector: function (pointer, matches, matchElements) {
for (var i = 0, len = matches.length; i < len; i++) {
var match = matches[i],
matchElement = matchElements[i],
action = validateAction(match.getAction(pointer, this, matchElement), match);
if (action && withinInteractionLimit(match, matchElement, action)) {
this.target = match;
this.element = matchElement;
return action;
}
}
},
setSnapping: function (pageCoords, status) {
var snap = this.target.options.snap,
anchors = snap.anchors,
page,
closest,
range,
inRange,
snapChanged,
dx,
dy,
distance,
i, len;
status = status || this.snapStatus;
if (status.useStatusXY) {
page = { x: status.x, y: status.y };
}
else {
var origin = getOriginXY(this.target, this.element);
page = extend({}, pageCoords);
page.x -= origin.x;
page.y -= origin.y;
}
page.x -= this.inertiaStatus.resumeDx;
page.y -= this.inertiaStatus.resumeDy;
status.realX = page.x;
status.realY = page.y;
// change to infinite range when range is negative
if (snap.range < 0) { snap.range = Infinity; }
// create an anchor representative for each path's returned point
if (snap.mode === 'path') {
anchors = [];
for (i = 0, len = snap.paths.length; i < len; i++) {
var path = snap.paths[i];
if (isFunction(path)) {
path = path(page.x, page.y);
}
anchors.push({
x: isNumber(path.x) ? path.x : page.x,
y: isNumber(path.y) ? path.y : page.y,
range: isNumber(path.range)? path.range: snap.range
});
}
}
if ((snap.mode === 'anchor' || snap.mode === 'path') && anchors.length) {
closest = {
anchor: null,
distance: 0,
range: 0,
dx: 0,
dy: 0
};
for (i = 0, len = anchors.length; i < len; i++) {
var anchor = anchors[i];
range = isNumber(anchor.range)? anchor.range: snap.range;
dx = anchor.x - page.x + this.snapOffset.x;
dy = anchor.y - page.y + this.snapOffset.y;
distance = hypot(dx, dy);
inRange = distance < range;
// Infinite anchors count as being out of range
// compared to non infinite ones that are in range
if (range === Infinity && closest.inRange && closest.range !== Infinity) {
inRange = false;
}
if (!closest.anchor || (inRange?
// is the closest anchor in range?
(closest.inRange && range !== Infinity)?
// the pointer is relatively deeper in this anchor
distance / range < closest.distance / closest.range:
//the pointer is closer to this anchor
distance < closest.distance:
// The other is not in range and the pointer is closer to this anchor
(!closest.inRange && distance < closest.distance))) {
if (range === Infinity) {
inRange = true;
}
closest.anchor = anchor;
closest.distance = distance;
closest.range = range;
closest.inRange = inRange;
closest.dx = dx;
closest.dy = dy;
status.range = range;
}
}
inRange = closest.inRange;
snapChanged = (closest.anchor.x !== status.x || closest.anchor.y !== status.y);
status.snappedX = closest.anchor.x;
status.snappedY = closest.anchor.y;
status.dx = closest.dx;
status.dy = closest.dy;
}
else if (snap.mode === 'grid') {
var gridx = Math.round((page.x - snap.gridOffset.x - this.snapOffset.x) / snap.grid.x),
gridy = Math.round((page.y - snap.gridOffset.y - this.snapOffset.y) / snap.grid.y),
newX = gridx * snap.grid.x + snap.gridOffset.x + this.snapOffset.x,
newY = gridy * snap.grid.y + snap.gridOffset.y + this.snapOffset.y;
dx = newX - page.x;
dy = newY - page.y;
distance = hypot(dx, dy);
inRange = distance < snap.range;
snapChanged = (newX !== status.snappedX || newY !== status.snappedY);
status.snappedX = newX;
status.snappedY = newY;
status.dx = dx;
status.dy = dy;
status.range = snap.range;
}
status.changed = (snapChanged || (inRange && !status.locked));
status.locked = inRange;
return status;
},
setRestriction: function (pageCoords, status) {
var target = this.target,
action = /resize/.test(this.prepared)? 'resize' : this.prepared,
restrict = target && target.options.restrict,
restriction = restrict && restrict[action],
page;
if (!restriction) {
return status;
}
status = status || this.restrictStatus;
page = status.useStatusXY
? page = { x: status.x, y: status.y }
: page = extend({}, pageCoords);
if (status.snap && status.snap.locked) {
page.x += status.snap.dx || 0;
page.y += status.snap.dy || 0;
}
page.x -= this.inertiaStatus.resumeDx;
page.y -= this.inertiaStatus.resumeDy;
status.dx = 0;
status.dy = 0;
status.restricted = false;
var rect, restrictedX, restrictedY;
if (isString(restriction)) {
if (restriction === 'parent') {
restriction = this.element.parentNode;
}
else if (restriction === 'self') {
restriction = target.getRect(this.element);
}
else {
restriction = closest(this.element, restriction);
}
if (!restriction) { return status; }
}
if (isFunction(restriction)) {
restriction = restriction(page.x, page.y, this.element);
}
if (isElement(restriction)) {
restriction = getElementRect(restriction);
}
rect = restriction;
// object is assumed to have
// x, y, width, height or
// left, top, right, bottom
if ('x' in restriction && 'y' in restriction) {
restrictedX = Math.max(Math.min(rect.x + rect.width - this.restrictOffset.right , page.x), rect.x + this.restrictOffset.left);
restrictedY = Math.max(Math.min(rect.y + rect.height - this.restrictOffset.bottom, page.y), rect.y + this.restrictOffset.top );
}
else {
restrictedX = Math.max(Math.min(rect.right - this.restrictOffset.right , page.x), rect.left + this.restrictOffset.left);
restrictedY = Math.max(Math.min(rect.bottom - this.restrictOffset.bottom, page.y), rect.top + this.restrictOffset.top );
}
status.dx = restrictedX - page.x;
status.dy = restrictedY - page.y;
status.changed = status.restrictedX !== restrictedX || status.restrictedY !== restrictedY;
status.restricted = !!(status.dx || status.dy);
status.restrictedX = restrictedX;
status.restrictedY = restrictedY;
return status;
},
checkAndPreventDefault: function (event, interactable, element) {
if (!(interactable = interactable || this.target)) { return; }
var options = interactable.options,
prevent = options.preventDefault;
if (prevent === 'auto' && element && !/^input$|^textarea$/i.test(element.nodeName)) {
// do not preventDefault on pointerdown if the prepared action is a drag
// and dragging can only start from a certain direction - this allows
// a touch to pan the viewport if a drag isn't in the right direction
if (/down|start/i.test(event.type)
&& this.prepared === 'drag' && options.dragAxis !== 'xy') {
return;
}
event.preventDefault();
return;
}
if (prevent === true) {
event.preventDefault();
return;
}
},
calcInertia: function (status) {
var inertiaOptions = this.target.options.inertia,
lambda = inertiaOptions.resistance,
inertiaDur = -Math.log(inertiaOptions.endSpeed / status.v0) / lambda;
status.x0 = this.prevEvent.pageX;
status.y0 = this.prevEvent.pageY;
status.t0 = status.startEvent.timeStamp / 1000;
status.sx = status.sy = 0;
status.modifiedXe = status.xe = (status.vx0 - inertiaDur) / lambda;
status.modifiedYe = status.ye = (status.vy0 - inertiaDur) / lambda;
status.te = inertiaDur;
status.lambda_v0 = lambda / status.v0;
status.one_ve_v0 = 1 - inertiaOptions.endSpeed / status.v0;
}
};
function getInteractionFromPointer (pointer, eventType, eventTarget) {
var i = 0, len = interactions.length,
mouseEvent = (/mouse/i.test(pointer.pointerType || eventType)
// MSPointerEvent.MSPOINTER_TYPE_MOUSE
|| pointer.pointerType === 4),
interaction;
var id = getPointerId(pointer);
// try to resume inertia with a new pointer
if (/down|start/i.test(eventType)) {
for (i = 0; i < len; i++) {
interaction = interactions[i];
var element = eventTarget;
if (interaction.inertiaStatus.active && interaction.target.options.inertia.allowResume
&& (interaction.mouse === mouseEvent)) {
while (element) {
// if the element is the interaction element
if (element === interaction.element) {
// update the interaction's pointer
interaction.removePointer(interaction.pointers[0]);
interaction.addPointer(pointer);
return interaction;
}
element = element.parentNode;
}
}
}
}
// if it's a mouse interaction
if (mouseEvent || !(supportsTouch || supportsPointerEvent)) {
// find a mouse interaction that's not in inertia phase
for (i = 0; i < len; i++) {
if (interactions[i].mouse && !interactions[i].inertiaStatus.active) {
return interactions[i];
}
}
// find any interaction specifically for mouse.
// if the eventType is a mousedown, and inertia is active
// ignore the interaction
for (i = 0; i < len; i++) {
if (interactions[i].mouse && !(/down/.test(eventType) && interactions[i].inertiaStatus.active)) {
return interaction;
}
}
// create a new interaction for mouse
interaction = new Interaction();
interaction.mouse = true;
return interaction;
}
// get interaction that has this pointer
for (i = 0; i < len; i++) {
if (contains(interactions[i].pointerIds, id)) {
return interactions[i];
}
}
// at this stage, a pointerUp should not return an interaction
if (/up|end|out/i.test(eventType)) {
return null;
}
// get first idle interaction
for (i = 0; i < len; i++) {
interaction = interactions[i];
if ((!interaction.prepared || (interaction.target.gesturable()))
&& !interaction.interacting()
&& !(!mouseEvent && interaction.mouse)) {
interaction.addPointer(pointer);
return interaction;
}
}
return new Interaction();
}
function doOnInteractions (method) {
return (function (event) {
var interaction,
eventTarget = getActualElement(event.target),
curEventTarget = getActualElement(event.currentTarget),
i;
if (supportsTouch && /touch/.test(event.type)) {
prevTouchTime = new Date().getTime();
for (i = 0; i < event.changedTouches.length; i++) {
var pointer = event.changedTouches[i];
interaction = getInteractionFromPointer(pointer, event.type, eventTarget);
if (!interaction) { continue; }
interaction[method](pointer, event, eventTarget, curEventTarget);
}
}
else {
if (!supportsPointerEvent && /mouse/.test(event.type)) {
// ignore mouse events while touch interactions are active
for (i = 0; i < interactions.length; i++) {
if (!interactions[i].mouse && interactions[i].pointerIsDown) {
return;
}
}
// try to ignore mouse events that are simulated by the browser
// after a touch event
if (new Date().getTime() - prevTouchTime < 500) {
return;
}
}
interaction = getInteractionFromPointer(event, event.type, eventTarget);
if (!interaction) { return; }
interaction[method](event, event, eventTarget, curEventTarget);
}
});
}
function InteractEvent (interaction, event, action, phase, element, related) {
var client,
page,
target = interaction.target,
snapStatus = interaction.snapStatus,
restrictStatus = interaction.restrictStatus,
pointers = interaction.pointers,
deltaSource = (target && target.options || defaultOptions).deltaSource,
sourceX = deltaSource + 'X',
sourceY = deltaSource + 'Y',
options = target? target.options: defaultOptions,
origin = getOriginXY(target, element),
starting = phase === 'start',
ending = phase === 'end',
coords = starting? interaction.startCoords : interaction.curCoords;
element = element || interaction.element;
page = extend({}, coords.page);
client = extend({}, coords.client);
page.x -= origin.x;
page.y -= origin.y;
client.x -= origin.x;
client.y -= origin.y;
if (checkSnap(target, action) && !(starting && options.snap.elementOrigin)) {
this.snap = {
range : snapStatus.range,
locked : snapStatus.locked,
x : snapStatus.snappedX,
y : snapStatus.snappedY,
realX : snapStatus.realX,
realY : snapStatus.realY,
dx : snapStatus.dx,
dy : snapStatus.dy
};
if (snapStatus.locked) {
page.x += snapStatus.dx;
page.y += snapStatus.dy;
client.x += snapStatus.dx;
client.y += snapStatus.dy;
}
}
if (checkRestrict(target, action) && !(starting && options.restrict.elementRect) && restrictStatus.restricted) {
page.x += restrictStatus.dx;
page.y += restrictStatus.dy;
client.x += restrictStatus.dx;
client.y += restrictStatus.dy;
this.restrict = {
dx: restrictStatus.dx,
dy: restrictStatus.dy
};
}
this.pageX = page.x;
this.pageY = page.y;
this.clientX = client.x;
this.clientY = client.y;
this.x0 = interaction.startCoords.page.x;
this.y0 = interaction.startCoords.page.y;
this.clientX0 = interaction.startCoords.client.x;
this.clientY0 = interaction.startCoords.client.y;
this.ctrlKey = event.ctrlKey;
this.altKey = event.altKey;
this.shiftKey = event.shiftKey;
this.metaKey = event.metaKey;
this.button = event.button;
this.target = element;
this.t0 = interaction.downTimes[0];
this.type = action + (phase || '');
this.interaction = interaction;
this.interactable = target;
var inertiaStatus = interaction.inertiaStatus;
if (inertiaStatus.active) {
this.detail = 'inertia';
}
if (related) {
this.relatedTarget = related;
}
// end event dx, dy is difference between start and end points
if (ending || action === 'drop') {
if (deltaSource === 'client') {
this.dx = client.x - interaction.startCoords.client.x;
this.dy = client.y - interaction.startCoords.client.y;
}
else {
this.dx = page.x - interaction.startCoords.page.x;
this.dy = page.y - interaction.startCoords.page.y;
}
}
else if (starting) {
this.dx = 0;
this.dy = 0;
}
// copy properties from previousmove if starting inertia
else if (phase === 'inertiastart') {
this.dx = interaction.prevEvent.dx;
this.dy = interaction.prevEvent.dy;
}
else {
if (deltaSource === 'client') {
this.dx = client.x - interaction.prevEvent.clientX;
this.dy = client.y - interaction.prevEvent.clientY;
}
else {
this.dx = page.x - interaction.prevEvent.pageX;
this.dy = page.y - interaction.prevEvent.pageY;
}
}
if (interaction.prevEvent && interaction.prevEvent.detail === 'inertia'
&& !inertiaStatus.active && options.inertia.zeroResumeDelta) {
inertiaStatus.resumeDx += this.dx;
inertiaStatus.resumeDy += this.dy;
this.dx = this.dy = 0;
}
if (action === 'resize') {
if (options.squareResize || event.shiftKey) {
if (interaction.resizeAxes === 'y') {
this.dx = this.dy;
}
else {
this.dy = this.dx;
}
this.axes = 'xy';
}
else {
this.axes = interaction.resizeAxes;
if (interaction.resizeAxes === 'x') {
this.dy = 0;
}
else if (interaction.resizeAxes === 'y') {
this.dx = 0;
}
}
}
else if (action === 'gesture') {
this.touches = [pointers[0], pointers[1]];
if (starting) {
this.distance = touchDistance(pointers, deltaSource);
this.box = touchBBox(pointers);
this.scale = 1;
this.ds = 0;
this.angle = touchAngle(pointers, undefined, deltaSource);
this.da = 0;
}
else if (ending || event instanceof InteractEvent) {
this.distance = interaction.prevEvent.distance;
this.box = interaction.prevEvent.box;
this.scale = interaction.prevEvent.scale;
this.ds = this.scale - 1;
this.angle = interaction.prevEvent.angle;
this.da = this.angle - interaction.gesture.startAngle;
}
else {
this.distance = touchDistance(pointers, deltaSource);
this.box = touchBBox(pointers);
this.scale = this.distance / interaction.gesture.startDistance;
this.angle = touchAngle(pointers, interaction.gesture.prevAngle, deltaSource);
this.ds = this.scale - interaction.gesture.prevScale;
this.da = this.angle - interaction.gesture.prevAngle;
}
}
if (starting) {
this.timeStamp = interaction.downTimes[0];
this.dt = 0;
this.duration = 0;
this.speed = 0;
this.velocityX = 0;
this.velocityY = 0;
}
else if (phase === 'inertiastart') {
this.timeStamp = interaction.prevEvent.timeStamp;
this.dt = interaction.prevEvent.dt;
this.duration = interaction.prevEvent.duration;
this.speed = interaction.prevEvent.speed;
this.velocityX = interaction.prevEvent.velocityX;
this.velocityY = interaction.prevEvent.velocityY;
}
else {
this.timeStamp = new Date().getTime();
this.dt = this.timeStamp - interaction.prevEvent.timeStamp;
this.duration = this.timeStamp - interaction.downTimes[0];
if (event instanceof InteractEvent) {
var dx = this[sourceX] - interaction.prevEvent[sourceX],
dy = this[sourceY] - interaction.prevEvent[sourceY],
dt = this.dt / 1000;
this.speed = hypot(dx, dy) / dt;
this.velocityX = dx / dt;
this.velocityY = dy / dt;
}
// if normal move or end event, use previous user event coords
else {
// speed and velocity in pixels per second
this.speed = interaction.pointerDelta[deltaSource].speed;
this.velocityX = interaction.pointerDelta[deltaSource].vx;
this.velocityY = interaction.pointerDelta[deltaSource].vy;
}
}
if ((ending || phase === 'inertiastart')
&& interaction.prevEvent.speed > 600 && this.timeStamp - interaction.prevEvent.timeStamp < 150) {
var angle = 180 * Math.atan2(interaction.prevEvent.velocityY, interaction.prevEvent.velocityX) / Math.PI,
overlap = 22.5;
if (angle < 0) {
angle += 360;
}
var left = 135 - overlap <= angle && angle < 225 + overlap,
up = 225 - overlap <= angle && angle < 315 + overlap,
right = !left && (315 - overlap <= angle || angle < 45 + overlap),
down = !up && 45 - overlap <= angle && angle < 135 + overlap;
this.swipe = {
up : up,
down : down,
left : left,
right: right,
angle: angle,
speed: interaction.prevEvent.speed,
velocity: {
x: interaction.prevEvent.velocityX,
y: interaction.prevEvent.velocityY
}
};
}
}
InteractEvent.prototype = {
preventDefault: blank,
stopImmediatePropagation: function () {
this.immediatePropagationStopped = this.propagationStopped = true;
},
stopPropagation: function () {
this.propagationStopped = true;
}
};
function preventOriginalDefault () {
this.originalEvent.preventDefault();
}
function defaultActionChecker (pointer, interaction, element) {
var rect = this.getRect(element),
right,
bottom,
action = null,
page = extend({}, interaction.curCoords.page),
options = this.options;
if (!rect) { return null; }
if (actionIsEnabled.resize && options.resizable) {
right = options.resizeAxis !== 'y' && page.x > (rect.right - margin);
bottom = options.resizeAxis !== 'x' && page.y > (rect.bottom - margin);
}
interaction.resizeAxes = (right?'x': '') + (bottom?'y': '');
action = (interaction.resizeAxes)?
'resize' + interaction.resizeAxes:
actionIsEnabled.drag && options.draggable?
'drag':
null;
if (actionIsEnabled.gesture
&& interaction.pointerIds.length >=2
&& !(interaction.dragging || interaction.resizing)) {
action = 'gesture';
}
return action;
}
// Check if action is enabled globally and the current target supports it
// If so, return the validated action. Otherwise, return null
function validateAction (action, interactable) {
if (!isString(action)) { return null; }
var actionType = action.search('resize') !== -1? 'resize': action,
options = interactable;
if (( (actionType === 'resize' && options.resizable )
|| (action === 'drag' && options.draggable )
|| (action === 'gesture' && options.gesturable))
&& actionIsEnabled[actionType]) {
if (action === 'resize' || action === 'resizeyx') {
action = 'resizexy';
}
return action;
}
return null;
}
var listeners = {},
interactionListeners = [
'dragStart', 'dragMove', 'resizeStart', 'resizeMove', 'gestureStart', 'gestureMove',
'pointerOver', 'pointerOut', 'pointerHover', 'selectorDown',
'pointerDown', 'pointerMove', 'pointerUp', 'pointerCancel', 'pointerEnd',
'addPointer', 'removePointer', 'recordPointer',
];
for (var i = 0, len = interactionListeners.length; i < len; i++) {
var name = interactionListeners[i];
listeners[name] = doOnInteractions(name);
}
// bound to the interactable context when a DOM event
// listener is added to a selector interactable
function delegateListener (event, useCapture) {
var fakeEvent = {},
delegated = delegatedEvents[event.type],
element = event.target;
useCapture = useCapture? true: false;
// duplicate the event so that currentTarget can be changed
for (var prop in event) {
fakeEvent[prop] = event[prop];
}
fakeEvent.originalEvent = event;
fakeEvent.preventDefault = preventOriginalDefault;
// climb up document tree looking for selector matches
while (element && (element.ownerDocument && element !== element.ownerDocument)) {
for (var i = 0; i < delegated.selectors.length; i++) {
var selector = delegated.selectors[i],
context = delegated.contexts[i];
if (matchesSelector(element, selector)
&& nodeContains(context, event.target)
&& nodeContains(context, element)) {
var listeners = delegated.listeners[i];
fakeEvent.currentTarget = element;
for (var j = 0; j < listeners.length; j++) {
if (listeners[j][1] === useCapture) {
listeners[j][0](fakeEvent);
}
}
}
}
element = element.parentNode;
}
}
function delegateUseCapture (event) {
return delegateListener.call(this, event, true);
}
interactables.indexOfElement = function indexOfElement (element, context) {
context = context || document;
for (var i = 0; i < this.length; i++) {
var interactable = this[i];
if ((interactable.selector === element
&& (interactable._context === context))
|| (!interactable.selector && interactable._element === element)) {
return i;
}
}
return -1;
};
interactables.get = function interactableGet (element, options) {
return this[this.indexOfElement(element, options && options.context)];
};
interactables.forEachSelector = function (callback) {
for (var i = 0; i < this.length; i++) {
var interactable = this[i];
if (!interactable.selector) {
continue;
}
var ret = callback(interactable, interactable.selector, interactable._context, i, this);
if (ret !== undefined) {
return ret;
}
}
};
/*\
* interact
[ method ]
*
* The methods of this variable can be used to set elements as
* interactables and also to change various default settings.
*
* Calling it as a function and passing an element or a valid CSS selector
* string returns an Interactable object which has various methods to
* configure it.
*
- element (Element | string) The HTML or SVG Element to interact with or CSS selector
= (object) An @Interactable
*
> Usage
| interact(document.getElementById('draggable')).draggable(true);
|
| var rectables = interact('rect');
| rectables
| .gesturable(true)
| .on('gesturemove', function (event) {
| // something cool...
| })
| .autoScroll(true);
\*/
function interact (element, options) {
return interactables.get(element, options) || new Interactable(element, options);
}
// A class for easy inheritance and setting of an Interactable's options
function IOptions (options) {
for (var option in defaultOptions) {
if (options.hasOwnProperty(option)
&& typeof options[option] === typeof defaultOptions[option]) {
this[option] = options[option];
}
}
}
IOptions.prototype = defaultOptions;
/*\
* Interactable
[ property ]
**
* Object type returned by @interact
\*/
function Interactable (element, options) {
this._element = element;
this._iEvents = this._iEvents || {};
var _window;
if (trySelector(element)) {
this.selector = element;
var context = options && options.context;
_window = context? getWindow(context) : window;
if (context && (_window.Node
? context instanceof _window.Node
: (isElement(context) || context === _window.document))) {
this._context = context;
}
}
else {
_window = getWindow(element);
if (isElement(element, _window)) {
if (PointerEvent) {
events.add(this._element, pEventTypes.down, listeners.pointerDown );
events.add(this._element, pEventTypes.move, listeners.pointerHover);
}
else {
events.add(this._element, 'mousedown' , listeners.pointerDown );
events.add(this._element, 'mousemove' , listeners.pointerHover);
events.add(this._element, 'touchstart', listeners.pointerDown );
events.add(this._element, 'touchmove' , listeners.pointerHover);
}
}
}
this._doc = _window.document;
if (!contains(documents, this._doc)) {
listenToDocument(this._doc);
}
interactables.push(this);
this.set(options);
}
Interactable.prototype = {
setOnEvents: function (action, phases) {
if (action === 'drop') {
var drop = phases.ondrop || phases.onDrop || phases.drop,
dropactivate = phases.ondropactivate || phases.onDropActivate || phases.dropactivate
|| phases.onactivate || phases.onActivate || phases.activate,
dropdeactivate = phases.ondropdeactivate || phases.onDropDeactivate || phases.dropdeactivate
|| phases.ondeactivate || phases.onDeactivate || phases.deactivate,
dragenter = phases.ondragenter || phases.onDropEnter || phases.dragenter
|| phases.onenter || phases.onEnter || phases.enter,
dragleave = phases.ondragleave || phases.onDropLeave || phases.dragleave
|| phases.onleave || phases.onLeave || phases.leave,
dropmove = phases.ondropmove || phases.onDropMove || phases.dropmove
|| phases.onmove || phases.onMove || phases.move;
if (isFunction(drop) ) { this.ondrop = drop ; }
if (isFunction(dropactivate) ) { this.ondropactivate = dropactivate ; }
if (isFunction(dropdeactivate)) { this.ondropdeactivate = dropdeactivate; }
if (isFunction(dragenter) ) { this.ondragenter = dragenter ; }
if (isFunction(dragleave) ) { this.ondragleave = dragleave ; }
if (isFunction(dropmove) ) { this.ondropmove = dropmove ; }
}
else {
var start = phases.onstart || phases.onStart || phases.start,
move = phases.onmove || phases.onMove || phases.move,
end = phases.onend || phases.onEnd || phases.end,
inertiastart = phases.oninertiastart || phases.onInertiaStart || phases.inertiastart;
action = 'on' + action;
if (isFunction(start) ) { this[action + 'start' ] = start ; }
if (isFunction(move) ) { this[action + 'move' ] = move ; }
if (isFunction(end) ) { this[action + 'end' ] = end ; }
if (isFunction(inertiastart)) { this[action + 'inertiastart' ] = inertiastart ; }
}
return this;
},
/*\
* Interactable.draggable
[ method ]
*
* Gets or sets whether drag actions can be performed on the
* Interactable
*
= (boolean) Indicates if this can be the target of drag events
| var isDraggable = interact('ul li').draggable();
* or
- options (boolean | object) #optional true/false or An object with event listeners to be fired on drag events (object makes the Interactable draggable)
= (object) This Interactable
| interact(element).draggable({
| onstart: function (event) {},
| onmove : function (event) {},
| onend : function (event) {},
|
| // the axis in which the first movement must be
| // for the drag sequence to start
| // 'xy' by default - any direction
| axis: 'x' || 'y' || 'xy',
|
| // max number of drags that can happen concurrently
| // with elements of this Interactable. 1 by default
| max: Infinity,
|
| // max number of drags that can target the same element
| // 1 by default
| maxPerElement: 2
| });
\*/
draggable: function (options) {
if (isObject(options)) {
this.options.draggable = true;
this.setOnEvents('drag', options);
if (isNumber(options.max)) {
this.options.dragMax = options.max;
}
if (isNumber(options.maxPerElement)) {
this.options.dragMaxPerElement = options.maxPerElement;
}
if (/^x$|^y$|^xy$/.test(options.axis)) {
this.options.dragAxis = options.axis;
}
else if (options.axis === null) {
delete this.options.dragAxis;
}
return this;
}
if (isBool(options)) {
this.options.draggable = options;
return this;
}
if (options === null) {
delete this.options.draggable;
return this;
}
return this.options.draggable;
},
/*\
* Interactable.dropzone
[ method ]
*
* Returns or sets whether elements can be dropped onto this
* Interactable to trigger drop events
*
* Dropzones can receive the following events:
* - `dragactivate` and `dragdeactivate` when an acceptable drag starts and ends
* - `dragenter` and `dragleave` when a draggable enters and leaves the dropzone
* - `drop` when a draggable is dropped into this dropzone
*
* Use the `accept` option to allow only elements that match the given CSS selector or element.
*
* Use the `overlap` option to set how drops are checked for. The allowed values are:
* - `'pointer'`, the pointer must be over the dropzone (default)
* - `'center'`, the draggable element's center must be over the dropzone
* - a number from 0-1 which is the `(intersection area) / (draggable area)`.
* e.g. `0.5` for drop to happen when half of the area of the
* draggable is over the dropzone
*
- options (boolean | object | null) #optional The new value to be set.
| interact('.drop').dropzone({
| accept: '.can-drop' || document.getElementById('single-drop'),
| overlap: 'pointer' || 'center' || zeroToOne
| }
= (boolean | object) The current setting or this Interactable
\*/
dropzone: function (options) {
if (isObject(options)) {
this.options.dropzone = true;
this.setOnEvents('drop', options);
this.accept(options.accept);
if (/^(pointer|center)$/.test(options.overlap)) {
this.options.dropOverlap = options.overlap;
}
else if (isNumber(options.overlap)) {
this.options.dropOverlap = Math.max(Math.min(1, options.overlap), 0);
}
return this;
}
if (isBool(options)) {
this.options.dropzone = options;
return this;
}
if (options === null) {
delete this.options.dropzone;
return this;
}
return this.options.dropzone;
},
/*\
* Interactable.dropCheck
[ method ]
*
* The default function to determine if a dragend event occured over
* this Interactable's element. Can be overridden using
* @Interactable.dropChecker.
*
- pointer (MouseEvent | PointerEvent | Touch) The event that ends a drag
- draggable (Interactable) The Interactable being dragged
- draggableElement (Element) The actual element that's being dragged
- dropElement (Element) The dropzone element
- rect (object) #optional The rect of dropElement
= (boolean) whether the pointer was over this Interactable
\*/
dropCheck: function (pointer, draggable, draggableElement, dropElement, rect) {
if (!(rect = rect || this.getRect(dropElement))) {
return false;
}
var dropOverlap = this.options.dropOverlap;
if (dropOverlap === 'pointer') {
var page = getPageXY(pointer),
origin = getOriginXY(draggable, draggableElement),
horizontal,
vertical;
page.x += origin.x;
page.y += origin.y;
horizontal = (page.x > rect.left) && (page.x < rect.right);
vertical = (page.y > rect.top ) && (page.y < rect.bottom);
return horizontal && vertical;
}
var dragRect = draggable.getRect(draggableElement);
if (dropOverlap === 'center') {
var cx = dragRect.left + dragRect.width / 2,
cy = dragRect.top + dragRect.height / 2;
return cx >= rect.left && cx <= rect.right && cy >= rect.top && cy <= rect.bottom;
}
if (isNumber(dropOverlap)) {
var overlapArea = (Math.max(0, Math.min(rect.right , dragRect.right ) - Math.max(rect.left, dragRect.left))
* Math.max(0, Math.min(rect.bottom, dragRect.bottom) - Math.max(rect.top , dragRect.top ))),
overlapRatio = overlapArea / (dragRect.width * dragRect.height);
return overlapRatio >= dropOverlap;
}
},
/*\
* Interactable.dropChecker
[ method ]
*
* Gets or sets the function used to check if a dragged element is
* over this Interactable. See @Interactable.dropCheck.
*
- checker (function) #optional
* The checker is a function which takes a mouseUp/touchEnd event as a
* parameter and returns true or false to indicate if the the current
* draggable can be dropped into this Interactable
*
= (Function | Interactable) The checker function or this Interactable
\*/
dropChecker: function (checker) {
if (isFunction(checker)) {
this.dropCheck = checker;
return this;
}
return this.dropCheck;
},
/*\
* Interactable.accept
[ method ]
*
* Gets or sets the Element or CSS selector match that this
* Interactable accepts if it is a dropzone.
*
- newValue (Element | string | null) #optional
* If it is an Element, then only that element can be dropped into this dropzone.
* If it is a string, the element being dragged must match it as a selector.
* If it is null, the accept options is cleared - it accepts any element.
*
= (string | Element | null | Interactable) The current accept option if given `undefined` or this Interactable
\*/
accept: function (newValue) {
if (isElement(newValue)) {
this.options.accept = newValue;
return this;
}
// test if it is a valid CSS selector
if (trySelector(newValue)) {
this.options.accept = newValue;
return this;
}
if (newValue === null) {
delete this.options.accept;
return this;
}
return this.options.accept;
},
/*\
* Interactable.resizable
[ method ]
*
* Gets or sets whether resize actions can be performed on the
* Interactable
*
= (boolean) Indicates if this can be the target of resize elements
| var isResizeable = interact('input[type=text]').resizable();
* or
- options (boolean | object) #optional true/false or An object with event listeners to be fired on resize events (object makes the Interactable resizable)
= (object) This Interactable
| interact(element).resizable({
| onstart: function (event) {},
| onmove : function (event) {},
| onend : function (event) {},
|
| axis : 'x' || 'y' || 'xy' // default is 'xy',
|
| // limit multiple resizes.
| // See the explanation in @Interactable.draggable example
| max: 1,
| maxPerElement: 1,
| });
\*/
resizable: function (options) {
if (isObject(options)) {
this.options.resizable = true;
this.setOnEvents('resize', options);
if (isNumber(options.max)) {
this.options.resizeMax = options.max;
}
if (isNumber(options.maxPerElement)) {
this.options.resizeMaxPerElement = options.maxPerElement;
}
if (/^x$|^y$|^xy$/.test(options.axis)) {
this.options.resizeAxis = options.axis;
}
else if (options.axis === null) {
this.options.resizeAxis = defaultOptions.resizeAxis;
}
return this;
}
if (isBool(options)) {
this.options.resizable = options;
return this;
}
return this.options.resizable;
},
// misspelled alias
resizeable: blank,
/*\
* Interactable.squareResize
[ method ]
*
* Gets or sets whether resizing is forced 1:1 aspect
*
= (boolean) Current setting
*
* or
*
- newValue (boolean) #optional
= (object) this Interactable
\*/
squareResize: function (newValue) {
if (isBool(newValue)) {
this.options.squareResize = newValue;
return this;
}
if (newValue === null) {
delete this.options.squareResize;
return this;
}
return this.options.squareResize;
},
/*\
* Interactable.gesturable
[ method ]
*
* Gets or sets whether multitouch gestures can be performed on the
* Interactable's element
*
= (boolean) Indicates if this can be the target of gesture events
| var isGestureable = interact(element).gesturable();
* or
- options (boolean | object) #optional true/false or An object with event listeners to be fired on gesture events (makes the Interactable gesturable)
= (object) this Interactable
| interact(element).gesturable({
| onstart: function (event) {},
| onmove : function (event) {},
| onend : function (event) {},
|
| // limit multiple gestures.
| // See the explanation in @Interactable.draggable example
| max: 1,
| maxPerElement: 1,
| });
\*/
gesturable: function (options) {
if (isObject(options)) {
this.options.gesturable = true;
this.setOnEvents('gesture', options);
if (isNumber(options.max)) {
this.options.gestureMax = options.max;
}
if (isNumber(options.maxPerElement)) {
this.options.gestureMaxPerElement = options.maxPerElement;
}
return this;
}
if (isBool(options)) {
this.options.gesturable = options;
return this;
}
if (options === null) {
delete this.options.gesturable;
return this;
}
return this.options.gesturable;
},
// misspelled alias
gestureable: blank,
/*\
* Interactable.autoScroll
[ method ]
*
* Returns or sets whether or not any actions near the edges of the
* window/container trigger autoScroll for this Interactable
*
= (boolean | object)
* `false` if autoScroll is disabled; object with autoScroll properties
* if autoScroll is enabled
*
* or
*
- options (object | boolean | null) #optional
* options can be:
* - an object with margin, distance and interval properties,
* - true or false to enable or disable autoScroll or
* - null to use default settings
= (Interactable) this Interactable
\*/
autoScroll: function (options) {
var defaults = defaultOptions.autoScroll;
if (isObject(options)) {
var autoScroll = this.options.autoScroll;
if (autoScroll === defaults) {
autoScroll = this.options.autoScroll = {
margin : defaults.margin,
distance : defaults.distance,
interval : defaults.interval,
container: defaults.container
};
}
autoScroll.margin = this.validateSetting('autoScroll', 'margin', options.margin);
autoScroll.speed = this.validateSetting('autoScroll', 'speed' , options.speed);
autoScroll.container =
(isElement(options.container) || isWindow(options.container)
? options.container
: defaults.container);
this.options.autoScrollEnabled = true;
this.options.autoScroll = autoScroll;
return this;
}
if (isBool(options)) {
this.options.autoScrollEnabled = options;
return this;
}
if (options === null) {
delete this.options.autoScrollEnabled;
delete this.options.autoScroll;
return this;
}
return (this.options.autoScrollEnabled
? this.options.autoScroll
: false);
},
/*\
* Interactable.snap
[ method ]
**
* Returns or sets if and how action coordinates are snapped. By
* default, snapping is relative to the pointer coordinates. You can
* change this by setting the
* [`elementOrigin`](https://github.com/taye/interact.js/pull/72).
**
= (boolean | object) `false` if snap is disabled; object with snap properties if snap is enabled
**
* or
**
- options (object | boolean | null) #optional
= (Interactable) this Interactable
> Usage
| interact('.handle').snap({
| mode : 'grid', // event coords should snap to the corners of a grid
| range : Infinity, // the effective distance of snap points
| grid : { x: 100, y: 100 }, // the x and y spacing of the grid points
| gridOffset : { x: 0, y: 0 }, // the offset of the grid points
| });
|
| interact('.handle').snap({
| mode : 'anchor', // snap to specified points
| anchors : [
| { x: 100, y: 100, range: 25 }, // a point with x, y and a specific range
| { x: 200, y: 200 } // a point with x and y. it uses the default range
| ]
| });
|
| interact(document.querySelector('#thing')).snap({
| mode : 'path',
| paths: [
| { // snap to points on these x and y axes
| x: 100,
| y: 100,
| range: 25
| },
| // give this function the x and y page coords and snap to the object returned
| function (x, y) {
| return {
| x: x,
| y: (75 + 50 * Math.sin(x * 0.04)),
| range: 40
| };
| }]
| })
|
| interact(element).snap({
| // do not snap during normal movement.
| // Instead, trigger only one snapped move event
| // immediately before the end event.
| endOnly: true,
|
| // https://github.com/taye/interact.js/pull/72#issue-41813493
| elementOrigin: { x: 0, y: 0 }
| });
\*/
snap: function (options) {
var defaults = defaultOptions.snap;
if (isObject(options)) {
var snap = this.options.snap;
if (snap === defaults) {
snap = {};
}
snap.mode = this.validateSetting('snap', 'mode' , options.mode);
snap.endOnly = this.validateSetting('snap', 'endOnly' , options.endOnly);
snap.actions = this.validateSetting('snap', 'actions' , options.actions);
snap.range = this.validateSetting('snap', 'range' , options.range);
snap.paths = this.validateSetting('snap', 'paths' , options.paths);
snap.grid = this.validateSetting('snap', 'grid' , options.grid);
snap.gridOffset = this.validateSetting('snap', 'gridOffset' , options.gridOffset);
snap.anchors = this.validateSetting('snap', 'anchors' , options.anchors);
snap.elementOrigin = this.validateSetting('snap', 'elementOrigin', options.elementOrigin);
this.options.snapEnabled = true;
this.options.snap = snap;
return this;
}
if (isBool(options)) {
this.options.snapEnabled = options;
return this;
}
if (options === null) {
delete this.options.snapEnabled;
delete this.options.snap;
return this;
}
return (this.options.snapEnabled
? this.options.snap
: false);
},
/*\
* Interactable.inertia
[ method ]
**
* Returns or sets if and how events continue to run after the pointer is released
**
= (boolean | object) `false` if inertia is disabled; `object` with inertia properties if inertia is enabled
**
* or
**
- options (object | boolean | null) #optional
= (Interactable) this Interactable
> Usage
| // enable and use default settings
| interact(element).inertia(true);
|
| // enable and use custom settings
| interact(element).inertia({
| // value greater than 0
| // high values slow the object down more quickly
| resistance : 16,
|
| // the minimum launch speed (pixels per second) that results in inertia start
| minSpeed : 200,
|
| // inertia will stop when the object slows down to this speed
| endSpeed : 20,
|
| // boolean; should actions be resumed when the pointer goes down during inertia
| allowResume : true,
|
| // boolean; should the jump when resuming from inertia be ignored in event.dx/dy
| zeroResumeDelta: false,
|
| // if snap/restrict are set to be endOnly and inertia is enabled, releasing
| // the pointer without triggering inertia will animate from the release
| // point to the snaped/restricted point in the given amount of time (ms)
| smoothEndDuration: 300,
|
| // an array of action types that can have inertia (no gesture)
| actions : ['drag', 'resize']
| });
|
| // reset custom settings and use all defaults
| interact(element).inertia(null);
\*/
inertia: function (options) {
var defaults = defaultOptions.inertia;
if (isObject(options)) {
var inertia = this.options.inertia;
if (inertia === defaults) {
inertia = this.options.inertia = {
resistance : defaults.resistance,
minSpeed : defaults.minSpeed,
endSpeed : defaults.endSpeed,
actions : defaults.actions,
allowResume : defaults.allowResume,
zeroResumeDelta : defaults.zeroResumeDelta,
smoothEndDuration: defaults.smoothEndDuration
};
}
inertia.resistance = this.validateSetting('inertia', 'resistance' , options.resistance);
inertia.minSpeed = this.validateSetting('inertia', 'minSpeed' , options.minSpeed);
inertia.endSpeed = this.validateSetting('inertia', 'endSpeed' , options.endSpeed);
inertia.actions = this.validateSetting('inertia', 'actions' , options.actions);
inertia.allowResume = this.validateSetting('inertia', 'allowResume' , options.allowResume);
inertia.zeroResumeDelta = this.validateSetting('inertia', 'zeroResumeDelta' , options.zeroResumeDelta);
inertia.smoothEndDuration = this.validateSetting('inertia', 'smoothEndDuration', options.smoothEndDuration);
this.options.inertiaEnabled = true;
this.options.inertia = inertia;
return this;
}
if (isBool(options)) {
this.options.inertiaEnabled = options;
return this;
}
if (options === null) {
delete this.options.inertiaEnabled;
delete this.options.inertia;
return this;
}
return (this.options.inertiaEnabled
? this.options.inertia
: false);
},
getAction: function (pointer, interaction, element) {
var action = this.defaultActionChecker(pointer, interaction, element);
if (this.options.actionChecker) {
action = this.options.actionChecker(pointer, action, this, element, interaction);
}
return action;
},
defaultActionChecker: defaultActionChecker,
/*\
* Interactable.actionChecker
[ method ]
*
* Gets or sets the function used to check action to be performed on
* pointerDown
*
- checker (function | null) #optional A function which takes a pointer event, defaultAction string and an interactable as parameters and returns 'drag' 'resize[axes]' or 'gesture' or null.
= (Function | Interactable) The checker function or this Interactable
\*/
actionChecker: function (newValue) {
if (isFunction(newValue)) {
this.options.actionChecker = newValue;
return this;
}
if (newValue === null) {
delete this.options.actionChecker;
return this;
}
return this.options.actionChecker;
},
/*\
* Interactable.getRect
[ method ]
*
* The default function to get an Interactables bounding rect. Can be
* overridden using @Interactable.rectChecker.
*
- element (Element) #optional The element to measure. Meant to be used for selector Interactables which don't have a specific element.
= (object) The object's bounding rectangle.
o {
o top : 0,
o left : 0,
o bottom: 0,
o right : 0,
o width : 0,
o height: 0
o }
\*/
getRect: function rectCheck (element) {
element = element || this._element;
if (this.selector && !(isElement(element))) {
element = this._context.querySelector(this.selector);
}
return getElementRect(element);
},
/*\
* Interactable.rectChecker
[ method ]
*
* Returns or sets the function used to calculate the interactable's
* element's rectangle
*
- checker (function) #optional A function which returns this Interactable's bounding rectangle. See @Interactable.getRect
= (function | object) The checker function or this Interactable
\*/
rectChecker: function (checker) {
if (isFunction(checker)) {
this.getRect = checker;
return this;
}
if (checker === null) {
delete this.options.getRect;
return this;
}
return this.getRect;
},
/*\
* Interactable.styleCursor
[ method ]
*
* Returns or sets whether the action that would be performed when the
* mouse on the element are checked on `mousemove` so that the cursor
* may be styled appropriately
*
- newValue (boolean) #optional
= (boolean | Interactable) The current setting or this Interactable
\*/
styleCursor: function (newValue) {
if (isBool(newValue)) {
this.options.styleCursor = newValue;
return this;
}
if (newValue === null) {
delete this.options.styleCursor;
return this;
}
return this.options.styleCursor;
},
/*\
* Interactable.preventDefault
[ method ]
*
* Returns or sets whether to prevent the browser's default behaviour
* in response to pointer events. Can be set to
* - `true` to always prevent
* - `false` to never prevent
* - `'auto'` to allow interact.js to try to guess what would be best
* - `null` to set to the default ('auto')
*
- newValue (boolean | string | null) #optional `true`, `false` or `'auto'`
= (boolean | string | Interactable) The current setting or this Interactable
\*/
preventDefault: function (newValue) {
if (isBool(newValue) || newValue === 'auto') {
this.options.preventDefault = newValue;
return this;
}
if (newValue === null) {
delete this.options.preventDefault;
return this;
}
return this.options.preventDefault;
},
/*\
* Interactable.origin
[ method ]
*
* Gets or sets the origin of the Interactable's element. The x and y
* of the origin will be subtracted from action event coordinates.
*
- origin (object | string) #optional An object eg. { x: 0, y: 0 } or string 'parent', 'self' or any CSS selector
* OR
- origin (Element) #optional An HTML or SVG Element whose rect will be used
**
= (object) The current origin or this Interactable
\*/
origin: function (newValue) {
if (trySelector(newValue)) {
this.options.origin = newValue;
return this;
}
else if (isObject(newValue)) {
this.options.origin = newValue;
return this;
}
if (newValue === null) {
delete this.options.origin;
return this;
}
return this.options.origin;
},
/*\
* Interactable.deltaSource
[ method ]
*
* Returns or sets the mouse coordinate types used to calculate the
* movement of the pointer.
*
- newValue (string) #optional Use 'client' if you will be scrolling while interacting; Use 'page' if you want autoScroll to work
= (string | object) The current deltaSource or this Interactable
\*/
deltaSource: function (newValue) {
if (newValue === 'page' || newValue === 'client') {
this.options.deltaSource = newValue;
return this;
}
if (newValue === null) {
delete this.options.deltaSource;
return this;
}
return this.options.deltaSource;
},
/*\
* Interactable.restrict
[ method ]
**
* Returns or sets the rectangles within which actions on this
* interactable (after snap calculations) are restricted. By default,
* restricting is relative to the pointer coordinates. You can change
* this by setting the
* [`elementRect`](https://github.com/taye/interact.js/pull/72).
**
- newValue (object) #optional an object with keys drag, resize, and/or gesture whose values are rects, Elements, CSS selectors, or 'parent' or 'self'
= (object) The current restrictions object or this Interactable
**
| interact(element).restrict({
| // the rect will be `interact.getElementRect(element.parentNode)`
| drag: element.parentNode,
|
| // x and y are relative to the the interactable's origin
| resize: { x: 100, y: 100, width: 200, height: 200 }
| })
|
| interact('.draggable').restrict({
| // the rect will be the selected element's parent
| drag: 'parent',
|
| // do not restrict during normal movement.
| // Instead, trigger only one restricted move event
| // immediately before the end event.
| endOnly: true,
|
| // https://github.com/taye/interact.js/pull/72#issue-41813493
| elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
| });
\*/
restrict: function (newValue) {
if (newValue === undefined) {
return this.options.restrict;
}
if (isBool(newValue)) {
defaultOptions.restrictEnabled = newValue;
}
else if (isObject(newValue)) {
var newRestrictions = {};
if (isObject(newValue.drag) || trySelector(newValue.drag)) {
newRestrictions.drag = newValue.drag;
}
if (isObject(newValue.resize) || trySelector(newValue.resize)) {
newRestrictions.resize = newValue.resize;
}
if (isObject(newValue.gesture) || trySelector(newValue.gesture)) {
newRestrictions.gesture = newValue.gesture;
}
if (isBool(newValue.endOnly)) {
newRestrictions.endOnly = newValue.endOnly;
}
if (isObject(newValue.elementRect)) {
newRestrictions.elementRect = newValue.elementRect;
}
this.options.restrictEnabled = true;
this.options.restrict = newRestrictions;
}
else if (newValue === null) {
delete this.options.restrict;
delete this.options.restrictEnabled;
}
return this;
},
/*\
* Interactable.context
[ method ]
*
* Get's the selector context Node of the Interactable. The default is `window.document`.
*
= (Node) The context Node of this Interactable
**
\*/
context: function () {
return this._context;
},
_context: document,
/*\
* Interactable.ignoreFrom
[ method ]
*
* If the target of the `mousedown`, `pointerdown` or `touchstart`
* event or any of it's parents match the given CSS selector or
* Element, no drag/resize/gesture is started.
*
- newValue (string | Element | null) #optional a CSS selector string, an Element or `null` to not ignore any elements
= (string | Element | object) The current ignoreFrom value or this Interactable
**
| interact(element, { ignoreFrom: document.getElementById('no-action') });
| // or
| interact(element).ignoreFrom('input, textarea, a');
\*/
ignoreFrom: function (newValue) {
if (trySelector(newValue)) { // CSS selector to match event.target
this.options.ignoreFrom = newValue;
return this;
}
if (isElement(newValue)) { // specific element
this.options.ignoreFrom = newValue;
return this;
}
if (newValue === null) {
delete this.options.ignoreFrom;
return this;
}
return this.options.ignoreFrom;
},
/*\
* Interactable.allowFrom
[ method ]
*
* A drag/resize/gesture is started only If the target of the
* `mousedown`, `pointerdown` or `touchstart` event or any of it's
* parents match the given CSS selector or Element.
*
- newValue (string | Element | null) #optional a CSS selector string, an Element or `null` to allow from any element
= (string | Element | object) The current allowFrom value or this Interactable
**
| interact(element, { allowFrom: document.getElementById('drag-handle') });
| // or
| interact(element).allowFrom('.handle');
\*/
allowFrom: function (newValue) {
if (trySelector(newValue)) { // CSS selector to match event.target
this.options.allowFrom = newValue;
return this;
}
if (isElement(newValue)) { // specific element
this.options.allowFrom = newValue;
return this;
}
if (newValue === null) {
delete this.options.allowFrom;
return this;
}
return this.options.allowFrom;
},
/*\
* Interactable.validateSetting
[ method ]
*
- context (string) eg. 'snap', 'autoScroll'
- option (string) The name of the value being set
- value (any type) The value being validated
*
= (typeof value) A valid value for the give context-option pair
* - null if defaultOptions[context][value] is undefined
* - value if it is the same type as defaultOptions[context][value],
* - this.options[context][value] if it is the same type as defaultOptions[context][value],
* - or defaultOptions[context][value]
\*/
validateSetting: function (context, option, value) {
var defaults = defaultOptions[context],
current = this.options[context];
if (defaults !== undefined && defaults[option] !== undefined) {
if ('objectTypes' in defaults && defaults.objectTypes.test(option)) {
if (isObject(value)) { return value; }
else {
return (option in current && isObject(current[option])
? current [option]
: defaults[option]);
}
}
if ('arrayTypes' in defaults && defaults.arrayTypes.test(option)) {
if (isArray(value)) { return value; }
else {
return (option in current && isArray(current[option])
? current[option]
: defaults[option]);
}
}
if ('stringTypes' in defaults && defaults.stringTypes.test(option)) {
if (isString(value)) { return value; }
else {
return (option in current && isString(current[option])
? current[option]
: defaults[option]);
}
}
if ('numberTypes' in defaults && defaults.numberTypes.test(option)) {
if (isNumber(value)) { return value; }
else {
return (option in current && isNumber(current[option])
? current[option]
: defaults[option]);
}
}
if ('boolTypes' in defaults && defaults.boolTypes.test(option)) {
if (isBool(value)) { return value; }
else {
return (option in current && isBool(current[option])
? current[option]
: defaults[option]);
}
}
if ('elementTypes' in defaults && defaults.elementTypes.test(option)) {
if (isElement(value)) { return value; }
else {
return (option in current && isElement(current[option])
? current[option]
: defaults[option]);
}
}
}
return null;
},
/*\
* Interactable.element
[ method ]
*
* If this is not a selector Interactable, it returns the element this
* interactable represents
*
= (Element) HTML / SVG Element
\*/
element: function () {
return this._element;
},
/*\
* Interactable.fire
[ method ]
*
* Calls listeners for the given InteractEvent type bound globally
* and directly to this Interactable
*
- iEvent (InteractEvent) The InteractEvent object to be fired on this Interactable
= (Interactable) this Interactable
\*/
fire: function (iEvent) {
if (!(iEvent && iEvent.type) || !contains(eventTypes, iEvent.type)) {
return this;
}
var listeners,
i,
len,
onEvent = 'on' + iEvent.type,
funcName = '';
// Interactable#on() listeners
if (iEvent.type in this._iEvents) {
listeners = this._iEvents[iEvent.type];
for (i = 0, len = listeners.length; i < len && !iEvent.immediatePropagationStopped; i++) {
funcName = listeners[i].name;
listeners[i](iEvent);
}
}
// interactable.onevent listener
if (isFunction(this[onEvent])) {
funcName = this[onEvent].name;
this[onEvent](iEvent);
}
// interact.on() listeners
if (iEvent.type in globalEvents && (listeners = globalEvents[iEvent.type])) {
for (i = 0, len = listeners.length; i < len && !iEvent.immediatePropagationStopped; i++) {
funcName = listeners[i].name;
listeners[i](iEvent);
}
}
return this;
},
/*\
* Interactable.on
[ method ]
*
* Binds a listener for an InteractEvent or DOM event.
*
- eventType (string | array) The type of event or array of types to listen for
- listener (function) The function to be called on the given event(s)
- useCapture (boolean) #optional useCapture flag for addEventListener
= (object) This Interactable
\*/
on: function (eventType, listener, useCapture) {
var i;
if (isArray(eventType)) {
for (i = 0; i < eventType.length; i++) {
this.on(eventType[i], listener, useCapture);
}
return this;
}
if (eventType === 'wheel') {
eventType = wheelEvent;
}
// convert to boolean
useCapture = useCapture? true: false;
if (contains(eventTypes, eventType)) {
// if this type of event was never bound to this Interactable
if (!(eventType in this._iEvents)) {
this._iEvents[eventType] = [listener];
}
else {
this._iEvents[eventType].push(listener);
}
}
// delegated event for selector
else if (this.selector) {
if (!delegatedEvents[eventType]) {
delegatedEvents[eventType] = {
selectors: [],
contexts : [],
listeners: []
};
// add delegate listener functions
for (i = 0; i < documents.length; i++) {
events.add(documents[i], eventType, delegateListener);
events.add(documents[i], eventType, delegateUseCapture, true);
}
}
var delegated = delegatedEvents[eventType],
index;
for (index = delegated.selectors.length - 1; index >= 0; index--) {
if (delegated.selectors[index] === this.selector
&& delegated.contexts[index] === this._context) {
break;
}
}
if (index === -1) {
index = delegated.selectors.length;
delegated.selectors.push(this.selector);
delegated.contexts .push(this._context);
delegated.listeners.push([]);
}
// keep listener and useCapture flag
delegated.listeners[index].push([listener, useCapture]);
}
else {
events.add(this._element, eventType, listener, useCapture);
}
return this;
},
/*\
* Interactable.off
[ method ]
*
* Removes an InteractEvent or DOM event listener
*
- eventType (string | array) The type of event or array of types that were listened for
- listener (function) The listener function to be removed
- useCapture (boolean) #optional useCapture flag for removeEventListener
= (object) This Interactable
\*/
off: function (eventType, listener, useCapture) {
var i;
if (isArray(eventType)) {
for (i = 0; i < eventType.length; i++) {
this.off(eventType[i], listener, useCapture);
}
return this;
}
var eventList,
index = -1;
// convert to boolean
useCapture = useCapture? true: false;
if (eventType === 'wheel') {
eventType = wheelEvent;
}
// if it is an action event type
if (contains(eventTypes, eventType)) {
eventList = this._iEvents[eventType];
if (eventList && (index = indexOf(eventList, listener)) !== -1) {
this._iEvents[eventType].splice(index, 1);
}
}
// delegated event
else if (this.selector) {
var delegated = delegatedEvents[eventType],
matchFound = false;
if (!delegated) { return this; }
// count from last index of delegated to 0
for (index = delegated.selectors.length - 1; index >= 0; index--) {
// look for matching selector and context Node
if (delegated.selectors[index] === this.selector
&& delegated.contexts[index] === this._context) {
var listeners = delegated.listeners[index];
// each item of the listeners array is an array: [function, useCaptureFlag]
for (i = listeners.length - 1; i >= 0; i--) {
var fn = listeners[i][0],
useCap = listeners[i][1];
// check if the listener functions and useCapture flags match
if (fn === listener && useCap === useCapture) {
// remove the listener from the array of listeners
listeners.splice(i, 1);
// if all listeners for this interactable have been removed
// remove the interactable from the delegated arrays
if (!listeners.length) {
delegated.selectors.splice(index, 1);
delegated.contexts .splice(index, 1);
delegated.listeners.splice(index, 1);
// remove delegate function from context
events.remove(this._context, eventType, delegateListener);
events.remove(this._context, eventType, delegateUseCapture, true);
// remove the arrays if they are empty
if (!delegated.selectors.length) {
delegatedEvents[eventType] = null;
}
}
// only remove one listener
matchFound = true;
break;
}
}
if (matchFound) { break; }
}
}
}
// remove listener from this Interatable's element
else {
events.remove(this, listener, useCapture);
}
return this;
},
/*\
* Interactable.set
[ method ]
*
* Reset the options of this Interactable
- options (object) The new settings to apply
= (object) This Interactablw
\*/
set: function (options) {
if (!options || !isObject(options)) {
options = {};
}
this.options = new IOptions(options);
this.draggable ('draggable' in options? options.draggable : this.options.draggable );
this.dropzone ('dropzone' in options? options.dropzone : this.options.dropzone );
this.resizable ('resizable' in options? options.resizable : this.options.resizable );
this.gesturable('gesturable' in options? options.gesturable: this.options.gesturable);
var settings = [
'accept', 'actionChecker', 'allowFrom', 'autoScroll', 'deltaSource',
'dropChecker', 'ignoreFrom', 'inertia', 'origin', 'preventDefault',
'rectChecker', 'restrict', 'snap', 'styleCursor'
];
for (var i = 0, len = settings.length; i < len; i++) {
var setting = settings[i];
if (setting in options) {
this[setting](options[setting]);
}
}
return this;
},
/*\
* Interactable.unset
[ method ]
*
* Remove this interactable from the list of interactables and remove
* it's drag, drop, resize and gesture capabilities
*
= (object) @interact
\*/
unset: function () {
events.remove(this, 'all');
if (!isString(this.selector)) {
events.remove(this, 'all');
if (this.options.styleCursor) {
this._element.style.cursor = '';
}
}
else {
// remove delegated events
for (var type in delegatedEvents) {
var delegated = delegatedEvents[type];
for (var i = 0; i < delegated.selectors.length; i++) {
if (delegated.selectors[i] === this.selector
&& delegated.contexts[i] === this._context) {
delegated.selectors.splice(i, 1);
delegated.contexts .splice(i, 1);
delegated.listeners.splice(i, 1);
// remove the arrays if they are empty
if (!delegated.selectors.length) {
delegatedEvents[type] = null;
}
}
events.remove(this._context, type, delegateListener);
events.remove(this._context, type, delegateUseCapture, true);
break;
}
}
}
this.dropzone(false);
interactables.splice(indexOf(interactables, this), 1);
return interact;
}
};
Interactable.prototype.gestureable = Interactable.prototype.gesturable;
Interactable.prototype.resizeable = Interactable.prototype.resizable;
/*\
* interact.isSet
[ method ]
*
* Check if an element has been set
- element (Element) The Element being searched for
= (boolean) Indicates if the element or CSS selector was previously passed to interact
\*/
interact.isSet = function(element, options) {
return interactables.indexOfElement(element, options && options.context) !== -1;
};
/*\
* interact.on
[ method ]
*
* Adds a global listener for an InteractEvent or adds a DOM event to
* `document`
*
- type (string | array) The type of event or array of types to listen for
- listener (function) The function to be called on the given event(s)
- useCapture (boolean) #optional useCapture flag for addEventListener
= (object) interact
\*/
interact.on = function (type, listener, useCapture) {
if (isArray(type)) {
for (var i = 0; i < type.length; i++) {
interact.on(type[i], listener, useCapture);
}
return interact;
}
// if it is an InteractEvent type, add listener to globalEvents
if (contains(eventTypes, type)) {
// if this type of event was never bound
if (!globalEvents[type]) {
globalEvents[type] = [listener];
}
else {
globalEvents[type].push(listener);
}
}
// If non InteractEvent type, addEventListener to document
else {
events.add(document, type, listener, useCapture);
}
return interact;
};
/*\
* interact.off
[ method ]
*
* Removes a global InteractEvent listener or DOM event from `document`
*
- type (string | array) The type of event or array of types that were listened for
- listener (function) The listener function to be removed
- useCapture (boolean) #optional useCapture flag for removeEventListener
= (object) interact
\*/
interact.off = function (type, listener, useCapture) {
if (isArray(type)) {
for (var i = 0; i < type.length; i++) {
interact.off(type[i], listener, useCapture);
}
return interact;
}
if (!contains(eventTypes, type)) {
events.remove(document, type, listener, useCapture);
}
else {
var index;
if (type in globalEvents
&& (index = indexOf(globalEvents[type], listener)) !== -1) {
globalEvents[type].splice(index, 1);
}
}
return interact;
};
/*\
* interact.simulate
[ method ]
*
* Simulate pointer down to begin to interact with an interactable element
- action (string) The action to be performed - drag, resize, etc.
- element (Element) The DOM Element to resize/drag
- pointerEvent (object) #optional Pointer event whose pageX/Y coordinates will be the starting point of the interact drag/resize
= (object) interact
\*/
interact.simulate = function (action, element, pointerEvent) {
var event = {},
clientRect;
if (action === 'resize') {
action = 'resizexy';
}
// return if the action is not recognised
if (!/^(drag|resizexy|resizex|resizey)$/.test(action)) {
return interact;
}
if (pointerEvent) {
extend(event, pointerEvent);
}
else {
clientRect = (element instanceof SVGElement)
? element.getBoundingClientRect()
: clientRect = element.getClientRects()[0];
if (action === 'drag') {
event.pageX = clientRect.left + clientRect.width / 2;
event.pageY = clientRect.top + clientRect.height / 2;
}
else {
event.pageX = clientRect.right;
event.pageY = clientRect.bottom;
}
}
event.target = event.currentTarget = element;
event.preventDefault = event.stopPropagation = blank;
listeners.pointerDown(event, action);
return interact;
};
/*\
* interact.enableDragging
[ method ]
*
* Returns or sets whether dragging is enabled for any Interactables
*
- newValue (boolean) #optional `true` to allow the action; `false` to disable action for all Interactables
= (boolean | object) The current setting or interact
\*/
interact.enableDragging = function (newValue) {
if (newValue !== null && newValue !== undefined) {
actionIsEnabled.drag = newValue;
return interact;
}
return actionIsEnabled.drag;
};
/*\
* interact.enableResizing
[ method ]
*
* Returns or sets whether resizing is enabled for any Interactables
*
- newValue (boolean) #optional `true` to allow the action; `false` to disable action for all Interactables
= (boolean | object) The current setting or interact
\*/
interact.enableResizing = function (newValue) {
if (newValue !== null && newValue !== undefined) {
actionIsEnabled.resize = newValue;
return interact;
}
return actionIsEnabled.resize;
};
/*\
* interact.enableGesturing
[ method ]
*
* Returns or sets whether gesturing is enabled for any Interactables
*
- newValue (boolean) #optional `true` to allow the action; `false` to disable action for all Interactables
= (boolean | object) The current setting or interact
\*/
interact.enableGesturing = function (newValue) {
if (newValue !== null && newValue !== undefined) {
actionIsEnabled.gesture = newValue;
return interact;
}
return actionIsEnabled.gesture;
};
interact.eventTypes = eventTypes;
/*\
* interact.debug
[ method ]
*
* Returns debugging data
= (object) An object with properties that outline the current state and expose internal functions and variables
\*/
interact.debug = function () {
var interaction = interactions[0] || new Interaction();
return {
interactions : interactions,
target : interaction.target,
dragging : interaction.dragging,
resizing : interaction.resizing,
gesturing : interaction.gesturing,
prepared : interaction.prepared,
matches : interaction.matches,
matchElements : interaction.matchElements,
prevCoords : interaction.prevCoords,
startCoords : interaction.startCoords,
pointerIds : interaction.pointerIds,
pointers : interaction.pointers,
addPointer : listeners.addPointer,
removePointer : listeners.removePointer,
recordPointer : listeners.recordPointer,
snap : interaction.snapStatus,
restrict : interaction.restrictStatus,
inertia : interaction.inertiaStatus,
downTime : interaction.downTimes[0],
downEvent : interaction.downEvent,
downPointer : interaction.downPointer,
prevEvent : interaction.prevEvent,
Interactable : Interactable,
IOptions : IOptions,
interactables : interactables,
pointerIsDown : interaction.pointerIsDown,
defaultOptions : defaultOptions,
defaultActionChecker : defaultActionChecker,
actionCursors : actionCursors,
dragMove : listeners.dragMove,
resizeMove : listeners.resizeMove,
gestureMove : listeners.gestureMove,
pointerUp : listeners.pointerUp,
pointerDown : listeners.pointerDown,
pointerMove : listeners.pointerMove,
pointerHover : listeners.pointerHover,
events : events,
globalEvents : globalEvents,
delegatedEvents : delegatedEvents
};
};
// expose the functions used to calculate multi-touch properties
interact.getTouchAverage = touchAverage;
interact.getTouchBBox = touchBBox;
interact.getTouchDistance = touchDistance;
interact.getTouchAngle = touchAngle;
interact.getElementRect = getElementRect;
interact.matchesSelector = matchesSelector;
interact.closest = closest;
/*\
* interact.margin
[ method ]
*
* Returns or sets the margin for autocheck resizing used in
* @Interactable.getAction. That is the distance from the bottom and right
* edges of an element clicking in which will start resizing
*
- newValue (number) #optional
= (number | interact) The current margin value or interact
\*/
interact.margin = function (newvalue) {
if (isNumber(newvalue)) {
margin = newvalue;
return interact;
}
return margin;
};
/*\
* interact.styleCursor
[ styleCursor ]
*
* Returns or sets whether the cursor style of the document is changed
* depending on what action is being performed
*
- newValue (boolean) #optional
= (boolean | interact) The current setting of interact
\*/
interact.styleCursor = function (newValue) {
if (isBool(newValue)) {
defaultOptions.styleCursor = newValue;
return interact;
}
return defaultOptions.styleCursor;
};
/*\
* interact.autoScroll
[ method ]
*
* Returns or sets whether or not actions near the edges of the window or
* specified container element trigger autoScroll by default
*
- options (boolean | object) true or false to simply enable or disable or an object with margin, distance, container and interval properties
= (object) interact
* or
= (boolean | object) `false` if autoscroll is disabled and the default autoScroll settings if it is enabled
\*/
interact.autoScroll = function (options) {
var defaults = defaultOptions.autoScroll;
if (isObject(options)) {
defaultOptions.autoScrollEnabled = true;
if (isNumber(options.margin)) { defaults.margin = options.margin;}
if (isNumber(options.speed) ) { defaults.speed = options.speed ;}
defaults.container =
(isElement(options.container) || isWindow(options.container)
? options.container
: defaults.container);
return interact;
}
if (isBool(options)) {
defaultOptions.autoScrollEnabled = options;
return interact;
}
// return the autoScroll settings if autoScroll is enabled
// otherwise, return false
return defaultOptions.autoScrollEnabled? defaults: false;
};
/*\
* interact.snap
[ method ]
*
* Returns or sets whether actions are constrained to a grid or a
* collection of coordinates
*
- options (boolean | object) #optional New settings
* `true` or `false` to simply enable or disable
* or an object with some of the following properties
o {
o mode : 'grid', 'anchor' or 'path',
o range : the distance within which snapping to a point occurs,
o actions: ['drag', 'resizex', 'resizey', 'resizexy'], an array of action types that can snapped (['drag'] by default) (no gesture)
o grid : {
o x, y: the distances between the grid lines,
o },
o gridOffset: {
o x, y: the x/y-axis values of the grid origin
o },
o anchors: [
o {
o x: x coordinate to snap to,
o y: y coordinate to snap to,
o range: optional range for this anchor
o }
o {
o another anchor
o }
o ]
o }
*
= (object | interact) The default snap settings object or interact
\*/
interact.snap = function (options) {
var snap = defaultOptions.snap;
if (isObject(options)) {
defaultOptions.snapEnabled = true;
if (isString(options.mode) ) { snap.mode = options.mode; }
if (isBool (options.endOnly) ) { snap.endOnly = options.endOnly; }
if (isNumber(options.range) ) { snap.range = options.range; }
if (isArray (options.actions) ) { snap.actions = options.actions; }
if (isArray (options.anchors) ) { snap.anchors = options.anchors; }
if (isObject(options.grid) ) { snap.grid = options.grid; }
if (isObject(options.gridOffset) ) { snap.gridOffset = options.gridOffset; }
if (isObject(options.elementOrigin)) { snap.elementOrigin = options.elementOrigin; }
return interact;
}
if (isBool(options)) {
defaultOptions.snapEnabled = options;
return interact;
}
return defaultOptions.snapEnabled;
};
/*\
* interact.inertia
[ method ]
*
* Returns or sets inertia settings.
*
* See @Interactable.inertia
*
- options (boolean | object) #optional New settings
* `true` or `false` to simply enable or disable
* or an object of inertia options
= (object | interact) The default inertia settings object or interact
\*/
interact.inertia = function (options) {
var inertia = defaultOptions.inertia;
if (isObject(options)) {
defaultOptions.inertiaEnabled = true;
if (isNumber(options.resistance) ) { inertia.resistance = options.resistance ; }
if (isNumber(options.minSpeed) ) { inertia.minSpeed = options.minSpeed ; }
if (isNumber(options.endSpeed) ) { inertia.endSpeed = options.endSpeed ; }
if (isNumber(options.smoothEndDuration)) { inertia.smoothEndDuration = options.smoothEndDuration; }
if (isBool (options.allowResume) ) { inertia.allowResume = options.allowResume ; }
if (isBool (options.zeroResumeDelta) ) { inertia.zeroResumeDelta = options.zeroResumeDelta ; }
if (isArray (options.actions) ) { inertia.actions = options.actions ; }
return interact;
}
if (isBool(options)) {
defaultOptions.inertiaEnabled = options;
return interact;
}
return {
enabled: defaultOptions.inertiaEnabled,
resistance: inertia.resistance,
minSpeed: inertia.minSpeed,
endSpeed: inertia.endSpeed,
actions: inertia.actions,
allowResume: inertia.allowResume,
zeroResumeDelta: inertia.zeroResumeDelta
};
};
/*\
* interact.supportsTouch
[ method ]
*
= (boolean) Whether or not the browser supports touch input
\*/
interact.supportsTouch = function () {
return supportsTouch;
};
/*\
* interact.supportsPointerEvent
[ method ]
*
= (boolean) Whether or not the browser supports PointerEvents
\*/
interact.supportsPointerEvent = function () {
return supportsPointerEvent;
};
/*\
* interact.currentAction
[ method ]
*
= (string) What action is currently being performed
\*/
interact.currentAction = function () {
for (var i = 0, len = interactions.length; i < len; i++) {
var action = interactions[i].currentAction();
if (action) { return action; }
}
return null;
};
/*\
* interact.stop
[ method ]
*
* Cancels the current interaction
*
- event (Event) An event on which to call preventDefault()
= (object) interact
\*/
interact.stop = function (event) {
for (var i = interactions.length - 1; i > 0; i--) {
interactions[i].stop(event);
}
return interact;
};
/*\
* interact.dynamicDrop
[ method ]
*
* Returns or sets whether the dimensions of dropzone elements are
* calculated on every dragmove or only on dragstart for the default
* dropChecker
*
- newValue (boolean) #optional True to check on each move. False to check only before start
= (boolean | interact) The current setting or interact
\*/
interact.dynamicDrop = function (newValue) {
if (isBool(newValue)) {
//if (dragging && dynamicDrop !== newValue && !newValue) {
//calcRects(dropzones);
//}
dynamicDrop = newValue;
return interact;
}
return dynamicDrop;
};
/*\
* interact.deltaSource
[ method ]
* Returns or sets weather pageX/Y or clientX/Y is used to calculate dx/dy.
*
* See @Interactable.deltaSource
*
- newValue (string) #optional 'page' or 'client'
= (string | Interactable) The current setting or interact
\*/
interact.deltaSource = function (newValue) {
if (newValue === 'page' || newValue === 'client') {
defaultOptions.deltaSource = newValue;
return this;
}
return defaultOptions.deltaSource;
};
/*\
* interact.restrict
[ method ]
*
* Returns or sets the default rectangles within which actions (after snap
* calculations) are restricted.
*
* See @Interactable.restrict
*
- newValue (object) #optional an object with keys drag, resize, and/or gesture and rects or Elements as values
= (object) The current restrictions object or interact
\*/
interact.restrict = function (newValue) {
var defaults = defaultOptions.restrict;
if (newValue === undefined) {
return defaultOptions.restrict;
}
if (isBool(newValue)) {
defaultOptions.restrictEnabled = newValue;
}
else if (isObject(newValue)) {
if (isObject(newValue.drag) || /^parent$|^self$/.test(newValue.drag)) {
defaults.drag = newValue.drag;
}
if (isObject(newValue.resize) || /^parent$|^self$/.test(newValue.resize)) {
defaults.resize = newValue.resize;
}
if (isObject(newValue.gesture) || /^parent$|^self$/.test(newValue.gesture)) {
defaults.gesture = newValue.gesture;
}
if (isBool(newValue.endOnly)) {
defaults.endOnly = newValue.endOnly;
}
if (isObject(newValue.elementRect)) {
defaults.elementRect = newValue.elementRect;
}
defaultOptions.restrictEnabled = true;
}
else if (newValue === null) {
defaults.drag = defaults.resize = defaults.gesture = null;
defaults.endOnly = false;
}
return this;
};
/*\
* interact.pointerMoveTolerance
[ method ]
* Returns or sets the distance the pointer must be moved before an action
* sequence occurs. This also affects tolerance for tap events.
*
- newValue (number) #optional The movement from the start position must be greater than this value
= (number | Interactable) The current setting or interact
\*/
interact.pointerMoveTolerance = function (newValue) {
if (isNumber(newValue)) {
defaultOptions.pointerMoveTolerance = newValue;
return this;
}
return defaultOptions.pointerMoveTolerance;
};
/*\
* interact.maxInteractions
[ method ]
**
* Returns or sets the maximum number of concurrent interactions allowed.
* By default only 1 interaction is allowed at a time (for backwards
* compatibility). To allow multiple interactions on the same Interactables
* and elements, you need to enable it in the draggable, resizable and
* gesturable `'max'` and `'maxPerElement'` options.
**
- newValue (number) #optional Any number. newValue <= 0 means no interactions.
\*/
interact.maxInteractions = function (newValue) {
if (isNumber(newValue)) {
maxInteractions = newValue;
return this;
}
return maxInteractions;
};
function endAllInteractions (event) {
for (var i = 0; i < interactions.length; i++) {
interactions[i].pointerEnd(event, event);
}
}
function listenToDocument (doc) {
if (contains(documents, doc)) { return; }
var win = doc.defaultView || doc.parentWindow;
// add delegate event listener
for (var eventType in delegatedEvents) {
events.add(doc, eventType, delegateListener);
events.add(doc, eventType, delegateUseCapture, true);
}
if (PointerEvent) {
if (PointerEvent === win.MSPointerEvent) {
pEventTypes = {
up: 'MSPointerUp', down: 'MSPointerDown', over: 'mouseover',
out: 'mouseout', move: 'MSPointerMove', cancel: 'MSPointerCancel' };
}
else {
pEventTypes = {
up: 'pointerup', down: 'pointerdown', over: 'pointerover',
out: 'pointerout', move: 'pointermove', cancel: 'pointercancel' };
}
events.add(doc, pEventTypes.down , listeners.selectorDown );
events.add(doc, pEventTypes.move , listeners.pointerMove );
events.add(doc, pEventTypes.over , listeners.pointerOver );
events.add(doc, pEventTypes.out , listeners.pointerOut );
events.add(doc, pEventTypes.up , listeners.pointerUp );
events.add(doc, pEventTypes.cancel, listeners.pointerCancel);
// autoscroll
events.add(doc, pEventTypes.move, autoScroll.edgeMove);
}
else {
events.add(doc, 'mousedown', listeners.selectorDown);
events.add(doc, 'mousemove', listeners.pointerMove );
events.add(doc, 'mouseup' , listeners.pointerUp );
events.add(doc, 'mouseover', listeners.pointerOver );
events.add(doc, 'mouseout' , listeners.pointerOut );
events.add(doc, 'touchstart' , listeners.selectorDown );
events.add(doc, 'touchmove' , listeners.pointerMove );
events.add(doc, 'touchend' , listeners.pointerUp );
events.add(doc, 'touchcancel', listeners.pointerCancel);
// autoscroll
events.add(doc, 'mousemove', autoScroll.edgeMove);
events.add(doc, 'touchmove', autoScroll.edgeMove);
}
events.add(win, 'blur', endAllInteractions);
try {
if (win.frameElement) {
var parentDoc = win.frameElement.ownerDocument,
parentWindow = parentDoc.defaultView;
events.add(parentDoc , 'mouseup' , listeners.pointerEnd);
events.add(parentDoc , 'touchend' , listeners.pointerEnd);
events.add(parentDoc , 'touchcancel' , listeners.pointerEnd);
events.add(parentDoc , 'pointerup' , listeners.pointerEnd);
events.add(parentDoc , 'MSPointerUp' , listeners.pointerEnd);
events.add(parentWindow, 'blur' , endAllInteractions );
}
}
catch (error) {
interact.windowParentError = error;
}
// For IE's lack of Event#preventDefault
if (events.useAttachEvent) {
events.add(doc, 'selectstart', function (event) {
var interaction = interactions[0];
if (interaction.currentAction()) {
interaction.checkAndPreventDefault(event);
}
});
}
documents.push(doc);
}
listenToDocument(document);
function indexOf (array, target) {
for (var i = 0, len = array.length; i < len; i++) {
if (array[i] === target) {
return i;
}
}
return -1;
}
function contains (array, target) {
return indexOf(array, target) !== -1;
}
function matchesSelector (element, selector, nodeList) {
if (ie8MatchesSelector) {
return ie8MatchesSelector(element, selector, nodeList);
}
return element[prefixedMatchesSelector](selector);
}
// For IE8's lack of an Element#matchesSelector
// taken from http://tanalin.com/en/blog/2012/12/matches-selector-ie8/ and modified
if (!(prefixedMatchesSelector in Element.prototype) || !isFunction(Element.prototype[prefixedMatchesSelector])) {
ie8MatchesSelector = function (element, selector, elems) {
elems = elems || element.parentNode.querySelectorAll(selector);
for (var i = 0, len = elems.length; i < len; i++) {
if (elems[i] === element) {
return true;
}
}
return false;
};
}
// requestAnimationFrame polyfill
(function() {
var lastTime = 0,
vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
reqFrame = window[vendors[x]+'RequestAnimationFrame'];
cancelFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!reqFrame) {
reqFrame = function(callback) {
var currTime = new Date().getTime(),
timeToCall = Math.max(0, 16 - (currTime - lastTime)),
id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!cancelFrame) {
cancelFrame = function(id) {
clearTimeout(id);
};
}
}());
/* global exports: true, module, define */
// http://documentcloud.github.io/underscore/docs/underscore.html#section-11
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = interact;
}
exports.interact = interact;
}
// AMD
else if (typeof define === 'function' && define.amd) {
define('interact', function() {
return interact;
});
}
else {
window.interact = interact;
}
} ());
| emilkje/interact.js | interact.js | JavaScript | mit | 210,270 |
var base64url = require('urlsafe-base64')
, After = require('json-list-response').After
, inherits = require('util').inherits
module.exports = DateAfter
function DateAfter(value, options) {
After.call(this, value, options)
this.skip = 0
this.value = 0
if (value) {
value = base64url.decode(value)
if (value.length === 9) {
this.value = value.readDoubleBE(0)
this.skip = value.readUInt8(8)
}
}
}
inherits(DateAfter, After)
DateAfter.prototype.add = function (row) {
var value = row[this.key]
if (!value) return
if (+this.value === +value) {
this.skip++
} else {
this.skip = 0
this.value = value
}
}
DateAfter.prototype.toString = function () {
if (!this.value) return ''
var buf = new Buffer(9)
buf.writeDoubleBE(+this.value || 0, 0)
buf.writeUInt8(this.skip, 8)
return base64url.encode(buf)
}
DateAfter.prototype.mongoSorting = function (list, sorting) {
var obj = {}
obj[sorting.key] = {}
obj[sorting.key][sorting.descending ? '$lte' : '$gte'] = new Date(this.value)
list.selector.$and.push(obj)
list.cursor.skip(this.skip + 1)
}
| tellnes/mongo-list | lib/after/date.js | JavaScript | mit | 1,122 |
<?php
require __DIR__ . "/../vendor/autoload.php";
// NOTE: To run this you need to have installed violent-death
// see https://github.com/gabrielelana/violent-death
// Sorry but I don't want to have an explicit dependency
// with violent-death (wich is not so easy to install) only
// to run this example
// The output will be:
//
// Segmentation fault in 3... 2... 1...
// You didn't notice but it happend! ;-)
GracefulDeath::around(function() {
echo "Segmentation fault in 3... 2... 1...\n";
die_violently();
})
->afterViolentDeath(
"You didn't notice but it happend! ;-)\n"
)
->run();
| gabrielelana/graceful-death | examples/catch_segmentation_fault.php | PHP | mit | 606 |
"""94. Binary Tree Inorder Traversal
https://leetcode.com/problems/binary-tree-inorder-traversal/
Given a binary tree, return the in-order traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
"""
from typing import List
from common.tree_node import TreeNode
class Solution:
def iterative_inorder_traversal(self, root: TreeNode) -> List[int]:
"""
iterative traversal
"""
ans = []
stack = []
while root or stack:
if root:
stack.append(root)
root = root.left
else:
root = stack.pop()
ans.append(root.val)
root = root.right
return ans
def recursive_inorder_traversal(self, root: TreeNode) -> List[int]:
"""
recursive traversal, process left if needed, then val, at last right
"""
if not root:
return []
ans = []
ans += self.recursive_inorder_traversal(root.left)
ans.append(root.val)
ans += self.recursive_inorder_traversal(root.right)
return ans
| isudox/leetcode-solution | python-algorithm/leetcode/problem_94.py | Python | mit | 1,229 |
import React, { MouseEvent, FunctionComponent } from 'react';
import classnames from 'classnames';
import rcFont from '../../assets/RcFont/RcFont.scss';
import styles from './styles.scss';
export interface RemoveButtonProps {
className?: string;
visibility?: boolean;
onClick: (ev: MouseEvent) => void;
}
export const RemoveButton: FunctionComponent<RemoveButtonProps> = ({
className,
onClick,
visibility,
}) => {
return (
<span
data-sign="removeBtn"
className={classnames(
styles.container,
className,
!visibility && styles.hideRemoveButton,
)}
onClick={visibility ? onClick : null}
>
<i className={rcFont.uni2471} />
</span>
);
};
RemoveButton.defaultProps = {
className: null,
visibility: true,
};
| ringcentral/ringcentral-js-widget | packages/ringcentral-widgets/components/RemoveButton/RemoveButton.tsx | TypeScript | mit | 790 |
export goCommand from './goCommand'
export goReducer from './goReducer'
export parseBestmove from './parseBestmove'
export parseId from './parseId'
export parseInfo from './parseInfo'
export parseOption from './parseOption'
export initReducer from './initReducer'
| ebemunk/node-uci | src/parseUtil/index.js | JavaScript | mit | 264 |
package domain;
import java.util.Date;
/**
* @author Verbroucht Johann
* Test Java Date : 15 aot. 2011
*/
public class Mark {
private Date date;
private int mark;
public Mark(Date _date, int _mark) {
this.date = _date;
this.mark = _mark;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getMark() {
return mark;
}
public void setMark(int mark) {
this.mark = mark;
}
}
| johannv/javaTestEasy | src/domain/Mark.java | Java | mit | 497 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using SharpDX;
namespace Oggy
{
public class MapLayoutResource : IDisposable// : ResourceBase
{
#region properties
private List<Entry> m_entryList;
public ReadOnlyCollection<Entry> Entries
{
get
{
return m_entryList.AsReadOnly();
}
}
#endregion // properties
#region public types
public struct Entry
{
public int ModelId;
public Matrix Layout;
}
#endregion // public types
public MapLayoutResource(String uid)
//: base(uid)
{
m_entryList = new List<Entry>(10);
}
public static MapLayoutResource FromScene(String uid, BlenderScene scene)
{
var res = new MapLayoutResource(uid);
foreach (var n in scene.LinkList)
{
var match = _ModelIdRegex.Match(n.TargetFileName);
int modelId = int.Parse(match.Groups[1].Value);
res.m_entryList.Add(new Entry() { ModelId = modelId, Layout = n.Layout });
}
return res;
}
public void Dispose()
{
m_entryList.Clear();
}
private static Regex _ModelIdRegex = new Regex(@"p(\d+)\.blend");
#region private members
#endregion // private members
}
}
| oggy83/OculusWalkerDemo | OculusWalkerDemo/Map/MapLayoutResource.cs | C# | mit | 1,291 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using PubSub;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using System.Threading;
namespace MonitorTest
{
public class Program
{
IConfiguration Config { get; set; }
IServiceProvider Provider { get; set; }
IPublisher Publisher { get; set; }
IPublisherClient Session { get; set; }
public void Main(string[] args)
{
Config = new Configuration();
var services = new ServiceCollection();
services.AddPublisher();
Provider = services.BuildServiceProvider();
Publisher = Provider.GetService<IPublisher>();
GetConnected();
}
static string linePat = @"(?<command>[supe])\w+\s*(?<topic>\w+)?\s*(?<content>.*$)?";
static System.Text.RegularExpressions.Regex lineRegex = new System.Text.RegularExpressions.Regex(linePat);
static string defaultEndpoint = "ws://localhost:44000/ws";
void GetConnected()
{
while (true)
{
Console.Write("Endpoint[" + defaultEndpoint + "]: ");
var endpoint = Console.ReadLine();
if (string.IsNullOrEmpty(endpoint))
endpoint = defaultEndpoint;
try
{
this.Session = Publisher.ConnectAsync(endpoint, CancellationToken.None).Result;
}
catch (Exception e)
{
Console.WriteLine("?connect failed: " + e.Message);
continue;
}
if (Session != null)
break;
Console.WriteLine("?failed to connect to: " + endpoint);
}
Session.OnPublish += Session_OnPublish;
}
private void Session_OnPublish(IPublisherClient session, Messages.Message m)
{
Console.WriteLine("Received Message: " + m.Type);
if (m is TopicUpdate)
{
var u = (TopicUpdate)m;
Console.WriteLine("Topic: " + u.Topic + "\nContent: " + u.Content);
}
else
{
Console.WriteLine("Unhandled message type: " + m.GetType());
}
}
void RunConnected()
{
while (true)
{
Console.WriteLine(@"
Options:
[s]ubscribe topic
[u]nsubcribe topic
[p]ublish topic content
[e]xit
");
var line = Console.ReadLine();
var m = lineRegex.Match(line);
if (!m.Success)
{
Console.WriteLine("?Could not match command: " + line);
continue;
}
var command = m.Groups["command"].Value;
switch (command)
{
case "s":
{
var topic = m.Groups["topic"].Value;
Session.SubscribeAsync(topic);
break;
}
case "u":
{
var topic = m.Groups["topic"].Value;
Session.UnsubscribeAsync(topic);
break;
}
case "p":
{
var topic = m.Groups["topic"].Value;
var content = m.Groups["content"].Value;
Session.PublishAsync(topic, content);
break;
}
case "e":
Console.WriteLine("Exiting...");
return;
default:
throw new ApplicationException("unhandled command: " + command);
}
}
}
}
}
| zbrad/WebSocketsDemo | archive/MonitorDemo/MonitorTest/Program.cs | C# | mit | 4,080 |
<?php
namespace Tyler\TopTrumpsBundle\Controller;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\ContainerInterface;
class RequestUtilityFunctions
{
/**
* @param ObjectManager $em
* @param Request $request
* @param $container
* @return Query - A query object from which we can retrieve a set of
* decks.
*/
public static function createDeckQueryFromRequest(ObjectManager $em,
Request $request,
ContainerInterface $container)
{
$pageSize = $request->get('pageSize');
$page = $request->get('page', 0);
$filterUnsafe = $request->query->get('filter', '%');
$orderByDirSafe = $request->get('orderByDirection', 'ASC');
if ($orderByDirSafe !== 'DESC' && $orderByDirSafe !== 'ASC') {
$orderByDirSafe = 'ASC';
}
/*
* Bind the page size between the minimum and maximum sensible values.
*
* These are set to keep memory usage on the server down.
*/
if (!is_numeric($pageSize) ||
$pageSize > $container->getParameter('max_deck_page_size') ||
$pageSize < $container->getParameter('min_deck_page_size')) {
$pageSize = $container->getParameter('default_deck_page_size');
}
if (!is_numeric($page)) {
$page = 0;
}
/*
* The order by field cannot be set dynamically in the query builder
* so we set it using a switch instead. Note this couples the class
* to the notion of a deck more closely.
*/
$orderByUnsafe = $request->get('orderBy', 'name');
switch ($orderByUnsafe) {
case 'Name':
case 'name':
$orderBySafe = 'd.name';
break;
default:
$orderBySafe = 'd.name';
break;
}
/* @var $qb QueryBuilder */
$qb = $em->createQueryBuilder();
$query = $qb
->select('d')
->from('TylerTopTrumpsBundle:Deck', 'd')
->where($qb->expr()->orX($qb->expr()->like('d.name', ':filter'),
$qb->expr()->like('d.description', ':filter')))
->orderBy($orderBySafe, $orderByDirSafe)
->setParameter('filter', '%'.$filterUnsafe.'%')
->setFirstResult($pageSize * $page)
->setMaxResults($pageSize)
->getQuery();
return $query;
}
} | DaveTCode/TopTrumps-PHPSymfony | src/Tyler/TopTrumpsBundle/Controller/RequestUtilityFunctions.php | PHP | mit | 2,688 |
exports.translate = function(tag) {
return this.import("riot").compile(tag);
};
| lixiaoyan/jspm-plugin-riot | riot.js | JavaScript | mit | 82 |
<?php
return array (
'id' => 'lenovo_a2207_ver1_suban41',
'fallback' => 'lenovo_a2207_ver1',
'capabilities' =>
array (
'device_os_version' => '4.1',
),
);
| cuckata23/wurfl-data | data/lenovo_a2207_ver1_suban41.php | PHP | mit | 170 |
package cognitiveservices
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// PrivateLinkResourcesClient is the cognitive Services Management Client
type PrivateLinkResourcesClient struct {
BaseClient
}
// NewPrivateLinkResourcesClient creates an instance of the PrivateLinkResourcesClient client.
func NewPrivateLinkResourcesClient(subscriptionID string) PrivateLinkResourcesClient {
return NewPrivateLinkResourcesClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewPrivateLinkResourcesClientWithBaseURI creates an instance of the PrivateLinkResourcesClient client using a custom
// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure
// stack).
func NewPrivateLinkResourcesClientWithBaseURI(baseURI string, subscriptionID string) PrivateLinkResourcesClient {
return PrivateLinkResourcesClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// List gets the private link resources that need to be created for a Cognitive Services account.
// Parameters:
// resourceGroupName - the name of the resource group. The name is case insensitive.
// accountName - the name of Cognitive Services account.
func (client PrivateLinkResourcesClient) List(ctx context.Context, resourceGroupName string, accountName string) (result PrivateLinkResourceListResult, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkResourcesClient.List")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}},
{TargetValue: accountName,
Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "accountName", Name: validation.MinLength, Rule: 2, Chain: nil},
{Target: "accountName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`, Chain: nil}}},
{TargetValue: client.SubscriptionID,
Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil {
return result, validation.NewError("cognitiveservices.PrivateLinkResourcesClient", "List", err.Error())
}
req, err := client.ListPreparer(ctx, resourceGroupName, accountName)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.PrivateLinkResourcesClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "cognitiveservices.PrivateLinkResourcesClient", "List", resp, "Failure sending request")
return
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.PrivateLinkResourcesClient", "List", resp, "Failure responding to request")
return
}
return
}
// ListPreparer prepares the List request.
func (client PrivateLinkResourcesClient) ListPreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"accountName": autorest.Encode("path", accountName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2021-04-30"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateLinkResources", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client PrivateLinkResourcesClient) ListSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client PrivateLinkResourcesClient) ListResponder(resp *http.Response) (result PrivateLinkResourceListResult, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
| Azure/azure-sdk-for-go | services/cognitiveservices/mgmt/2021-04-30/cognitiveservices/privatelinkresources.go | GO | mit | 5,466 |
# -*- coding: utf-8 -*-
from django.core.cache import cache
from django.shortcuts import render
from django.http import Http404
from styleguide.utils import (Styleguide, STYLEGUIDE_DIR_NAME,
STYLEGUIDE_DEBUG, STYLEGUIDE_CACHE_NAME,
STYLEGUIDE_ACCESS)
def index(request, module_name=None, component_name=None):
if not STYLEGUIDE_ACCESS(request.user):
raise Http404()
styleguide = None
if not STYLEGUIDE_DEBUG:
styleguide = cache.get(STYLEGUIDE_CACHE_NAME)
if styleguide is None:
styleguide = Styleguide()
cache.set(STYLEGUIDE_CACHE_NAME, styleguide, None)
if module_name is not None:
styleguide.set_current_module(module_name)
context = {'styleguide': styleguide}
index_path = "%s/index.html" % STYLEGUIDE_DIR_NAME
return render(request, index_path, context)
| andrefarzat/django-styleguide | styleguide/views.py | Python | mit | 897 |
from quotes.models import Quote
from django.contrib import admin
class QuoteAdmin(admin.ModelAdmin):
list_display = ('message', 'name', 'program', 'class_of',
'submission_time')
admin.site.register(Quote, QuoteAdmin)
| k4rtik/alpo | quotes/admin.py | Python | mit | 243 |
<div class="main-content">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="<?php echo site_url('Home') ?>">Sistem Informasi Kasir</a>
</li><li>
<i class="ace-icon fa fa-briefcase"></i>
<a href="<?php echo site_url('modal') ?>"> Modal</a>
</li>
<li class="active">EDIT</li>
</ul><!-- /.breadcrumb -->
</div>
<div class="page-content">
<!--Setting-->
<?php $this->load->view('setting'); ?>
<!--End Setting-->
<div class="row">
<div class="col-xs-12">
<!-- PAGE CONTENT BEGINS -->
<!--KONTEN-->
<div class="row">
<div class="col-sm-8">
<div class="widget-box">
<div class="widget-header">
<h4 class="widget-title">EDIT MODAL <?php echo $modal['nama_bahan'] ?></h4>
</div>
<div class="widget-body">
<div class="widget-main no-padding">
<?php echo form_open('modal/edit_proses/'.$modal['id_modal']); ?>
<!-- <legend>Form</legend> -->
<fieldset class="form-group">
<label>ID Modal</label>
<input class="form-control" type="text" name="id_modal" value="<?php echo $modal['id_modal'] ?>" readonly/>
<?php echo form_error('id_modal') ?>
<br>
<label>Nama Bahan</label>
<input class="form-control" type="text" name="nama_bahan" value="<?php echo $modal['nama_bahan'] ?>" />
<?php echo form_error('nama_bahan') ?>
</fieldset>
<fieldset class="col-sm-6">
<label>Jumlah</label>
<div>
<input class="form-control" type="number" name="jumlah_bahan" value="<?php echo $modal['jumlah_bahan'] ?>"></input>
<?php echo form_error('jumlah_bahan') ?>
</div>
<br>
</fieldset>
<fieldset class="col-sm-6">
<label>Satuan</label>
<div>
<input class="form-control" type="text" name="satuan" value="<?php echo $modal['satuan'] ?>"></input>
<?php echo form_error('satuan') ?>
</div>
<br>
</fieldset>
<fieldset>
<label>Harga Beli</label>
<input class="form-control" name="harga_beli" value="<?php echo $modal['harga_beli'] ?>"></input>
<?php echo form_error('harga_beli') ?>
<br>
</fieldset>
<div class="form-actions center">
<button type="submit" class="btn btn-sm btn-success">
<i class="ace-icon fa fa-pencil icon-on-right bigger-110"></i>
Edit
</button>
</div>
<?php echo form_close(); ?>
</div>
</div>
</div>
</div>
</div>
<!--END KONTEN-->
<!-- PAGE CONTENT ENDS -->
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content --> | ElfanRodh/sikame | application/views/modal/edit.php | PHP | mit | 3,353 |
using UnityEngine;
using System.Collections;
/// <summary>
/// THIS IS OBSOLETE CLASS
/// Use PowerUpManager instead
/// </summary>
public class PowerUpElement : MonoBehaviour {
const float SUPERCHARGE_BASE_TIME = 5.0f;
Animator animator;
public enum PowerUpType { pu_triple_shot, pu_safety_net, pu_reinforced_glass, pu_supercharged_wall };
public PowerUpType powerup_type;
PowerUpUI powerup_ui;
PowerupMeter powerup_meter;
KeyboardController kbc;
CooldownMeter cdm;
GestureDetector gd;
WallPhysics bouncer_left;
WallPhysics bouncer_right;
public float PowerRequirement {
get {
switch(powerup_type) {
case PowerUpType.pu_triple_shot: return 0.75f;
case PowerUpType.pu_safety_net: return 0.25f;
case PowerUpType.pu_supercharged_wall: return 0.25f;
case PowerUpType.pu_reinforced_glass: return 0.25f;
default: return 0f;
}
}
}
// Use this for initialization
void Start () {
animator = GetComponentInChildren<Animator>();
powerup_ui = transform.parent.GetComponentInChildren<PowerUpUI>();
powerup_meter = GameObject.FindObjectOfType<PowerupMeter>();
gd = GameObject.FindObjectOfType<GestureDetector>();
InitializeCooldownMeter();
InitializeBouncers();
}
void InitializeBouncers() {
foreach(WallPhysics wp in GameObject.FindObjectsOfType<WallPhysics>()) {
switch (wp.wall_type) {
case WallPhysics.WallType.wall_left: bouncer_left = wp; break;
case WallPhysics.WallType.wall_right: bouncer_right = wp; break;
}
}
}
void InitializeCooldownMeter() {
cdm = GetComponentInChildren<CooldownMeter>();
if (cdm == null) { return; }
switch(powerup_type) {
case PowerUpType.pu_triple_shot: cdm.BaseCooldown = 10.0f; break;
case PowerUpType.pu_safety_net: cdm.BaseCooldown = 20.0f; break;
case PowerUpType.pu_supercharged_wall: cdm.BaseCooldown = 10.0f; break;
case PowerUpType.pu_reinforced_glass: cdm.BaseCooldown = 1.0f; break;
}
}
// Update is called once per frame
void Update () {
}
//void OnMouseDown() {
// switch(powerup_type) {
// case PowerUpType.pu_triple_shot:
// if (CheckPrerequisite()) {
// FindSubject();
// kbc.SetTripleShot();
// cdm.Activate();
// }
// break;
// case PowerUpType.pu_safety_net:
// if (CheckPrerequisite()) {
// FindSafetyNet();
// cdm.Activate();
// }
// break;
// case PowerUpType.pu_supercharged_wall:
// if (CheckPrerequisite()) {
// gd.WaitForSwipe(this);
// }
// break;
// }
// powerup_ui.ToggleVisibility();
//}
//public void OnSwipeDetected(GestureDetector.SwipeDirection swipe) {
// if (bouncer_left == null) {
// InitializeBouncers();
// }
// bool inversion = PhotonNetwork.connected && PhotonNetwork.isMasterClient;
// switch (swipe) {
// case GestureDetector.SwipeDirection.swipe_right:
// if (inversion) {
// bouncer_left.SetSupercharge(SUPERCHARGE_BASE_TIME);
// //bouncer_left.ChangeColor();
// } else {
// bouncer_right.SetSupercharge(SUPERCHARGE_BASE_TIME);
// //bouncer_right.ChangeColor();
// }
// cdm.Activate();
// powerup_meter.ExecuteSubtract(1);
// break;
// case GestureDetector.SwipeDirection.swipe_left:
// if (inversion) {
// bouncer_right.SetSupercharge(SUPERCHARGE_BASE_TIME);
// //bouncer_right.ChangeColor();
// } else {
// bouncer_left.SetSupercharge(SUPERCHARGE_BASE_TIME);
// //bouncer_left.ChangeColor();
// }
// cdm.Activate();
// powerup_meter.ExecuteSubtract(1);
// break;
// default:
// break;
// }
//}
//bool CheckPrerequisite() {
// if (!GetComponentInChildren<DisablerMask>().GetComponent<SpriteRenderer>().enabled && !cdm.IsInCooldown) {
// animator.SetBool("is_clicked", true);
// return true;
// }
// return false;
//}
//void FindSafetyNet() {
// foreach (SafetyNet sfn in GameObject.FindObjectsOfType<SafetyNet>()) {
// bool is_mine = sfn.GetComponent<PhotonView>().isMine;
// if (!PhotonNetwork.connected || is_mine) {
// sfn.SetEnable(true);
// powerup_meter.ExecuteSubtract(1);
// break;
// }
// }
//}
//void FindSubject() {
// foreach (KeyboardController _k in GameObject.FindObjectsOfType<KeyboardController>()) {
// bool is_mine = _k.GetComponent<PhotonView>().isMine;
// if (!PhotonNetwork.connected || is_mine) {
// kbc = _k;
// break;
// }
// }
//}
}
| gbudiman/glass | Gloria_Huixin_Glass/Assets/Networking/PowerUpElement.cs | C# | mit | 4,705 |
en.resources.define("audio",{
name: "Engine",
src: "./audio/ship_engine.ogg",
}, function(content, callback){
var sound = client.audio.createSound();
sound.load(content.src, function(sound){
content.sound = sound;
callback(content.type, content);
});
}, function(content){
return content.sound;
}); | thehink/GLWars | client/assets_types/audio.js | JavaScript | mit | 319 |
from tkinter import *
import tkinter
import HoursParser
class UserInterface(tkinter.Frame):
def __init__(self, master):
self.master = master
self.events_list = []
# Set window size
master.minsize(width=800, height=600)
master.maxsize(width=800, height=600)
# File Parser
self.parser = HoursParser.FileParser()
# Filename Label
self.file_select_text = tkinter.StringVar()
self.file_select_text.set(" ")
# Initialize Widgets
super().__init__(master)
self.pack()
# Label for Application
self.title_label = LabelFrame(master, text="Technical Services - Scheduler (Alpha)")
self.title_label.pack(fill="both", expand="yes")
self.inner_label = Label(self.title_label, text="Choose Hours File")
self.inner_label.pack()
# Button for File Selection
self.file_select_button = Button(self.title_label, text="Select File", command=lambda: self.file_button_press())
self.file_select_button.pack()
# Label for File Selection Button
self.file_select_label = Label(self.title_label, textvariable=self.file_select_text)
self.file_select_label.pack()
# Button for Parsing File
self.file_parse_button = Button(self.title_label, state=DISABLED, text="Read File", command=lambda: self.parse_button_pressed())
self.file_parse_button.pack()
# List of Events
self.events_list_box = Listbox(self.title_label)
self.events_list_box.pack()
# Show Info Button
self.show_info_button = Button(self.title_label, state="disabled", command=lambda: self.show_event_info())
self.show_info_button.pack()
# Shows information about event
self.text_area = Text(self.title_label)
self.text_area.pack()
# Called when Select File button is pressed.
def file_button_press(self):
self.parser.choose_file()
self.file_select_text.set(self.parser.file_name)
if self.parser.file_name is not None:
self.file_parse_button['state'] = 'normal'
def parse_button_pressed(self):
self.events_list = self.parser.parse_file()
self.populate_list_box(self.events_list_box)
# Puts names of events in a list from parsed file.
def populate_list_box(self, list_box):
i = 0
for event in self.events_list:
list_box.insert(i, event.get_event_name())
i += 1
self.show_info_button['state'] = 'normal'
def show_event_info(self):
# Store Active Time Index
event_list_index = int(self.events_list_box.index(ACTIVE))
# Clear text box from previous event details
# if self.text_area.get(END) is not "\n":
# self.text_area.delete(0, 'end')
# Display Formatted Information about Event.
self.text_area.insert(END, "Event: " + self.events_list[event_list_index].get_event_name())
self.text_area.insert(END, '\n')
self.text_area.insert(END, "Location: " + self.events_list[event_list_index].get_event_location())
self.text_area.insert(END, '\n')
self.text_area.insert(END, "Start Time: " + self.events_list[event_list_index].get_event_start_time())
self.text_area.insert(END, '\n')
self.text_area.insert(END, "End Time: " + self.events_list[event_list_index].get_event_end_time())
self.text_area.insert(END, '\n')
self.text_area.insert(END, "# of Staff: " + self.events_list[event_list_index].get_event_number_employees())
self.text_area.insert(END, '\n')
root = Tk()
root.wm_title("Scheduler (Alpha)")
main_app = UserInterface(master=root)
main_app.mainloop()
| itsknob/TechnicalServicesScheduler-Python | interface.py | Python | mit | 3,856 |
required_states = ['accept', 'reject', 'init']
class TuringMachine(object):
def __init__(self, sigma, gamma, delta):
self.sigma = sigma
self.gamma = gamma
self.delta = delta
self.state = None
self.tape = None
self.head_position = None
return
def initialize(self, input_string):
for char in input_string:
assert char in self.sigma
self.tape = list(input_string)
self.state = 'init'
self.head_position = 0
return
def simulate_one_step(self, verbose=False):
if self.state in ['accept', 'reject']:
print "# %s " % self.state
cur_symbol = self.tape[self.head_position]
transition = self.delta[(self.state, cur_symbol)]
if verbose:
self.print_tape_contents()
template = "delta({q_old}, {s_old}) = ({q}, {s}, {arr})"
print(template.format(q_old=self.state,
s_old=cur_symbol,
q=transition[0],
s=transition[1],
arr=transition[2])
)
self.state = transition[0]
self.tape[self.head_position] = transition[1]
if(transition[2] == 'left'):
self.head_position = max(0, self.head_position - 1)
else:
assert(transition[2] == 'right')
if self.head_position == len(self.tape) - 1:
self.tape.append('#')
self.head_position +=1
if verbose:
self.print_tape_contents()
return
def print_tape_contents(self):
formatted = ''.join(char if i != self.head_position else '[%s]' % char
for i, char in enumerate(self.tape))
print(formatted)
def run(self, input_string, verbose=False):
self.initialize(input_string)
while self.state not in ['reject', 'accept']:
self.simulate_one_step(verbose)
return str(self.tape)
| ssanderson/turing.py | turing.py | Python | mit | 2,182 |
using System.Web;
using System.Web.Optimization;
namespace SimpleSTS
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
| johnproctor/ThinktectureSSODemo | SimpleSTS/App_Start/BundleConfig.cs | C# | mit | 1,240 |
<?php
namespace ZfbUser\Options;
/**
* Interface ResetPasswordFormOptionsInterface
*
* @package ZfbUser\Options
*/
interface ResetPasswordFormOptionsInterface extends FormOptionsInterface
{
/**
* @return string
*/
public function getCredentialFieldLabel(): string;
/**
* @return string
*/
public function getCredentialFieldName(): string;
/**
* @return string
*/
public function getCredentialVerifyFieldLabel(): string;
/**
* @return string
*/
public function getCredentialVerifyFieldName(): string;
}
| narekps/ZfbUser | src/Options/ResetPasswordFormOptionsInterface.php | PHP | mit | 583 |
module ArrayNamedAccess
def second
self[1]
end
def third
self[2]
end
end | jimjames99/group_by_summary | lib/array_named_access.rb | Ruby | mit | 91 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mardin.job.widgets.wizard.ui;
import com.mardin.job.R;
import com.mardin.job.widgets.wizard.model.Page;
import com.mardin.job.widgets.wizard.model.SingleFixedChoicePage;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class SingleChoiceFragment extends ListFragment {
private static final String ARG_KEY = "key";
private PageFragmentCallbacks mCallbacks;
private List<String> mChoices;
private String mKey;
private Page mPage;
public static SingleChoiceFragment create(String key) {
Bundle args = new Bundle();
args.putString(ARG_KEY, key);
SingleChoiceFragment fragment = new SingleChoiceFragment();
fragment.setArguments(args);
return fragment;
}
public SingleChoiceFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
mKey = args.getString(ARG_KEY);
mPage = mCallbacks.onGetPage(mKey);
SingleFixedChoicePage fixedChoicePage = (SingleFixedChoicePage) mPage;
mChoices = new ArrayList<String>();
for (int i = 0; i < fixedChoicePage.getOptionCount(); i++) {
mChoices.add(fixedChoicePage.getOptionAt(i));
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_page, container, false);
((TextView) rootView.findViewById(android.R.id.title)).setText(mPage.getTitle());
final ListView listView = (ListView) rootView.findViewById(android.R.id.list);
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_single_choice,
android.R.id.text1,
mChoices));
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// Pre-select currently selected item.
new Handler().post(new Runnable() {
@Override
public void run() {
String selection = mPage.getData().getString(Page.SIMPLE_DATA_KEY);
for (int i = 0; i < mChoices.size(); i++) {
if (mChoices.get(i).equals(selection)) {
listView.setItemChecked(i, true);
break;
}
}
}
});
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof PageFragmentCallbacks)) {
throw new ClassCastException("Activity must implement PageFragmentCallbacks");
}
mCallbacks = (PageFragmentCallbacks) activity;
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
mPage.getData().putString(Page.SIMPLE_DATA_KEY,
getListAdapter().getItem(position).toString());
mPage.notifyDataChanged();
}
}
| wawaeasybuy/jobandroid | Job/app/src/main/java/com/mardin/job/widgets/wizard/ui/SingleChoiceFragment.java | Java | mit | 4,068 |
/// <reference path="../../tsd.d.ts" />
import {
Component, View,
} from 'angular2/core';
import { CORE_DIRECTIVES } from 'angular2/common';
import {tabs} from '../../ng2-bootstrap';
import {TimepickerDemo} from './timepicker/timepicker-demo';
let name = 'Timepicker';
let src = 'https://github.com/valor-software/ng2-bootstrap/blob/master/components/timepicker/timepicker.ts';
// webpack html imports
let doc = require('../../components/timepicker/readme.md');
let titleDoc = require('../../components/timepicker/title.md');
let ts = require('!!prismjs?lang=typescript!./timepicker/timepicker-demo.ts');
let html = require('!!prismjs?lang=markup!./timepicker/timepicker-demo.html');
@Component({
selector: 'timepicker-section'
})
@View({
template: `
<br>
<section id="${name.toLowerCase()}">
<div class="row"><h1>${name}<small>(<a href="${src}">src</a>)</small></h1></div>
<hr>
<div class="row"><div class="col-md-12">${titleDoc}</div></div>
<div class="row">
<h2>Example</h2>
<div class="card card-block panel panel-default panel-body">
<timepicker-demo></timepicker-demo>
</div>
</div>
<br>
<div class="row">
<tabset>
<tab heading="Markup">
<div class="card card-block panel panel-default panel-body">
<pre class="language-html"><code class="language-html" ng-non-bindable>${html}</code></pre>
</div>
</tab>
<tab heading="TypeScript">
<div class="card card-block panel panel-default panel-body">
<pre class="language-typescript"><code class="language-typescript" ng-non-bindable>${ts}</code></pre>
</div>
</tab>
</tabset>
</div>
<br>
<div class="row">
<h2>API</h2>
<div class="card card-block panel panel-default panel-body">${doc}</div>
</div>
</section>
`,
directives: [TimepickerDemo, tabs, CORE_DIRECTIVES]
})
export class TimepickerSection {
}
| ciriarte/ng2-bootstrap | demo/components/timepicker-section.ts | TypeScript | mit | 1,970 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="tr" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Mojocoin</source>
<translation>Mojocoin Hakkında</translation>
</message>
<message>
<location line="+39"/>
<source><b>Mojocoin</b> version</source>
<translation><b>Mojocoin</b> versiyonu</translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The MojoCoin developers
Copyright © 2014 The Mojocoin developers</source>
<translation>Telif Hakkı © 2009-2014 Bitcoin geliştiricileri
Telif Hakkı © 2012-2014 MojoCoin geliştiricileri
Telif Hakkı © 2014 Mojocoin geliştiricileri</translation>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or <a href="http://www.opensource.org/licenses/mit-license.php">http://www.opensource.org/licenses/mit-license.php</a>.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (<a href="https://www.openssl.org/">https://www.openssl.org/</a>) and cryptographic software written by Eric Young (<a href="mailto:eay@cryptsoft.com">eay@cryptsoft.com</a>) and UPnP software written by Thomas Bernard.</source>
<translation>
Bu, deneysel bir yazılımdır.
MIT/X11 yazılım lisansı kapsamında yayınlanmıştır, beraberindeki COPYING dosyasına veya <a href="http://www.opensource.org/licenses/mit-license.php">http://www.opensource.org/licenses/mit-license.php</a> sayfasına bakınız.
Bu ürün, OpenSSL projesi tarafından OpenSSL araç takımıThis product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (<a href="https://www.openssl.org/">https://www.openssl.org/</a>) için geliştirilmiş yazılımı, Eric Young (<a href="mailto:eay@cryptsoft.com">eay@cryptsoft.com</a>) tarafından hazırlanmış şifreleme yazılımı ve Thomas Bernard tarafından yazılmış UPnP yazılımı içerir.</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adres Defteri</translation>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Adresi ya da etiketi düzenlemek için çift tıklayınız</translation>
</message>
<message>
<location line="+24"/>
<source>Create a new address</source>
<translation>Yeni bir adres oluştur</translation>
</message>
<message>
<location line="+10"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Seçili adresi sistem panosuna kopyala</translation>
</message>
<message>
<location line="-7"/>
<source>&New Address</source>
<translation>&Yeni Adres</translation>
</message>
<message>
<location line="-43"/>
<source>These are your Mojocoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Bunlar, ödeme almak için Mojocoin adreslerinizdir. Her bir göndericiye farklı birini verebilir, böylece size kimin ödeme yaptığını takip edebilirsiniz.</translation>
</message>
<message>
<location line="+53"/>
<source>&Copy Address</source>
<translation>Adresi &Kopyala</translation>
</message>
<message>
<location line="+7"/>
<source>Show &QR Code</source>
<translation>&QR Kodunu Göster</translation>
</message>
<message>
<location line="+7"/>
<source>Sign a message to prove you own a Mojocoin address</source>
<translation>Bir Mojocoin adresine sahip olduğunu ispatlamak için bir mesaj imzala</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>&Mesaj İmzala</translation>
</message>
<message>
<location line="+17"/>
<source>Delete the currently selected address from the list</source>
<translation>Seçili adresi listeden sil</translation>
</message>
<message>
<location line="-10"/>
<source>Verify a message to ensure it was signed with a specified Mojocoin address</source>
<translation>Mesajın, belirli bir Mojocoin adresiyle imzalandığından emin olmak için onu doğrula</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>Mesajı &Doğrula</translation>
</message>
<message>
<location line="+10"/>
<source>&Delete</source>
<translation>&Sil</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+66"/>
<source>Copy &Label</source>
<translation>&Etiketi Kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Düzenle</translation>
</message>
<message>
<location line="+248"/>
<source>Export Address Book Data</source>
<translation>Adres Defteri Verisini Dışarı Aktar</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Virgülle ayrılmış değerler dosyası (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Dışarı aktarım hatası</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>%1 dosyasına yazılamadı.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+145"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(boş etiket)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Parola Diyaloğu</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Parolayı giriniz</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Yeni parola</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Yeni parolayı tekrarlayınız</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation>OS hesabı tehlike girdiğinde önemsiz para gönderme özelliğini devre dışı bırakmayı sağlar. Gerçek anlamda bir güvenlik sağlamaz.</translation>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation>Sadece pay almak için</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+38"/>
<source>Encrypt wallet</source>
<translation>Cüzdanı şifrele</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Bu işlem cüzdan kilidini açmak için cüzdan parolanızı gerektirir.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Cüzdan kilidini aç</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Bu işlem, cüzdan şifresini açmak için cüzdan parolasını gerektirir.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Cüzdan şifresini aç</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Parolayı değiştir</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Cüzdan için eski ve yeni parolaları giriniz.</translation>
</message>
<message>
<location line="+45"/>
<source>Confirm wallet encryption</source>
<translation>Cüzdan şifrelenmesini teyit eder</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation>Uyarı: Eğer cüzdanınızı şifreleyip parolanızı kaybederseniz, <b> TÜM COINLERİNİZİ KAYBEDECEKSİNİZ</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Cüzdanınızı şifrelemek istediğinizden emin misiniz?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>ÖNEMLİ: Önceden yapmış olduğunuz cüzdan dosyası yedeklemelerinin yeni oluşturulan, şifrelenmiş cüzdan dosyası ile değiştirilmeleri gerekmektedir. Güvenlik nedenleriyle yeni, şifrelenmiş cüzdanı kullanmaya başladığınızda, şifrelenmemiş cüzdan dosyasının önceki yedekleri işe yaramaz hale gelecektir.</translation>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Uyarı: Caps Lock tuşu faal durumda!</translation>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Cüzdan şifrelendi</translation>
</message>
<message>
<location line="-140"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Cüzdanınız için yeni parolayı giriniz.<br/>Lütfen <b>on veya daha fazla rastgele karakter</b> ya da <b>sekiz veya daha fazla kelime</b> içeren bir parola seçiniz.</translation>
</message>
<message>
<location line="+82"/>
<source>Mojocoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation>Mojocoin, şifreleme işlemini tamamlamak için şimdi kapatılacak. Cüzdanınızı şifrelemenin; coinlerinizin, bilgisayarınızı etkileyen zararlı yazılımlar tarafından çalınmasını bütünüyle engelleyemeyebileceğini unutmayınız.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Cüzdan şifrelemesi başarısız oldu</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Dahili bir hata sebebiyle cüzdan şifrelemesi başarısız oldu. Cüzdanınız şifrelenmedi.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>Girilen parolalar birbirleriyle eşleşmiyor.</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>Cüzdan kilidinin açılması başarısız oldu</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Cüzdan şifresinin açılması için girilen parola yanlıştı.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Cüzdan şifresinin açılması başarısız oldu</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Cüzdan parolası başarılı bir şekilde değiştirildi.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+297"/>
<source>Sign &message...</source>
<translation>&Mesaj imzala...</translation>
</message>
<message>
<location line="-64"/>
<source>Show general overview of wallet</source>
<translation>Cüzdana genel bakışı göster</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&İşlemler</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>İşlem geçmişine göz at</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation>&Adres Defteri</translation>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Kayıtlı adresler ve etiketler listesini düzenle</translation>
</message>
<message>
<location line="-18"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Ödeme almak için kullanılan adres listesini göster</translation>
</message>
<message>
<location line="+34"/>
<source>E&xit</source>
<translation>&Çık</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Uygulamadan çık</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Mojocoin</source>
<translation>Mojocoin hakkındaki bilgiyi göster</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>&Qt hakkında</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Qt hakkındaki bilgiyi göster</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Seçenekler...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>Cüzdanı &Şifrele...</translation>
</message>
<message>
<location line="+2"/>
<source>&Backup Wallet...</source>
<translation>Cüzdanı &Yedekle...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>Parolayı &Değiştir...</translation>
</message>
<message>
<location line="+9"/>
<source>&Export...</source>
<translation>&Dışarı aktar...</translation>
</message>
<message>
<location line="-55"/>
<source>Send coins to a Mojocoin address</source>
<translation>Bir Mojocoin adresine coin gönder</translation>
</message>
<message>
<location line="+39"/>
<source>Modify configuration options for Mojocoin</source>
<translation>Mojocoin yapılandırma seçeneklerini değiştir</translation>
</message>
<message>
<location line="+17"/>
<source>Export the data in the current tab to a file</source>
<translation>Mevcut sekmedeki veriyi bir dosyaya aktar</translation>
</message>
<message>
<location line="-13"/>
<source>Encrypt or decrypt wallet</source>
<translation>Cüzdanı şifrele veya cüzdanın şifresini aç</translation>
</message>
<message>
<location line="+2"/>
<source>Backup wallet to another location</source>
<translation>Cüzdanı başka bir konuma yedekle</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Cüzdan şifrelemesi için kullanılan parolayı değiştir</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation>&Hata ayıklama penceresi</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Hata ayıklama ve teşhis penceresini aç</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>Mesajı &doğrula...</translation>
</message>
<message>
<location line="-214"/>
<location line="+555"/>
<source>Mojocoin</source>
<translation>Mojocoin</translation>
</message>
<message>
<location line="-555"/>
<source>Wallet</source>
<translation>Cüzdan</translation>
</message>
<message>
<location line="+193"/>
<source>&About Mojocoin</source>
<translation>Mojocoin &Hakkında</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Göster / Gizle</translation>
</message>
<message>
<location line="+8"/>
<source>Unlock wallet</source>
<translation>Cüzdanın kilidini aç</translation>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation>Cüzdanı &Kilitle</translation>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation>Cüzdanı kilitle</translation>
</message>
<message>
<location line="+32"/>
<source>&File</source>
<translation>&Dosya</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>&Ayarlar</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>&Yardım</translation>
</message>
<message>
<location line="+17"/>
<source>Tabs toolbar</source>
<translation>Sekme araç çubuğu</translation>
</message>
<message>
<location line="+46"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+0"/>
<location line="+58"/>
<source>Mojocoin client</source>
<translation>Mojocoin istemcisi</translation>
</message>
<message numerus="yes">
<location line="+70"/>
<source>%n active connection(s) to Mojocoin network</source>
<translation><numerusform>Mojocoin ağına %n etkin bağlantı</numerusform><numerusform>Mojocoin ağına %n etkin bağlantı</numerusform></translation>
</message>
<message>
<location line="+488"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation>Pay alınıyor.<br>Sizin ağırlığınız %1<br>Ağın ağırlığı %2<br>Ödül almak için tahmini süre %3</translation>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation>Pay alınmıyor çünkü cüzdan kilitlidir</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation>Pay alınmıyor çünkü cüzdan çevrimdışıdır</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation>Pay alınmıyor çünkü cüzdan senkronize ediliyor</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation>Pay alınmıyor çünkü olgunlaşmış coininiz yoktur</translation>
</message>
<message>
<location line="-812"/>
<source>&Dashboard</source>
<translation>&Pano</translation>
</message>
<message>
<location line="+6"/>
<source>&Receive</source>
<translation>&Al</translation>
</message>
<message>
<location line="+6"/>
<source>&Send</source>
<translation>&Gönder</translation>
</message>
<message>
<location line="+49"/>
<source>&Unlock Wallet...</source>
<translation>Cüzdanı &Kilitle...</translation>
</message>
<message>
<location line="+277"/>
<source>Up to date</source>
<translation>Güncel</translation>
</message>
<message>
<location line="+43"/>
<source>Catching up...</source>
<translation>Aralık kapatılıyor...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>İşlem ücretini onayla</translation>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>İşlem gerçekleştirildi</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Gelen işlem</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Tarih: %1
Miktar: %2
Tür: %3
Adres: %4
</translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation>URI işleme</translation>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid Mojocoin address or malformed URI parameters.</source>
<translation>URI ayrıştırılamadı! Bu, geçersiz bir Mojocoin adresi veya hatalı URI parametreleri nedeniyle olabilir.</translation>
</message>
<message>
<location line="+9"/>
<source>Wallet is <b>not encrypted</b></source>
<translation>Cüzdan <b>şifreli değil</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Cüzdan <b>şifrelenmiştir</b> ve şu anda <b>kilidi açıktır</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Cüzdan <b>şifrelenmiştir</b> ve şu anda <b>kilitlidir</b></translation>
</message>
<message>
<location line="+24"/>
<source>Backup Wallet</source>
<translation>Cüzdanı Yedekle</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Cüzdan Verisi (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Yedekleme Başarısız Oldu</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Cüzdan verisi, yeni bir konuma kaydedilmeye çalışılırken bir hata oluştu.</translation>
</message>
<message numerus="yes">
<location line="+91"/>
<source>%n second(s)</source>
<translation><numerusform>%n saniye</numerusform><numerusform>%n saniye</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation><numerusform>%n dakika</numerusform><numerusform>%n dakika</numerusform></translation>
</message>
<message numerus="yes">
<location line="-429"/>
<location line="+433"/>
<source>%n hour(s)</source>
<translation><numerusform>%n saat</numerusform><numerusform>%n saat</numerusform></translation>
</message>
<message>
<location line="-456"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>Muamele tarihçesindeki %1 blok işlendi.</translation>
</message>
<message numerus="yes">
<location line="+27"/>
<location line="+433"/>
<source>%n day(s)</source>
<translation><numerusform>%n gün</numerusform><numerusform>%n gün</numerusform></translation>
</message>
<message numerus="yes">
<location line="-429"/>
<location line="+6"/>
<source>%n week(s)</source>
<translation><numerusform>%n hafta</numerusform><numerusform>%n hafta</numerusform></translation>
</message>
<message>
<location line="+0"/>
<source>%1 and %2</source>
<translation>%1 ve %2</translation>
</message>
<message numerus="yes">
<location line="+0"/>
<source>%n year(s)</source>
<translation><numerusform>%n yıl</numerusform><numerusform>%n yıl</numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>%1 behind</source>
<translation>%1 geride</translation>
</message>
<message>
<location line="+15"/>
<source>Last received block was generated %1 ago.</source>
<translation>Son alınan blok %1 önce üretildi.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>Bundan sonraki işlemler daha görünür olmayacaktır.</translation>
</message>
<message>
<location line="+23"/>
<source>Error</source>
<translation>Hata</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Uyarı</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Bilgi</translation>
</message>
<message>
<location line="+69"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>Bu işlem, büyüklük sınırının üzerindedir. İşleminizi gerçekleştirecek devrelere gidecek ve ağı desteklemeye yardımcı olacak %1 ücretle coin gönderebilirsiniz. Ücreti ödemek istiyor musunuz?</translation>
</message>
<message>
<location line="+324"/>
<source>Not staking</source>
<translation>Pay alınmıyor</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+104"/>
<source>A fatal error occurred. Mojocoin can no longer continue safely and will quit.</source>
<translation>Önemli bir hata oluştu. Mojocoin artık güvenli bir şekilde devam edemez ve şimdi kapatılacak.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+110"/>
<source>Network Alert</source>
<translation>Ağ Uyarısı</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation>Coin Kontrolü</translation>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>Adet:</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation>Bayt:</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Miktar:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>Öncelik:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>Ücret:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Düşük Çıktı:</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+537"/>
<source>no</source>
<translation>hayır</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>Ücretten sonra:</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>Para üstü:</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation>tümünü seç(me)</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>Ağaç kipi</translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>Liste kipi</translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Miktar</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Tarih</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>Onaylar</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Onaylandı</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>Öncelik</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-500"/>
<source>Copy address</source>
<translation>Adresi kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Etiketi kopyala</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Miktarı kopyala</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>İşlem Numarasını Kopyala</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>Adedi kopyala</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Ücreti kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Ücretten sonrakini kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Baytları kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Önceliği kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Düşük çıktıyı kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Para üstünü kopyala</translation>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation>en yüksek</translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation>yüksek</translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation>orta-yüksek</translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation>orta</translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation>düşük-orta</translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation>düşük</translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation>en düşük</translation>
</message>
<message>
<location line="+140"/>
<source>DUST</source>
<translation>BOZUKLUK</translation>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>evet</translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation>İşlem büyüklüğü 10000 bayttan büyükse, bu etiket kırmızıya dönüşür.
Bu, kb başına en az %1 ücret gerektiği anlamına gelir.
Girdi başına +/- 1 Byte değişkenlik gösterebilir.</translation>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation>Yüksek öncelikli işlemler, daha yüksek ihtimalle bir bloğa düşer.
Öncelik "orta" seviyeden düşükse, bu etiket kırmızıya döner.
Bu, kb başına en az %1 ücret gerektiği anlamına gelir.</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation>Eğer herhangi bir alıcı, %1'den daha küçük bir miktar alırsa, bu etiket kırmızıya dönüşür.
Bu, en az %2 bir ücretin gerektiği anlamına gelir.
Minimum aktarım ücretinin 0.546 katından düşük miktarlar, BOZUKLUK olarak gösterilir.</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation>Eğer para üstü %1'den küçükse, bu etiket kırmızıya dönüşür.
Bu, en az %2 bir ücretin gerektiği anlamına gelir.</translation>
</message>
<message>
<location line="+36"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(boş etiket)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation>%1 unsurundan para üstü (%2)</translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(para üstü)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Adresi düzenle</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Etiket</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Bu adres defteri kaydıyla ilişkili etiket</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adres</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Bu adres defteri kaydıyla ilişkili etiket. Bu, sadece gönderi adresleri için değiştirilebilir.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Yeni alım adresi</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Yeni gönderi adresi</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Alım adresini düzenle</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Gönderi adresini düzenle</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Girilen "%1" adresi hâlihazırda adres defterinde mevcuttur.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Mojocoin address.</source>
<translation>Girilen %1 adresi, geçerli bir Mojocoin adresi değildir.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Cüzdan kilidi açılamadı.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Yeni anahtar oluşturulması başarısız oldu.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+426"/>
<location line="+12"/>
<source>Mojocoin-Qt</source>
<translation>Mojocoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versiyon</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Kullanım:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>komut satırı seçenekleri</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>GA seçenekleri</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Dili ayarla, örneğin "de_DE" (varsayılan: sistem yerel ayarları)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Simge durumunda başlat</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Başlangıçta açılış ekranını göster (varsayılan: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Seçenekler</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Esas ayarlar</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation>İşlemlerinizin hızlıca gerçekleştirilmesini sağlayan kB başına opsiyonel işlem ücreti. Birçok işlem 1 kB'tır. Tavsiye edilen ücret 0.01'dir.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>İşlem ücreti &öde</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation>Ayrılan miktar, pay almaya katılamıyor ve bu yüzden herhangi bir anda harcanabilir.</translation>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation>Ayrılan</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Mojocoin after logging in to the system.</source>
<translation>Sisteme giriş yaptıktan sonra Mojocoin'i otomatik olarak başlat</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Mojocoin on system login</source>
<translation>Sisteme girişte Mojocoin'i &başlat</translation>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Şebeke</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Mojocoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Yönelticide Mojocoin istemci portunu otomatik olarak aç. Bu, sadece yönelticiniz UPnP'i desteklediğinde ve etkin olduğunda çalışır.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Portları &UPnP kullanarak haritala</translation>
</message>
<message>
<location line="+19"/>
<source>Proxy &IP:</source>
<translation>Vekil &İP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Vekil sunucunun IP adresi (örn. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Vekil sunucunun portu (mesela 9050)</translation>
</message>
<message>
<location line="-57"/>
<source>Connect to the Mojocoin network through a SOCKS5 proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS5 proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+90"/>
<source>&Window</source>
<translation>&Pencere</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Küçültüldükten sonra sadece çekmece ikonu göster.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>İşlem çubuğu yerine sistem çekmecesine &küçült</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Pencere kapatıldığında uygulamadan çıkmak yerine uygulamayı küçültür. Bu seçenek etkinleştirildiğinde, uygulama sadece menüden çıkış seçildiğinde kapanacaktır.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>Kapatma sırasında k&üçült</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Görünüm</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Kullanıcı arayüzü &lisanı:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Mojocoin.</source>
<translation>Kullanıcı arabirimi dili buradan ayarlanabilir. Ayar, Mojocoin yeniden başlatıldığında etkin olacaktır.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>Meblağları göstermek için &birim:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Bitcoin gönderildiğinde arayüzde gösterilecek varsayılan alt birimi seçiniz.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show coin control features or not.</source>
<translation>Para kontrol özelliklerinin gösterilip gösterilmeyeceğini ayarlar.</translation>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation>Coin &kontrol özelliklerini göster (sadece uzman kişiler!)</translation>
</message>
<message>
<location line="+7"/>
<source>Whether to select the coin outputs randomly or with minimal coin age.</source>
<translation>Coin çıktılarını rastgele veya asgari coin yıllandırmasına göre seçme.</translation>
</message>
<message>
<location line="+3"/>
<source>Minimize weight consumption (experimental)</source>
<translation>Ağırlık tüketimini minimuma indirme (deneysel)</translation>
</message>
<message>
<location line="+7"/>
<source>Use black visual theme (requires restart)</source>
<translation>Siyah görsel temayı kullan (baştan başlatmayı gerektirir)</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&Tamam</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&İptal</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Uygula</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+47"/>
<source>default</source>
<translation>varsayılan</translation>
</message>
<message>
<location line="+148"/>
<location line="+9"/>
<source>Warning</source>
<translation>Uyarı</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Mojocoin.</source>
<translation>Bu ayar, Mojocoin'i yeniden başlattıktan sonra etkin olacaktır.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Girilen vekil sunucu adresi geçersizdir.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location line="+46"/>
<location line="+247"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Mojocoin network after a connection is established, but this process has not completed yet.</source>
<translation>Görüntülenen bilginin tarihi geçmiş olabilir. Cüzdanınız, bağlantı kurulduktan sonra otomatik olarak Mojocoin ağı ile senkronize olur ancak bu süreç, henüz tamamlanmamıştır.</translation>
</message>
<message>
<location line="-173"/>
<source>Stake:</source>
<translation>Pay:</translation>
</message>
<message>
<location line="+32"/>
<source>Unconfirmed:</source>
<translation>Doğrulanmamış:</translation>
</message>
<message>
<location line="-113"/>
<source>Wallet</source>
<translation>Cüzdan</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation>Harcanabilir:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation>Güncel harcanabilir bakiyeniz</translation>
</message>
<message>
<location line="+80"/>
<source>Immature:</source>
<translation>Olgunlaşmamış:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Oluşturulan bakiye henüz olgunlaşmamıştır</translation>
</message>
<message>
<location line="+23"/>
<source>Total:</source>
<translation>Toplam:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation>Güncel toplam bakiyeniz</translation>
</message>
<message>
<location line="+50"/>
<source><b>Recent transactions</b></source>
<translation><b>Son işlemler</b></translation>
</message>
<message>
<location line="-118"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Henüz onaylanmamış ve mevcut bakiyede yer almayan işlemler toplamı</translation>
</message>
<message>
<location line="-32"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation>Pay alınmış ve mevcut bakiyede yer almayan coin toplamı</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>eşleşme dışı</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start mojocoin: click-to-pay handler</source>
<translation>Mojocoin: tıkla-ve-öde işleyicisi başlatılamıyor</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR Kodu İletisi</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Ödeme Talep Et</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Miktar:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Etiket:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Mesaj:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Farklı Kaydet...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>URI'nin QR koduna kodlanmasında hata oluştu.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Girilen miktar geçersizdir, lütfen kontrol ediniz.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Sonuç URI'si çok uzundur, etiket / mesaj için olan metni kısaltmaya çalışın.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>QR Kodu'nu Kaydet</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG İmgeleri (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>İstemci ismi</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<source>N/A</source>
<translation>Mevcut değil</translation>
</message>
<message>
<location line="-194"/>
<source>Client version</source>
<translation>İstemci sürümü</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Malumat</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Kullanılan OpenSSL sürümü</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Başlama zamanı</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Şebeke</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Bağlantı sayısı</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Testnet üzerinde</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Blok zinciri</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Güncel blok sayısı</translation>
</message>
<message>
<location line="+197"/>
<source>&Network Traffic</source>
<translation>&Şebeke Trafiği</translation>
</message>
<message>
<location line="+52"/>
<source>&Clear</source>
<translation>&Temizle</translation>
</message>
<message>
<location line="+13"/>
<source>Totals</source>
<translation>Toplam</translation>
</message>
<message>
<location line="+64"/>
<source>In:</source>
<translation>Gelen:</translation>
</message>
<message>
<location line="+80"/>
<source>Out:</source>
<translation>Giden:</translation>
</message>
<message>
<location line="-383"/>
<source>Last block time</source>
<translation>Son blok zamanı</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Aç</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Komut satırı seçenekleri</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Mojocoin-Qt help message to get a list with possible Mojocoin command-line options.</source>
<translation>Muhtemel Mojocoin komut satırı seçeneklerinin bir listesini getirmek için Mojocoin-Qt yardım mesajını göster</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Göster</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konsol</translation>
</message>
<message>
<location line="-237"/>
<source>Build date</source>
<translation>Derleme tarihi</translation>
</message>
<message>
<location line="-104"/>
<source>Mojocoin - Debug window</source>
<translation>Mojocoin - Hata ayıklama penceresi</translation>
</message>
<message>
<location line="+25"/>
<source>Mojocoin Core</source>
<translation>Mojocoin Core</translation>
</message>
<message>
<location line="+256"/>
<source>Debug log file</source>
<translation>Hata ayıklama kütük dosyası</translation>
</message>
<message>
<location line="+7"/>
<source>Open the Mojocoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Mojocoin hata ayıklama günlük kütüğü dosyasını, mevcut veri klasöründen aç. Bu işlem, büyük günlük kütüğü dosyaları için birkaç saniye sürebilir.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Konsolu temizle</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="+325"/>
<source>Welcome to the Mojocoin RPC console.</source>
<translation>Mojocoin RPC konsoluna hoş geldiniz.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Tarihçede gezinmek için imleç tuşlarını kullanınız, <b>Ctrl-L</b> ile de ekranı temizleyebilirsiniz.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Mevcut komutların listesi için <b>help</b> yazınız.</translation>
</message>
<message>
<location line="+127"/>
<source>%1 B</source>
<translation>%1 B</translation>
</message>
<message>
<location line="+2"/>
<source>%1 KB</source>
<translation>%1 KB</translation>
</message>
<message>
<location line="+2"/>
<source>%1 MB</source>
<translation>%1 MB</translation>
</message>
<message>
<location line="+2"/>
<source>%1 GB</source>
<translation>%1 GB</translation>
</message>
<message>
<location line="+7"/>
<source>%1 m</source>
<translation>%1 dk</translation>
</message>
<message>
<location line="+5"/>
<source>%1 h</source>
<translation>%1 sa</translation>
</message>
<message>
<location line="+2"/>
<source>%1 h %2 m</source>
<translation>%1 sa %2 dk</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Bitcoin yolla</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation>Para kontrolü özellikleri</translation>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation>Girdiler...</translation>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation>otomatik seçilmiş</translation>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation>Yetersiz fon!</translation>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation>Miktar:</translation>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation>0</translation>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation>Bayt:</translation>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation>Meblağ:</translation>
</message>
<message>
<location line="+35"/>
<source>Priority:</source>
<translation>Öncelik:</translation>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation>orta</translation>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation>Ücret:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Düşük çıktı:</translation>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation>hayır</translation>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation>Ücretten sonra:</translation>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation>Değiştir</translation>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation>özel adres değişikliği</translation>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>Birçok alıcıya aynı anda gönder</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Alıcı ekle</translation>
</message>
<message>
<location line="+16"/>
<source>Remove all transaction fields</source>
<translation>Tüm işlem alanlarını kaldır</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Tümünü &temizle</translation>
</message>
<message>
<location line="+24"/>
<source>Balance:</source>
<translation>Bakiye:</translation>
</message>
<message>
<location line="+47"/>
<source>Confirm the send action</source>
<translation>Yollama etkinliğini teyit ediniz</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>G&önder</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-174"/>
<source>Enter a Mojocoin address (e.g. MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</source>
<translation>Bir Mojocoin adresi gir (örn: MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</translation>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation>Miktarı kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Meblağı kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation>Ücreti kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Ücretten sonrakini kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Baytları kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Önceliği kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Düşük çıktıyı kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Para üstünü kopyala</translation>
</message>
<message>
<location line="+87"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> %2'ye (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Gönderiyi teyit ediniz</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>%1 göndermek istediğinizden emin misiniz?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>ve</translation>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Alıcı adresi geçerli değildir, lütfen denetleyiniz.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Ödeyeceğiniz tutarın sıfırdan yüksek olması gerekir.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Tutar bakiyenizden yüksektir.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Toplam, %1 işlem ücreti ilâve edildiğinde bakiyenizi geçmektedir.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Çift adres bulundu, belli bir gönderi sırasında her adrese sadece tek bir gönderide bulunulabilir.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Hata: İşlem yaratma başarısız oldu!</translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Hata: İşlem reddedildi. Bu, örneğin wallet.dat dosyasının bir kopyasını kullandıysanız ve coinler, kopyada harcanmış ve burada harcanmış olarak işaretlenmemişse, cüzdanınızdaki coinlerin bir bölümünün harcanması nedeniyle olabilir. </translation>
</message>
<message>
<location line="+247"/>
<source>WARNING: Invalid Mojocoin address</source>
<translation>UYARI: Geçersiz Mojocoin adresi</translation>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(boş etiket)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation>UYARI: bilinmeyen adres değişikliği</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Mebla&ğ:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>&Şu adrese öde:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</source>
<translation>Ödemenin gönderileceği adres (örn: MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</translation>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Adres defterinize eklemek için bu adrese ilişik bir etiket giriniz</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Etiket:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Adres defterinden adres seç</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Panodan adres yapıştır</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Bu alıcıyı kaldır</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Mojocoin address (e.g. MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</source>
<translation>Bir Mojocoin adresi girin (örn: MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>İmzalar - Mesaj İmzala / Kontrol et</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>Mesaj &imzala</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Bir adresin sizin olduğunu ispatlamak için adresinizle mesaj imzalayabilirsiniz. Oltalama saldırılarının kimliğinizi imzanızla elde etmeyi deneyebilecekleri için belirsiz hiçbir şey imzalamamaya dikkat ediniz. Sadece ayrıntılı açıklaması olan ve tümüne katıldığınız ifadeleri imzalayınız.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</source>
<translation>Mesajın imzalanacağı adres (örn: MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</translation>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation>Adres defterinden adres seç</translation>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Panodan adres yapıştır</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>İmzalamak istediğiniz mesajı burada giriniz</translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Güncel imzayı sistem panosuna kopyala</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Mojocoin address</source>
<translation>Bu Mojocoin adresine sahip olduğunuzu ispatlamak için mesajı imzala</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation>Tüm mesaj alanlarını sıfırla</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Tümünü &temizle</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation>Mesaj &kontrol et</translation>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>İmza için kullanılan adresi, mesajı (satır sonları, boşluklar, sekmeler vs. karakterleri tam olarak kopyaladığınızdan emin olunuz) ve imzayı aşağıda giriniz. Bir ortadaki adam saldırısı tarafından kandırılmaya mâni olmak için imzadan, imzalı mesajın içeriğini aşan bir anlam çıkarmamaya dikkat ediniz.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</source>
<translation>Mesajın imzalandığı adres (örn: MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Mojocoin address</source>
<translation>Mesajın, belirtilen Mojocoin adresiyle imzalandığından emin olmak için onu doğrula</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation>Tüm mesaj kontrolü alanlarını sıfırla</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Mojocoin address (e.g. MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</source>
<translation>Bir Mojocoin adresi girin (örn: MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>İmzayı oluşturmak için "Mesaj İmzala" unsurunu tıklayın</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Mojocoin signature</source>
<translation>Mojocoin imzası gir</translation>
</message>
<message>
<location line="+85"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Girilen adres geçersizdir.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Adresi kontrol edip tekrar deneyiniz.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Girilen adres herhangi bir anahtara işaret etmemektedir.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Cüzdan kilidinin açılması iptal edildi.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Girilen adres için özel anahtar mevcut değildir.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Mesajın imzalanması başarısız oldu.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Mesaj imzalandı.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>İmzanın kodu çözülemedi.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>İmzayı kontrol edip tekrar deneyiniz.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>İmza mesajın hash değeri ile eşleşmedi.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Mesaj doğrulaması başarısız oldu.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Mesaj doğrulandı.</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<location filename="../trafficgraphwidget.cpp" line="+75"/>
<source>KB/s</source>
<translation>KB/s</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+25"/>
<source>Open until %1</source>
<translation>%1 değerine dek açık</translation>
</message>
<message>
<location line="+6"/>
<source>conflicted</source>
<translation>çakışma</translation>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/çevrim dışı</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/doğrulanmadı</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 teyit</translation>
</message>
<message>
<location line="+17"/>
<source>Status</source>
<translation>Durum</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, %n devre üzerinde yayınlama</numerusform><numerusform>, %n devre üzerinde yayınlama</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Tarih</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Kaynak</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Oluşturuldu</translation>
</message>
<message>
<location line="+5"/>
<location line="+13"/>
<source>From</source>
<translation>Gönderen</translation>
</message>
<message>
<location line="+1"/>
<location line="+19"/>
<location line="+58"/>
<source>To</source>
<translation>Alıcı</translation>
</message>
<message>
<location line="-74"/>
<location line="+2"/>
<source>own address</source>
<translation>kendi adresiniz</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>etiket</translation>
</message>
<message>
<location line="+34"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Gider</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>%n blok içerisinde olgunlaşıyor</numerusform><numerusform>%n blok içerisinde olgunlaşıyor</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>kabul edilmedi</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Gelir</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>İşlem ücreti</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Net meblağ</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Mesaj</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Yorum</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>İşlem NO</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 510 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 "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Üretilen coinler, harcanmaya başlamadan önce 510 blokta olgunlaşmalıdır. Bu bloğu ürettiğinizde, blok zincirine eklenmek üzere ağda yayınlanır. Eğer blok, zincire girmede başarısız olursa, bloğun durumu "kabul edilmedi"ye dönüşür ve harcanamaz. Bu, başka bir devre sizden birkaç saniye önce bir blok ürettiyse gerçekleşebilir.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Hata ayıklama verileri</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>İşlem</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>Girdiler</translation>
</message>
<message>
<location line="+21"/>
<source>Amount</source>
<translation>Meblağ</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>doğru</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>yanlış</translation>
</message>
<message>
<location line="-202"/>
<source>, has not been successfully broadcast yet</source>
<translation>, henüz başarılı bir şekilde yayınlanmadı</translation>
</message>
<message numerus="yes">
<location line="-36"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>%n blok için aç</numerusform><numerusform>%n blok için aç</numerusform></translation>
</message>
<message>
<location line="+67"/>
<source>unknown</source>
<translation>bilinmiyor</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>İşlem detayları</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Bu pano işlemlerin ayrıntılı açıklamasını gösterir</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+231"/>
<source>Date</source>
<translation>Tarih</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tür</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Meblağ</translation>
</message>
<message>
<location line="+52"/>
<source>Open until %1</source>
<translation>%1 değerine dek açık</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Doğrulandı (%1 teyit)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>%n blok için aç</numerusform><numerusform>%n blok için aç</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation>Çevrim dışı</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation>Teyit edilmemiş</translation>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation>Teyit ediliyor (tavsiye edilen %2 teyit üzerinden %1 doğrulama)</translation>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation>Çakışma</translation>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation>Olgunlaşmamış (%1 teyit, %2 teyit ardından kullanılabilir olacaktır)</translation>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Bu blok başka hiçbir düğüm tarafından alınmamıştır ve muhtemelen kabul edilmeyecektir!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Oluşturuldu ama kabul edilmedi</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Şununla alındı</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Alındığı kişi</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Gönderildiği adres</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Kendinize ödeme</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Madenden çıkarılan</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(mevcut değil)</translation>
</message>
<message>
<location line="+194"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>İşlem durumu. Doğrulama sayısını görüntülemek için imleci bu alanda tutunuz.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>İşlemin alındığı tarih ve zaman.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>İşlemin türü.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>İşlemin alıcı adresi.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Bakiyeden alınan ya da bakiyeye eklenen meblağ.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+54"/>
<location line="+17"/>
<source>All</source>
<translation>Hepsi</translation>
</message>
<message>
<location line="-16"/>
<source>Today</source>
<translation>Bugün</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Bu hafta</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Bu ay</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Geçen ay</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Bu sene</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Aralık...</translation>
</message>
<message>
<location line="+12"/>
<source>Received with</source>
<translation>Şununla alınan</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Gönderildiği adres</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Kendinize</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Oluşturulan</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Diğer</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Aranacak adres ya da etiket giriniz</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Asgari meblağ</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Adresi kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Etiketi kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Meblağı kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>İşlem numarasını kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Etiketi düzenle</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>İşlem detaylarını göster</translation>
</message>
<message>
<location line="+138"/>
<source>Export Transaction Data</source>
<translation>İşlem Verisini Dışarı Aktar</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Virgülle ayrılmış değerler dosyası (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Doğrulandı</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Tarih</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tür</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Meblağ</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>Tanımlayıcı</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Dışarı aktarmada hata</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>%1 dosyasına yazılamadı.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Aralık:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>ilâ</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+212"/>
<source>Sending...</source>
<translation>Gönderiyor...</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+171"/>
<source>Mojocoin version</source>
<translation>Mojocoin versiyonu</translation>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Kullanım:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or mojocoind</source>
<translation>-sunucu veya mojocoind'ye komut gönder</translation>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>Komutları listele</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Bir komut için yardım al</translation>
</message>
<message>
<location line="-145"/>
<source>Options:</source>
<translation>Seçenekler:</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: mojocoin.conf)</source>
<translation>Konfigürasyon dosyasını belirt (varsayılan: mojocoin.conf)</translation>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: mojocoind.pid)</source>
<translation>pid dosyasını belirt (varsayılan: mojocoin.pid)</translation>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation>Cüzdan dosyası belirtiniz (veri klasörünün içinde)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Veri dizinini belirt</translation>
</message>
<message>
<location line="-25"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=mojocoinrpc
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 "Mojocoin Alert" admin@foo.com
</source>
<translation>%s, konfigürasyon dosyasında bir rpcpassword belirlemelisiniz:
%s
Aşağıdaki rastgele şifreyi kullanmanız tavsiye edilir:
rpcuser=mojocoinrpc
rpcpassword=%s
(bu şifreyi hatırlamanız gerekmemektedir)
Kullanıcı adı ve şifre aynı OLMAMALIDIR.
Dosya mevcut değilse, sadece sahibi tarafından okunabilir yetkiyle yaratın.
Ayrıca sorunlardan haberdar edilmek için alertnotify parametresini doldurmanız önerilir;
örneğin: alertnotify=echo %%s | mail -s "Mojocoin Alarmı" admin@foo.com
</translation>
</message>
<message>
<location line="+27"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Veritabanı önbellek boyutunu megabayt olarak belirt (varsayılan: 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation>Veritabanı disk log boyutunu megabayt olarak ayarla (varsayılan: 100)</translation>
</message>
<message>
<location line="+5"/>
<source>Listen for connections on <port> (default: 9495 or testnet: 19495)</source>
<translation><port> üzerinde bağlantıları dinle (varsayılan: 9495 veya testnet: 19495)</translation>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Eşler ile en çok <n> adet bağlantı kur (varsayılan: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Eş adresleri elde etmek için bir düğüme bağlan ve ardından bağlantıyı kes</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Kendi genel adresinizi tanımlayın</translation>
</message>
<message>
<location line="+4"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation>Belirtilen adrese bağlı. IPv6 için [host]:port notasyonunu kullan</translation>
</message>
<message>
<location line="+1"/>
<source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source>
<translation>DNS araması ile eş adresleri sorgula, adres sayısı az ise (varsayılan: 1 -connect hariç)</translation>
</message>
<message>
<location line="+3"/>
<source>Always query for peer addresses via DNS lookup (default: 0)</source>
<translation>DNS araması ile eş adresleri her zaman sorgula (varsayılan: 0)</translation>
</message>
<message>
<location line="+4"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Aksaklık gösteren eşlerle bağlantıyı kesme sınırı (varsayılan: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Aksaklık gösteren eşlerle yeni bağlantıları engelleme süresi, saniye olarak (varsayılan: 86400)</translation>
</message>
<message>
<location line="-35"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>IPv4 üzerinde dinlemek için %u numaralı RPC portunun kurulumu sırasında hata meydana geldi: %s</translation>
</message>
<message>
<location line="+62"/>
<source>Listen for JSON-RPC connections on <port> (default: 9496 or testnet: 19496)</source>
<translation><port> üzerinde JSON-RPC bağlantılarını dinle (varsayılan: 9496 veya testnet: 19496)</translation>
</message>
<message>
<location line="-16"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Konut satırı ve JSON-RPC komutlarını kabul et</translation>
</message>
<message>
<location line="+1"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Arka planda daemon (servis) olarak çalış ve komutları kabul et</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Deneme şebekesini kullan</translation>
</message>
<message>
<location line="-23"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Dışarıdan gelen bağlantıları kabul et (varsayılan: -proxy veya -connect yoksa 1)</translation>
</message>
<message>
<location line="-28"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>IPv6 üzerinde dinlemek için %u numaralı RPC portu kurulurken bir hata meydana geldi, IPv4'e dönülüyor: %s</translation>
</message>
<message>
<location line="+93"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Bayt olarak yüksek öncelikli/düşük ücretli işlemlerin maksimum boyutunu belirle (varsayılan: 27000)</translation>
</message>
<message>
<location line="+15"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Uyarı: -paytxfee çok yüksek bir değere ayarlanmış! Bu, bir işlem gönderdiğiniz takdirde ödeyeceğiniz ücrettir.</translation>
</message>
<message>
<location line="-103"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Mojocoin will not work properly.</source>
<translation>Uyarı: Lütfen bilgisayarınızın tarih ve saatinin doğru olduğunu kontrol ediniz! Saatiniz yanlış ise, Mojocoin düzgün çalışmayacaktır.</translation>
</message>
<message>
<location line="+130"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Uyarı: wallet.dat dosyasının okunması sırasında bir hata meydana geldi! Tüm anahtarlar doğru bir şekilde okundu, ancak işlem verileri ya da adres defteri girdileri hatalı veya eksik olabilir.</translation>
</message>
<message>
<location line="-16"/>
<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>Uyarı: wallet.dat bozuk, veriler geri kazanıldı! Orijinal wallet.dat, wallet.{zamandamgası}.bak olarak %s klasörüne kaydedildi; bakiyeniz ya da işlemleriniz yanlışsa bir yedekten tekrar yüklemelisiniz.</translation>
</message>
<message>
<location line="-34"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Bozuk bir wallet.dat dosyasından özel anahtarları geri kazanmayı dene</translation>
</message>
<message>
<location line="+5"/>
<source>Block creation options:</source>
<translation>Blok oluşturma seçenekleri:</translation>
</message>
<message>
<location line="-67"/>
<source>Connect only to the specified node(s)</source>
<translation>Sadece belirtilen düğüme veya düğümlere bağlan</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Kendi IP adresini keşfet (varsayılan: dinlenildiğinde ve -externalip yoksa 1)</translation>
</message>
<message>
<location line="+101"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Herhangi bir portun dinlenmesi başarısız oldu. Bunu istiyorsanız -listen=0 seçeneğini kullanınız.</translation>
</message>
<message>
<location line="-2"/>
<source>Invalid -tor address: '%s'</source>
<translation>Geçersiz -tor adresi: '%s'</translation>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation>-reservebalance=<amount> için geçersiz miktar</translation>
</message>
<message>
<location line="-89"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Bağlantı başına azami alım tamponu, <n>*1000 bayt (varsayılan: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Bağlantı başına azami yollama tamponu, <n>*1000 bayt (varsayılan: 1000)</translation>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Sadece <net> şebekesindeki düğümlere bağlan (IPv4, IPv6 ya da Tor)</translation>
</message>
<message>
<location line="+30"/>
<source>Prepend debug output with timestamp</source>
<translation>Tarih bilgisini, hata ayıklama çıktısının başına ekle</translation>
</message>
<message>
<location line="+40"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation> SSL seçenekleri: (SSL kurulum bilgisi için Bitcoin vikisine bakınız)</translation>
</message>
<message>
<location line="-38"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Trace/hata ayıklama verilerini debug.log dosyası yerine konsola gönder</translation>
</message>
<message>
<location line="+34"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Bayt olarak maksimum blok boyutunu belirle (varsayılan: 250000)</translation>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Bayt olarak asgari blok boyutunu tanımla (varsayılan: 0)</translation>
</message>
<message>
<location line="-34"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>İstemci başlatıldığında debug.log dosyasını küçült (varsayılan: -debug bulunmadığında 1)</translation>
</message>
<message>
<location line="-41"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Bağlantı zaman aşım süresini milisaniye olarak belirt (varsayılan: 5000)</translation>
</message>
<message>
<location line="+28"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Dinlenecek portu haritalamak için UPnP kullan (varsayılan: 0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Dinlenecek portu haritalamak için UPnP kullan (varsayılan: dinlenildiğinde 1)</translation>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Tor gizli servisine erişim için vekil sunucu kullan (varsayılan: -proxy ile aynı)</translation>
</message>
<message>
<location line="+45"/>
<source>Username for JSON-RPC connections</source>
<translation>JSON-RPC bağlantıları için kullanıcı ismi</translation>
</message>
<message>
<location line="+54"/>
<source>Verifying database integrity...</source>
<translation>Veritabanı bütünlüğü doğrulanıyor...</translation>
</message>
<message>
<location line="+42"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>Hata: Cüzdan kilitli, işlem yaratılamıyor!</translation>
</message>
<message>
<location line="+2"/>
<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>Hata: Bu işlem; miktarı, karmaşıklığı veya son alınan miktarın kullanımı nedeniyle en az %s işlem ücreti gerektirir!</translation>
</message>
<message>
<location line="+3"/>
<source>Error: Transaction creation failed!</source>
<translation>Hata: İşlem yaratma başarısız oldu!</translation>
</message>
<message>
<location line="+2"/>
<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>Hata: İşlem reddedildi. Bu; cüzdanınızdaki bazı coinler, önceden harcanmışsa, örneğin wallet.dat dosyasının bir kopyasını kullandıysanız ve bu kopyadaki coinler harcanmış ve burada harcanmış olarak işaretlenmediyse gerçekleşebilir.</translation>
</message>
<message>
<location line="+7"/>
<source>Warning</source>
<translation>Uyarı</translation>
</message>
<message>
<location line="+1"/>
<source>Information</source>
<translation>Bilgi</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Uyarı: Bu sürüm çok eskidir, güncellemeniz gerekir!</translation>
</message>
<message>
<location line="-52"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat bozuk, geri kazanım başarısız oldu</translation>
</message>
<message>
<location line="-59"/>
<source>Password for JSON-RPC connections</source>
<translation>JSON-RPC bağlantıları için parola</translation>
</message>
<message>
<location line="-47"/>
<source>Connect through SOCKS5 proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation>Diğer devrelerle saati senkronize et. Sisteminizdeki saat doğru ise devre dışı bırakın, örn: NTC ile senkronize etme (varsayılan: 1)</translation>
</message>
<message>
<location line="+12"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation>İşlem yaratırken, bundan daha küçük değere sahip girdileri yok say (varsayılan: 0.01)</translation>
</message>
<message>
<location line="+6"/>
<source>Output debugging information (default: 0, supplying <category> is optional)</source>
<translation>Hata ayıklama bilgisi çıktısı al (varsayılan: 0, <category> belirtmek isteğe bağlıdır)</translation>
</message>
<message>
<location line="+2"/>
<source>If <category> is not supplied, output all debugging information.</source>
<translation><category> belirtilmediyse, bütün ayıklama bilgisinin çıktısını al.</translation>
</message>
<message>
<location line="+1"/>
<source><category> can be:</source>
<translation><category> şunlar olabilir:</translation>
</message>
<message>
<location line="+4"/>
<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>Bağlanım deneme moduna gir, bu mod blokların anında çözülebilmesini sağlayan özel bir zincir kullanır. Bu seçenek bağlanım deneme araçları ve uygulama geliştirme için tasarlanmıştır.</translation>
</message>
<message>
<location line="+8"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Belirtilen İP adresinden JSON-RPC bağlantılarını kabul et</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Şu <ip> adresinde (varsayılan: 127.0.0.1) çalışan düğüme komut yolla</translation>
</message>
<message>
<location line="+1"/>
<source>Wait for RPC server to start</source>
<translation>RPC sunucusunun başlamasını bekle</translation>
</message>
<message>
<location line="+1"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>RPC çağrı hizmeti verecek dizi sayısını ayarla (varsayılan: 4)</translation>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>En iyi blok değiştiğinde komutu çalıştır (komut için %s parametresi blok hash değeri ile değiştirilecektir)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Bir cüzdan işlemi değiştiğinde komutu çalıştır (komuttaki %s TxID ile değiştirilecektir)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation>Değişim için bir onay sayısı talep et (varsayılan: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>İlgili alarm alındığında komutu çalıştır (cmd'deki %s, mesaj ile değiştirilecektir)</translation>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>Cüzdanı en yeni biçime güncelle</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Anahtar alan boyutunu <n> değerine ayarla (varsayılan: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Blok zincirini eksik cüzdan işlemleri için tekrar tara</translation>
</message>
<message>
<location line="+3"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation>Blok kontrolünün ne kadar derin olacağı (0-6, varsayılan: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation>Harici blk000?.dat dosyasından blok içeri aktar</translation>
</message>
<message>
<location line="+1"/>
<source>Keep at most <n> MiB of unconnectable blocks in memory (default: %u)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>JSON-RPC bağlantıları için OpenSSL (https) kullan</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Sunucu sertifika dosyası (varsayılan: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Sunucu özel anahtarı (varsayılan: server.pem)</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Initialization sanity check failed. Mojocoin is shutting down.</source>
<translation>Başlangıç uygunluk kontrolü başarısız oldu. Mojocoin kapatılıyor.</translation>
</message>
<message>
<location line="+20"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation>Hata: Cüzdanın kilidi sadece pay almak için açılmıştır, işlem yaratılamıyor.</translation>
</message>
<message>
<location line="+16"/>
<source>Error: Disk space is low!</source>
<translation>Uyarı: Disk alanı düşük!</translation>
</message>
<message>
<location line="+1"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation>Bu bir ön test sürümüdür - kullanım riski size aittir - madencilik veya ticari uygulamalarda kullanmayın</translation>
</message>
<message>
<location line="-168"/>
<source>This help message</source>
<translation>Bu yardım mesajı</translation>
</message>
<message>
<location line="+104"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation>Cüzdan %s, veri klasörü %s dışında yer alıyor.</translation>
</message>
<message>
<location line="+35"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Bu bilgisayarda %s unsuruna bağlanılamadı. (bind şu hatayı iletti: %d, %s)</translation>
</message>
<message>
<location line="-129"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>-addnode, -seednode ve -connect için DNS aramalarına izin ver</translation>
</message>
<message>
<location line="+125"/>
<source>Loading addresses...</source>
<translation>Adresler yükleniyor...</translation>
</message>
<message>
<location line="-10"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>wallet.dat dosyasının yüklenmesinde hata oluştu: bozuk cüzdan</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of Mojocoin</source>
<translation>wallet.dat yüklenirken hata: Cüzdan, daha yeni bir Mojocoin versiyonuna ihtiyaç duyuyor.</translation>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart Mojocoin to complete</source>
<translation>Cüzdanın yeniden yazılması gerekmektedir: Tamamlamak için Mojocoin'i yeniden başlatın</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>wallet.dat dosyasının yüklenmesinde hata oluştu</translation>
</message>
<message>
<location line="-15"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Geçersiz -proxy adresi: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>-onlynet için bilinmeyen bir şebeke belirtildi: '%s'</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>-bind adresi çözümlenemedi: '%s'</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>-externalip adresi çözümlenemedi: '%s'</translation>
</message>
<message>
<location line="-22"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>-paytxfee=<meblağ> için geçersiz meblağ: '%s'</translation>
</message>
<message>
<location line="+58"/>
<source>Sending...</source>
<translation>Gönderiyor...</translation>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Geçersiz meblağ</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Yetersiz bakiye</translation>
</message>
<message>
<location line="-40"/>
<source>Loading block index...</source>
<translation>Blok indeksi yükleniyor...</translation>
</message>
<message>
<location line="-109"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Bağlanılacak düğüm ekle ve bağlantıyı zinde tutmaya çalış</translation>
</message>
<message>
<location line="+124"/>
<source>Unable to bind to %s on this computer. Mojocoin is probably already running.</source>
<translation>Bu bilgisayarda %s bağlanamadı. Mojocoin muhtemelen halen çalışmaktadır.</translation>
</message>
<message>
<location line="-101"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Gönderdiğiniz işleme eklenmek üzere KB başına ücret</translation>
</message>
<message>
<location line="+33"/>
<source>Minimize weight consumption (experimental) (default: 0)</source>
<translation>Ağırlık tüketimini minimuma indirme (deneysel) (varsayılan: 0)</translation>
</message>
<message>
<location line="+8"/>
<source>How many blocks to check at startup (default: 500, 0 = all)</source>
<translation>Başlangıçta kontrol edilecek blok sayısı (varsayılan: 500, 0 = tümü)</translation>
</message>
<message>
<location line="+14"/>
<source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source>
<translation>Kabul edilebilir şifre kodları (varsayılan: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source>
<translation>Uyarı: Artık kullanılmayan değişken -debugnet yoksayıldı. Bunun yerine -debug=net kullanın.</translation>
</message>
<message>
<location line="+8"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation>-mininput=<amount>: '%s' için geçersiz miktar</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Mojocoin is probably already running.</source>
<translation>Veri klasörü %s üzerinde kilit elde edilemedi. Mojocoin muhtemelen halen çalışmaktadır.</translation>
</message>
<message>
<location line="+4"/>
<source>Error initializing wallet database environment %s!</source>
<translation>Cüzdan veritabanı ortamı %s başlatılmaya çalışılırken hata oluştu!</translation>
</message>
<message>
<location line="+15"/>
<source>Loading wallet...</source>
<translation>Cüzdan yükleniyor...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>Cüzdan eski biçime geri alınamaz</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Varsayılan adres yazılamadı</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Yeniden tarama...</translation>
</message>
<message>
<location line="+2"/>
<source>Done loading</source>
<translation>Yükleme tamamlandı</translation>
</message>
<message>
<location line="-159"/>
<source>To use the %s option</source>
<translation>%s seçeneğini kullanmak için</translation>
</message>
<message>
<location line="+186"/>
<source>Error</source>
<translation>Hata</translation>
</message>
<message>
<location line="-18"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>rpcpassword=<parola> şu yapılandırma dosyasında belirtilmelidir:
%s
Dosya mevcut değilse, sadece sahibi için okumayla sınırlı izin ile oluşturunuz.</translation>
</message>
</context>
</TS> | MOJOv3/mojocoin | src/qt/locale/bitcoin_tr.ts | TypeScript | mit | 131,730 |
var express = require("express");
var Pusher = require("pusher");
var bodyParser = require("body-parser");
var env = require("node-env-file");
var app = express();
app.use(bodyParser.urlencoded());
try {
env(__dirname + "/.env");
} catch (_error) {
error = _error;
console.log(error);
}
var pusher = new Pusher({
appId: process.env.PUSHER_APP_ID,
key: process.env.PUSHER_APP_KEY,
secret: process.env.PUSHER_APP_SECRET
});
app.use('/', express["static"]('dist'));
app.post("/pusher/auth", function(req, res) {
var socketId = req.body.socket_id;
var channel = req.body.channel_name;
var auth = pusher.authenticate(socketId, channel);
res.send(auth);
});
var port = process.env.PORT || 5000;
app.listen(port);
| adambutler/geo-pusher | server.js | JavaScript | mit | 735 |
module Protobuf
module ActiveRecord
class Railtie < Rails::Railtie
config.protobuf_active_record = Protobuf::ActiveRecord.config
ActiveSupport.on_load(:active_record) do
on_inherit do
include Protobuf::ActiveRecord::Model if Protobuf::ActiveRecord.config.autoload
end
end
ActiveSupport.on_load(:protobuf_rpc_service) do
Protobuf::Rpc.middleware.insert_after Protobuf::Rpc::Middleware::Logger, Middleware::ConnectionManagement
Protobuf::Rpc.middleware.insert_after Middleware::ConnectionManagement, Middleware::QueryCache
end
end
end
end
| film42/protobuf-activerecord | lib/protobuf/active_record/railtie.rb | Ruby | mit | 623 |
<html>
<head>
<title>
The rising resistance
</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>
</head>
<body bgcolor="#FFFFCC" text="000000" link="990000" vlink="660000" alink="003366" leftmargin="0" topmargin="0">
<table width="744" cellspacing="0" cellpadding="0" border="0">
<tr><td width="474"><a name="Top"></a><?php include "../../legacy-includes/TopLogo.htmlf" ?></td>
<td width="270"><?php include "../../legacy-includes/TopAd.htmlf" ?>
</td></tr></table>
<table width="744" cellspacing="0" cellpadding="0" border="0">
<tr><td width="18" bgcolor="FFCC66"></td>
<td width="108" bgcolor="FFCC66" valign=top><?php include "../../legacy-includes/LeftButtons.htmlf" ?></td>
<td width="18"></td>
<td width="480" valign="top">
<?php include "../../legacy-includes/BodyInsert.htmlf" ?>
<P><font face="Arial, Helvetica, sans-serif" size="2"><b>WHAT WE THINK</b></font><BR>
<font face="Times New Roman, Times, serif" size="5"><b>The rising resistance</b></font></P>
<p><font face="Arial, Helvetica, sans-serif" size="2">February 14, 2003 | Page 3</font></p>
<font face="Times New Roman, Times, serif" size="3"><P>THE ANTIWAR movement will reach a new milestone at demonstrations in New York City February 15 and San Francisco the following day. With hundreds of thousands expected at the two main protests--and thousands more at smaller regional protests--the scale of the growing opposition to George W. Bush's war on Iraq is clearer than ever.</P>
<P>Already, the corporate media has been forced to shift from ignoring the antiwar movement to grudgingly acknowledging protests, speak-outs and activism. "Under scrutiny from both antiwar advocates and media-watchdog groups, most major U.S. newspapers took seriously the sentiment percolating from large rallies January 18 in Washington, San Francisco and a host of smaller cities," observed <I>Editor & Publisher,</I> a trade publication for the newspaper industry.</P>
<P>If press coverage of antiwar activism has improved, it's because the movement has grown not only in size, but social diversity. Campus teach-ins, community mobilizations and antiwar resolutions passed in union halls across the U.S. reflect a movement that's already broader than the one that opposed the 1991 Gulf War--all before a war has begun.</P>
<P>In San Francisco, organizers agreed to move their planned demonstration to February 16 so as not to conflict with the traditional Chinese New Year celebration. In return, Chinese community leaders--backed by local politicians--endorsed the antiwar demonstration and are promoting it along with their New Year's festivities, and Chinese dragons will lead the protest.</P>
<P>In New York City, however, Mayor Michael Bloomberg had so far refused to grant a permit for the short march from the United Nations to Central Park as <I>Socialist Worker</I> went to press, and his decision had been backed up by a federal judge.</P>
<P>Meanwhile, Attorney General John Ashcroft is pushing Congress to back his proposed Domestic Security Enhancement Act. If Ashcroft has his way, the FBI and state police could monitor what Web sites you visit and what you searched for, and read your e-mail for up to 48 hours without a court order--all to monitor "activities threatening the national interest."</P>
<P>But this fear mongering hasn't prevented the antiwar movement from growing. As Bush has said repeatedly, Iraq is only the next phase in an endless "war on terror." Washington has already indicated its future targets by stepping up the pressure on Iran and North Korea, the other supposed members of the "axis of evil" along with Iraq.</P>
<P>The war that the U.S. wants in Iraq isn't about "weapons of mass destruction," "regime change" or even oil. It's a one-sided slaughter designed to demonstrate the might of U.S. imperialism and prevent the emergence of any rival, as Bush's National Security Strategy document spelled out last summer. "The vision laid out in the Bush document is a vision of what used to be called, when we believed it to be the Soviet ambition, world domination," wrote Hendrick Hertzberg in the <I>New Yorker</I>.</P>
<P>The Bush gang makes no secret of its aims. And so the antiwar movement must prepare to meet this challenge--not only standing up against the planned slaughter in Iraq, but Washington's drive to dominate the world.</P>
<P>This weekend will be an important new step in our fight. And after the demonstrations, we need to return to our communities, our workplaces and our campuses to organize protests and actions that can continue to put real pressure on Bush and the U.S. war machine--and end their senseless butchery.</P>
<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>
<td width="12"></td>
<td width="108" valign="top">
<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>
</td>
</tr>
</table>
</body>
</html>
| ISO-tech/sw-d8 | web/2003-1/440/440_03_Resistance.php | PHP | mit | 4,954 |
var app = angular.module("ethics-app");
// User create controller
app.controller("userCreateController", function($scope, $rootScope, $routeParams, $filter, $translate, $location, config, $window, $authenticationService, $userService, $universityService, $instituteService) {
/*************************************************
FUNCTIONS
*************************************************/
/**
* [redirect description]
* @param {[type]} path [description]
* @return {[type]} [description]
*/
$scope.redirect = function(path){
$location.url(path);
};
/**
* [description]
* @param {[type]} former_status [description]
* @return {[type]} [description]
*/
$scope.getGroupName = function(former_status){
if(former_status){
return $filter('translate')('FORMER_INSTITUTES');
} else {
return $filter('translate')('INSTITUTES');
}
};
/**
* [send description]
* @return {[type]} [description]
*/
$scope.send = function(){
// Validate input
if($scope.createUserForm.$invalid) {
// Update UI
$scope.createUserForm.email_address.$pristine = false;
$scope.createUserForm.title.$pristine = false;
$scope.createUserForm.first_name.$pristine = false;
$scope.createUserForm.last_name.$pristine = false;
$scope.createUserForm.institute_id.$pristine = false;
$scope.createUserForm.blocked.$pristine = false;
} else {
$scope.$parent.loading = { status: true, message: $filter('translate')('CREATING_NEW_USER') };
// Create new user
$userService.create($scope.new_user)
.then(function onSuccess(response) {
var user = response.data;
// Redirect
$scope.redirect("/users/" + user.user_id);
})
.catch(function onError(response) {
$window.alert(response.data);
});
}
};
/**
* [description]
* @param {[type]} related_data [description]
* @return {[type]} [description]
*/
$scope.load = function(related_data){
// Check which kind of related data needs to be requested
switch (related_data) {
case 'universities': {
$scope.$parent.loading = { status: true, message: $filter('translate')('LOADING_UNIVERSITIES') };
// Load universities
$universityService.list({
orderby: 'name.asc',
limit: null,
offset: null
})
.then(function onSuccess(response) {
$scope.universities = response.data;
$scope.$parent.loading = { status: false, message: "" };
})
.catch(function onError(response) {
$window.alert(response.data);
});
break;
}
case 'institutes': {
if($scope.university_id){
if($scope.university_id !== null){
$scope.$parent.loading = { status: true, message: $filter('translate')('LOADING_INSTITUTES') };
// Load related institutes
$instituteService.listByUniversity($scope.university_id, {
orderby: 'name.asc',
limit: null,
offset: null,
former: false
})
.then(function onSuccess(response) {
$scope.institutes = response.data;
$scope.$parent.loading = { status: false, message: "" };
})
.catch(function onError(response) {
$window.alert(response.data);
});
} else {
// Reset institutes
$scope.institutes = [];
$scope.new_user.institute_id = null;
}
} else {
// Reset institutes
$scope.institutes = [];
$scope.new_user.institute_id = null;
}
break;
}
}
};
/*************************************************
INIT
*************************************************/
$scope.new_user = $userService.init();
$scope.authenticated_member = $authenticationService.get();
// Load universities
$scope.load('universities');
// Set default value by member
$scope.university_id = $scope.authenticated_member.university_id;
// Load related institutes
$scope.load('institutes');
// Set default value by member
$scope.new_user.institute_id = $scope.authenticated_member.institute_id;
});
| sitcomlab/Ethics-app | public/member-client/js/controllers/user/createController.js | JavaScript | mit | 5,089 |
package sample.rabbitmq;
import static sample.rabbitmq.annotation.RabbitDirectRouting.*;
import java.util.Arrays;
import java.util.concurrent.*;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.ListenerContainerConsumerFailedEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
import sample.model.News;
import sample.rabbitmq.annotation.RabbitDirectRouting;
/**
* RabbitMQ の Exchange#Direct ( 1-1 ) 接続サンプル。
* <p>Sender -> Receiver
* <p>利用する Exchange / Queue は RabbitListener を用いて自動的に作成しています。
* <p>Rabbit の依存を避けてベタに定義したい場合は Queue / Exchange をコンテナに登録し、
* 受信コンポーネントを SimpleMessageListenerContainer で構築してください。
*/
@Slf4j
@Component
public class RabbitDirectChecker {
@Autowired
private NewsSender newsSender;
@Autowired
private NewsReceiver newsReceiver;
public void checkDirect() {
log.info("## RabbitMQ DirectCheck ###");
log.info("### send");
newsSender.send(new News(1L, "subject", "body"));
log.info("### wait...");
newsReceiver.waitMessage();
log.info("### finish");
}
/**
* コンシューマ定義。
* <p>RabbitListener と admin 指定を利用する事で動的に Exchange と Queue の定義 ( Binding 含 ) を行っている。
* 1-n の時は使い捨ての Queue を前提にして名称は未指定で。
* <pre>
* [NewsRoutingKey] -> -1- [NewsQueue] -1-> Queue
* </pre>
* <p>アノテーションを別途切り出す例 ( RabbitDirectRouting )。逆に分かりにくいかも、、
*/
@Component
@RabbitDirectRouting
static class NewsReceiver {
private final CountDownLatch latch = new CountDownLatch(1);
@RabbitHandler
public void receiveMessage(News... news) {
log.info("receive message.");
Arrays.stream(news)
.map(News::toString)
.forEach(log::info);
latch.countDown();
}
public void waitMessage() {
try {
latch.await(5000, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
}
}
/** <pre>Message -> [NewsRoutingKey]</pre> */
@Component
static class NewsSender {
@Autowired
RabbitTemplate tmpl;
public NewsSender send(News... news) {
tmpl.convertAndSend(NewsDirect, NewsRoutingKey, news);
return this;
}
}
@EventListener
void handleContextRefresh(ListenerContainerConsumerFailedEvent event) {
log.error("起動失敗事由: " + event.getReason());
}
}
| jkazama/sandbox | amqp/src/main/java/sample/rabbitmq/RabbitDirectChecker.java | Java | mit | 3,030 |
/*
* Author: 陈志杭 Caspar
* Contact: 279397942@qq.com qq:279397942
* Description: 数据接口契约文件
* 文件由模板生成,请不要直接修改文件,如需修改请创建一个对应的partial文件
*/
using System;
using System.Collections;
using Zh.DAL.Define.Entities;
using Zh.DAL.Define;
using Zh.DAL.Base.Define;
using Zh.DAL.Define.Contracts;
namespace Zh.DAL.Define.Contracts.Imp
{
/// <summary>
/// dt_Article()表访问类
/// </summary>
public partial class dtArticleDao : BaseDao<dt_Article>,IdtArticleDao
{
}
}
| Caspar12/Csharp | src/Zh.DAL.Define/Contracts/Imp/AutoCode/dtArticleDao.cs | C# | mit | 580 |
/*
* Author: 陈志杭 Caspar
* Contact: 279397942@qq.com qq:279397942
* Description: 数据契约实体模型文件
* 文件由模板生成,请不要直接修改文件,如需修改请创建一个对应的partial文件
*/
using System;
using System.Collections;
using System.Collections.Generic;
using Zh.DAL.Define.Entities;
using Zh.DAL.Base.Define.Entities;
namespace Zh.DAL.Define.Entities
{
#region Activity_AC_Match
/// <summary>
/// 对抗类比赛表
/// Activity_AC_Match object for mapped table 'Activity_AC_Match'.
/// </summary>
public partial class Activity_AC_Match
{
#region Constructors
public Activity_AC_Match() { }
public Activity_AC_Match( Guid iD, int identity, DateTime beginTime, DateTime endTime, Guid aTeamID, Guid bTeamID, int type, string shopID, int? aTeamScore, int? bTeamScore )
{
this.ID = iD;
this.Identity = identity;
this.BeginTime = beginTime;
this.EndTime = endTime;
this.ATeamID = aTeamID;
this.BTeamID = bTeamID;
this.Type = type;
this.ShopID = shopID;
this.ATeamScore = aTeamScore;
this.BTeamScore = bTeamScore;
}
#endregion
#region Public Properties
/// <summary>
/// ID
/// </summary>
public virtual Guid ID { get; set; }
/// <summary>
/// 自增ID
/// </summary>
public virtual int Identity { get; set; }
/// <summary>
/// 比赛 开始时间
/// </summary>
public virtual DateTime BeginTime { get; set; }
/// <summary>
/// 比赛 结束时间
/// </summary>
public virtual DateTime EndTime { get; set; }
/// <summary>
/// A 队伍ID
/// </summary>
public virtual Guid ATeamID { get; set; }
/// <summary>
/// B 队伍ID
/// </summary>
public virtual Guid BTeamID { get; set; }
/// <summary>
/// 比赛类型(0:普通,1:16强,2::8强,3:4强,4:决赛)
/// </summary>
public virtual int Type { get; set; }
/// <summary>
/// 网点ID
/// </summary>
public virtual string ShopID { get; set; }
/// <summary>
/// A队伍比赛结果
/// </summary>
public virtual int? ATeamScore { get; set; }
/// <summary>
/// B队伍比赛结果
/// </summary>
public virtual int? BTeamScore { get; set; }
/// <summary>
/// 队伍
/// </summary>
public virtual Activity_Team Activity_Team{get;set;}
/// <summary>
/// 队伍
/// </summary>
public virtual Activity_Team Activity_Team2{get;set;}
/// <summary>
/// 积分竞猜记录
/// </summary>
public virtual IList<Activity_AC_WinnerGuessRecord> Activity_AC_WinnerGuessRecord{get;set;}
/// <summary>
/// 对抗类比赛竞猜比分
/// </summary>
public virtual IList<Activity_AC_ScoreGuessRecord> Activity_AC_ScoreGuessRecord{get;set;}
#endregion
}
#endregion
}
| Caspar12/Csharp | src/Zh.DAL.Define/Entities/AutoCode/Activity_AC_Match.cs | C# | mit | 3,078 |
#!/usr/bin/env node
var child_process = require('child_process');
var argv = require('yargs')
.boolean(['readability', 'open'])
.argv;
var pdfdify = require('../lib');
var srcUrl = argv._[0];
console.log("Convertering: '"+srcUrl+"'");
pdfdify.convert({
title:argv.title|| srcUrl,
readability:argv.readability,
srcUrl:srcUrl
},function (err, pdfFile) {
if (err) {
throw err;
}
console.log("Created: '"+pdfFile+"'");
if(argv.open) {
child_process.exec('open "'+pdfFile+'"');
}
}); | darvin/prince-bookmarklet | bin/pdfdify.js | JavaScript | mit | 507 |
module WargamingApi::Util
end
require 'wargaming_api/util/uri'
require 'wargaming_api/util/params'
require 'wargaming_api/util/http' | DmitryDrobotov/wargaming_api_ruby | lib/wargaming_api/util.rb | Ruby | mit | 133 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HelpTheHomelessApp.Models;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace HelpTheHomelessApp
{
public partial class SurveyPage : ContentPage
{
public List<SurveyQuestionModel> Questions;
public SurveyQuestionModel CurrentQuestion;
public SurveyPage()
{
InitializeComponent();
initQuestions();
CurrentQuestion = Questions.First();
LabelQuestion.Text = CurrentQuestion.QuestionText;
LabelQuestionDetail.Text = CurrentQuestion.DetailText;
ButtonYes.Clicked += ButtonYes_Clicked;
ButtonNo.Clicked += ButtonNo_Clicked;
}
private void ButtonYes_Clicked(object sender, EventArgs e)
{
CurrentQuestion.Response = true;
if (CurrentQuestion.ID == Questions.Count)
{
showResult();
}
else
{
getNextQuestion();
}
}
private void ButtonNo_Clicked(object sender, EventArgs e)
{
CurrentQuestion.Response = false;
if (CurrentQuestion.ID == Questions.Count)
{
showResult();
}
else
{
getNextQuestion();
}
}
private void initQuestions()
{
Questions = new List<SurveyQuestionModel>();
var i = 1;
Questions.Add(new SurveyQuestionModel("Do you currently have a permanent residence?", "For example are privately renting a house/unit", 1, i++));
// Detail from https://www.ag.gov.au/RightsAndProtections/HumanRights/Human-rights-scrutiny/PublicSectorGuidanceSheets/Pages/Righttoanadequatestandardoflivingincludingfoodwaterandhousing.aspx
Questions.Add(new SurveyQuestionModel("Are the living conditions appropriate and adequate?", "Everyone has the right to an adequate standard of living including adequate food, water and housing and to the continuous improvement of living conditions.", 2, i++));
Questions.Add(new SurveyQuestionModel("Do you have a source of income?", "Either from employment or benefits etc.", 2, i++));
Questions.Add(new SurveyQuestionModel("Do you live alone?", "", 3, i++));
Questions.Add(new SurveyQuestionModel("Is there a risk of or are you experiencing domestic/family violence at your current residence?", "", 4, i++));
Questions.Add(new SurveyQuestionModel("Are you currently studying?", "e.g. School, Tafe or University student", 1, i++));
// Detail from http://www.stresstips.com/what-is-financial-stress/
Questions.Add(new SurveyQuestionModel("Are you under financial stress?", "In other words, this is stress that comes from being in debt, that comes from being unable to make the rent/mortgage repayment or that comes from knowing you’re going to have to spend a huge amount of money.", 2, i++));
Questions.Add(new SurveyQuestionModel("Have you had an episode of homelessness before?", "", 3, i++));
}
private void getNextQuestion()
{
CurrentQuestion = Questions[CurrentQuestion.ID];
LabelQuestion.Text = CurrentQuestion.QuestionText;
LabelQuestionDetail.Text = CurrentQuestion.DetailText;
if (CurrentQuestion.ID == 7)
{
LabelQuickTips.Text = "Did you know that most financial insitutions have a Hardship team there to assist you in difficult times? They may be able to temporarily reduce the financial strain to help you get back in control.";
}
else {
LabelQuickTips.Text = "";
}
}
private int getScore()
{
var score = 0;
foreach (var question in Questions)
{
if (question.Response)
{
score += question.Score;
}
}
return score;
}
private void showResult()
{
LabelQuestion.Text = "Score: " + getScore();
}
}
}
| leightonb/HomelessHack2017 | HelpTheHomelessApp/HelpTheHomelessApp/SurveyPage.xaml.cs | C# | mit | 4,006 |
package graphql.analysis;
import graphql.PublicApi;
import graphql.execution.AbortExecutionException;
import graphql.execution.instrumentation.InstrumentationContext;
import graphql.execution.instrumentation.SimpleInstrumentation;
import graphql.execution.instrumentation.parameters.InstrumentationValidationParameters;
import graphql.validation.ValidationError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import static graphql.Assert.assertNotNull;
import static graphql.execution.instrumentation.SimpleInstrumentationContext.whenCompleted;
import static java.util.Optional.ofNullable;
/**
* Prevents execution if the query complexity is greater than the specified maxComplexity.
*
* Use the {@code Function<QueryComplexityInfo, Boolean>} parameter to supply a function to perform a custom action when the max complexity
* is exceeded. If the function returns {@code true} a {@link AbortExecutionException} is thrown.
*/
@PublicApi
public class MaxQueryComplexityInstrumentation extends SimpleInstrumentation {
private static final Logger log = LoggerFactory.getLogger(MaxQueryComplexityInstrumentation.class);
private final int maxComplexity;
private final FieldComplexityCalculator fieldComplexityCalculator;
private final Function<QueryComplexityInfo, Boolean> maxQueryComplexityExceededFunction;
/**
* new Instrumentation with default complexity calculator which is `1 + childComplexity`
*
* @param maxComplexity max allowed complexity, otherwise execution will be aborted
*/
public MaxQueryComplexityInstrumentation(int maxComplexity) {
this(maxComplexity, (queryComplexityInfo) -> true);
}
/**
* new Instrumentation with default complexity calculator which is `1 + childComplexity`
*
* @param maxComplexity max allowed complexity, otherwise execution will be aborted
* @param maxQueryComplexityExceededFunction the function to perform when the max complexity is exceeded
*/
public MaxQueryComplexityInstrumentation(int maxComplexity, Function<QueryComplexityInfo, Boolean> maxQueryComplexityExceededFunction) {
this(maxComplexity, (env, childComplexity) -> 1 + childComplexity, maxQueryComplexityExceededFunction);
}
/**
* new Instrumentation with custom complexity calculator
*
* @param maxComplexity max allowed complexity, otherwise execution will be aborted
* @param fieldComplexityCalculator custom complexity calculator
*/
public MaxQueryComplexityInstrumentation(int maxComplexity, FieldComplexityCalculator fieldComplexityCalculator) {
this(maxComplexity, fieldComplexityCalculator, (queryComplexityInfo) -> true);
}
/**
* new Instrumentation with custom complexity calculator
*
* @param maxComplexity max allowed complexity, otherwise execution will be aborted
* @param fieldComplexityCalculator custom complexity calculator
* @param maxQueryComplexityExceededFunction the function to perform when the max complexity is exceeded
*/
public MaxQueryComplexityInstrumentation(int maxComplexity, FieldComplexityCalculator fieldComplexityCalculator,
Function<QueryComplexityInfo, Boolean> maxQueryComplexityExceededFunction) {
this.maxComplexity = maxComplexity;
this.fieldComplexityCalculator = assertNotNull(fieldComplexityCalculator, () -> "calculator can't be null");
this.maxQueryComplexityExceededFunction = maxQueryComplexityExceededFunction;
}
@Override
public InstrumentationContext<List<ValidationError>> beginValidation(InstrumentationValidationParameters parameters) {
return whenCompleted((errors, throwable) -> {
if ((errors != null && errors.size() > 0) || throwable != null) {
return;
}
QueryTraverser queryTraverser = newQueryTraverser(parameters);
Map<QueryVisitorFieldEnvironment, Integer> valuesByParent = new LinkedHashMap<>();
queryTraverser.visitPostOrder(new QueryVisitorStub() {
@Override
public void visitField(QueryVisitorFieldEnvironment env) {
int childsComplexity = valuesByParent.getOrDefault(env, 0);
int value = calculateComplexity(env, childsComplexity);
valuesByParent.compute(env.getParentEnvironment(), (key, oldValue) ->
ofNullable(oldValue).orElse(0) + value
);
}
});
int totalComplexity = valuesByParent.getOrDefault(null, 0);
if (log.isDebugEnabled()) {
log.debug("Query complexity: {}", totalComplexity);
}
if (totalComplexity > maxComplexity) {
QueryComplexityInfo queryComplexityInfo = QueryComplexityInfo.newQueryComplexityInfo()
.complexity(totalComplexity)
.instrumentationValidationParameters(parameters)
.build();
boolean throwAbortException = maxQueryComplexityExceededFunction.apply(queryComplexityInfo);
if (throwAbortException) {
throw mkAbortException(totalComplexity, maxComplexity);
}
}
});
}
/**
* Called to generate your own error message or custom exception class
*
* @param totalComplexity the complexity of the query
* @param maxComplexity the maximum complexity allowed
*
* @return a instance of AbortExecutionException
*/
protected AbortExecutionException mkAbortException(int totalComplexity, int maxComplexity) {
return new AbortExecutionException("maximum query complexity exceeded " + totalComplexity + " > " + maxComplexity);
}
QueryTraverser newQueryTraverser(InstrumentationValidationParameters parameters) {
return QueryTraverser.newQueryTraverser()
.schema(parameters.getSchema())
.document(parameters.getDocument())
.operationName(parameters.getOperation())
.variables(parameters.getVariables())
.build();
}
private int calculateComplexity(QueryVisitorFieldEnvironment queryVisitorFieldEnvironment, int childsComplexity) {
if (queryVisitorFieldEnvironment.isTypeNameIntrospectionField()) {
return 0;
}
FieldComplexityEnvironment fieldComplexityEnvironment = convertEnv(queryVisitorFieldEnvironment);
return fieldComplexityCalculator.calculate(fieldComplexityEnvironment, childsComplexity);
}
private FieldComplexityEnvironment convertEnv(QueryVisitorFieldEnvironment queryVisitorFieldEnvironment) {
FieldComplexityEnvironment parentEnv = null;
if (queryVisitorFieldEnvironment.getParentEnvironment() != null) {
parentEnv = convertEnv(queryVisitorFieldEnvironment.getParentEnvironment());
}
return new FieldComplexityEnvironment(
queryVisitorFieldEnvironment.getField(),
queryVisitorFieldEnvironment.getFieldDefinition(),
queryVisitorFieldEnvironment.getFieldsContainer(),
queryVisitorFieldEnvironment.getArguments(),
parentEnv
);
}
}
| graphql-java/graphql-java | src/main/java/graphql/analysis/MaxQueryComplexityInstrumentation.java | Java | mit | 7,538 |
package com.github.maxopoly.finale.combat;
public class CombatConfig {
private int cpsLimit;
private long cpsCounterInterval;
private boolean noCooldown;
private double maxReach;
private boolean sweepEnabled;
private CombatSoundConfig combatSounds;
private double horizontalKb;
private double verticalKb;
private double sprintHorizontal;
private double sprintVertical;
private double airHorizontal;
private double airVertical;
private double waterHorizontal;
private double waterVertical;
private double attackMotionModifier;
private boolean stopSprinting;
private double potionCutOffDistance;
public CombatConfig(boolean noCooldown, int cpsLimit, long cpsCounterInterval, double maxReach, boolean sweepEnabled, CombatSoundConfig combatSounds,
double horizontalKb, double verticalKb, double sprintHorizontal, double sprintVertical, double airHorizontal, double airVertical,
double waterHorizontal, double waterVertical, double attackMotionModifier, boolean stopSprinting, double potionCutOffDistance) {
this.noCooldown = noCooldown;
this.cpsLimit = cpsLimit;
this.cpsCounterInterval = cpsCounterInterval;
this.maxReach = maxReach;
this.sweepEnabled = sweepEnabled;
this.combatSounds = combatSounds;
this.horizontalKb = horizontalKb;
this.verticalKb = verticalKb;
this.sprintHorizontal = sprintHorizontal;
this.sprintVertical = sprintVertical;
this.airHorizontal = airHorizontal;
this.airVertical = airVertical;
this.waterHorizontal = waterHorizontal;
this.waterVertical = waterVertical;
this.attackMotionModifier = attackMotionModifier;
this.stopSprinting = stopSprinting;
this.potionCutOffDistance = potionCutOffDistance;
}
public void setPotionCutOffDistance(double potionCutOffDistance) {
this.potionCutOffDistance = potionCutOffDistance;
}
public double getPotionCutOffDistance() {
return potionCutOffDistance;
}
public void setHorizontalKb(double horizontalKb) {
this.horizontalKb = horizontalKb;
}
public void setVerticalKb(double verticalKb) {
this.verticalKb = verticalKb;
}
public void setSprintHorizontal(double sprintHorizontal) {
this.sprintHorizontal = sprintHorizontal;
}
public void setSprintVertical(double sprintVertical) {
this.sprintVertical = sprintVertical;
}
public void setAirHorizontal(double airHorizontal) {
this.airHorizontal = airHorizontal;
}
public void setAirVertical(double airVertical) {
this.airVertical = airVertical;
}
public void setWaterHorizontal(double waterHorizontal) {
this.waterHorizontal = waterHorizontal;
}
public void setWaterVertical(double waterVertical) {
this.waterVertical = waterVertical;
}
public void setAttackMotionModifier(double attackMotionModifier) {
this.attackMotionModifier = attackMotionModifier;
}
public void setStopSprinting(boolean stopSprinting) {
this.stopSprinting = stopSprinting;
}
public double getAirHorizontal() {
return airHorizontal;
}
public double getAirVertical() {
return airVertical;
}
public double getWaterHorizontal() {
return waterHorizontal;
}
public double getWaterVertical() {
return waterVertical;
}
public boolean isStopSprinting() {
return stopSprinting;
}
public double getHorizontalKb() {
return horizontalKb;
}
public double getVerticalKb() {
return verticalKb;
}
public double getSprintHorizontal() {
return sprintHorizontal;
}
public double getSprintVertical() {
return sprintVertical;
}
public double getAttackMotionModifier() {
return attackMotionModifier;
}
public int getCPSLimit() {
return cpsLimit;
}
public long getCpsCounterInterval() {
return cpsCounterInterval;
}
public boolean isNoCooldown() {
return noCooldown;
}
public double getMaxReach() {
return maxReach;
}
public boolean isSweepEnabled() {
return sweepEnabled;
}
public CombatSoundConfig getCombatSounds() {
return combatSounds;
}
public double getHorizontalKB() {
return horizontalKb;
}
public double getVerticalKB() {
return verticalKb;
}
}
| Maxopoly/Finale | src/main/java/com/github/maxopoly/finale/combat/CombatConfig.java | Java | mit | 4,053 |
//
// Created by Chris Richards on 28/04/2016.
//
#include <gtest/gtest.h>
#include <DbfTable.h>
class Dbase31TableFixture : public ::testing::Test {
protected:
virtual void SetUp() {
dbf_table_ = DbfTablePtr(new DbfTable("/Users/chrisr/Development/ClionProjects/dbf2csv/dbf_tests/fixtures/dbase_31.dbf"));
}
virtual void TearDown() {
dbf_table_->close();
}
public:
Dbase31TableFixture() : Test() {
}
virtual ~Dbase31TableFixture() {
}
DbfTablePtr dbf_table_;
};
TEST_F(Dbase31TableFixture, good_check) {
EXPECT_TRUE(dbf_table_->good());
}
TEST_F(Dbase31TableFixture, has_memo_check) {
EXPECT_FALSE(dbf_table_->has_memo_file());
}
| yellowfeather/dbf2csv | dbf_tests/dbase31_tests/Dbase31TableFixture.cpp | C++ | mit | 699 |
/**
* Sizzle Engine Support v2.2.0
* http://rightjs.org/plugins/sizzle
*
* Copyright (C) 2009-2011 Nikolay Nemshilov
*/
/**
* sizzle initialization script
*
* Copyright (C) 2010-2011 Nikolay Nemshilov
*/
RightJS.Sizzle = {
version: '2.2.0'
};
/*!
* Sizzle CSS Selector Engine - v1.0
* Copyright 2009, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
(function(){
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
done = 0,
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function(){
baseHasDuplicate = false;
return 0;
});
var Sizzle = function(selector, context, results, seed) {
results = results || [];
context = context || document;
var origContext = context;
if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
var parts = [], m, set, checkSet, extra, prune = true, contextXML = Sizzle.isXML(context),
soFar = selector, ret, cur, pop, i;
// Reset the position of the chunker regexp (start from head)
do {
chunker.exec("");
m = chunker.exec(soFar);
if ( m ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
} while ( m );
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] ) {
selector += parts.shift();
}
set = posProcess( selector, set );
}
}
} else {
// Take a shortcut and set the context if the root selector is an ID
// (but not if it'll be faster if the inner selector is an ID)
if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
ret = Sizzle.find( parts.shift(), context, contextXML );
context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0];
}
if ( context ) {
ret = seed ?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set;
if ( parts.length > 0 ) {
checkSet = makeArray(set);
} else {
prune = false;
}
while ( parts.length ) {
cur = parts.pop();
pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, contextXML );
}
} else {
checkSet = parts = [];
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
Sizzle.error( cur || selector );
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context && context.nodeType === 1 ) {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
Sizzle( extra, origContext, results, seed );
Sizzle.uniqueSort( results );
}
return results;
};
Sizzle.uniqueSort = function(results){
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort(sortOrder);
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[i-1] ) {
results.splice(i--, 1);
}
}
}
}
return results;
};
Sizzle.matches = function(expr, set){
return Sizzle(expr, null, null, set);
};
Sizzle.find = function(expr, context, isXML){
var set;
if ( !expr ) {
return [];
}
for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
var type = Expr.order[i], match;
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
var left = match[1];
match.splice(1,1);
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace(/\\/g, "");
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = context.getElementsByTagName("*");
}
return {set: set, expr: expr};
};
Sizzle.filter = function(expr, set, inplace, not){
var old = expr, result = [], curLoop = set, match, anyFound,
isXMLFilter = set && set[0] && Sizzle.isXML(set[0]);
while ( expr && set.length ) {
for ( var type in Expr.filter ) {
if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
var filter = Expr.filter[ type ], found, item, left = match[1];
anyFound = false;
match.splice(1,1);
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
var pass = not ^ !!found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
Sizzle.error = function( msg ) {
throw "Syntax error, unrecognized expression: " + msg;
};
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
match: {
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},
leftMatch: {},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function(elem){
return elem.getAttribute("href");
}
},
relative: {
"+": function(checkSet, part){
var isPartStr = typeof part === "string",
isTag = isPartStr && !/\W/.test(part),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
part = part.toLowerCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function(checkSet, part){
var isPartStr = typeof part === "string",
elem, i = 0, l = checkSet.length;
if ( isPartStr && !/\W/.test(part) ) {
part = part.toLowerCase();
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
} else {
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function(checkSet, part, isXML){
var doneName = done++, checkFn = dirCheck, nodeCheck;
if ( typeof part === "string" && !/\W/.test(part) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
},
"~": function(checkSet, part, isXML){
var doneName = done++, checkFn = dirCheck, nodeCheck;
if ( typeof part === "string" && !/\W/.test(part) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
}
},
find: {
ID: function(match, context, isXML){
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
},
NAME: function(match, context){
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [], results = context.getElementsByName(match[1]);
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function(match, context){
return context.getElementsByTagName(match[1]);
}
},
preFilter: {
CLASS: function(match, curLoop, inplace, result, not, isXML){
match = " " + match[1].replace(/\\/g, "") + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function(match){
return match[1].replace(/\\/g, "");
},
TAG: function(match, curLoop){
return match[1].toLowerCase();
},
CHILD: function(match){
if ( match[1] === "nth" ) {
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function(match, curLoop, inplace, result, not, isXML){
var name = match[1].replace(/\\/g, "");
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function(match, curLoop, inplace, result, not){
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function(match){
match.unshift( true );
return match;
}
},
filters: {
enabled: function(elem){
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function(elem){
return elem.disabled === true;
},
checked: function(elem){
return elem.checked === true;
},
selected: function(elem){
// Accessing this property makes selected-by-default
// options in Safari work properly
elem.parentNode.selectedIndex;
return elem.selected === true;
},
parent: function(elem){
return !!elem.firstChild;
},
empty: function(elem){
return !elem.firstChild;
},
has: function(elem, i, match){
return !!Sizzle( match[3], elem ).length;
},
header: function(elem){
return (/h\d/i).test( elem.nodeName );
},
text: function(elem){
return "text" === elem.type;
},
radio: function(elem){
return "radio" === elem.type;
},
checkbox: function(elem){
return "checkbox" === elem.type;
},
file: function(elem){
return "file" === elem.type;
},
password: function(elem){
return "password" === elem.type;
},
submit: function(elem){
return "submit" === elem.type;
},
image: function(elem){
return "image" === elem.type;
},
reset: function(elem){
return "reset" === elem.type;
},
button: function(elem){
return "button" === elem.type || elem.nodeName.toLowerCase() === "button";
},
input: function(elem){
return (/input|select|textarea|button/i).test(elem.nodeName);
}
},
setFilters: {
first: function(elem, i){
return i === 0;
},
last: function(elem, i, match, array){
return i === array.length - 1;
},
even: function(elem, i){
return i % 2 === 0;
},
odd: function(elem, i){
return i % 2 === 1;
},
lt: function(elem, i, match){
return i < match[3] - 0;
},
gt: function(elem, i, match){
return i > match[3] - 0;
},
nth: function(elem, i, match){
return match[3] - 0 === i;
},
eq: function(elem, i, match){
return match[3] - 0 === i;
}
},
filter: {
PSEUDO: function(elem, match, i, array){
var name = match[1], filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "contains" ) {
return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var j = 0, l = not.length; j < l; j++ ) {
if ( not[j] === elem ) {
return false;
}
}
return true;
} else {
Sizzle.error( "Syntax error, unrecognized expression: " + name );
}
},
CHILD: function(elem, match){
var type = match[1], node = elem;
switch (type) {
case 'only':
case 'first':
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
case 'last':
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
case 'nth':
var first = match[2], last = match[3];
if ( first === 1 && last === 0 ) {
return true;
}
var doneName = match[0],
parent = elem.parentNode;
if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
var count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent.sizcache = doneName;
}
var diff = elem.nodeIndex - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
}
},
ID: function(elem, match){
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
TAG: function(elem, match){
return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
},
CLASS: function(elem, match){
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function(elem, match){
var name = match[1],
result = Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value !== check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
POS: function(elem, match, i, array){
var name = match[2], filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
var origPOS = Expr.match.POS,
fescape = function(all, num){
return "\\" + (num - 0 + 1);
};
for ( var type in Expr.match ) {
Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}
var makeArray = function(array, results) {
array = Array.prototype.slice.call( array, 0 );
if ( results ) {
results.push.apply( results, array );
return results;
}
return array;
};
// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
// Provide a fallback method if it does not work
} catch(e){
makeArray = function(array, results) {
var ret = results || [], i = 0;
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( ; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder, siblingCheck;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
return a.compareDocumentPosition ? -1 : 1;
}
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
} else {
sortOrder = function( a, b ) {
var ap = [], bp = [], aup = a.parentNode, bup = b.parentNode,
cur = aup, al, bl;
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// If the nodes are siblings (or identical) we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
siblingCheck = function( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
};
}
// Utility function for retreiving the text value of an array of DOM nodes
Sizzle.getText = function( elems ) {
var ret = "", elem;
for ( var i = 0; elems[i]; i++ ) {
elem = elems[i];
// Get the text from text nodes and CDATA nodes
if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
ret += elem.nodeValue;
// Traverse everything else, except comment nodes
} else if ( elem.nodeType !== 8 ) {
ret += Sizzle.getText( elem.childNodes );
}
}
return ret;
};
// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
// We're going to inject a fake input element with a specified name
var form = document.createElement("div"),
id = "script" + (new Date()).getTime();
form.innerHTML = "<a name='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
var root = document.documentElement;
root.insertBefore( form, root.firstChild );
// The workaround has to do additional checks after a getElementById
// Which slows things down for other browsers (hence the branching)
if ( document.getElementById( id ) ) {
Expr.find.ID = function(match, context, isXML){
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : [];
}
};
Expr.filter.ID = function(elem, match){
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return elem.nodeType === 1 && node && node.nodeValue === match;
};
}
root.removeChild( form );
root = form = null; // release memory in IE
})();
(function(){
// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
// Create a fake element
var div = document.createElement("div");
div.appendChild( document.createComment("") );
// Make sure no comments are found
if ( div.getElementsByTagName("*").length > 0 ) {
Expr.find.TAG = function(match, context){
var results = context.getElementsByTagName(match[1]);
// Filter out possible comments
if ( match[1] === "*" ) {
var tmp = [];
for ( var i = 0; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
};
}
// Check to see if an attribute returns normalized href attributes
div.innerHTML = "<a href='#'></a>";
if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
div.firstChild.getAttribute("href") !== "#" ) {
Expr.attrHandle.href = function(elem){
return elem.getAttribute("href", 2);
};
}
div = null; // release memory in IE
})();
if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle, div = document.createElement("div");
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
Sizzle = function(query, context, extra, seed){
context = context || document;
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && context.nodeType === 9 && !Sizzle.isXML(context) ) {
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(e){}
}
return oldSizzle(query, context, extra, seed);
};
for ( var prop in oldSizzle ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
div = null; // release memory in IE
})();
}
(function(){
var div = document.createElement("div");
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
// Opera can't find a second classname (in 9.6)
// Also, make sure that getElementsByClassName actually exists
if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
return;
}
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
if ( div.getElementsByClassName("e").length === 1 ) {
return;
}
Expr.order.splice(1, 0, "CLASS");
Expr.find.CLASS = function(match, context, isXML) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
div = null; // release memory in IE
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
elem = elem[dir];
var match = false;
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem.sizcache = doneName;
elem.sizset = i;
}
if ( elem.nodeName.toLowerCase() === cur ) {
match = elem;
break;
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
elem = elem[dir];
var match = false;
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem.sizcache = doneName;
elem.sizset = i;
}
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
break;
}
} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
Sizzle.contains = document.compareDocumentPosition ? function(a, b){
return !!(a.compareDocumentPosition(b) & 16);
} : function(a, b){
return a !== b && (a.contains ? a.contains(b) : true);
};
Sizzle.isXML = function(elem){
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
var posProcess = function(selector, context){
var tmpSet = [], later = "", match,
root = context.nodeType ? [context] : context;
// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( Expr.match.PSEUDO, "" );
}
selector = Expr.relative[selector] ? selector + "*" : selector;
for ( var i = 0, l = root.length; i < l; i++ ) {
Sizzle( selector, root[i], tmpSet );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
window.Sizzle = Sizzle;
})();
RightJS([RightJS.Document, RightJS.Element]).each('include', {
first: function(rule) {
return this.find(rule)[0];
},
find: function(rule) {
return RightJS(Sizzle(rule, this._)).map(RightJS.$);
}
});
| MadRabbit/right-rails | vendor/assets/javascripts/right/sizzle-src.js | JavaScript | mit | 30,339 |
#!/usr/bin/python
import argparse
from os import path as os_path
import demo_project as demo
import traceback
def set_host_url_arg():
parser.add_argument('--host', required=True,
help='the url for the Materials Commons server')
def set_datapath_arg():
parser.add_argument('--datapath', required=True,
help='the path to the directory containing the files used by the build')
def set_apikey_arg():
parser.add_argument('--apikey', required=True, help='rapikey for the user building the demo project')
parser = argparse.ArgumentParser(description='Build Demo Project.')
set_host_url_arg()
set_datapath_arg()
set_apikey_arg()
args = parser.parse_args()
host = args.host
path = os_path.abspath(args.datapath)
key = args.apikey
# log_messages
# print "Running script to build demo project: "
# print " host = " + host + ", "
# print " key = " + key + ", "
# print " path = " + path
try:
builder = demo.DemoProject(host, path, key)
# a basic get request that makes no changes; will fail if there is a problem with the host or key
flag = builder.does_project_exist()
project = builder.build_project()
if flag:
print "Refreshed project with name = " + project.name
else:
print "Built project with name = " + project.name
except Exception as err:
traceback.print_exc()
print 'Error: ', err
| materials-commons/materialscommons.org | backend/scripts/demo-project/build_project.py | Python | mit | 1,400 |
import React from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import getIn from '@mzvonar/getin';
import isEvent from './../utils/isEvent';
import getPath from './../utils/getPath';
import deepEqual from 'react-fast-compare';
function deleteChildren(object, children) {
let deleted = {};
for(let i = 0, length = children.length; i < length; i += 1) {
const key = children[i];
if(Object.prototype.hasOwnProperty.call(object, key)) {
deleted[key] = object[key];
delete object[key];
}
}
return deleted;
}
function cleanComponentProps(value, props) {
const componentProps = Object.assign({}, props);
const input = componentProps.input;
// const value = componentProps.value;
deleteChildren(componentProps, [
'component',
'_mrf',
'input',
'value',
'validate',
'formSubmitted',
'readOnly',
'disabled'
]);
const inputProps = {};
if(componentProps.type === 'radio') {
inputProps.checked = value === componentProps.value;
}
else if(componentProps.type === 'checkbox') {
inputProps.checked = !!value;
}
else {
inputProps.value = typeof value !== 'undefined' ? value : /*(!props.input.dirty ? props.initialValue : '') ||*/ '';
}
inputProps.id = props.id;
inputProps.readOnly = props.readOnly;
inputProps.disabled = props.disabled;
inputProps.autoComplete = props.autoComplete;
inputProps.maxLength = props.maxLength;
componentProps.input = inputProps;
return componentProps;
}
function getValue(event) {
if(isEvent(event)) {
return event.target.value;
}
else {
return event;
}
}
function generateErrorMessages(errors, errorMessages) {
const messages = [];
if(errors && errors.length > 0 && errorMessages) {
for(let i = 0, length = errors.length; i < length; i += 1) {
if(errorMessages[errors[i]]) {
messages.push(errorMessages[errors[i]]);
}
}
}
return messages;
}
const ignoreForUpdate = [
'_mrf'
];
class ConnectedInput extends React.Component {
static get propTypes() {
return {
component: PropTypes.oneOfType([PropTypes.func, PropTypes.string]).isRequired,
name: PropTypes.string.isRequired
}
}
static get defaultProps() {
return {
component: 'input',
}
}
constructor(props, context) {
super(props, context);
this.state = {
value: props.value
};
this.onChange = this.onChange.bind(this);
this.onBlur = this.onBlur.bind(this);
}
componentDidMount() {
this.props._mrf.registerInput(this.props.name, {
required: this.props.required,
validate: this.props.validate,
value: (this.props.type === 'hidden' && this.props.inputValue) ? this.props.inputValue : undefined
}, this.props.initialValue, this.props.initialErrors);
}
UNSAFE_componentWillReceiveProps(nextProps) {
if(nextProps.value !== this.props.value) {
this.setState({
value: nextProps.value
});
}
if(this.props.type === 'hidden' && nextProps.inputValue !== this.props.inputValue) {
this.props._mrf.inputChange(this.props.name, nextProps.inputValue);
}
}
componentWillUnmount() {
this.props._mrf.removeInput(this.props.name);
}
shouldComponentUpdate(nextProps, nextState) {
const nextPropsKeys = Object.keys(nextProps);
const thisPropsKeys = Object.keys(this.props);
if(nextPropsKeys.length !== thisPropsKeys.length || nextState.value !== this.state.value) {
return true;
}
for(let i = 0, length = nextPropsKeys.length; i < length; i += 1) {
const key = nextPropsKeys[i];
if(!~ignoreForUpdate.indexOf(key) && !deepEqual(this.props[key], nextProps[key])) {
return true
}
}
return false;
}
// UNSAFE_componentWillReceiveProps(nextProps) {
// if(this.props.type === 'hidden' && nextProps.value !== this.props.value) {
// this.onChange(nextProps.value);
// }
// }
onChange(e) {
const value = getValue(e);
this.setState({
value: value
});
this.props._mrf.inputChange(this.props.name, value);
if(this.props.onChange) {
this.props.onChange(e);
}
}
onBlur(e) {
this.props._mrf.inputBlur(this.props.name);
if(this.props._mrf.asyncValidate) {
this.props._mrf.asyncValidate(this.props.name, getValue(e), true, false);
}
if(this.props.onBlur) {
this.props.onBlur(e);
}
}
render() {
const formSubmitted = this.props.formSubmitted;
let componentProps = cleanComponentProps(this.state.value, this.props);
componentProps.input.onChange = this.onChange;
componentProps.input.onBlur = this.onBlur;
if(typeof this.props.component === 'string') {
return React.createElement(this.props.component, Object.assign(componentProps.input, {
type: this.props.type,
className: this.props.className
}));
}
else {
return React.createElement(this.props.component, Object.assign(componentProps, {
meta: {
pristine: this.props.input.pristine,
dirty: this.props.input.dirty,
touched: formSubmitted === true ? true : this.props.input.touched,
valid: this.props.input.valid,
errors: this.props.input.errors,
errorMessages: generateErrorMessages(this.props.input.errors, this.props.errors),
initialErrors: this.props.input.initialErrors,
asyncValidation: this.props.input.asyncValidation,
asyncErrors: this.props.input.asyncErrors,
formSubmitted: formSubmitted
}
}));
}
}
}
function mapStateToProps(state, ownProps) {
const formState = ownProps._mrf.getFormState(state);
return {
input: getIn(formState, ['inputs', ownProps.name]) || {},
value: getIn(formState, ['values', ...getPath(ownProps.name)]),
initialValue: getIn(formState, ['initialValues', ...getPath(ownProps.name)]),
initialErrors: getIn(formState, ['initialInputErrors', ownProps.name]),
inputValue: ownProps.value,
formSubmitted: getIn(formState, 'submitted', false)
}
}
const mapDispatchToProps = {};
export default connect(mapStateToProps, mapDispatchToProps)(ConnectedInput); | mzvonar/modular-redux-form | src/components/ConnectedInput.js | JavaScript | mit | 6,941 |
using System.Xml.Serialization;
namespace MovieDatabase.ImportDataFromFiles.ImportingData.XMLModels
{
public class Director
{
[XmlElement("firstName")]
public string FirstName { get; set; }
[XmlElement("lastName")]
public string LastName { get; set; }
[XmlElement("age")]
public int Age { get; set; }
[XmlElement("salary")]
public decimal Salary { get; set; }
}
} | Team-Singapore-Sling/TeamWork | MovieDatabase/MovieDatabase.ImportDataFromFiles/ImportingData/XMLModels/Director.cs | C# | mit | 446 |
# frozen_string_literal: true
# Job is a base class that jobs must subclass
class DivvyUp::Job
class << self
attr_reader :queue
def perform_async(*args)
DivvyUp.service.enqueue job_class: self, args: args
end
end
end
| nilobject/divvyup | lib/divvyup/job.rb | Ruby | mit | 241 |
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using Quasar.Communication.Packets.Outgoing.Users;
using Quasar.Database.Interfaces;
namespace Quasar.Communication.Packets.Incoming.Users
{
class CheckValidNameEvent : IPacketEvent
{
public void Parse(HabboHotel.GameClients.GameClient Session, ClientPacket Packet)
{
bool InUse = false;
string Name = Packet.PopString();
using (IQueryAdapter dbClient = QuasarEnvironment.GetDatabaseManager().GetQueryReactor())
{
dbClient.SetQuery("SELECT COUNT(0) FROM `users` WHERE `username` = @name LIMIT 1");
dbClient.AddParameter("name", Name);
InUse = dbClient.getInteger() == 1;
}
char[] Letters = Name.ToLower().ToCharArray();
string AllowedCharacters = "abcdefghijklmnopqrstuvwxyz.,_-;:?!1234567890";
foreach (char Chr in Letters)
{
if (!AllowedCharacters.Contains(Chr))
{
Session.SendMessage(new NameChangeUpdateComposer(Name, 4));
return;
}
}
string word;
if (QuasarEnvironment.GetGame().GetChatManager().GetFilter().IsUnnaceptableWord(Name, out word))
{
Session.SendMessage(new NameChangeUpdateComposer(Name, 4));
return;
}
if (!Session.GetHabbo().GetPermissions().HasRight("mod_tool") && Name.ToLower().Contains("mod") || Name.ToLower().Contains("adm") || Name.ToLower().Contains("admin") || Name.ToLower().Contains("m0d"))
{
Session.SendMessage(new NameChangeUpdateComposer(Name, 4));
return;
}
else if (!Name.ToLower().Contains("mod") && (Session.GetHabbo().Rank == 2 || Session.GetHabbo().Rank == 3))
{
Session.SendMessage(new NameChangeUpdateComposer(Name, 4));
return;
}
else if (Name.Length > 15)
{
Session.SendMessage(new NameChangeUpdateComposer(Name, 3));
return;
}
else if (Name.Length < 3)
{
Session.SendMessage(new NameChangeUpdateComposer(Name, 2));
return;
}
else if (InUse)
{
ICollection<string> Suggestions = new List<string>();
for (int i = 100; i < 103; i++)
{
Suggestions.Add(i.ToString());
}
Session.SendMessage(new NameChangeUpdateComposer(Name, 5, Suggestions));
return;
}
else
{
Session.SendMessage(new NameChangeUpdateComposer(Name, 0));
return;
}
}
}
}
| slaapkopamy/PlusEmu-making-ready-for-linux-server | Communication/Packets/Incoming/Users/CheckValidNameEvent.cs | C# | mit | 2,939 |
# frozen_string_literal: true
module Eve
class RegionContractsJob < ApplicationJob
queue_as :default
retry_on EveOnline::Exceptions::Timeout,
EveOnline::Exceptions::ServiceUnavailable,
EveOnline::Exceptions::BadGateway,
EveOnline::Exceptions::InternalServerError,
OpenSSL::SSL::SSLError,
Faraday::TimeoutError,
Faraday::ConnectionFailed
def perform(region_id, page = 1)
Eve::RegionContractsImporter.new(region_id, page).import
end
end
end
| biow0lf/evemonk | app/jobs/eve/region_contracts_job.rb | Ruby | mit | 504 |
/**
* Global Variable Configuration
* (sails.config.globals)
*
* Configure which global variables which will be exposed
* automatically by Sails.
*
* For more information on configuration, check out:
* http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.globals.html
*/
module.exports.globals = {
/****************************************************************************
* *
* Expose the lodash installed in Sails core as a global variable. If this *
* is disabled, like any other node module you can always run npm install *
* lodash --save, then var _ = require('lodash') at the top of any file. *
* *
****************************************************************************/
// _: true,
/****************************************************************************
* *
* Expose the async installed in Sails core as a global variable. If this is *
* disabled, like any other node module you can always run npm install async *
* --save, then var async = require('async') at the top of any file. *
* *
****************************************************************************/
// async: true,
/****************************************************************************
* *
* Expose the sails instance representing your app. If this is disabled, you *
* can still get access via req._sails. *
* *
****************************************************************************/
// sails: true,
/****************************************************************************
* *
* Expose each of your app's services as global variables (using their *
* "globalId"). E.g. a service defined in api/models/NaturalLanguage.js *
* would have a globalId of NaturalLanguage by default. If this is disabled, *
* you can still access your services via sails.services.* *
* *
****************************************************************************/
// services: true,
/****************************************************************************
* *
* Expose each of your app's models as global variables (using their *
* "globalId"). E.g. a model defined in api/models/User.js would have a *
* globalId of User by default. If this is disabled, you can still access *
* your models via sails.models.*. *
* *
****************************************************************************/
// models: true
};
| dcamachoj/rauxa-code | config/globals.js | JavaScript | mit | 3,304 |
/***
* Inferno Engine v4 2015-2017
* Written by Tomasz "Rex Dex" Jonarski
*
* [# filter: elements\controls\simple #]
***/
#include "build.h"
#include "uiProgressBar.h"
#include "ui/toolkit/include/uiStaticContent.h"
namespace ui
{
//---
// active area element, does nothing but is
class ProgressBarArea : public IElement
{
RTTI_DECLARE_VIRTUAL_CLASS(ProgressBarArea, IElement);
public:
ProgressBarArea()
{}
};
RTTI_BEGIN_TYPE_NOCOPY_CLASS(ProgressBarArea);
RTTI_METADATA(ElementClassName).setName("ProgressBarArea");
RTTI_END_TYPE();
//--
RTTI_BEGIN_TYPE_NOCOPY_CLASS(ProgressBar);
RTTI_METADATA(ElementClassName).setName("ProgressBar");
RTTI_END_TYPE();
ProgressBar::ProgressBar()
: m_pos(0.5f)
{
setLayoutMode(LayoutMode::Vertical);
m_bar = base::CreateSharedPtr<ProgressBarArea>();
m_bar->setIgnoredInAutomaticLayout(true);
attachChild(m_bar);
}
void ProgressBar::setPosition(const Float pos)
{
const auto clampedPos = std::clamp<Float>(pos, 0.0f, 1.0f);
if (m_pos != clampedPos)
{
m_pos = clampedPos;
if (m_bar)
m_bar->setCustomProportion(m_pos);
if (m_text)
m_text->setText(base::TempString("{}%", pos * 100.0f));
invalidateLayout();
}
}
Bool ProgressBar::handleTemplateProperty(const base::StringView<AnsiChar>& name, const base::StringView<AnsiChar>& value)
{
if (name == "showPercents" || name == "text" || name == "showPercent")
{
Bool flag = false;
if (base::MatchResult::OK != value.match(flag))
return false;
if (flag && !m_text)
{
m_text = base::CreateSharedPtr<StaticContent>();
m_text->setName("ProgressCaption");
m_text->setText(base::TempString("{}%", m_pos * 100.0f));
attachChild(m_text);
}
return true;
}
else if (name == "value")
{
Float pos = 0.0f;
if (base::MatchResult::OK != value.match(pos))
return false;
setPosition(pos);
return true;
}
return TBaseClass::handleTemplateProperty(name, value);
}
void ProgressBar::arrangeChildren(const ElementArea& innerArea, const ElementArea& clipArea, ArrangedChildren& outArrangedChildren, const ElementDynamicSizing* dynamicSizing) const
{
if (m_pos > 0.0f)
{
const auto pos = innerArea.getLeft() + (Float)(innerArea.getSize().x * m_pos);
const auto area = ElementArea(innerArea.getLeft(), innerArea.getTop(), pos, innerArea.getBottom());
outArrangedChildren.add(m_bar, area, clipArea);
}
return TBaseClass::arrangeChildren(innerArea, clipArea, outArrangedChildren, dynamicSizing);
}
//---
} // ui
| InfernoEngine/engine | dev/src/ui/widgets/src/uiProgressBar.cpp | C++ | mit | 3,017 |
<?php
/**
* Flash Messenger - implement session-based messages
*
* @author Loïc Frering <loic.frering@gmail.com>
*/
class LoSo_Zend_Controller_Action_Helper_FlashMessenger extends Zend_Controller_Action_Helper_FlashMessenger
{
/**
* preDispatch() - runs before action is dispatched.
*
* @return LoSo_Zend_Controller_Action_Helper_FlashMessenger Provides a fluent interface
*/
public function preDispatch()
{
$controller = $this->getActionController();
$controller->view->infoMessages = $this->setNamespace('default')->getMessages();
$controller->view->successMessages = $this->setNamespace('success')->getMessages();
$controller->view->errorMessages = $this->setNamespace('error')->getMessages();
$controller->view->warnMessages = $this->setNamespace('warn')->getMessages();
}
/**
* addMessage() - Add a message to flash message
*
* @param string $message
* @param string $namespace
* @return LoSo_Zend_Controller_Action_Helper_FlashMessenger Provides a fluent interface
*/
public function addMessage($message, $namespace = null)
{
if (!empty($namespace)) {
$this->setNamespace($namespace);
}
return parent::addMessage($message);
}
/**
* Strategy pattern: proxy to addMessage()
*
* @param string $message
* @param string $namespace
* @return void
*/
public function direct($message, $namespace = null)
{
return $this->addMessage($message, $namespace);
}
}
| loicfrering/losolib | src/LoSo/Zend/Controller/Action/Helper/FlashMessenger.php | PHP | mit | 1,579 |
#include "MW_Timer.hpp"
MW_Timer::MW_Timer(double periodInSeconds): period(periodInSeconds)
{
reset();
}
bool MW_Timer::get() const
{
b_mutex.lock();
bool retVal = MPI::Wtime() > expirationTime;
b_mutex.unlock();
return retVal;
}
void MW_Timer::reset()
{
b_mutex.lock();
expirationTime = MPI::Wtime() + period;
b_mutex.unlock();
}
| seanjh/parallel_lab2 | MW_Timer.cpp | C++ | mit | 344 |
using StatsdClient.MetricTypes;
using System;
using System.Collections.Generic;
namespace StatsdClient
{
public interface IStatsd
{
void Send<TCommandType>(string name, int value) where TCommandType : Metric, IAllowsInteger, new();
void Send<TCommandType>(string name, double value) where TCommandType : Metric, IAllowsDouble, new();
void Send<TCommandType>(string name, int value, double sampleRate) where TCommandType : Metric, IAllowsInteger, IAllowsSampleRate, new();
void Send<TCommandType>(string name, string value) where TCommandType : Metric, IAllowsString, new();
void Send(Action actionToTime, string statName, double sampleRate=1);
}
} | Kyle2123/statsd-csharp-client | src/StatsdClient/IStatsd.cs | C# | mit | 714 |
#require 'byebug'
require_relative '../models/url'
get '/' do
@urls = Url.last
erb :"static/index"
end
post '/urls' do
x = Url.new(long_url: params[:long_url])
x.shorten
x.save!
x.to_json
# redirect to '/'
#use return @long_url to immediately return the long_url without going to the controller
#ajax is using this method, and return value back to ajax
end
get '/:short_url' do
y = Url.find_by(short_url: params[:short_url])
y.click_count += 1
y.save
redirect to "#{y.long_url}"
end
| anyatan/bitly-clone | app/controllers/static.rb | Ruby | mit | 504 |
this.NesDb = this.NesDb || {};
NesDb[ '9F3DE783494F7FF30679A17B0C5B912834121095' ] = {
"$": {
"name": "Nekketsu Kouha Kunio-kun",
"altname": "熱血硬派くにおくん",
"class": "Licensed",
"catalog": "TJC-KN",
"publisher": "Technos",
"developer": "Technos",
"region": "Japan",
"players": "2",
"date": "1987-04-17"
},
"cartridge": [
{
"$": {
"system": "Famicom",
"crc": "A7D3635E",
"sha1": "9F3DE783494F7FF30679A17B0C5B912834121095",
"dump": "ok",
"dumper": "bootgod",
"datedumped": "2007-06-24"
},
"board": [
{
"$": {
"type": "HVC-UNROM",
"pcb": "HVC-UNROM-02",
"mapper": "2"
},
"prg": [
{
"$": {
"name": "TJC-KN-0 PRG",
"size": "128k",
"crc": "A7D3635E",
"sha1": "9F3DE783494F7FF30679A17B0C5B912834121095"
}
}
],
"vram": [
{
"$": {
"size": "8k"
}
}
],
"chip": [
{
"$": {
"type": "74xx161"
}
},
{
"$": {
"type": "74xx32"
}
}
],
"pad": [
{
"$": {
"h": "1",
"v": "0"
}
}
]
}
]
}
]
};
| peteward44/WebNES | project/js/db/9F3DE783494F7FF30679A17B0C5B912834121095.js | JavaScript | mit | 1,227 |
<?php
/*
* This file is part of Pimple.
*
* Copyright (c) 2009 Fabien Potencier
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace Alpipego\Resizefly\Common\Pimple\Exception;
use Alpipego\Resizefly\Common\Psr\Container\NotFoundExceptionInterface;
/**
* The identifier of a valid service or parameter was expected.
*
* @author Pascal Luna <skalpa@zetareticuli.org>
*/
class UnknownIdentifierException extends \InvalidArgumentException implements NotFoundExceptionInterface
{
/**
* @param string $id The unknown identifier
*/
public function __construct($id)
{
parent::__construct(\sprintf('Identifier "%s" is not defined.', $id));
}
}
| alpipego/resizefly | src/Common/Pimple/Exception/UnknownIdentifierException.php | PHP | mit | 1,717 |
/**
* Interaction for the tags module
*
* @author Tijs Verkoyen <tijs@sumocoders.be>
*/
jsBackend.tags =
{
// init, something like a constructor
init: function()
{
$dataGridTag = $('.jsDataGrid td.tag');
if($dataGridTag.length > 0) $dataGridTag.inlineTextEdit({ params: { fork: { action: 'edit' } }, tooltip: jsBackend.locale.msg('ClickToEdit') });
}
};
$(jsBackend.tags.init);
| jlglorences/jorge_prueba | src/Backend/Modules/Tags/Js/Tags.js | JavaScript | mit | 392 |
/* global WebFont */
(function () {
'use strict';
function FontLoaderFactory () {
return {
setFonts : function () {
WebFont.load({
custom: {
families: [ 'FontAwesome','Ubuntu','Oxygen','Open Sans' ],
urls: [ '/fonts/base.css']
}
});
}
};
}
angular.module('app.core.fontloader', [])
.factory('FontLoader',FontLoaderFactory);
})();
| dlfinis/master-sigma | assets/angular/components/core/fontloader/fontloader.mdl.js | JavaScript | mit | 428 |
module.exports = handler
var debug = require('../debug').server
var fs = require('fs')
function handler (err, req, res, next) {
debug('Error page because of ' + err.message)
var ldp = req.app.locals.ldp
// If the user specifies this function
// then, they can customize the error programmatically
if (ldp.errorHandler) {
return ldp.errorHandler(err, req, res, next)
}
// If noErrorPages is set,
// then use built-in express default error handler
if (ldp.noErrorPages) {
return res
.status(err.status)
.send(err.message + '\n' || '')
}
// Check if error page exists
var errorPage = ldp.errorPages + err.status.toString() + '.html'
fs.readFile(errorPage, 'utf8', function (readErr, text) {
if (readErr) {
return res
.status(err.status)
.send(err.message || '')
}
res.status(err.status)
res.header('Content-Type', 'text/html')
res.send(text)
})
}
| nicola/ldnode | lib/handlers/error-pages.js | JavaScript | mit | 941 |
export interface IArticle {
articleId: number,
name: string,
description: string,
prix: number,
stock: number
} | milleniu/JavaForWeb.CandiesForAll | app/candiesForAll/src/app/model/article.model.ts | TypeScript | mit | 131 |
package redis.clients.jedis.util;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* The class implements a buffered output stream without synchronization There are also special
* operations like in-place string encoding. This stream fully ignore mark/reset and should not be
* used outside Jedis
*/
public final class RedisOutputStream extends FilterOutputStream {
protected final byte[] buf;
protected int count;
private final static int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999,
999999999, Integer.MAX_VALUE };
private final static byte[] DigitTens = { '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1',
'1', '1', '1', '1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '2', '2', '2', '2',
'2', '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4', '4', '4',
'4', '4', '4', '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', '6', '6', '6', '6', '6',
'6', '6', '6', '6', '6', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '8', '8', '8',
'8', '8', '8', '8', '8', '8', '8', '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', };
private final static byte[] DigitOnes = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4',
'5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2',
'3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', };
private final static byte[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y', 'z' };
public RedisOutputStream(final OutputStream out) {
this(out, 8192);
}
public RedisOutputStream(final OutputStream out, final int size) {
super(out);
if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buf = new byte[size];
}
private void flushBuffer() throws IOException {
if (count > 0) {
out.write(buf, 0, count);
count = 0;
}
}
public void write(final byte b) throws IOException {
if (count == buf.length) {
flushBuffer();
}
buf[count++] = b;
}
@Override
public void write(final byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
public void write(final byte[] b, final int off, final int len) throws IOException {
if (len >= buf.length) {
flushBuffer();
out.write(b, off, len);
} else {
if (len >= buf.length - count) {
flushBuffer();
}
System.arraycopy(b, off, buf, count, len);
count += len;
}
}
public void writeCrLf() throws IOException {
if (2 >= buf.length - count) {
flushBuffer();
}
buf[count++] = '\r';
buf[count++] = '\n';
}
public void writeIntCrLf(int value) throws IOException {
if (value < 0) {
write((byte) '-');
value = -value;
}
int size = 0;
while (value > sizeTable[size])
size++;
size++;
if (size >= buf.length - count) {
flushBuffer();
}
int q, r;
int charPos = count + size;
while (value >= 65536) {
q = value / 100;
r = value - ((q << 6) + (q << 5) + (q << 2));
value = q;
buf[--charPos] = DigitOnes[r];
buf[--charPos] = DigitTens[r];
}
for (;;) {
q = (value * 52429) >>> (16 + 3);
r = value - ((q << 3) + (q << 1));
buf[--charPos] = digits[r];
value = q;
if (value == 0) break;
}
count += size;
writeCrLf();
}
@Override
public void flush() throws IOException {
flushBuffer();
out.flush();
}
}
| xetorthio/jedis | src/main/java/redis/clients/jedis/util/RedisOutputStream.java | Java | mit | 4,015 |
/***********************************************************************\
| |
| File: SGD_AudioManager.cpp |
| Author: Douglas Monroe |
| Last Modified: 2014-03-10 |
| |
| Purpose: To load and play audio files |
| .wav - sound effect |
| .xwm - music |
| |
| © 2014 Full Sail, Inc. All rights reserved. The terms "Full Sail", |
| "Full Sail University", and the Full Sail University logo are |
| either registered service marks or service marks of Full Sail, Inc. |
| |
| Derived From: "XAudio2 Programming Guide" - MSDN |
| http://msdn.microsoft.com/en-us/library/hh405049%28v=vs.85%29.aspx |
| |
\***********************************************************************/
#include "stdafx.h"
#include "SGD_AudioManager.h"
// Uses assert for debug breaks
#include <cassert>
// Uses OutputDebugString for debug text
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <cstring>
// Uses std::multimap for storing voices
#include <map>
// Uses DirectInput to solve random memory-leak detection bug?!?
#define DIRECTINPUT_VERSION 0x0800
#include <dinput.h>
#pragma comment(lib, "dinput8.lib")
// Uses XAudio2 for audio
#include <XAudio2.h>
#pragma comment (lib, "dxguid.lib")
// Uses HandleManager for storing data
#include "SGD_HandleManager.h"
namespace SGD
{
namespace SGD_IMPLEMENTATION
{
//*************************************************************//
// AudioInfo
// - stores info for the audio file: name, buffer, reference count
struct AudioInfo
{
wchar_t* wszFilename; // file name
unsigned int unRefCount; // reference count
WAVEFORMATEXTENSIBLE format; // wave format (sample rate, etc)
XAUDIO2_BUFFER buffer; // buffer
XAUDIO2_BUFFER_WMA bufferwma; // additional buffer packets for xwm
float fVolume; // audio volume
};
//*************************************************************//
//*************************************************************//
// VoiceInfo
// - stores info for the source voice instance: audio handle, buffer, state
struct VoiceInfo
{
HAudio audio; // audio handle
IXAudio2SourceVoice* voice; // source voice
bool loop; // should repeat
bool paused; // currently paused
};
//*************************************************************//
//*************************************************************//
// AudioManager
// - concrete class for loading and playing audio files
// - only supports .wav and .xwm files
// - .wav files are categorized as 'Sound Effects'
// - .xwm files are categorized as 'Music'
// - uses IHandleManager to store audio data
class AudioManager : public SGD::AudioManager
{
public:
// SINGLETON
static AudioManager* GetInstance ( void );
static void DeleteInstance ( void );
virtual bool Initialize ( void ) override;
virtual bool Update ( void ) override;
virtual bool Terminate ( void ) override;
//enum class AudioCategory
//{
// Music, // *.xwm files
// SoundEffects, // *.wav files
//};
virtual int GetMasterVolume ( AudioGroup group ) override;
virtual bool SetMasterVolume ( AudioGroup group, int value ) override;
virtual HAudio LoadAudio ( const wchar_t* filename ) override;
virtual HAudio LoadAudio ( const char* filename ) override;
virtual HVoice PlayAudio ( HAudio handle, bool looping ) override;
virtual bool IsAudioPlaying ( HAudio handle ) override;
virtual bool StopAudio ( HAudio handle ) override;
virtual bool UnloadAudio ( HAudio& handle ) override;
virtual bool IsVoiceValid ( HVoice handle ) override;
virtual bool IsVoicePlaying ( HVoice handle ) override;
virtual bool PauseVoice ( HVoice handle, bool pause ) override;
virtual bool StopVoice ( HVoice& handle ) override;
virtual int GetVoiceVolume ( HVoice handle ) override;
virtual bool SetVoiceVolume ( HVoice handle, int value ) override;
virtual int GetAudioVolume ( HAudio handle ) override;
virtual bool SetAudioVolume ( HAudio handle, int value ) override;
private:
// SINGLETON
static AudioManager* s_Instance; // the ONE instance
AudioManager ( void ) = default; // Default constructor
virtual ~AudioManager ( void ) = default; // Destructor
AudioManager ( const AudioManager& ) = delete; // Copy constructor
AudioManager& operator= ( const AudioManager& ) = delete; // Assignment operator
// Wrapper Status
enum EAudioManagerStatus
{
E_UNINITIALIZED,
E_INITIALIZED,
E_DESTROYED
};
EAudioManagerStatus m_eStatus = E_UNINITIALIZED; // wrapper initialization status
IXAudio2* m_pXAudio = nullptr; // XAudio2 api
IXAudio2MasteringVoice* m_pMasterVoice = nullptr; // master voice
IXAudio2SubmixVoice* m_pSfxVoice = nullptr; // sound effects submix voice
IXAudio2SubmixVoice* m_pMusVoice = nullptr; // music submix voice
DWORD m_dwChannelMask = 0; // speaker configuration
UINT32 m_unChannels = 0; // speaker configuration count
typedef std::multimap< HAudio, HVoice > VoiceMap;
VoiceMap m_mVoices; // source voice map
HandleManager< AudioInfo > m_HandleManager; // data storage
HandleManager< VoiceInfo > m_VoiceManager; // voice storage
// AUDIO LOADING HELPER METHODS
static HRESULT FindChunk ( HANDLE hFile, DWORD fourcc, DWORD& dwChunkSize, DWORD& dwChunkDataPosition );
static HRESULT ReadChunkData ( HANDLE hFile, void* buffer, DWORD buffersize, DWORD bufferoffset );
static HRESULT LoadAudio ( const wchar_t* filename, WAVEFORMATEXTENSIBLE& wfx, XAUDIO2_BUFFER& buffer, XAUDIO2_BUFFER_WMA& bufferWMA );
// AUDIO REFERENCE HELPER METHOD
struct SearchInfo
{
const wchar_t* filename; // input
AudioInfo* audio; // output
HAudio handle; // output
};
static bool FindAudioByName( Handle handle, AudioInfo& data, SearchInfo* extra );
};
//*************************************************************//
} // namespace SGD_IMPLEMENTATION
//*****************************************************************//
// Interface singleton accessor
/*static*/ AudioManager* AudioManager::GetInstance( void )
{
// Return the implementation singleton (upcasted to interface)
return (SGD::AudioManager*)SGD_IMPLEMENTATION::AudioManager::GetInstance();
}
// Interface singleton destructor
/*static*/ void AudioManager::DeleteInstance( void )
{
// Deallocate the implementation singleton
return SGD_IMPLEMENTATION::AudioManager::DeleteInstance();
}
//*****************************************************************//
namespace SGD_IMPLEMENTATION
{
//*************************************************************//
// SINGLETON
// Instantiate static pointer to null (no instance yet)
/*static*/ AudioManager* AudioManager::s_Instance = nullptr;
// Singleton accessor
/*static*/ AudioManager* AudioManager::GetInstance( void )
{
// Allocate singleton on first use
if( AudioManager::s_Instance == nullptr )
AudioManager::s_Instance = new AudioManager;
// Return the singleton
return AudioManager::s_Instance;
}
// Singleton destructor
/*static*/ void AudioManager::DeleteInstance( void )
{
// Deallocate singleton
delete AudioManager::s_Instance;
AudioManager::s_Instance = nullptr;
}
//*************************************************************//
//*************************************************************//
// INITIALIZE
bool AudioManager::Initialize( void )
{
// Sanity-check the wrapper's status
assert( m_eStatus == E_UNINITIALIZED && "AudioManager::Initialize - wrapper has already been initialized" );
if( m_eStatus != E_UNINITIALIZED )
return false;
HRESULT hResult = S_OK;
// When using a COM object, the thread should be CoInitialized
CoInitializeEx( nullptr, COINIT_MULTITHREADED );
// HACK: Somehow creating DirectInput will allow memory leak detection?!?
IDirectInput8W* pDI_Hack;
DirectInput8Create( (HINSTANCE)GetModuleHandle( nullptr ), DIRECTINPUT_VERSION, IID_IDirectInput8W, (void**)&pDI_Hack, NULL);
pDI_Hack->Release();
// Attempt to create the XAudio2 interface
hResult = XAudio2Create( &m_pXAudio, 0 );
if( FAILED( hResult ) )
{
CoUninitialize();
// MESSAGE
char szBuffer[ 128 ];
_snprintf_s( szBuffer, 128, _TRUNCATE, "!!! AudioManager::Initialize - failed to initialize XAudio2 (0x%X) !!!\n", hResult );
OutputDebugStringA( szBuffer );
return false;
}
// Attempt to create the mastering voice
hResult = m_pXAudio->CreateMasteringVoice( &m_pMasterVoice );
if( FAILED( hResult ) )
{
m_pXAudio->Release();
m_pXAudio = nullptr;
CoUninitialize();
// MESSAGE
char szBuffer[ 128 ];
_snprintf_s( szBuffer, 128, _TRUNCATE, "!!! AudioManager::Initialize - failed to initialize XAudio2 master voice (0x%X) !!!\n", hResult );
OutputDebugStringA( szBuffer );
return false;
}
// Get the speaker configuration
XAUDIO2_DEVICE_DETAILS details;
m_pXAudio->GetDeviceDetails( 0U, &details );
m_dwChannelMask = details.OutputFormat.dwChannelMask;
m_unChannels = details.OutputFormat.Format.nChannels;
// Attempt to create the sfx submix voice
hResult = m_pXAudio->CreateSubmixVoice( &m_pSfxVoice, m_unChannels, 44100, XAUDIO2_VOICE_USEFILTER );
if( FAILED( hResult ) )
{
m_pMasterVoice->DestroyVoice();
m_pMasterVoice = nullptr;
m_pXAudio->Release();
m_pXAudio = nullptr;
CoUninitialize();
// MESSAGE
char szBuffer[ 128 ];
_snprintf_s( szBuffer, 128, _TRUNCATE, "!!! AudioManager::Initialize - failed to initialize XAudio2 sfx submix voice (0x%X) !!!\n", hResult );
OutputDebugStringA( szBuffer );
return false;
}
// Attempt to create the music submix voice
hResult = m_pXAudio->CreateSubmixVoice( &m_pMusVoice, m_unChannels, 44100, XAUDIO2_VOICE_USEFILTER );
if( FAILED( hResult ) )
{
m_pSfxVoice->DestroyVoice();
m_pSfxVoice = nullptr;
m_pMasterVoice->DestroyVoice();
m_pMasterVoice = nullptr;
m_pXAudio->Release();
m_pXAudio = nullptr;
CoUninitialize();
// MESSAGE
char szBuffer[ 128 ];
_snprintf_s( szBuffer, 128, _TRUNCATE, "!!! AudioManager::Initialize - failed to initialize XAudio2 music submix voice (0x%X) !!!\n", hResult );
OutputDebugStringA( szBuffer );
return false;
}
// Success!
m_eStatus = E_INITIALIZED;
return true;
}
//*************************************************************//
//*************************************************************//
// UPDATE
bool AudioManager::Update( void )
{
// Sanity-check the wrapper's status
assert( m_eStatus == E_INITIALIZED && "AudioManager::Update - wrapper has not been initialized" );
if( m_eStatus != E_INITIALIZED )
return false;
// Update the current voices
VoiceMap::iterator iter = m_mVoices.begin();
while( iter != m_mVoices.end() )
{
// Get the voice info from the handle manager
VoiceInfo* info = m_VoiceManager.GetData( iter->second );
assert( info != nullptr && "AudioManager::Update - voice handle has expired" );
if( info == nullptr )
{
iter = m_mVoices.erase( iter );
continue;
}
// Has the voice ended?
XAUDIO2_VOICE_STATE state;
info->voice->GetState( &state );
if( state.BuffersQueued == 0 )
{
// Should it loop?
if( info->loop == true )
{
// Get the data from the Handle Manager
AudioInfo* data = m_HandleManager.GetData( iter->first );
assert( data != nullptr && "AudioManager::Update - voice refers to removed audio" );
if( data == nullptr )
{
// Remove the voice (could recycle it ...)
info->voice->DestroyVoice();
iter = m_mVoices.erase( iter );
continue;
}
// Play wav or wma?
if( data->bufferwma.PacketCount == 0 )
info->voice->SubmitSourceBuffer( &data->buffer );
else
info->voice->SubmitSourceBuffer( &data->buffer, &data->bufferwma );
}
else
{
// Remove the voice (could recycle it ...)
info->voice->DestroyVoice();
iter = m_mVoices.erase( iter );
continue;
}
}
++iter;
}
return true;
}
//*************************************************************//
//*************************************************************//
// TERMINATE
bool AudioManager::Terminate( void )
{
// Sanity-check the wrapper's status
assert( m_eStatus == E_INITIALIZED && "AudioManager::Terminate - wrapper has not been initialized" );
if( m_eStatus != E_INITIALIZED )
return false;
// Release all audio voices
for( VoiceMap::iterator iter = m_mVoices.begin(); iter != m_mVoices.end(); ++iter )
{
// Get the voice info from the handle manager
VoiceInfo* info = m_VoiceManager.GetData( iter->second );
if( info == nullptr )
continue;
//info->voice->Stop();
//info->voice->FlushSourceBuffers();
info->voice->DestroyVoice();
}
m_mVoices.clear();
// Clear handles
m_VoiceManager.Clear();
m_HandleManager.Clear();
// Release submix & master voices
m_pMusVoice->DestroyVoice();
m_pMusVoice = nullptr;
m_pSfxVoice->DestroyVoice();
m_pSfxVoice = nullptr;
m_pMasterVoice->DestroyVoice();
m_pMasterVoice = nullptr;
// Release XAudio2
m_pXAudio->Release();
m_pXAudio = nullptr;
CoUninitialize();
m_eStatus = E_DESTROYED;
return true;
}
//*************************************************************//
//*************************************************************//
// GET MASTER VOLUME
int AudioManager::GetMasterVolume( AudioGroup group )
{
// Sanity-check the wrapper's status
assert( m_eStatus == E_INITIALIZED && "AudioManager::GetMasterVolume - wrapper has not been initialized" );
if( m_eStatus != E_INITIALIZED )
return 0;
// Sanity-check the parameter
assert( (group == AudioGroup::Music || group == AudioGroup::SoundEffects) && "AudioManager::GetMasterVolume - invalid group" );
// Get the master volume from the submix voice
float fVolume = 0.0f;
if( group == AudioGroup::Music )
m_pMusVoice->GetVolume( &fVolume );
else //if( type == AudioGroup::SoundEffects )
m_pSfxVoice->GetVolume( &fVolume );
// Scale 0 -> +100 (account for floating point error)
return (int)(fVolume * 100.0f + 0.5f);
}
//*************************************************************//
//*************************************************************//
// SET MASTER VOLUME
bool AudioManager::SetMasterVolume( AudioGroup group, int value )
{
// Sanity-check the wrapper's status
assert( m_eStatus == E_INITIALIZED && "AudioManager::SetMasterVolume - wrapper has not been initialized" );
if( m_eStatus != E_INITIALIZED )
return false;
// Sanity-check the parameter
assert( (group == AudioGroup::Music || group == AudioGroup::SoundEffects) && "AudioManager::SetMasterVolume - invalid group" );
//assert( value >= 0 && value <= 100 && "AudioManager::SetMasterVolume - volume must be between 0 -> 100" );
// Cap the range 0->100
if( value < 0 )
value = 0;
else if( value > 100 )
value = 100;
// Set the submix voice volume
HRESULT result = 0;
if( group == AudioGroup::Music )
result = m_pMusVoice->SetVolume( (float)( value / 100.0f ) );
else //if( group == AudioGroup::SoundEffects )
result = m_pSfxVoice->SetVolume( (float)( value / 100.0f ) );
return SUCCEEDED( result );
}
//*************************************************************//
//*************************************************************//
// LOAD AUDIO
HAudio AudioManager::LoadAudio( const wchar_t* filename )
{
// Sanity-check the wrapper's status
assert( m_eStatus == E_INITIALIZED && "AudioManager::LoadAudio - wrapper has not been initialized" );
if( m_eStatus != E_INITIALIZED )
return SGD::INVALID_HANDLE;
assert( filename != nullptr && filename[0] != L'\0' && "AudioManager::LoadAudio - invalid filename" );
if( filename == nullptr || filename[0] == L'\0' )
return SGD::INVALID_HANDLE;
// Attempt to find the audio in the Handle Manager
SearchInfo search = { filename, nullptr, SGD::INVALID_HANDLE };
m_HandleManager.ForEach( &AudioManager::FindAudioByName, &search );
// If it was found, increase the reference & return the existing handle
if( search.audio != NULL )
{
search.audio->unRefCount++;
return search.handle;
}
// Could not find audio in the Handle Manager
AudioInfo data = { };
ZeroMemory( &data.format, sizeof( data.format ) );
ZeroMemory( &data.buffer, sizeof( data.buffer ) );
ZeroMemory( &data.bufferwma, sizeof( data.bufferwma ) );
// Attempt to load from file
HRESULT hResult = LoadAudio( filename, data.format, data.buffer, data.bufferwma );
if( FAILED( hResult ) )
{
// MESSAGE
wchar_t wszBuffer[ 256 ];
_snwprintf_s( wszBuffer, 256, _TRUNCATE, L"!!! AudioManager::LoadAudio - failed to load audio file \"%ws\" (0x%X) !!!", filename, hResult );
OutputDebugStringW( wszBuffer );
OutputDebugStringA( "\n" );
MessageBoxW( GetActiveWindow(), wszBuffer, L"AudioManager::LoadAudio", MB_OK );
return SGD::INVALID_HANDLE;
}
// Audio loaded successfully
data.wszFilename = _wcsdup( filename );
data.unRefCount = 1;
data.fVolume = 1.0f;
// Store audio into the Handle Manager
return m_HandleManager.StoreData( data );
}
//*************************************************************//
//*************************************************************//
// LOAD AUDIO
HAudio AudioManager::LoadAudio( const char* filename )
{
// Sanity-check the wrapper's status
assert( m_eStatus == E_INITIALIZED && "AudioManager::LoadAudio - wrapper has not been initialized" );
if( m_eStatus != E_INITIALIZED )
return SGD::INVALID_HANDLE;
assert( filename != nullptr && filename[0] != '\0' && "AudioManager::LoadAudio - invalid filename" );
if( filename == nullptr || filename[0] == '\0' )
return SGD::INVALID_HANDLE;
// Convert the filename to UTF16
wchar_t widename[ MAX_PATH * 4 ];
int ret = MultiByteToWideChar( CP_UTF8, 0, filename, -1, widename, MAX_PATH * 4 );
if( ret == 0 )
{
// MESSAGE
char szBuffer[ 256 ];
_snprintf_s( szBuffer, 256, _TRUNCATE, "!!! AudioManager::LoadAudio - invalid filename \"%hs\" (0x%X) !!!", filename, GetLastError() );
OutputDebugStringA( szBuffer );
OutputDebugStringA( "\n" );
return SGD::INVALID_HANDLE;
}
// Use the UTF16 load
return LoadAudio( widename );
}
//*************************************************************//
//*************************************************************//
// PLAY AUDIO
HVoice AudioManager::PlayAudio( HAudio handle, bool looping )
{
// Sanity-check the wrapper's status
assert( m_eStatus == E_INITIALIZED && "AudioManager::PlayAudio - wrapper has not been initialized" );
if( m_eStatus != E_INITIALIZED )
return SGD::INVALID_HANDLE;
assert( handle != SGD::INVALID_HANDLE && "AudioManager::PlayAudio - invalid handle" );
if( handle == SGD::INVALID_HANDLE )
return SGD::INVALID_HANDLE;
// Could create a VoicePool to recycle voices
// Voices can be reused for other audio files as long
// as they have the same samplerate and channels
// (the frequency rate may need to be modified)
// Get the audio info from the handle manager
AudioInfo* data = m_HandleManager.GetData( handle );
assert( data != nullptr && "AudioManager::PlayAudio - handle has expired" );
if( data == nullptr )
return SGD::INVALID_HANDLE;
HRESULT hResult = S_OK;
// Create parameter (send descriptor) for submix voice
XAUDIO2_SEND_DESCRIPTOR desc = { 0 };
if( data->bufferwma.PacketCount == 0 )
desc.pOutputVoice = m_pSfxVoice;
else
desc.pOutputVoice = m_pMusVoice;
XAUDIO2_VOICE_SENDS sendlist = { 1, &desc };
// Create a voice with the proper wave format
IXAudio2SourceVoice* pVoice = nullptr;
hResult = m_pXAudio->CreateSourceVoice( &pVoice, (WAVEFORMATEX*)&data->format, 0U, 2.0f, nullptr, &sendlist );
if( FAILED( hResult ) )
{
// MESSAGE
char szBuffer[ 128 ];
_snprintf_s( szBuffer, 128, _TRUNCATE, "!!! AudioManager::PlayAudio - failed to create voice (0x%X) !!!\n", hResult );
OutputDebugStringA( szBuffer );
return SGD::INVALID_HANDLE;
}
// Use the XAUDIO2_BUFFER for the voice's source
if( data->bufferwma.PacketCount == 0 )
hResult = pVoice->SubmitSourceBuffer( &data->buffer );
else
hResult = pVoice->SubmitSourceBuffer( &data->buffer, &data->bufferwma );
if( FAILED( hResult ) )
{
pVoice->DestroyVoice();
pVoice = nullptr;
// MESSAGE
char szBuffer[ 128 ];
_snprintf_s( szBuffer, 128, _TRUNCATE, "!!! AudioManager::PlayAudio - failed to submit source buffer (0x%X) !!!\n", hResult );
OutputDebugStringA( szBuffer );
return SGD::INVALID_HANDLE;
}
// Set the volume
pVoice->SetVolume( data->fVolume );
// Start the voice's thread
hResult = pVoice->Start( 0 );
if( FAILED( hResult ) )
{
pVoice->DestroyVoice();
pVoice = nullptr;
// MESSAGE
char szBuffer[ 128 ];
_snprintf_s( szBuffer, 128, _TRUNCATE, "!!! AudioManager::PlayAudio - failed to start voice (0x%X) !!!\n", hResult );
OutputDebugStringA( szBuffer );
return SGD::INVALID_HANDLE;
}
// Store the voice
VoiceInfo info = { handle, pVoice, looping, false };
HVoice hv = m_VoiceManager.StoreData( info );
if( hv != SGD::INVALID_HANDLE )
m_mVoices.insert( VoiceMap::value_type( handle, hv ) );
return hv;
}
//*************************************************************//
//*************************************************************//
// IS AUDIO PLAYING
bool AudioManager::IsAudioPlaying( HAudio handle )
{
// Sanity-check the wrapper's status
assert( m_eStatus == E_INITIALIZED && "AudioManager::IsAudioPlaying - wrapper has not been initialized" );
if( m_eStatus != E_INITIALIZED )
return false;
assert( handle != SGD::INVALID_HANDLE && "AudioManager::IsAudioPlaying - invalid handle" );
if( handle == SGD::INVALID_HANDLE )
return false;
// Find all voices with this handle
VoiceMap::_Paircc range = m_mVoices.equal_range( handle );
for( VoiceMap::const_iterator iter = range.first; iter != range.second; ++iter )
{
// Check if there are any active voices for this handle
if( IsVoicePlaying( iter->second ) == true )
return true;
}
return false;
}
//*************************************************************//
//*************************************************************//
// STOP AUDIO
bool AudioManager::StopAudio( HAudio handle )
{
// Sanity-check the wrapper's status
assert( m_eStatus == E_INITIALIZED && "AudioManager::StopAudio - wrapper has not been initialized" );
if( m_eStatus != E_INITIALIZED )
return false;
assert( handle != SGD::INVALID_HANDLE && "AudioManager::StopAudio - invalid handle" );
if( handle == SGD::INVALID_HANDLE )
return false;
// Find all voices with this handle
VoiceMap::_Paircc range = m_mVoices.equal_range( handle );
for( VoiceMap::const_iterator iter = range.first; iter != range.second; ++iter )
{
// Get the voice info from the Handle Manager
VoiceInfo* info = m_VoiceManager.GetData( iter->second );
if( info == nullptr )
continue;
// Destroy (or recycle) the voice
info->voice->DestroyVoice();
info->voice = nullptr;
// Remove the voice from the HandleManager
m_VoiceManager.RemoveData( iter->second, nullptr );
}
// Remove the voices from the active map
m_mVoices.erase( handle );
return true;
}
//*************************************************************//
//*************************************************************//
// UNLOAD AUDIO
bool AudioManager::UnloadAudio( HAudio& handle )
{
// Sanity-check the wrapper's status
assert( m_eStatus == E_INITIALIZED && "AudioManager::UnloadAudio - wrapper has not been initialized" );
if( m_eStatus != E_INITIALIZED )
return false;
// Quietly ignore bad handles
if( m_HandleManager.IsHandleValid( handle ) == false )
{
handle = SGD::INVALID_HANDLE;
return false;
}
// Get the audio info from the handle manager
AudioInfo* data = m_HandleManager.GetData( handle );
if( data == nullptr )
return false;
// Release a reference
data->unRefCount--;
// Is this the last reference?
if( data->unRefCount == 0 )
{
// Stop the audio
StopAudio( handle );
// Deallocate the audio buffers
delete[] data->buffer.pAudioData;
delete[] data->bufferwma.pDecodedPacketCumulativeBytes;
// Deallocate the name
delete[] data->wszFilename;
// Remove the audio info from the handle manager
m_HandleManager.RemoveData( handle, nullptr );
}
// Invalidate the handle
handle = INVALID_HANDLE;
return true;
}
//*************************************************************//
//*************************************************************//
// IS VOICE VALID
bool AudioManager::IsVoiceValid( HVoice handle )
{
// Sanity-check the wrapper's status
assert( m_eStatus == E_INITIALIZED && "AudioManager::IsVoicePlaying - wrapper has not been initialized" );
if( m_eStatus != E_INITIALIZED )
return false;
// Validate the handle
return m_VoiceManager.IsHandleValid( handle );
}
//*************************************************************//
//*************************************************************//
// IS VOICE PLAYING
bool AudioManager::IsVoicePlaying( HVoice handle )
{
// Sanity-check the wrapper's status
assert( m_eStatus == E_INITIALIZED && "AudioManager::IsVoicePlaying - wrapper has not been initialized" );
if( m_eStatus != E_INITIALIZED )
return false;
assert( handle != SGD::INVALID_HANDLE && "AudioManager::IsVoicePlaying - invalid handle" );
if( handle == SGD::INVALID_HANDLE )
return false;
// Get the voice info from the handle manager
VoiceInfo* data = m_VoiceManager.GetData( handle );
assert( data != nullptr && "AudioManager::IsVoicePlaying - handle has expired" );
if( data == nullptr )
return false;
// Is the voice playing?
return !data->paused;
}
//*************************************************************//
//*************************************************************//
// PAUSE VOICE
bool AudioManager::PauseVoice( HVoice handle, bool pause )
{
// Sanity-check the wrapper's status
assert( m_eStatus == E_INITIALIZED && "AudioManager::PauseVoice - wrapper has not been initialized" );
if( m_eStatus != E_INITIALIZED )
return false;
assert( handle != SGD::INVALID_HANDLE && "AudioManager::PauseVoice - invalid handle" );
if( handle == SGD::INVALID_HANDLE )
return false;
// Get the voice info from the handle manager
VoiceInfo* data = m_VoiceManager.GetData( handle );
assert( data != nullptr && "AudioManager::PauseVoice - handle has expired" );
if( data == nullptr )
return false;
// Stop the voice?
if( pause == true )
{
HRESULT hResult = data->voice->Stop( 0 );
if( FAILED( hResult ) )
{
// MESSAGE
char szBuffer[ 128 ];
_snprintf_s( szBuffer, 128, _TRUNCATE, "!!! AudioManager::PauseVoice - failed to stop voice (0x%X) !!!\n", hResult );
OutputDebugStringA( szBuffer );
return false;
}
}
else
{
HRESULT hResult = data->voice->Start( 0 );
if( FAILED( hResult ) )
{
// MESSAGE
char szBuffer[ 128 ];
_snprintf_s( szBuffer, 128, _TRUNCATE, "!!! AudioManager::PauseVoice - failed to start voice (0x%X) !!!\n", hResult );
OutputDebugStringA( szBuffer );
return false;
}
}
data->paused = pause;
return true;
}
//*************************************************************//
//*************************************************************//
// STOP VOICE
bool AudioManager::StopVoice( HVoice& handle )
{
// Sanity-check the wrapper's status
assert( m_eStatus == E_INITIALIZED && "AudioManager::StopVoice - wrapper has not been initialized" );
if( m_eStatus != E_INITIALIZED )
return false;
assert( handle != SGD::INVALID_HANDLE && "AudioManager::StopVoice - invalid handle" );
if( handle == SGD::INVALID_HANDLE )
return false;
// Get the voice info from the handle manager
VoiceInfo* data = m_VoiceManager.GetData( handle );
assert( data != nullptr && "AudioManager::StopVoice - handle has expired" );
if( data == nullptr )
return false;
// Stop the voice
HRESULT hResult = data->voice->Stop( 0 );
if( FAILED( hResult ) )
{
// MESSAGE
char szBuffer[ 128 ];
_snprintf_s( szBuffer, 128, _TRUNCATE, "!!! AudioManager::StopVoice - failed to stop voice (0x%X) !!!\n", hResult );
OutputDebugStringA( szBuffer );
return false;
}
// Destroy the voice
data->voice->DestroyVoice();
data->voice = nullptr;
// Find all voices with the audio handle
VoiceMap::_Paircc range = m_mVoices.equal_range( data->audio );
for( VoiceMap::const_iterator iter = range.first; iter != range.second; ++iter )
{
// Remove this voice handle
if( iter->second == handle )
{
m_mVoices.erase( iter );
break;
}
}
// Remove the voice info from the handle manager
m_VoiceManager.RemoveData( handle, nullptr );
// Invalidate the handle
handle = SGD::INVALID_HANDLE;
return true;
}
//*************************************************************//
//*************************************************************//
// GET VOICE VOLUME
int AudioManager::GetVoiceVolume( HVoice handle )
{
// Sanity-check the wrapper's status
assert( m_eStatus == E_INITIALIZED && "AudioManager::GetVoiceVolume - wrapper has not been initialized" );
if( m_eStatus != E_INITIALIZED )
return 0;
assert( handle != SGD::INVALID_HANDLE && "AudioManager::GetVoiceVolume - invalid handle" );
if( handle == SGD::INVALID_HANDLE )
return 0;
// Get the voice info from the handle manager
VoiceInfo* data = m_VoiceManager.GetData( handle );
assert( data != nullptr && "AudioManager::GetVoiceVolume - handle has expired" );
if( data == nullptr )
return 0;
// Scale 0 -> +100 (account for floating point error)
float fVolume = 0.0f;
data->voice->GetVolume( &fVolume );
return (int)(fVolume * 100.0f + 0.5f);
}
//*************************************************************//
//*************************************************************//
// SET VOICE VOLUME
bool AudioManager::SetVoiceVolume( HVoice handle, int value )
{
// Sanity-check the wrapper's status
assert( m_eStatus == E_INITIALIZED && "AudioManager::SetVoiceVolume - wrapper has not been initialized" );
if( m_eStatus != E_INITIALIZED )
return false;
assert( handle != SGD::INVALID_HANDLE && "AudioManager::SetVoiceVolume - invalid handle" );
if( handle == SGD::INVALID_HANDLE )
return false;
// Get the voice info from the handle manager
VoiceInfo* data = m_VoiceManager.GetData( handle );
assert( data != nullptr && "AudioManager::SetVoiceVolume - handle has expired" );
if( data == nullptr )
return false;
// Cap the range 0->100
if( value < 0 )
value = 0;
else if( value > 100 )
value = 100;
float fVolume = value / 100.0f; // scaled to 0 -> +1
HRESULT hResult = data->voice->SetVolume( fVolume );
if( FAILED( hResult ) )
return false;
return true;
}
//*************************************************************//
//*************************************************************//
// GET AUDIO VOLUME
int AudioManager::GetAudioVolume( HAudio handle )
{
// Sanity-check the wrapper's status
assert( m_eStatus == E_INITIALIZED && "AudioManager::GetAudioVolume - wrapper has not been initialized" );
if( m_eStatus != E_INITIALIZED )
return 0;
assert( handle != SGD::INVALID_HANDLE && "AudioManager::GetAudioVolume - invalid handle" );
if( handle == SGD::INVALID_HANDLE )
return 0;
// Get the audio info from the handle manager
AudioInfo* data = m_HandleManager.GetData( handle );
assert( data != nullptr && "AudioManager::GetAudioVolume - handle has expired" );
if( data == nullptr )
return 0;
// Scale 0 -> +100 (account for floating point error)
return (int)(data->fVolume * 100.0f + 0.5f);
}
//*************************************************************//
//*************************************************************//
// SET AUDIO ATTRIBUTE
bool AudioManager::SetAudioVolume( HAudio handle, int value )
{
// Sanity-check the wrapper's status
assert( m_eStatus == E_INITIALIZED && "AudioManager::SetAudioVolume - wrapper has not been initialized" );
if( m_eStatus != E_INITIALIZED )
return false;
assert( handle != SGD::INVALID_HANDLE && "AudioManager::SetAudioVolume - invalid handle" );
if( handle == SGD::INVALID_HANDLE )
return false;
// Get the audio info from the handle manager
AudioInfo* data = m_HandleManager.GetData( handle );
assert( data != nullptr && "AudioManager::SetAudioVolume - handle has expired" );
if( data == nullptr )
return false;
// Cap the range 0->100
if( value < 0 )
value = 0;
else if( value > 100 )
value = 100;
data->fVolume = value / 100.0f; // scaled to 0 -> +1
// Set active voices' volume
bool success = true;
std::pair< VoiceMap::const_iterator, VoiceMap::const_iterator > rangePair = m_mVoices.equal_range( handle );
for( VoiceMap::const_iterator iter = rangePair.first; iter != rangePair.second; ++iter )
{
// Get the voice info from the handle manager
VoiceInfo* info = m_VoiceManager.GetData( iter->second );
assert( info != nullptr && "AudioManager::SetAudioVolume - voice handle has expired" );
if( info == nullptr )
continue;
HRESULT hResult = info->voice->SetVolume( data->fVolume );
if( FAILED( hResult ) )
success = false;
}
return success;
}
//*************************************************************//
//*************************************************************//
// XAudio2 file input
// - MSDN http://msdn.microsoft.com/en-us/library/windows/desktop/ee415781%28v=vs.85%29.aspx
#ifdef _XBOX // Big-Endian
enum ECharacterCode
{
E_CC_RIFF = 'RIFF',
E_CC_DATA = 'data',
E_CC_FMT = 'fmt ',
E_CC_WAVE = 'WAVE',
E_CC_XWMA = 'XWMA',
E_CC_DPDS = 'dpds'
};
#else // Little-Endian
enum ECharacterCode
{
E_CC_RIFF = 'FFIR',
E_CC_DATA = 'atad',
E_CC_FMT = ' tmf',
E_CC_WAVE = 'EVAW',
E_CC_XWMA = 'AMWX',
E_CC_DPDS = 'sdpd'
};
#endif
/*static*/ HRESULT AudioManager::FindChunk( HANDLE hFile, DWORD fourcc, DWORD& dwChunkSize, DWORD& dwChunkDataPosition )
{
HRESULT hResult = S_OK;
if( INVALID_SET_FILE_POINTER == SetFilePointer( hFile, 0, NULL, FILE_BEGIN ) )
return HRESULT_FROM_WIN32( GetLastError() );
DWORD dwChunkType;
DWORD dwChunkDataSize;
DWORD dwRIFFDataSize = 0;
DWORD dwFileType;
DWORD bytesRead = 0;
DWORD dwOffset = 0;
while( hResult == S_OK )
{
DWORD dwRead;
if( 0 == ReadFile( hFile, &dwChunkType, sizeof(DWORD), &dwRead, NULL ) )
hResult = HRESULT_FROM_WIN32( GetLastError() );
if( 0 == ReadFile( hFile, &dwChunkDataSize, sizeof(DWORD), &dwRead, NULL ) )
hResult = HRESULT_FROM_WIN32( GetLastError() );
switch( dwChunkType )
{
case E_CC_RIFF:
dwRIFFDataSize = dwChunkDataSize;
dwChunkDataSize = 4;
if( 0 == ReadFile( hFile, &dwFileType, sizeof(DWORD), &dwRead, NULL ) )
hResult = HRESULT_FROM_WIN32( GetLastError() );
break;
default:
if( INVALID_SET_FILE_POINTER == SetFilePointer( hFile, dwChunkDataSize, NULL, FILE_CURRENT ) )
return HRESULT_FROM_WIN32( GetLastError() );
}
dwOffset += sizeof(DWORD) * 2;
if( dwChunkType == fourcc )
{
dwChunkSize = dwChunkDataSize;
dwChunkDataPosition = dwOffset;
return S_OK;
}
dwOffset += dwChunkDataSize;
if( bytesRead >= dwRIFFDataSize )
return S_FALSE;
}
return S_OK;
}
/*static*/ HRESULT AudioManager::ReadChunkData( HANDLE hFile, void* buffer, DWORD buffersize, DWORD bufferoffset )
{
HRESULT hResult = S_OK;
if( INVALID_SET_FILE_POINTER == SetFilePointer( hFile, bufferoffset, NULL, FILE_BEGIN ) )
return HRESULT_FROM_WIN32( GetLastError() );
DWORD dwRead;
if( 0 == ReadFile( hFile, buffer, buffersize, &dwRead, NULL ) )
hResult = HRESULT_FROM_WIN32( GetLastError() );
return hResult;
}
/*static*/ HRESULT AudioManager::LoadAudio( const wchar_t* filename, WAVEFORMATEXTENSIBLE& wfx, XAUDIO2_BUFFER& buffer, XAUDIO2_BUFFER_WMA& bufferWMA )
{
// Open the file
HANDLE hFile = CreateFileW( filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
if( hFile == INVALID_HANDLE_VALUE )
return HRESULT_FROM_WIN32( GetLastError() );
if( SetFilePointer( hFile, 0, NULL, FILE_BEGIN ) == INVALID_SET_FILE_POINTER )
return HRESULT_FROM_WIN32( GetLastError() );
// Check the file type, should be 'WAVE' or 'XWMA'
DWORD dwChunkSize;
DWORD dwChunkPosition;
FindChunk( hFile, E_CC_RIFF, dwChunkSize, dwChunkPosition );
DWORD filetype;
ReadChunkData( hFile, &filetype, sizeof(DWORD), dwChunkPosition );
if( filetype == E_CC_WAVE || filetype == E_CC_XWMA )
{
// Fill out the WAVEFORMATEXTENSIBLE structure with the contents of the FMT chunk.
FindChunk( hFile, E_CC_FMT, dwChunkSize, dwChunkPosition );
ReadChunkData( hFile, &wfx, dwChunkSize, dwChunkPosition );
// Read the contents of the DATA chunk into the audio data buffer
FindChunk( hFile, E_CC_DATA, dwChunkSize, dwChunkPosition );
BYTE* pDataBuffer = new BYTE[ dwChunkSize ];
ReadChunkData( hFile, pDataBuffer, dwChunkSize, dwChunkPosition );
// Fill the XAUDIO2_BUFFER
buffer.AudioBytes = dwChunkSize; // size of the audio buffer in bytes
buffer.pAudioData = pDataBuffer; // buffer containing audio data
buffer.Flags = XAUDIO2_END_OF_STREAM; // tell the source voice not to expect any data after this buffer
// Fill the wma buffer if necessary
if( filetype == E_CC_XWMA )
{
// Read the contents of the DPDS chunk into the wma data buffer
FindChunk( hFile, E_CC_DPDS, dwChunkSize, dwChunkPosition );
UINT32 nPackets = (dwChunkSize + (sizeof(UINT32)-1)) / sizeof(UINT32); // round size to number of DWORDS
UINT32* pWmaDataBuffer = new UINT32[ nPackets ];
ReadChunkData( hFile, pWmaDataBuffer, dwChunkSize, dwChunkPosition );
// Fill the XAUDIO2_BUFFER_WMA
bufferWMA.PacketCount = nPackets; // size of the audio buffer in DWORDS
bufferWMA.pDecodedPacketCumulativeBytes = pWmaDataBuffer; // buffer containing wma data
}
return S_OK;
}
else
{
return E_UNEXPECTED;
}
}
//*************************************************************//
//*************************************************************//
// FIND AUDIO BY NAME
/*static*/ bool AudioManager::FindAudioByName( Handle handle, AudioInfo& data, SearchInfo* extra )
{
// Compare the names
if( wcscmp( data.wszFilename, extra->filename ) == 0 )
{
// Audio does exist!
extra->audio = &data;
extra->handle = handle;
return false;
}
// Did not find yet
return true;
}
//*************************************************************//
} // namespace SGD_IMPLEMENTATION
} // namespace SGD
| Poofyfancypants/Destiny-Falls | DestinyFalls/SGD Wrappers/SGD_AudioManager.cpp | C++ | mit | 40,414 |
<?php
/** Tabbed Pane.
*
* Copyright (c) 2008 Oliver C Dodd
*
* 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.
*/
def('pTABS', '');
def('REQUEST_ID', 'tp');
class TabbedPane
{
/*--------------------------------------------------------------------*\
|* CONSTANTS *|
\*--------------------------------------------------------------------*/
static $lasKeyIndex = 0;
/*--------------------------------------------------------------------*\
|* VARIABLES *|
\*--------------------------------------------------------------------*/
public $id;
public $label;
public $file;
public $keyIndex;
private $className;
/*--------------------------------------------------------------------*\
|* CONSTRUCTOR *|
\*--------------------------------------------------------------------*/
public function __construct($id,$label,$file=null,$keyIndex=null)
{
$this->id = $id;
$this->label = $label;
$this->file = $file === null ? pTABS."$id.php" : $file;
$this->keyIndex = $keyIndex === null
? ++self::$lasKeyIndex
: $keyIndex;
}
/*--------------------------------------------------------------------*\
|* DISPLAY *|
\*--------------------------------------------------------------------*/
public function tab($group="")
{
$cl = get_class($this);
return "<div id='tab$this->id'
class='$cl tab $group $this->id'
onclick='$cl$group.change(\"$this->id\");'>
$this->label
</div>";
}
public function pane($group="")
{
$cl = get_class($this);
$content = Filesystem::includeContents($this->file);
return "<div id='pane$this->id'
class='$cl pane $group $this->id'
style='display:none;'>
$content
</div>";
}
/*--------------------------------------------------------------------*\
|* TABS/PANES *|
\*--------------------------------------------------------------------*/
public static function tabs($tabbedPanes,$group="")
{
$tabs = "";
foreach ($tabbedPanes as $tp)
$tabs .= $tp->tab($group);
return $tabs;
}
public static function panes($tabbedPanes,$group="",$registerKeys=true)
{
$panes = "";
$default = isset($_REQUEST[REQUEST_ID])&&
isset($tabbedPanes[$_REQUEST[REQUEST_ID]])
? $tabbedPanes[$_REQUEST[REQUEST_ID]]
: current($tabbedPanes);
foreach ($tabbedPanes as $tp)
$panes .= $tp->pane($group);
if ($registerKeys) {
$registerKeys = array();
foreach ($tabbedPanes as $t)
$registerKeys[$t->keyIndex] = $t->id;
}
return $panes.self::js($default,$group,$registerKeys);
}
/*--------------------------------------------------------------------*\
|* JAVASCRIPT *|
\*--------------------------------------------------------------------*/
protected static function js($default=null,$group="",$registerKeys=true)
{
$class = __CLASS__;
$c = $class.$group;
ob_start();
?>
<script type="text/javascript">
<?php echo $c; ?> = {
/*-VARIABLES/CONSTANTS----------------------------------------*/
className: "<?php echo $class; ?>",
group: "<?php echo $group; ?>",
tabs: <?php echo json_encode($registerKeys); ?>,
/*-CHANGE TAB-------------------------------------------------*/
change: function(id)
{
this.stripActive();
this.setActive(id);
this.hidePanes();
this.showPane(id);
<?php if (_::C('GOOGLE_ANALYTICS')) echo "
try { var t = _gat._getTracker('"._::C('GOOGLE_ANALYTICS')."');
t._initData();
t._trackEvent('tab', id);
} catch(e) {}";
?>
},
/*-ACTIVE TAB-------------------------------------------------*/
stripActive: function()
{
var e = $$("."+this.className+"."+this.group);
for (var i = 0; i < e.length; i++)
e[i].removeClassName("active");
},
setActive: function(id)
{
$("tab"+id).addClassName("active");
$("pane"+id).addClassName("active");
},
/*-SHOW/HIDE--------------------------------------------------*/
hidePanes: function()
{
var e = $$("."+this.className+".pane."+this.group);
for (var i = 0; i < e.length; i++)
e[i].hide();
},
showPane: function(id)
{
$("pane"+id).show();
},
/*-KEY SWITCH-------------------------------------------------*/
keySwitch: function(e)
{
if (!e.altKey) return;
var key = String.fromCharCode(
(typeof e.which != "undefined")
? e.which
: e.keyCode);
if (this.tabs[key] != undefined)
this.change(this.tabs[key]);
}
};
<?php if ($default !== null) { ?>
<?php echo $c; ?>.change(<?php echo "'$default->id','$group','$class'"; ?>);
<?php } ?>
<?php if ($registerKeys) { ?>
Event.observe(window,"keydown",<?php echo $c; ?>.keySwitch.bind(<?php echo $c; ?>));
Event.observe(document.body,"keydown",<?php echo $c; ?>.keySwitch.bind(<?php echo $c; ?>));
<?php } ?>
</script>
<?php
$js = ob_get_contents();
ob_end_clean();
return $js;
}
}
?> | oliverdodd/0 | components/php/TabbedPane.php | PHP | mit | 6,362 |
const DateTime = Jymfony.Component.DateTime.DateTime;
const DateTimeZone = Jymfony.Component.DateTime.DateTimeZone;
const TimeSpan = Jymfony.Component.DateTime.TimeSpanInterface;
const { expect } = require('chai');
describe('[DateTime] DateTime', function () {
it('should accept string on construction', () => {
const dt = new DateTime('2017-03-24T00:00:00', 'Etc/UTC');
expect(dt).to.be.instanceOf(DateTime);
});
it('should accept unix timestamp on construction', () => {
const dt = new DateTime(1490313600, 'Etc/UTC');
expect(dt).to.be.instanceOf(DateTime);
});
it('should accept a js Date object on construction', () => {
const date = new Date(1490313600000);
const dt = new DateTime(date, 'Etc/UTC');
expect(dt).to.be.instanceOf(DateTime);
expect(dt.year).to.be.equal(2017);
expect(dt.month).to.be.equal(3);
expect(dt.day).to.be.equal(24);
expect(dt.hour).to.be.equal(0);
expect(dt.minute).to.be.equal(0);
expect(dt.second).to.be.equal(0);
expect(dt.millisecond).to.be.equal(0);
});
it('today should set time to midnight', () => {
const dt = DateTime.today;
expect(dt.hour).to.be.equal(0);
expect(dt.minute).to.be.equal(0);
expect(dt.second).to.be.equal(0);
expect(dt.millisecond).to.be.equal(0);
});
it('yesterday should set time to midnight', () => {
const dt = DateTime.yesterday;
expect(dt.hour).to.be.equal(0);
expect(dt.minute).to.be.equal(0);
expect(dt.second).to.be.equal(0);
expect(dt.millisecond).to.be.equal(0);
});
let tests = [
[ '2017-01-01T00:00:00', 'P-1D', '2016-12-31T00:00:00+0000' ],
[ '2016-12-31T00:00:00', 'P+1D', '2017-01-01T00:00:00+0000' ],
[ '2016-11-30T00:00:00', 'P+1D', '2016-12-01T00:00:00+0000' ],
[ '2017-01-01T00:00:00', 'P-1Y', '2016-01-01T00:00:00+0000' ],
[ '2016-02-29T00:00:00', 'P-1Y', '2015-02-28T00:00:00+0000' ],
];
for (const t of tests) {
it('add timespan should work correctly', () => {
const [ date, span, expected ] = t;
let dt = new DateTime(date);
dt = dt.modify(new TimeSpan(span));
expect(dt.toString()).to.be.equal(expected);
});
}
it('createFromFormat should correctly parse a date', () => {
const dt = DateTime.createFromFormat(DateTime.RFC2822, 'Wed, 20 Jun 2018 10:19:32 GMT');
expect(dt.toString()).to.be.equal('2018-06-20T10:19:32+0000');
});
tests = [
[ '2020 mar 29 01:00 Europe/Rome', 3600, 1, 0 ],
[ '2020 mar 29 02:00 Europe/Rome', 7200, 3, 0 ],
[ '2020 mar 29 03:00 Europe/Rome', 7200, 3, 0 ],
[ '2020 mar 29 04:00 Europe/Rome', 7200, 4, 0 ],
[ '2020 may 04 02:00 Europe/Rome', 7200, 2, 0 ],
];
for (const index of tests.keys()) {
const t = tests[index];
it('should correctly handle timezone transitions #'+index, () => {
const dt = new DateTime(t[0]);
expect(dt.timezone).to.be.instanceOf(DateTimeZone);
expect(dt.timezone.getOffset(dt)).to.be.equal(t[1]);
expect(dt.hour).to.be.equal(t[2]);
expect(dt.minute).to.be.equal(t[3]);
});
}
it('should correctly handle timezone transitions on modify', () => {
let dt = new DateTime('2020 mar 29 01:59:59 Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
dt = dt.modify(new TimeSpan('PT1S'));
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.hour).to.be.equal(3);
expect(dt.minute).to.be.equal(0);
});
it('should correctly handle between rules', () => {
let dt = new DateTime('1866 dec 11 00:00 Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(2996);
dt = new DateTime('1866 dec 11 23:59:59 Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(2996);
expect(dt.toString()).to.be.equal('1866-12-11T23:59:59+0049');
dt = dt.modify(new TimeSpan('PT1S'));
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(2996);
expect(dt.hour).to.be.equal(0);
expect(dt.minute).to.be.equal(0);
dt = new DateTime('1893 Oct 31 23:49:55', 'Europe/Rome');
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(2996);
expect(dt.day).to.be.equal(31);
expect(dt.hour).to.be.equal(23);
expect(dt.minute).to.be.equal(49);
expect(dt.second).to.be.equal(55);
dt = dt.modify(new TimeSpan('PT1S'));
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
expect(dt.hour).to.be.equal(0);
expect(dt.minute).to.be.equal(0);
expect(dt.second).to.be.equal(0);
dt = new DateTime('1916 Jun 3 23:59:59', 'Europe/Rome');
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
expect(dt.hour).to.be.equal(23);
expect(dt.minute).to.be.equal(59);
expect(dt.second).to.be.equal(59);
dt = dt.modify(new TimeSpan('PT1S'));
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.month).to.be.equal(6);
expect(dt.day).to.be.equal(4);
expect(dt.hour).to.be.equal(1);
expect(dt.minute).to.be.equal(0);
expect(dt.second).to.be.equal(0);
dt = new DateTime('2020 Oct 25 01:59:59', 'Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.hour).to.be.equal(1);
expect(dt.minute).to.be.equal(59);
expect(dt.second).to.be.equal(59);
dt = dt.modify(new TimeSpan('PT1H'));
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.hour).to.be.equal(2);
expect(dt.minute).to.be.equal(59);
expect(dt.second).to.be.equal(59);
dt = dt.modify(new TimeSpan('PT1S'));
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
expect(dt.hour).to.be.equal(2);
expect(dt.minute).to.be.equal(0);
expect(dt.second).to.be.equal(0);
dt = new DateTime('2020 Oct 25 01:59:59', 'Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
dt = dt.modify(new TimeSpan('P1D'));
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
expect(dt.timestamp).to.be.equal(1603673999);
expect(dt.hour).to.be.equal(1);
expect(dt.minute).to.be.equal(59);
expect(dt.second).to.be.equal(59);
dt = dt.modify(new TimeSpan('P-1D'));
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.timestamp).to.be.equal(1603583999);
expect(dt.hour).to.be.equal(1);
expect(dt.minute).to.be.equal(59);
expect(dt.second).to.be.equal(59);
dt = dt.modify(new TimeSpan('P1M'));
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
expect(dt.timestamp).to.be.equal(1606265999);
expect(dt.hour).to.be.equal(1);
expect(dt.minute).to.be.equal(59);
expect(dt.second).to.be.equal(59);
expect(dt.day).to.be.equal(25);
expect(dt.month).to.be.equal(11);
expect(dt.year).to.be.equal(2020);
dt = dt.modify(new TimeSpan('P-1M'));
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.timestamp).to.be.equal(1603583999);
dt = dt.modify(new TimeSpan('P1Y'));
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.timestamp).to.be.equal(1635119999);
expect(dt.hour).to.be.equal(1);
expect(dt.minute).to.be.equal(59);
expect(dt.second).to.be.equal(59);
expect(dt.day).to.be.equal(25);
expect(dt.month).to.be.equal(10);
expect(dt.year).to.be.equal(2021);
dt = dt.modify(new TimeSpan('P7D'));
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
expect(dt.timestamp).to.be.equal(1635728399);
dt = dt.modify(new TimeSpan('P-1Y7D'));
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.timestamp).to.be.equal(1603583999);
});
it ('invalid times for timezone', () => {
let dt = new DateTime('1893 Oct 31 23:49:58', 'Europe/Rome');
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
expect(dt.year).to.be.equal(1893);
expect(dt.month).to.be.equal(11);
expect(dt.day).to.be.equal(1);
expect(dt.hour).to.be.equal(0);
expect(dt.minute).to.be.equal(0);
expect(dt.second).to.be.equal(2);
dt = new DateTime('2020 mar 29 02:01:00 Europe/Rome');
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.hour).to.be.equal(3);
expect(dt.minute).to.be.equal(1);
});
});
| alekitto/jymfony | src/Component/DateTime/test/DateTimeTest.js | JavaScript | mit | 9,292 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace abbTools
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new windowMain());
}
}
}
| piopon/abb-tools | abbTools/Program.cs | C# | mit | 514 |
class ParticipantInvitation < ActiveRecord::Base
include Invitable
before_create :generate_token
belongs_to :event
validates_uniqueness_of :email, scope: :event
def create_participant(person)
event.participants.create(person: person, role: role)
end
private
def generate_token
self.token = Digest::SHA1.hexdigest(Time.now.to_s + email + rand(1000).to_s)
end
end
# == Schema Information
#
# Table name: participant_invitations
#
# id :integer not null, primary key
# email :string
# state :string
# slug :string
# role :string
# token :string
# event_id :integer
# created_at :datetime
# updated_at :datetime
#
| jsis/cfp.jsconf.is | app/models/participant_invitation.rb | Ruby | mit | 698 |
package com.imrenagi.service_auth.service.security;
import com.imrenagi.service_auth.AuthApplication;
import com.imrenagi.service_auth.domain.User;
import com.imrenagi.service_auth.repository.UserRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
/**
* Created by imrenagi on 5/14/17.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = AuthApplication.class)
@WebAppConfiguration
public class MysqlUserDetailsServiceTest {
@InjectMocks
private MysqlUserDetailsService userDetailsService;
@Mock
private UserRepository repository;
@Before
public void setup() {
initMocks(this);
}
@Test
public void shouldReturnUserDetailWhenAUserIsFound() throws Exception {
final User user = new User("imrenagi", "1234", "imre", "nagi");
doReturn(user).when(repository).findByUsername(user.getUsername());
UserDetails found = userDetailsService.loadUserByUsername(user.getUsername());
assertEquals(user.getUsername(), found.getUsername());
assertEquals(user.getPassword(), found.getPassword());
verify(repository, times(1)).findByUsername(user.getUsername());
}
@Test
public void shouldFailWhenUserIsNotFound() throws Exception {
doReturn(null).when(repository).findByUsername(anyString());
try {
userDetailsService.loadUserByUsername(anyString());
fail();
} catch (Exception e) {
}
}
} | imrenagi/microservice-skeleton | service-auth/src/test/java/com/imrenagi/service_auth/service/security/MysqlUserDetailsServiceTest.java | Java | mit | 2,072 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package net.daw.bean;
import com.google.gson.annotations.Expose;
/**
*
* @author rafa
*/
public class Element implements IElement {
@Expose
private String tag;
// @Expose
// private String name;
@Expose
private String id;
@Expose
private String clase;
@Override
public String getTag() {
return tag;
}
@Override
public void setTag(String tag) {
this.tag = tag;
}
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public void setName(String name) {
// this.name = name;
// }
@Override
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
@Override
public String getTagClass() {
return clase;
}
@Override
public void setTagClass(String clase) {
this.clase = clase;
}
}
| Josecho93/ExamenCliente | src/main/java/net/daw/bean/Element.java | Java | mit | 1,120 |
package org.vitrivr.cineast.api.rest.handlers.actions.metadata;
import io.javalin.http.Context;
import io.javalin.plugin.openapi.dsl.OpenApiBuilder;
import io.javalin.plugin.openapi.dsl.OpenApiDocumentation;
import java.util.Map;
import org.vitrivr.cineast.api.messages.result.MediaObjectMetadataQueryResult;
import org.vitrivr.cineast.api.rest.OpenApiCompatHelper;
import org.vitrivr.cineast.api.rest.handlers.interfaces.GetRestHandler;
import org.vitrivr.cineast.api.rest.services.MetadataRetrievalService;
/**
* This class handles GET requests with an object id, domain and key and returns all matching metadata descriptors.
* <p>
* <h3>GET</h3>
* This action's resource should have the following structure: {@code find/metadata/of/:id/in/:domain/with/:key}. It returns then all metadata of the object with this id, belonging to that domain with the specified key.
* </p>
*/
public class FindObjectMetadataFullyQualifiedGetHandler implements
GetRestHandler<MediaObjectMetadataQueryResult> {
public static final String OBJECT_ID_NAME = "id";
public static final String DOMAIN_NAME = "domain";
public static final String KEY_NAME = "key";
public static final String ROUTE = "find/metadata/of/{" + OBJECT_ID_NAME + "}/in/{" + DOMAIN_NAME + "}/with/{" + KEY_NAME + "}";
@Override
public MediaObjectMetadataQueryResult doGet(Context ctx) {
final Map<String, String> parameters = ctx.pathParamMap();
final String objectId = parameters.get(OBJECT_ID_NAME);
final String domain = parameters.get(DOMAIN_NAME);
final String key = parameters.get(KEY_NAME);
final MetadataRetrievalService service = new MetadataRetrievalService();
return new MediaObjectMetadataQueryResult("", service.find(objectId, domain, key)
);
}
public OpenApiDocumentation docs() {
return OpenApiBuilder.document()
.operation(op -> {
op.description("The description");
op.summary("Find metadata for specific object id in given domain with given key");
op.addTagsItem(OpenApiCompatHelper.METADATA_OAS_TAG);
op.operationId("findMetaFullyQualified");
})
.pathParam(OBJECT_ID_NAME, String.class, param -> {
param.description("The object id");
})
.pathParam(DOMAIN_NAME, String.class, param -> {
param.description("The domain name");
})
.pathParam(KEY_NAME, String.class, param -> param.description("Metadata key"))
.json("200", outClass());
}
@Override
public String route() {
return ROUTE;
}
@Override
public Class<MediaObjectMetadataQueryResult> outClass() {
return MediaObjectMetadataQueryResult.class;
}
/* TODO Actually, there is a lot of refactoring potential in this entire package */
}
| vitrivr/cineast | cineast-api/src/main/java/org/vitrivr/cineast/api/rest/handlers/actions/metadata/FindObjectMetadataFullyQualifiedGetHandler.java | Java | mit | 2,769 |
require 'fileutils'
module TwitterSms
class Logger
def initialize(filename,log_size=5)
@log_size=log_size
@raw_filename = filename
@file = File.new(filename, "a") # 2x check mode
write_intro
end
def log(message)
@file.puts("#{Time.now.strftime("(%b %d - %H:%M:%S)")} #{message}")
if `du -sm #{@raw_filename}`.split[0].to_i > @log_size #mb
remake_file
end
end
private
def write_intro
str = "Twitter-sms log file of messages since #{Time.now}"
@file.puts(str)
end
def remake_file
FileUtils.rm @raw_filename
initialize
end
end
end
| rkneufeld/twitter-sms | lib/twitter-sms/logger.rb | Ruby | mit | 648 |
using System;
using System.Data;
using Signum.Utilities;
using Signum.Engine.Maps;
using System.IO;
using System.Data.Common;
using System.Linq.Expressions;
using Signum.Entities;
using Signum.Utilities.Reflection;
using System.Reflection;
using System.Threading.Tasks;
using System.Threading;
using System.Data.SqlClient;
using System.Collections.Generic;
namespace Signum.Engine
{
public abstract class Connector
{
static readonly Variable<Connector> currentConnector = Statics.ThreadVariable<Connector>("connection");
public SqlBuilder SqlBuilder;
public static IDisposable Override(Connector connector)
{
Connector oldConnection = currentConnector.Value;
currentConnector.Value = connector;
return new Disposable(() => currentConnector.Value = oldConnection);
}
public static Connector Current
{
get { return currentConnector.Value ?? Default; }
}
public static Connector Default { get; set; } = null!;
static readonly Variable<int?> scopeTimeout = Statics.ThreadVariable<int?>("scopeTimeout");
public static int? ScopeTimeout { get { return scopeTimeout.Value; } }
public static IDisposable CommandTimeoutScope(int? timeoutSeconds)
{
var old = scopeTimeout.Value;
scopeTimeout.Value = timeoutSeconds;
return new Disposable(() => scopeTimeout.Value = old);
}
public Connector(Schema schema)
{
this.Schema = schema;
this.IsolationLevel = IsolationLevel.Unspecified;
this.SqlBuilder = new SqlBuilder(this);
}
public Schema Schema { get; private set; }
static readonly Variable<TextWriter?> logger = Statics.ThreadVariable<TextWriter?>("connectionlogger");
public static TextWriter? CurrentLogger
{
get { return logger.Value; }
set { logger.Value = value; }
}
protected static void Log(SqlPreCommandSimple pcs)
{
var log = logger.Value;
if (log != null)
{
log.WriteLine(pcs.Sql);
if (pcs.Parameters != null)
log.WriteLine(pcs.Parameters
.ToString(p => "{0} {1}: {2}".FormatWith(
p.ParameterName,
Connector.Current.GetSqlDbType(p),
p.Value?.Let(v => v.ToString())), "\r\n"));
log.WriteLine();
}
}
public abstract string GetSqlDbType(DbParameter p);
protected internal abstract object? ExecuteScalar(SqlPreCommandSimple preCommand, CommandType commandType);
protected internal abstract int ExecuteNonQuery(SqlPreCommandSimple preCommand, CommandType commandType);
protected internal abstract DataTable ExecuteDataTable(SqlPreCommandSimple preCommand, CommandType commandType);
protected internal abstract DbDataReaderWithCommand UnsafeExecuteDataReader(SqlPreCommandSimple preCommand, CommandType commandType);
protected internal abstract Task<DbDataReaderWithCommand> UnsafeExecuteDataReaderAsync(SqlPreCommandSimple preCommand, CommandType commandType, CancellationToken token);
protected internal abstract void BulkCopy(DataTable dt, List<IColumn> columns, ObjectName destinationTable, SqlBulkCopyOptions options, int? timeout);
public abstract Connector ForDatabase(Maps.DatabaseName? database);
public abstract string DatabaseName();
public abstract string DataSourceName();
public abstract int MaxNameLength { get; }
public abstract void SaveTransactionPoint(DbTransaction transaction, string savePointName);
public abstract void RollbackTransactionPoint(DbTransaction Transaction, string savePointName);
public abstract DbParameter CloneParameter(DbParameter p);
public abstract DbConnection CreateConnection();
public IsolationLevel IsolationLevel { get; set; }
public abstract ParameterBuilder ParameterBuilder { get; protected set; }
public abstract void CleanDatabase(DatabaseName? database);
public abstract bool AllowsMultipleQueries { get; }
public abstract bool SupportsScalarSubquery { get; }
public abstract bool SupportsScalarSubqueryInAggregates { get; }
public static string? TryExtractDatabaseNameWithPostfix(ref string connectionString, string catalogPostfix)
{
string toFind = "+" + catalogPostfix;
string? result = connectionString.TryBefore(toFind).TryAfterLast("=");
if (result == null)
return null;
connectionString = connectionString.Replace(toFind, ""); // Remove toFind
return result + catalogPostfix;
}
public static string ExtractCatalogPostfix(ref string connectionString, string catalogPostfix)
{
string toFind = "+" + catalogPostfix;
int index = connectionString.IndexOf(toFind);
if (index == -1)
throw new InvalidOperationException("CatalogPostfix '{0}' not found in the connection string".FormatWith(toFind));
connectionString = connectionString.Substring(0, index) + connectionString.Substring(index + toFind.Length); // Remove toFind
return catalogPostfix;
}
public abstract bool AllowsSetSnapshotIsolation { get; }
public abstract bool AllowsIndexWithWhere(string where);
public abstract bool AllowsConvertToDate { get; }
public abstract bool AllowsConvertToTime { get; }
public abstract bool SupportsSqlDependency { get; }
public abstract bool SupportsFormat { get; }
public abstract bool SupportsTemporalTables { get; }
public abstract bool RequiresRetry { get; }
}
public abstract class ParameterBuilder
{
public static string GetParameterName(string name)
{
return "@" + name;
}
public DbParameter CreateReferenceParameter(string parameterName, PrimaryKey? id, IColumn column)
{
return CreateParameter(parameterName, column.DbType, null, column.Nullable.ToBool(), id == null ? null : id.Value.Object);
}
public DbParameter CreateParameter(string parameterName, object? value, Type type)
{
var pair = Schema.Current.Settings.GetSqlDbTypePair(type.UnNullify());
return CreateParameter(parameterName, pair.DbType, pair.UserDefinedTypeName, type == null || type.IsByRef || type.IsNullable(), value);
}
public abstract DbParameter CreateParameter(string parameterName, AbstractDbType dbType, string? udtTypeName, bool nullable, object? value);
public abstract MemberInitExpression ParameterFactory(Expression parameterName, AbstractDbType dbType, string? udtTypeName, bool nullable, Expression value);
protected static MethodInfo miAsserDateTime = ReflectionTools.GetMethodInfo(() => AssertDateTime(null));
protected static DateTime? AssertDateTime(DateTime? dateTime)
{
if (Schema.Current.TimeZoneMode == TimeZoneMode.Utc && dateTime.HasValue && dateTime.Value.Kind != DateTimeKind.Utc)
throw new InvalidOperationException("Attempt to use a non-Utc date in the database");
return dateTime;
}
}
public class DbDataReaderWithCommand : IDisposable
{
public DbDataReaderWithCommand(DbCommand command, DbDataReader reader)
{
Command = command;
Reader = reader;
}
public DbCommand Command { get; private set; }
public DbDataReader Reader { get; private set; }
public void Dispose()
{
Reader.Dispose();
}
}
}
| avifatal/framework | Signum.Engine/Connection/Connector.cs | C# | mit | 8,153 |
<?php
declare(strict_types=1);
namespace Fc2blog\Model;
class Validate
{
/**
* 必須チェック
* @param $value
* @param bool $isNeed true/false
* @return bool|string True is valid, string is some error message.
*/
public static function required($value, bool $isNeed)
{
if ($value == null || $value === '') {
// データが存在しない場合
if ($isNeed === false) {
return false;
}
return __('Please be sure to input');
}
// データが存在する場合 Validate処理を続ける
return true;
}
/**
* 数値チェック
* @param int|string $value
* @param array $options
* @return bool|string True is valid, string is some error message.
*/
public static function numeric($value, array $options)
{
$tmp = intval($value);
if ((string)$tmp === (string)$value) {
return true;
}
return $options['message'] ?? __('Please enter a number');
}
/**
* 半角英数チェック
* @param string $value
* @param array $options
* @return bool|string True is valid, string is some error message.
*/
public static function alphanumeric(string $value, array $options)
{
if (preg_match("/^[a-zA-Z0-9]+$/", $value)) {
return true;
}
return $options['message'] ?? __('Please enter alphanumeric');
}
/**
* 最大文字列チェック
* @param ?string $value (comment編集で、NULLがくることがある)
* @param array $options [*max] 最大文字列
* @return bool|string True is valid, string is some error message.
*/
public static function maxlength(?string $value, array $options)
{
if (mb_strlen((string)$value, 'UTF-8') <= $options['max']) {
return true;
}
$message = $options['message'] ?? __('Please enter at %d characters or less');
return sprintf($message, $options['max']);
}
/**
* 最小文字列チェック
* @param string|null $value
* @param array $options [*min] 最小文字列
* @return bool|string True is valid, string is some error message.
*/
public static function minlength(?string $value, array $options)
{
if (mb_strlen((string)$value, 'UTF-8') >= $options['min']) {
return true;
}
$message = $options['message'] ?? __('Please enter at %d characters or more');
return sprintf($message, $options['min']);
}
/**
* 最大値チェック
* @param int|string $value
* @param array $options [*max] 最大値
* @return bool|string True is valid, string is some error message.
*/
public static function max($value, array $options)
{
if ($value <= $options['max']) {
return true;
}
$message = $options['message'] ?? __('Please enter a value of %d or less');
return sprintf($message, $options['max']);
}
/**
* 最小値チェック
* @param int|string $value
* @param array $options [*min] 最小値
* @return bool|string True is valid, string is some error message.
*/
public static function min($value, array $options)
{
if ($value >= $options['min']) {
return true;
}
$message = $options['message'] ?? __('Please enter a value of %d or more');
return sprintf($message, $options['min']);
}
/**
* 日時チェック
* @param string $value
* @param array $options
* @return bool|string True is valid, string is some error message.
*/
public static function datetime(string $value, array $options)
{
$format = $options['format'] ?? '%Y-%m-%d %H:%M:%S';
if (strptime($value, $format) === false || strtotime($value) === false) {
return $options['message'] ?? __('Please enter the date and time');
}
return true;
}
/**
* メールアドレスチェック
* @param string $value
* @param array $options
* @return bool|string True is valid, string is some error message.
*/
public static function email(string $value, array $options)
{
/** @noinspection Annotator */
/** @noinspection RegExpUnnecessaryNonCapturingGroup */
/** @noinspection RegExpRedundantEscape */
/** @noinspection RegExpUnexpectedAnchor */
if (preg_match('/^(?:(?:(?:(?:[a-zA-Z0-9_!#\$\%&\'*+\/=?\^`{}~|\-]+)(?:\.(?:[a-zA-Z0-9_!#\$\%&\'*+\/=?\^`{}~|\-]+))*)|(?:"(?:\\[^\r\n]|[^\\"])*")))\@(?:(?:(?:(?:[a-zA-Z0-9_!#\$\%&\'*+\/=?\^`{}~|\-]+)(?:\.(?:[a-zA-Z0-9_!#\$\%&\'*+\/=?\^`{}~|\-]+))*)|(?:\[(?:\\\S|[\x21-\x5a\x5e-\x7e])*\])))$/', $value)) {
return true;
}
return $options['message'] ?? __('Please enter your e-mail address');
}
/**
* URLチェック
* @param string $value
* @param array $options
* @return bool|string True is valid, string is some error message.
*/
public static function url(string $value, array $options)
{
if (preg_match('/^(https?|ftp)(:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:@&=+\$,%#]+)$/', $value)) {
return true;
}
return $options['message'] ?? __('Please enter the URL');
}
/**
* ユニークチェック
* @param $value
* @param array $options
* @param string $key
* @param $data
* @param $model
* @return bool|string True is valid, string is some error message.
*/
public static function unique($value, array $options, string $key, $data, $model)
{
if (!$model->isExist(array('where' => $key . '=?', 'params' => array($value)))) {
return true;
}
return $options['message'] ?? __('Is already in use');
}
/**
* 配列に存在する値かチェック
* @param $value
* @param array $options
* @return bool|string True is valid, string is some error message.
*/
public static function in_array($value, array $options)
{
if (is_scalar($value)) {
$tmp = array_flip($options['values']);
if (isset($tmp[$value])) {
return true;
}
}
return $options['message'] ?? __('Value that does not exist has been entered');
}
/**
* Fileチェック
* @param array $value
* @param array $option
* @return bool|string True is valid, string is some error message.
*/
public static function file(array $value, array $option)
{
switch ($value['error']) {
case UPLOAD_ERR_OK:
break; // OK
case UPLOAD_ERR_NO_FILE:
if (empty($option['required'])) {
return false;
}
return __('Please upload a file');
case UPLOAD_ERR_INI_SIZE: // php.ini定義の最大サイズ超過
case UPLOAD_ERR_FORM_SIZE: // フォーム定義の最大サイズ超過
return __('File size is too large');
default: // 以外のエラー
return __('I failed to file upload');
}
// mimetype取得チェック
if (!empty($option['mime_type'])) {
if (function_exists('finfo_file') && defined('FILEINFO_MIME_TYPE')) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $value['tmp_name']);
finfo_close($finfo);
} else if (function_exists('mime_content_type')) {
// 非推奨
$mime_type = mime_content_type($value['tmp_name']);
} else {
// 調べる関数がライブラリに存在しない
return __('It was not possible to determine the mime type of the file');
}
if (!in_array($mime_type, $option['mime_type'])) {
return __('File format is different');
}
}
// sizeチェック
if (isset($option['size']) && $value['size'] > $option['size']) {
return __('File size is too large');
}
return true;
}
/**
* 独自チェック
* @param $value
* @param array $option
* @param string $key
* @param $data
* @param $model
* @return mixed
*/
public static function own(&$value, array $option, string $key, $data, $model)
{
$method = $option['method'];
return $model->$method($value, $option, $key, $data, $model);
}
/**
* 配列チェック関数
* @param $values
* @param array $valid
* @param $k
* @param $d
* @param $model
* @return mixed
*/
public static function multiple(&$values, array $valid, $k, $d, $model): bool
{
if (!is_array($values)) {
$values = array();
}
foreach ($valid as $mKey => $options) {
$method = is_array($options) && isset($options['rule']) ? $options['rule'] : $mKey;
foreach ($values as $key => $value) {
$error = Validate::$method($value, $options, $key, $values, $model);
if ($error === false) {
break;
}
if (getType($error) === 'string') {
return $error;
}
}
}
return true;
}
/**
* 空白除去処理
* @param string $value
* @return bool
*/
public static function trim(string &$value): bool
{
if (is_string($value)) {
$value = preg_replace("/(^\s+)|(\s+$)/us", "", $value);
}
return true;
}
/**
* int型に変換
* @param string|int $value
* @return bool
*/
public static function int(&$value): bool
{
$value = intval($value);
return true;
}
/**
* 小文字に変換
* @param string $value
* @return bool
*/
public static function strtolower(string &$value): bool
{
$value = strtolower($value);
return true;
}
/**
* 配列内重複排除
* @param $values
* @param bool $options
* @return bool
*/
public static function array_unique(&$values, bool $options): bool
{
if (!is_array($values)) {
$values = array();
return true;
}
$values = array_unique($values);
return true;
}
/**
* デフォルトデータ設定
* @param $value
* @param $default
* @return bool
* @noinspection PhpUnused
*/
public static function default_value(&$value, $default): bool
{
if ($value === null || $value === "") {
$value = $default;
}
return true;
}
/**
* データを置き換える
* @param $value
* @param $replaces
* @return bool
*/
public static function replace(&$value, $replaces): bool
{
$value = str_replace(array_keys($replaces), array_values($replaces), (string)$value);
return true;
}
}
| fc2blog/blog | app/src/Model/Validate.php | PHP | mit | 11,269 |
module.exports = function () {
var modules = [];
var creeps = Game.creeps;
var spawn = Game.spawns.Spawn1;
var score = spawn ? spawn.room.survivalInfo.score : 0;
var minions = {
total: 0,
build: 0,
carry: 0,
harvest: 0,
guard: 0,
medic: 0,
runner: 0
};
if (score == 0 || spawn.spawning != null) return; // no action when already spawning
for (var i in creeps) {
var creep = creeps[i];
minions.total++;
minions[creep.memory.module]++;
}
var getTough = function (amount) {
var modules = [];
amount += Math.round(score / 250);
for (var i = 0; i < amount; i++) {
modules.push(TOUGH);
}
return modules;
};
var spawnCreep = function (modules, memory) {
var creep = spawn.createCreep(modules, undefined, memory);
if (typeof creep != 'number') {
console.log('created ' + memory.module, modules);
}
return creep;
};
if (minions.harvest < 2) {
spawnCreep([WORK, WORK, WORK, CARRY, MOVE], {module: 'harvest'});
}
else if (minions.carry < 2) {
spawnCreep([CARRY, MOVE, MOVE], {module: 'carry'});
}
else if (score > 1000 && minions.runner < 1 || score > 2000 && minions.runner < 2) {
spawnCreep([CARRY, MOVE, MOVE, CARRY, MOVE], {module: 'runner'});
}
else if (minions.medic < minions.guard / 2) {
modules = [];
modules.push(HEAL, HEAL, HEAL, HEAL, MOVE);
spawnCreep(modules, {module: 'medic'});
}
else if (minions.harvest > 0 && ((score < 1100 && minions.guard < 6) || (score > 1100 && score < 2100 && minions.guard < 12) || score > 2100)) {
modules = getTough(0);
modules.push(RANGED_ATTACK, RANGED_ATTACK, RANGED_ATTACK, MOVE, MOVE);
spawnCreep(modules, {module: 'guard'});
}
};
| cameroncondry/cbc-screeps | game/clock.js | JavaScript | mit | 1,928 |
using System;
using System.IO;
using System.Text;
namespace VirtualObjects.Core
{
class TextWriterStub : TextWriter
{
public override Encoding Encoding
{
get { return null; }
}
}
}
| AlienEngineer/VirtualObjects | VirtualObjects/TextWriterStub.cs | C# | mit | 233 |
package com.indignado.logicbricks.utils.builders.joints;
import com.badlogic.gdx.physics.box2d.World;
/**
* @author Rubentxu
*/
public class JointBuilder {
private final World world;
private DistanceJointBuilder distanceJointBuilder;
private FrictionJointBuilder frictionJointBuilder;
private GearJointBuilder gearJointBuilder;
private PrismaticJointBuilder prismaticJointBuilder;
private PulleyJointBuilder pulleyJointBuilder;
private RevoluteJointBuilder revoluteJointBuilder;
private RopeJointBuilder ropeJointBuilder;
private WeldJointBuilder weldJointBuilder;
private WheelJointBuilder wheelJointBuilder;
public JointBuilder(World world) {
this.world = world;
}
public DistanceJointBuilder distanceJoint() {
if (distanceJointBuilder == null) distanceJointBuilder = new DistanceJointBuilder(world);
else distanceJointBuilder.reset();
return distanceJointBuilder;
}
public FrictionJointBuilder frictionJoint() {
if (frictionJointBuilder == null) frictionJointBuilder = new FrictionJointBuilder(world);
else frictionJointBuilder.reset();
return frictionJointBuilder;
}
public GearJointBuilder gearJoint() {
if (gearJointBuilder == null) gearJointBuilder = new GearJointBuilder(world);
else gearJointBuilder.reset();
return gearJointBuilder;
}
public PrismaticJointBuilder prismaticJoint() {
if (prismaticJointBuilder == null) prismaticJointBuilder = new PrismaticJointBuilder(world);
else prismaticJointBuilder.reset();
return prismaticJointBuilder;
}
public PulleyJointBuilder pulleyJoint() {
if (pulleyJointBuilder == null) pulleyJointBuilder = new PulleyJointBuilder(world);
else pulleyJointBuilder.reset();
return pulleyJointBuilder;
}
public RevoluteJointBuilder revoluteJoint() {
if (revoluteJointBuilder == null) revoluteJointBuilder = new RevoluteJointBuilder(world);
else revoluteJointBuilder.reset();
return revoluteJointBuilder;
}
public RopeJointBuilder ropeJoint() {
if (ropeJointBuilder == null) ropeJointBuilder = new RopeJointBuilder(world);
else ropeJointBuilder.reset();
return ropeJointBuilder;
}
public WeldJointBuilder weldJoint() {
if (weldJointBuilder == null) weldJointBuilder = new WeldJointBuilder(world);
else weldJointBuilder.reset();
return weldJointBuilder;
}
public WheelJointBuilder wheelJoint() {
if (wheelJointBuilder == null) wheelJointBuilder = new WheelJointBuilder(world);
else wheelJointBuilder.reset();
return wheelJointBuilder;
}
}
| Rubentxu/GDX-Logic-Bricks | gdx-logic-bricks/src/main/java/com/indignado/logicbricks/utils/builders/joints/JointBuilder.java | Java | mit | 2,754 |
# -*- coding: utf-8 -*-
# ProjectEuler/src/python/problem404.py
#
# Crisscross Ellipses
# ===================
# Published on Sunday, 2nd December 2012, 01:00 am
#
# Ea is an ellipse with an equation of the form x2 + 4y2 = 4a2. Ea' is the
# rotated image of Ea by θ degrees counterclockwise around the origin O(0, 0)
# for 0° θ 90°. b is the distance to the origin of the two intersection
# points closest to the origin and c is the distance of the two other
# intersection points. We call an ordered triplet (a, b, c) a canonical
# ellipsoidal triplet if a, b and c are positive integers. For example, (209,
# 247, 286) is a canonical ellipsoidal triplet. Let C(N) be the number of
# distinct canonical ellipsoidal triplets (a, b, c) for a N. It can be
# verified that C(103) = 7, C(104) = 106 and C(106) = 11845. Find C(1017).
import projecteuler as pe
def main():
pass
if __name__ == "__main__":
main()
| olduvaihand/ProjectEuler | src/python/problem404.py | Python | mit | 944 |
/**
* @class A wrapper around WebGL.
* @name GL
* @param {HTMLCanvasElement} element A canvas element.
* @param {function} onload A callback function.
* @param {function} callbacks.onerror A callback function.
* @param {function} callbacks.onprogress A callback function.
* @param {function} callbacks.onloadstart A callback function.
* @param {function} callbacks.onremove A callback function.
* @property {WebGLRenderingContext} ctx
*/
function GL(element, callbacks) {
var ctx,
identifiers = ["webgl", "experimental-webgl"],
i,
l;
for (var i = 0, l = identifiers.length; i < l; ++i) {
try {
ctx = element.getContext(identifiers[i], {antialias: true, alpha: false/*, preserveDrawingBuffer: true*/});
} catch(e) {
}
if (ctx) {
break;
}
}
if (!ctx) {
console.error("[WebGLContext]: Failed to create a WebGLContext");
throw "[WebGLContext]: Failed to create a WebGLContext";
}
var hasVertexTexture = ctx.getParameter(ctx.MAX_VERTEX_TEXTURE_IMAGE_UNITS) > 0;
var hasFloatTexture = ctx.getExtension("OES_texture_float");
var compressedTextures = ctx.getExtension("WEBGL_compressed_texture_s3tc");
if (!hasVertexTexture) {
console.error("[WebGLContext]: No vertex shader texture support");
throw "[WebGLContext]: No vertex shader texture support";
}
if (!hasFloatTexture) {
console.error("[WebGLContext]: No float texture support");
throw "[WebGLContext]: No float texture support";
}
if (!compressedTextures) {
console.warn("[WebGLContext]: No compressed textures support");
}
var refreshViewProjectionMatrix = false;
var projectionMatrix = mat4.create();
var viewMatrix = mat4.create();
var viewProjectionMatrix = mat4.create();
var matrixStack = [];
var textureStore = {};
var textureStoreById = {};
var shaderUnitStore = {};
var shaderStore = {};
var boundShader;
var boundShaderName = "";
var boundTextures = [];
var floatPrecision = "precision mediump float;\n";
var textureHandlers = {};
ctx.viewport(0, 0, element.clientWidth, element.clientHeight);
ctx.depthFunc(ctx.LEQUAL);
ctx.enable(ctx.DEPTH_TEST);
ctx.enable(ctx.CULL_FACE);
function textureOptions(wrapS, wrapT, magFilter, minFilter) {
ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_S, wrapS);
ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_T, wrapT);
ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_MAG_FILTER, magFilter);
ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_MIN_FILTER, minFilter);
}
/**
* Sets a perspective projection matrix.
*
* @memberof GL
* @instance
* @param {number} fovy
* @param {number} aspect
* @param {number} near
* @param {number} far
*/
function setPerspective(fovy, aspect, near, far) {
mat4.perspective(projectionMatrix, fovy, aspect, near, far);
refreshViewProjectionMatrix = true;
}
/**
* Sets an orthogonal projection matrix.
*
* @memberof GL
* @instance
* @param {number} left
* @param {number} right
* @param {number} bottom
* @param {number} top
* @param {number} near
* @param {number} far
*/
function setOrtho(left, right, bottom, top, near, far) {
mat4.ortho(projectionMatrix, left, right, bottom, top, near, far);
refreshViewProjectionMatrix = true;
}
/**
* Resets the view matrix.
*
* @memberof GL
* @instance
*/
function loadIdentity() {
mat4.identity(viewMatrix);
refreshViewProjectionMatrix = true;
}
/**
* Translates the view matrix.
*
* @memberof GL
* @instance
* @param {vec3} v Translation.
*/
function translate(v) {
mat4.translate(viewMatrix, viewMatrix, v);
refreshViewProjectionMatrix = true;
}
/**
* Rotates the view matrix.
*
* @memberof GL
* @instance
* @param {number} radians Angle.
* @param {vec3} axis The rotation axis..
*/
function rotate(radians, axis) {
mat4.rotate(viewMatrix, viewMatrix, radians, axis);
refreshViewProjectionMatrix = true;
}
/**
* Scales the view matrix.
*
* @memberof GL
* @instance
* @param {vec3} v Scaling.
*/
function scale(v) {
mat4.scale(viewMatrix, viewMatrix, v);
refreshViewProjectionMatrix = true;
}
/**
* Sets the view matrix to a look-at matrix.
*
* @memberof GL
* @instance
* @param {vec3} eye
* @param {vec3} center
* @param {vec3} up
*/
function lookAt(eye, center, up) {
mat4.lookAt(viewMatrix, eye, center, up);
refreshViewProjectionMatrix = true;
}
/**
* Multiplies the view matrix by another matrix.
*
* @memberof GL
* @instance
* @param {mat4} mat.
*/
function multMat(mat) {
mat4.multiply(viewMatrix, viewMatrix, mat);
refreshViewProjectionMatrix = true;
}
/**
* Pushes the current view matrix in the matrix stack.
*
* @memberof GL
* @instance
*/
function pushMatrix() {
matrixStack.push(mat4.clone(viewMatrix));
refreshViewProjectionMatrix = true;
}
/**
* Pops the matrix stacks and sets the popped matrix to the view matrix.
*
* @memberof GL
* @instance
*/
function popMatrix() {
viewMatrix = matrixStack.pop();
refreshViewProjectionMatrix = true;
}
/**
* Gets the view-projection matrix.
*
* @memberof GL
* @instance
* @returns {mat4} MVP.
*/
function getViewProjectionMatrix() {
if (refreshViewProjectionMatrix) {
mat4.multiply(viewProjectionMatrix, projectionMatrix, viewMatrix);
refreshViewProjectionMatrix = false;
}
return viewProjectionMatrix;
}
/**
* Gets the projection matrix.
*
* @memberof GL
* @instance
* @returns {mat4} P.
*/
function getProjectionMatrix() {
return projectionMatrix;
}
/**
* Gets the view matrix.
*
* @memberof GL
* @instance
* @returns {mat4} MV.
*/
function getViewMatrix() {
return viewMatrix;
}
function setProjectionMatrix(matrix) {
mat4.copy(projectionMatrix, matrix);
refreshViewProjectionMatrix = true;
}
function setViewMatrix(matrix) {
mat4.copy(viewMatrix, matrix);
refreshViewProjectionMatrix = true;
}
/**
* Creates a new {@link GL.ShaderUnit}, or grabs it from the cache if it was previously created, and returns it.
*
* @memberof GL
* @instance
* @param {string} source GLSL source.
* @param {number} type Shader unit type.
* @param {string} name Owning shader's name.
* @returns {GL.ShaderUnit} The created shader unit.
*/
function createShaderUnit(source, type, name) {
var hash = String.hashCode(source);
if (!shaderUnitStore[hash]) {
shaderUnitStore[hash] = new ShaderUnit(ctx, source, type, name);
}
return shaderUnitStore[hash];
}
/**
* Creates a new {@link GL.Shader} program, or grabs it from the cache if it was previously created, and returns it.
*
* @memberof GL
* @instance
* @param {string} name The name of the shader.
* @param {string} vertexSource Vertex shader GLSL source.
* @param {string} fragmentSource Fragment shader GLSL source.
* @param {array} defines An array of strings that will be added as #define-s to the shader source.
* @returns {GL.Shader?} The created shader, or a previously cached version, or null if it failed to compile and link.
*/
function createShader(name, vertexSource, fragmentSource, defines) {
if (!shaderStore[name]) {
defines = defines || [];
for (var i = 0; i < defines.length; i++) {
defines[i] = "#define " + defines[i];
}
defines = defines.join("\n") + "\n";
var vertexUnit = createShaderUnit(defines + vertexSource, ctx.VERTEX_SHADER, name);
var fragmentUnit = createShaderUnit(floatPrecision + defines + fragmentSource, ctx.FRAGMENT_SHADER, name);
if (vertexUnit.ready && fragmentUnit.ready) {
shaderStore[name] = new Shader(ctx, name, vertexUnit, fragmentUnit);
}
}
if (shaderStore[name] && shaderStore[name].ready) {
return shaderStore[name];
}
}
/**
* Checks if a shader is ready for use.
*
* @memberof GL
* @instance
* @param {string} name The name of the shader.
* @returns {boolean} The shader's status.
*/
function shaderStatus(name) {
var shader = shaderStore[name];
return shader && shader.ready;
}
/**
* Enables the WebGL vertex attribute arrays in the range defined by start-end.
*
* @memberof GL
* @instance
* @param {number} start The first attribute.
* @param {number} end The last attribute.
*/
function enableVertexAttribs(start, end) {
for (var i = start; i < end; i++) {
ctx.enableVertexAttribArray(i);
}
}
/**
* Disables the WebGL vertex attribute arrays in the range defined by start-end.
*
* @memberof GL
* @instance
* @param {number} start The first attribute.
* @param {number} end The last attribute.
*/
function disableVertexAttribs(start, end) {
for (var i = start; i < end; i++) {
ctx.disableVertexAttribArray(i);
}
}
/**
* Binds a shader. This automatically handles the vertex attribute arrays. Returns the currently bound shader.
*
* @memberof GL
* @instance
* @param {string} name The name of the shader.
* @returns {GL.Shader} The bound shader.
*/
function bindShader(name) {
var shader = shaderStore[name];
if (shader && (!boundShader || boundShader.id !== shader.id)) {
var oldAttribs = 0;
if (boundShader) {
oldAttribs = boundShader.attribs;
}
var newAttribs = shader.attribs;
ctx.useProgram(shader.id);
if (newAttribs > oldAttribs) {
enableVertexAttribs(oldAttribs, newAttribs);
} else if (newAttribs < oldAttribs) {
disableVertexAttribs(newAttribs, oldAttribs);
}
boundShaderName = name;
boundShader = shader;
}
return boundShader;
}
/**
* Loads a texture, with optional options that will be sent to the texture's constructor,
* If the texture was already loaded previously, it returns it.
*
* @memberof GL
* @instance
* @param {string} source The texture's url.
* @param {object} options Options.
*/
function loadTexture(source, fileType, isFromMemory, options) {
if (!textureStore[source]) {
textureStore[source] = new AsyncTexture(source, fileType, options, textureHandlers, ctx, compressedTextures, callbacks, isFromMemory);
textureStoreById[textureStore[source].id] = textureStore[source];
}
return textureStore[source];
}
/**
* Unloads a texture.
*
* @memberof GL
* @instance
* @param {string} source The texture's url.
*/
function removeTexture(source) {
if (textureStore[source]) {
callbacks.onremove(textureStore[source]);
delete textureStore[source];
}
}
function textureLoaded(source) {
var texture = textureStore[source];
return (texture && texture.loaded());
}
/**
* Binds a texture to the specified texture unit.
*
* @memberof GL
* @instance
* @param {(string|null)} object A texture source.
* @param {number} [unit] The texture unit.
*/
function bindTexture(source, unit) {
//console.log(source);
var texture;
unit = unit || 0;
if (typeof source === "string") {
texture = textureStore[source];
} else if (typeof source === "number") {
texture = textureStoreById[source];
}
if (texture && texture.impl && texture.impl.ready) {
// Only bind if actually necessary
if (!boundTextures[unit] || boundTextures[unit].id !== texture.id) {
boundTextures[unit] = texture.impl;
ctx.activeTexture(ctx.TEXTURE0 + unit);
ctx.bindTexture(ctx.TEXTURE_2D, texture.impl.id);
}
} else {
boundTextures[unit] = null;
ctx.activeTexture(ctx.TEXTURE0 + unit);
ctx.bindTexture(ctx.TEXTURE_2D, null);
}
}
/**
* Creates a new {@link GL.Rect} and returns it.
*
* @memberof GL
* @instance
* @param {number} x X coordinate.
* @param {number} y Y coordinate.
* @param {number} z Z coordinate.
* @param {number} hw Half of the width.
* @param {number} hh Half of the height.
* @param {number} stscale A scale that is applied to the texture coordinates.
* @returns {GL.Rect} The rectangle.
*/
function createRect(x, y, z, hw, hh, stscale) {
return new Rect(ctx, x, y, z, hw, hh, stscale);
}
/**
* Creates a new {@link GL.Cube} and returns it.
*
* @memberof GL
* @instance
* @param {number} x1 Minimum X coordinate.
* @param {number} y1 Minimum Y coordinate.
* @param {number} z1 Minimum Z coordinate.
* @param {number} x2 Maximum X coordinate.
* @param {number} y2 Maximum Y coordinate.
* @param {number} z2 Maximum Z coordinate.
* @returns {GL.Cube} The cube.
*/
function createCube(x1, y1, z1, x2, y2, z2) {
return new Cube(ctx, x1, y1, z1, x2, y2, z2);
}
/**
* Creates a new {@link GL.Sphere} and returns it.
*
* @memberof GL
* @instance
* @param {number} x X coordinate.
* @param {number} y Y coordinate.
* @param {number} z Z coordinate.
* @param {number} latitudeBands Latitude bands.
* @param {number} longitudeBands Longitude bands.
* @param {number} radius The sphere radius.
* @returns {GL.Sphere} The sphere.
*/
function createSphere(x, y, z, latitudeBands, longitudeBands, radius) {
return new Sphere(ctx, x, y, z, latitudeBands, longitudeBands, radius);
}
/**
* Creates a new {@link GL.Cylinder} and returns it.
*
* @memberof GL
* @instance
* @param {number} x X coordinate.
* @param {number} y Y coordinate.
* @param {number} z Z coordinate.
* @param {number} r The cylinder radius.
* @param {number} h The cylinder height.
* @param {number} bands Number of bands..
* @returns {GL.Cylinder} The cylinder.
*/
function createCylinder(x, y, z, r, h, bands) {
return new Cylinder(ctx, x, y, z, r, h, bands);
}
/**
* Registers an external handler for an unsupported texture type.
*
* @memberof GL
* @instance
* @param {string} fileType The file format the handler handles.
* @param {function} textureHandler
*/
function registerTextureHandler(fileType, textureHandler) {
textureHandlers[fileType] = textureHandler;
}
textureHandlers[".png"] = NativeTexture;
textureHandlers[".gif"] = NativeTexture;
textureHandlers[".jpg"] = NativeTexture;
return {
setPerspective: setPerspective,
setOrtho: setOrtho,
loadIdentity: loadIdentity,
translate: translate,
rotate: rotate,
scale: scale,
lookAt: lookAt,
multMat: multMat,
pushMatrix: pushMatrix,
popMatrix: popMatrix,
createShader: createShader,
shaderStatus: shaderStatus,
bindShader: bindShader,
getViewProjectionMatrix: getViewProjectionMatrix,
getProjectionMatrix: getProjectionMatrix,
getViewMatrix: getViewMatrix,
setProjectionMatrix: setProjectionMatrix,
setViewMatrix: setViewMatrix,
loadTexture: loadTexture,
removeTexture: removeTexture,
textureLoaded: textureLoaded,
textureOptions: textureOptions,
bindTexture: bindTexture,
createRect: createRect,
createSphere: createSphere,
createCube: createCube,
createCylinder: createCylinder,
ctx: ctx,
registerTextureHandler: registerTextureHandler
};
}
| emnh/mdx-m3-viewer | src/gl/gl.js | JavaScript | mit | 15,053 |
using System;
using System.Collections.Generic;
using PMKS;
using PMKS.PositionSolving;
using StarMathLib;
namespace PMKS
{
internal class GearData
{
internal readonly double radius1;
internal readonly double radius2;
internal readonly int gearTeethIndex;
internal readonly int connectingRodIndex;
internal readonly int gearCenter1Index;
internal readonly int gearCenter2Index;
internal readonly int gear1LinkIndex;
internal readonly int gear2LinkIndex;
internal GearData(Joint gearTeethJoint, int gearTeethIndex, Joint gearCenter1, int gearCenter1Index,
int gear1LinkIndex,
Joint gearCenter2, int gearCenter2Index, int gear2LinkIndex,
int connectingRodIndex, double initialGearAngle)
{
this.gearTeethIndex = gearTeethIndex;
this.gearCenter1Index = gearCenter1Index;
this.gear1LinkIndex = gear1LinkIndex;
this.gearCenter2Index = gearCenter2Index;
this.gear2LinkIndex = gear2LinkIndex;
this.connectingRodIndex = connectingRodIndex;
var dx1 = gearCenter1.xInitial - gearTeethJoint.xInitial;
var dy1 = gearCenter1.yInitial - gearTeethJoint.yInitial;
var dx2 = gearCenter2.xInitial - gearTeethJoint.xInitial;
var dy2 = gearCenter2.yInitial - gearTeethJoint.yInitial;
radius1 = Constants.distance(gearTeethJoint, gearCenter1);
radius2 = Constants.distance(gearTeethJoint, gearCenter2);
gearCenter1.OffsetSlideAngle = initialGearAngle;
radius1 = Math.Sqrt(dx1 * dx1 + dy1 * dy1);
radius2 = Math.Sqrt(dx2 * dx2 + dy2 * dy2);
if (dx1 * dx2 >= 0 && dy1 * dy2 >= 0)
{
//then they're both on the same side of the gear teeth
// and one is inverted (the bigger one to be precise).
if (radius1 > radius2) radius1 *= -1;
else radius2 *= -1;
}
}
internal bool IsGearSolvableRP_G_R(List<Joint> joints, List<Link> links)
{
return (links[gear1LinkIndex].AngleIsKnown == KnownState.Fully
&& joints[gearCenter1Index].positionKnown == KnownState.Fully
&& joints[gearCenter2Index].TypeOfJoint == JointType.R
&& joints[gearCenter2Index].positionKnown == KnownState.Fully);
}
internal bool IsGearSolvableR_G_RP(List<Joint> joints, List<Link> links)
{
return (links[gear2LinkIndex].AngleIsKnown == KnownState.Fully
&& joints[gearCenter2Index].positionKnown == KnownState.Fully
&& joints[gearCenter1Index].TypeOfJoint == JointType.R
&& joints[gearCenter1Index].positionKnown == KnownState.Fully);
}
internal Point SolveGearPositionAndAnglesRPGR(List<Joint> joints, List<Link> links,
out double angleChange)
{
var knownlink = links[gear1LinkIndex];
var rKnownGear = this.radius1;
var gearCenterKnown = joints[gearCenter1Index];
var unknownlink = links[gear2LinkIndex];
var rUnkGear = this.radius2;
var gearCenterUnknown = joints[gearCenter2Index];
angleChange = findUnknownGearAngleChange(rKnownGear, gearCenterKnown, rUnkGear, gearCenterUnknown, knownlink,
unknownlink);
return findGearTeethPointAlongConnectingRod(gearCenterKnown, rKnownGear, gearCenterUnknown, rUnkGear);
}
internal Point SolveGearPositionAndAnglesRGRP(List<Joint> joints, List<Link> links,
out double angleChange)
{
var knownlink = links[gear2LinkIndex];
var rKnownGear = radius2;
var gearCenterKnown = joints[gearCenter2Index];
var rUnkGear = radius1;
var gearCenterUnknown = joints[gearCenter1Index];
angleChange = findUnknownGearAngleChange(rKnownGear, gearCenterKnown, rUnkGear, gearCenterUnknown, knownlink);
return findGearTeethPointAlongConnectingRod(gearCenterKnown, rKnownGear, gearCenterUnknown, rUnkGear);
}
private static double findUnknownGearAngleChange(double rKnownGear, Joint gearCenterKnown, double rUnkGear,
Joint gearCenterUnknown,
Link knownlink, Link unknownlink = null)
{
var linkAngle = (knownlink.Angle - knownlink.AngleLast);
linkAngle *= -(rKnownGear / rUnkGear) *
(linkAngle + findAngleChangeBetweenOfConnectingRod(gearCenterKnown, gearCenterUnknown));
if (unknownlink == null) return linkAngle;
var change = linkAngle - unknownlink.AngleNumerical;
while (change > Math.PI)
{
linkAngle -= 2 * Math.PI;
change = linkAngle - unknownlink.AngleNumerical;
}
while (change < -Math.PI)
{
linkAngle += 2 * Math.PI;
change = linkAngle - unknownlink.AngleNumerical;
}
return linkAngle;
}
internal static Point findGearTeethPointAlongConnectingRod(Joint center1, double rGear1, Joint center2,
double rGear2)
{
var x = center1.x + rGear1 * (center2.x - center1.x) / (rGear2 + rGear1);
var y = center1.y + rGear1 * (center2.y - center1.y) / (rGear2 + rGear1);
return new Point(x, y);
}
internal static double findAngleChangeBetweenOfConnectingRod(Joint From, Joint To)
{
return Constants.angle(From.x, From.y, To.x, To.y) -
Constants.angle(From.xLast, From.yLast, To.xLast, To.yLast);
}
internal double FindNominalGearRotation(List<Link> links, Link knownlink)
{
var rKnownGear = radiusOfLink(links.IndexOf(knownlink));
var rUnkGear = radiusOfOtherLink(links.IndexOf(knownlink));
return -(rKnownGear / rUnkGear) * (knownlink.Angle - knownlink.AngleLast);
}
internal double radiusOfLink(int linkIndex)
{
if (linkIndex == gear1LinkIndex) return radius1;
if (linkIndex == gear2LinkIndex) return radius2;
return double.NaN;
}
internal double radiusOfOtherLink(int linkIndex)
{
if (linkIndex == gear1LinkIndex) return radius2;
if (linkIndex == gear2LinkIndex) return radius1;
return double.NaN;
}
internal int gearCenterIndex(int linkIndex)
{
if (linkIndex == gear1LinkIndex) return gearCenter1Index;
if (linkIndex == gear2LinkIndex) return gearCenter2Index;
return -1;
}
#region for R-R-G/G
internal static Boolean FindKnownGearAngleOnLink(Joint gearCenter, Link connectingRod, Link gearLink, List<Joint> joints,
List<Link> links, Dictionary<int, GearData> gearsData, out GearData gData)
{
if (gearLink.AngleIsKnown == KnownState.Fully)
{
foreach (var gearData in gearsData.Values)
{
if (connectingRod == links[gearData.connectingRodIndex])
{
var otherGear = (gearLink == links[gearData.gear1LinkIndex])
? links[gearData.gear2LinkIndex]
: links[gearData.gear1LinkIndex];
if (otherGear.AngleIsKnown == KnownState.Fully)
{
gData = gearData;
return true;
}
}
}
}
gData = null;
return false;
}
internal void SolveGearCenterFromKnownGearAngle(Joint gearCenter, Joint armPivot, List<Link> links, out double angleChange)
{
var angle1Change = links[gear1LinkIndex].Angle - links[gear1LinkIndex].AngleLast;
var angle2Change = links[gear2LinkIndex].Angle - links[gear2LinkIndex].AngleLast;
angleChange = (angle1Change + (radius2 / radius1) * angle2Change) / (1 + radius2 / radius1);
}
#endregion
#region for R-G-R
internal bool IsGearSolvableRGR(List<Joint> joints, List<Link> links)
{
return (joints[gearCenter1Index].positionKnown == KnownState.Fully &&
joints[gearCenter2Index].positionKnown == KnownState.Fully);
}
internal void SolveGearPositionAndAnglesRGR(List<Joint> joints, List<Link> links)
{
var gearTeeth = joints[gearTeethIndex];
var center1 = joints[gearCenter1Index];
var center2 = joints[gearCenter2Index];
gearTeeth.x = center1.x + radius1 * (center2.x - center1.x) / (radius2 + radius1);
gearTeeth.y = center1.y + radius1 * (center2.y - center1.y) / (radius2 + radius1);
gearTeeth.positionKnown = KnownState.Fully;
}
#endregion
#region for R-G-P or P-G-R
internal bool IsGearSolvableRGP(List<Joint> joints, List<Link> links)
{
return (joints[gearCenter2Index].positionKnown != KnownState.Unknown
&& links[gear2LinkIndex].AngleIsKnown == KnownState.Fully
&& joints[gearCenter1Index].positionKnown == KnownState.Fully);
}
internal void SolveGearPositionAndAnglesRGP(List<Joint> joints, List<Link> links)
{
var gearTeeth = joints[gearTeethIndex];
var angle = links[gear2LinkIndex].Angle;
var Pcenter = joints[gearCenter2Index];
var Rcenter = joints[gearCenter1Index];
SolveGearPositionAndAnglesPGR(gearTeeth, Pcenter, Rcenter, angle, radius1);
}
internal bool IsGearSolvablePGR(List<Joint> joints, List<Link> links)
{
return (joints[gearCenter1Index].positionKnown != KnownState.Unknown
&& links[gear1LinkIndex].AngleIsKnown == KnownState.Fully
&& joints[gearCenter2Index].positionKnown == KnownState.Fully);
}
internal void SolveGearPositionAndAnglesPGR(List<Joint> joints, List<Link> links)
{
var gearTeeth = joints[gearTeethIndex];
var angle = links[gear1LinkIndex].Angle;
var Pcenter = joints[gearCenter1Index];
var Rcenter = joints[gearCenter2Index];
SolveGearPositionAndAnglesPGR(gearTeeth, Pcenter, Rcenter, angle, radius2);
}
private void SolveGearPositionAndAnglesPGR(Joint gearTeeth, Joint Pcenter, Joint Rcenter, double angle, double gearRadius)
{
angle += Math.PI / 2;
var angleUnitVector = new[] { Math.Cos(angle), Math.Sin(angle) };
var toSlideVector = new[] { (Pcenter.x - Rcenter.x), (Pcenter.y - Rcenter.y) };
if (StarMath.dotProduct(angleUnitVector, toSlideVector) < 0)
{
angleUnitVector[0] = -angleUnitVector[0];
angleUnitVector[1] = -angleUnitVector[1];
}
gearTeeth.x = Rcenter.x + gearRadius * angleUnitVector[0];
gearTeeth.y = Rcenter.y + gearRadius * angleUnitVector[1];
gearTeeth.positionKnown = KnownState.Fully;
}
#endregion
/// <summary>
/// Sets the gear rotation only from setLinkPositionFromRotate
/// </summary>
/// <param name="knownGearLink">The known gear link.</param>
/// <param name="unknownGearLink">The unknown gear link.</param>
/// <param name="links">The links.</param>
/// <param name="joints">The joints.</param>
internal Boolean SetGearRotation(Link knownGearLink, Link unknownGearLink, List<Link> links, List<Joint> joints)
{
if (unknownGearLink.AngleIsKnown == KnownState.Fully) return false;
var rKnownGear = radiusOfLink(links.IndexOf(knownGearLink));
var rUnkGear = radiusOfOtherLink(links.IndexOf(knownGearLink));
var gearAngleChange = -(rKnownGear / rUnkGear) * (knownGearLink.Angle - knownGearLink.AngleLast);
if (joints[gearCenter1Index].positionKnown == KnownState.Fully &&
joints[gearCenter2Index].positionKnown == KnownState.Fully)
{
var From = joints[gearCenter1Index];
var To = joints[gearCenter2Index];
var connectingRodAngleChange = Constants.angle(From.x, From.y, To.x, To.y) -
Constants.angle(From.xLast, From.yLast, To.xLast, To.yLast);
unknownGearLink.Angle += connectingRodAngleChange * (1 + rKnownGear / rUnkGear) +
gearAngleChange;
unknownGearLink.AngleIsKnown = KnownState.Fully;
return true;
}
if (unknownGearLink.AngleIsKnown == KnownState.Unknown)
{
unknownGearLink.Angle = gearAngleChange + unknownGearLink.AngleLast;
unknownGearLink.AngleIsKnown = KnownState.Partially;
return false;
}
else
{
var angleTemp = gearAngleChange + unknownGearLink.AngleLast;
unknownGearLink.Angle = (unknownGearLink.Angle + angleTemp) / 2.0;
unknownGearLink.AngleIsKnown = KnownState.Fully;
return true;
}
}
}
}
| DesignEngrLab/PMKS | PlanarMechanismSimulator/gearData.cs | C# | mit | 13,965 |
module Generators
module Hobo
module Migration
class HabtmModelShim < Struct.new(:join_table, :foreign_keys, :connection)
def self.from_reflection(refl)
result = self.new
result.join_table = refl.options[:join_table].to_s
result.foreign_keys = [refl.primary_key_name.to_s, refl.association_foreign_key.to_s].sort
# this may fail in weird ways if HABTM is running across two DB connections (assuming that's even supported)
# figure that anybody who sets THAT up can deal with their own migrations...
result.connection = refl.active_record.connection
result
end
def table_name
self.join_table
end
def table_exists?
ActiveRecord::Migration.table_exists? table_name
end
def field_specs
i = 0
foreign_keys.inject({}) do |h, v|
# some trickery to avoid an infinite loop when FieldSpec#initialize tries to call model.field_specs
h[v] = HoboFields::Model::FieldSpec.new(self, v, :integer, :position => i)
i += 1
h
end
end
def primary_key
false
end
def index_specs
[]
end
end
class Migrator
class Error < RuntimeError; end
@ignore_models = []
@ignore_tables = []
class << self
attr_accessor :ignore_models, :ignore_tables, :disable_indexing
end
def self.run(renames={})
g = Migrator.new
g.renames = renames
g.generate
end
def self.default_migration_name
existing = Dir["#{Rails.root}/db/migrate/*hobo_migration*"]
max = existing.grep(/([0-9]+)\.rb$/) { $1.to_i }.max
n = max ? max + 1 : 1
"hobo_migration_#{n}"
end
def initialize(ambiguity_resolver={})
@ambiguity_resolver = ambiguity_resolver
@drops = []
@renames = nil
end
attr_accessor :renames
def load_rails_models
if defined? Rails.root
Dir["#{Rails.root}/app/models/**/[a-z0-9_]*.rb"].each do |f|
_, filename = *f.match(%r{/app/models/([_a-z0-9/]*).rb$})
filename.camelize.constantize
end
end
end
# Returns an array of model classes that *directly* extend
# ActiveRecord::Base, excluding anything in the CGI module
def table_model_classes
load_rails_models
ActiveRecord::Base.send(:descendants).reject {|c| (c.base_class != c) || c.name.starts_with?("CGI::") }
end
def self.connection
ActiveRecord::Base.connection
end
def connection; self.class.connection; end
def self.fix_native_types(types)
case connection.class.name
when /mysql/i
types[:integer][:limit] ||= 11
end
types
end
def self.native_types
@native_types ||= fix_native_types connection.native_database_types
end
def native_types; self.class.native_types; end
# list habtm join tables
def habtm_tables
reflections = Hash.new { |h, k| h[k] = Array.new }
ActiveRecord::Base.send(:descendants).map do |c|
c.reflect_on_all_associations(:has_and_belongs_to_many).each do |a|
reflections[a.options[:join_table].to_s] << a
end
end
reflections
end
# Returns an array of model classes and an array of table names
# that generation needs to take into account
def models_and_tables
ignore_model_names = Migrator.ignore_models.*.to_s.*.underscore
all_models = table_model_classes
hobo_models = all_models.select { |m| m.try.include_in_migration && m.name.underscore.not_in?(ignore_model_names) }
non_hobo_models = all_models - hobo_models
db_tables = connection.tables - Migrator.ignore_tables.*.to_s - non_hobo_models.*.table_name
[hobo_models, db_tables]
end
# return a hash of table renames and modifies the passed arrays so
# that renamed tables are no longer listed as to_create or to_drop
def extract_table_renames!(to_create, to_drop)
if renames
# A hash of table renames has been provided
to_rename = {}
renames.each_pair do |old_name, new_name|
new_name = new_name[:table_name] if new_name.is_a?(Hash)
next unless new_name
if to_create.delete(new_name.to_s) && to_drop.delete(old_name.to_s)
to_rename[old_name.to_s] = new_name.to_s
else
raise Error, "Invalid table rename specified: #{old_name} => #{new_name}"
end
end
to_rename
elsif @ambiguity_resolver
@ambiguity_resolver.call(to_create, to_drop, "table", nil)
else
raise Error, "Unable to resolve migration ambiguities"
end
end
def extract_column_renames!(to_add, to_remove, table_name)
if renames
to_rename = {}
column_renames = renames._?[table_name.to_sym]
if column_renames
# A hash of table renames has been provided
column_renames.each_pair do |old_name, new_name|
if to_add.delete(new_name.to_s) && to_remove.delete(old_name.to_s)
to_rename[old_name.to_s] = new_name.to_s
else
raise Error, "Invalid rename specified: #{old_name} => #{new_name}"
end
end
end
to_rename
elsif @ambiguity_resolver
@ambiguity_resolver.call(to_add, to_remove, "column", "#{table_name}.")
else
raise Error, "Unable to resolve migration ambiguities in table #{table_name}"
end
end
def always_ignore_tables
# TODO: figure out how to do this in a sane way and be compatible with 2.2 and 2.3 - class has moved
sessions_table = CGI::Session::ActiveRecordStore::Session.table_name if
defined?(CGI::Session::ActiveRecordStore::Session) &&
defined?(ActionController::Base) &&
ActionController::Base.session_store == CGI::Session::ActiveRecordStore
['schema_info', 'schema_migrations', sessions_table].compact
end
def generate
models, db_tables = models_and_tables
models_by_table_name = {}
models.each do |m|
if !models_by_table_name.has_key?(m.table_name)
models_by_table_name[m.table_name] = m
elsif m.superclass==models_by_table_name[m.table_name].superclass.superclass
# we need to ensure that models_by_table_name contains the
# base class in an STI hierarchy
models_by_table_name[m.table_name] = m
end
end
# generate shims for HABTM models
habtm_tables.each do |name, refls|
models_by_table_name[name] = HabtmModelShim.from_reflection(refls.first)
end
model_table_names = models_by_table_name.keys
to_create = model_table_names - db_tables
to_drop = db_tables - model_table_names - always_ignore_tables
to_change = model_table_names
to_rename = extract_table_renames!(to_create, to_drop)
renames = to_rename.map do |old_name, new_name|
"rename_table :#{old_name}, :#{new_name}"
end * "\n"
undo_renames = to_rename.map do |old_name, new_name|
"rename_table :#{new_name}, :#{old_name}"
end * "\n"
drops = to_drop.map do |t|
"drop_table :#{t}"
end * "\n"
undo_drops = to_drop.map do |t|
revert_table(t)
end * "\n\n"
creates = to_create.map do |t|
create_table(models_by_table_name[t])
end * "\n\n"
undo_creates = to_create.map do |t|
"drop_table :#{t}"
end * "\n"
changes = []
undo_changes = []
index_changes = []
undo_index_changes = []
to_change.each do |t|
model = models_by_table_name[t]
table = to_rename.key(t) || model.table_name
if table.in?(db_tables)
change, undo, index_change, undo_index = change_table(model, table)
changes << change
undo_changes << undo
index_changes << index_change
undo_index_changes << undo_index
end
end
up = [renames, drops, creates, changes, index_changes].flatten.reject(&:blank?) * "\n\n"
down = [undo_changes, undo_renames, undo_drops, undo_creates, undo_index_changes].flatten.reject(&:blank?) * "\n\n"
[up, down]
end
def create_table(model)
longest_field_name = model.field_specs.values.map { |f| f.sql_type.to_s.length }.max
if model.primary_key != "id"
if model.primary_key
primary_key_option = ", :primary_key => :#{model.primary_key}"
else
primary_key_option = ", :id => false"
end
end
(["create_table :#{model.table_name}#{primary_key_option} do |t|"] +
model.field_specs.values.sort_by{|f| f.position}.map {|f| create_field(f, longest_field_name)} +
["end"] + (Migrator.disable_indexing ? [] : create_indexes(model))) * "\n"
end
def create_indexes(model)
model.index_specs.map { |i| i.to_add_statement(model.table_name) }
end
def create_field(field_spec, field_name_width)
args = [field_spec.name.inspect] + format_options(field_spec.options, field_spec.sql_type)
" t.%-*s %s" % [field_name_width, field_spec.sql_type, args.join(', ')]
end
def change_table(model, current_table_name)
new_table_name = model.table_name
db_columns = model.connection.columns(current_table_name).index_by{|c|c.name}
key_missing = db_columns[model.primary_key].nil? && model.primary_key
db_columns -= [model.primary_key]
model_column_names = model.field_specs.keys.*.to_s
db_column_names = db_columns.keys.*.to_s
to_add = model_column_names - db_column_names
to_add += [model.primary_key] if key_missing && model.primary_key
to_remove = db_column_names - model_column_names
to_remove = to_remove - [model.primary_key.to_sym] if model.primary_key
to_rename = extract_column_renames!(to_add, to_remove, new_table_name)
db_column_names -= to_rename.keys
db_column_names |= to_rename.values
to_change = db_column_names & model_column_names
renames = to_rename.map do |old_name, new_name|
"rename_column :#{new_table_name}, :#{old_name}, :#{new_name}"
end
undo_renames = to_rename.map do |old_name, new_name|
"rename_column :#{new_table_name}, :#{new_name}, :#{old_name}"
end
to_add = to_add.sort_by {|c| model.field_specs[c].position }
adds = to_add.map do |c|
spec = model.field_specs[c]
args = [":#{spec.sql_type}"] + format_options(spec.options, spec.sql_type)
"add_column :#{new_table_name}, :#{c}, #{args * ', '}"
end
undo_adds = to_add.map do |c|
"remove_column :#{new_table_name}, :#{c}"
end
removes = to_remove.map do |c|
"remove_column :#{new_table_name}, :#{c}"
end
undo_removes = to_remove.map do |c|
revert_column(current_table_name, c)
end
old_names = to_rename.invert
changes = []
undo_changes = []
to_change.each do |c|
col_name = old_names[c] || c
col = db_columns[col_name]
spec = model.field_specs[c]
if spec.different_to?(col)
change_spec = {}
change_spec[:limit] = spec.limit unless spec.limit.nil? && col.limit.nil?
change_spec[:precision] = spec.precision unless spec.precision.nil?
change_spec[:scale] = spec.scale unless spec.scale.nil?
change_spec[:null] = spec.null unless spec.null && col.null
change_spec[:default] = spec.default unless spec.default.nil? && col.default.nil?
change_spec[:comment] = spec.comment unless spec.comment.nil? && col.try.comment.nil?
changes << "change_column :#{new_table_name}, :#{c}, " +
([":#{spec.sql_type}"] + format_options(change_spec, spec.sql_type, true)).join(", ")
back = change_column_back(current_table_name, col_name)
undo_changes << back unless back.blank?
else
nil
end
end.compact
index_changes, undo_index_changes = change_indexes(model, current_table_name)
[(renames + adds + removes + changes) * "\n",
(undo_renames + undo_adds + undo_removes + undo_changes) * "\n",
index_changes * "\n",
undo_index_changes * "\n"]
end
def change_indexes(model, old_table_name)
return [[],[]] if Migrator.disable_indexing || model.is_a?(HabtmModelShim)
new_table_name = model.table_name
existing_indexes = HoboFields::Model::IndexSpec.for_model(model, old_table_name)
model_indexes = model.index_specs
add_indexes = model_indexes - existing_indexes
drop_indexes = existing_indexes - model_indexes
undo_add_indexes = []
undo_drop_indexes = []
add_indexes.map! do |i|
undo_add_indexes << drop_index(old_table_name, i.name)
i.to_add_statement(new_table_name)
end
drop_indexes.map! do |i|
undo_drop_indexes << i.to_add_statement(old_table_name)
drop_index(new_table_name, i.name)
end
# the order is important here - adding a :unique, for instance needs to remove then add
[drop_indexes + add_indexes, undo_add_indexes + undo_drop_indexes]
end
def drop_index(table, name)
# see https://hobo.lighthouseapp.com/projects/8324/tickets/566
# for why the rescue exists
"remove_index :#{table}, :name => :#{name} rescue ActiveRecord::StatementInvalid"
end
def format_options(options, type, changing=false)
options.map do |k, v|
unless changing
next if k == :limit && (type == :decimal || v == native_types[type][:limit])
next if k == :null && v == true
end
"#{k.inspect} => #{v.inspect}"
end.compact
end
def revert_table(table)
res = StringIO.new
ActiveRecord::SchemaDumper.send(:new, ActiveRecord::Base.connection).send(:table, table, res)
res.string.strip.gsub("\n ", "\n")
end
def column_options_from_reverted_table(table, column)
revert = revert_table(table)
if (md = revert.match(/\s*t\.column\s+"#{column}",\s+(:[a-zA-Z0-9_]+)(?:,\s+(.*?)$)?/m))
# Ugly migration
_, type, options = *md
elsif (md = revert.match(/\s*t\.([a-z_]+)\s+"#{column}"(?:,\s+(.*?)$)?/m))
# Sexy migration
_, type, options = *md
type = ":#{type}"
end
[type, options]
end
def change_column_back(table, column)
type, options = column_options_from_reverted_table(table, column)
"change_column :#{table}, :#{column}, #{type}#{', ' + options.strip if options}"
end
def revert_column(table, column)
type, options = column_options_from_reverted_table(table, column)
"add_column :#{table}, :#{column}, #{type}#{', ' + options.strip if options}"
end
end
end
end
end
| activestylus/hobofields | lib/generators/hobo/migration/migrator.rb | Ruby | mit | 16,330 |
import hotkeys from "hotkeys-js";
export default class HotkeyHandler {
constructor(hotkeyRegistry) {
this.hotkeyRegistry = hotkeyRegistry;
hotkeys("*", { keyup: true, keydown: false }, event => {
event.preventDefault();
this.hotkeyRegistry.resetLastPressedKeyCodes();
return false;
});
hotkeys("*", { keyup: false, keydown: true }, event => {
event.preventDefault();
const pressed = hotkeys.getPressedKeyCodes();
this.hotkeyRegistry.onKeyPressed(pressed);
return false;
});
}
dispose() {
hotkeys.deleteScope("all");
}
}
| UnderNotic/KeyJitsu | src/game/HotkeyRegistry/index.js | JavaScript | mit | 602 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Rank extends MX_Controller {
public function __construct()
{
parent::__construct();
$this->load->config('rank');
$this->configs_rank = config_item('rank');
$this->players = $this->load->model('account/player_model');
$this->load->helper(array('url', 'date', 'html'));
$this->load->library('multworlds');
}
public function players_rank2()
{
$data['multworlds'] = $this->multworlds;
$this->players->where('world_id', $this->multworlds->setDefatulWorld());
if($this->input->post('vocation') or $this->session->userdata('filter_rank_vocations'))
{
if($this->input->post('vocation'))
{
$this->session->set_userdata('filter_rank_vocations', $this->input->post('vocation'));
$filtros = $this->session->userdata('filter_rank_vocations');
}
else
{
$filtros = $this->session->userdata('filter_rank_vocations');
}
$vocations_names = config_item('vocations_names');
$i = 0;
foreach ($filtros as $key => $value)
{
if(isset($vocations_names[$this->multworlds->setDefatulWorld()][$value]))
{
if ($i == 0)
{
$this->players->where('vocation', $value);
}
else
{
$this->players->or_where('vocation', $value);
foreach ($this->configs_rank['ocultgrup'] as $key)
{
$this->players->where('group_id !=', $key);
}
}
}
$i++;
}
}
else
{
foreach ($this->configs_rank['ocultgrup'] as $key)
{
$this->players->where('group_id !=', $key);
}
}
$page = $this->uri->segment('3');
$data['skill_rank'] = FALSE;
if (is_string($this->input->post('skill')))
{
if (array_key_exists('players', $this->configs_rank['type'][$this->multworlds->setDefatulWorld()]))
{
if(isset($this->configs_rank['type'][$this->multworlds->setDefatulWorld()]['players'][$this->input->post('skill')]['order_by']))
{
$this->players->order_by($this->input->post('skill'), $this->configs_rank['type'][$this->multworlds->setDefatulWorld()]['players'][$this->input->post('skill')]['order_by']);
}
}
$data['skill_rank'] = TRUE;
}
if(!$data['skill_rank'])
{
$this->players->order_by('level', 'DESC');
}
$data['list'] = $this->players->get_paged($page, $this->configs_rank['list_n']);
$data['config'] = $this->configs_rank;
//$this->players->check_last_query();
$this->load->view('players_rank', $data);
}
public function players_rank()
{
$array = array();
$page = $this->uri->segment('3');
$vocations_names = config_item('vocations_names');
if($this->session->userdata('filter_rank_vocations'))
{
foreach ($this->session->userdata('filter_rank_vocations') as $key => $value)
{
if(!array_key_exists($key, $vocations_names[$this->multworlds->setDefatulWorld()]) or in_array($key, $this->configs_rank['ocultvoc']))
{
$this->session->set_userdata('filter_rank_vocations', $vocations_names[$this->multworlds->setDefatulWorld()]);
}
}
}
else
{
$this->session->set_userdata('filter_rank_vocations', $vocations_names[$this->multworlds->setDefatulWorld()]);
}
if($this->input->post('vocation'))
{
foreach ($this->input->post('vocation') as $key)
{
if(array_key_exists($key, $vocations_names[$this->multworlds->setDefatulWorld()]) and !in_array($key, $this->configs_rank['ocultvoc']))
{
$array[$key] = null;
}
}
if(count($array))
{
$this->session->set_userdata('filter_rank_vocations', $array);
}
}
$filtros = $this->session->userdata('filter_rank_vocations');
$player_skills = (new Skill)->include_related('player', array('name', 'level', 'experience', 'maglevel', 'vocation', 'online', 'world_id'))
->where_not_in('group_id', $this->configs_rank['ocultgrup'])
->where('world_id', $this->multworlds->setDefatulWorld())
->where_in('vocation', array_keys($filtros));
$player_skills->where('skillid', 4);
$player_skills->order_by('level', 'DESC');
$player_skills->get_paged($page, '20');
//$player_skills->check_last_query();
$data['all_players'] = $player_skills;
$this->load->view('players_rank', $data);
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */ | WebATS/WebAAC | application/modules/tfs0.4/players/controllers/rank.php | PHP | mit | 4,297 |
<?php
namespace Helpers;
/**
* Assets static helper
* @date 27th November, 2014
* @date May 18 2015
*/
class Assets
{
/**
* @var array Asset templates
*/
protected static $templates = array
(
'js' => '<script src="%s" type="text/javascript"></script>',
'css' => '<link href="%s" rel="stylesheet" type="text/css">'
);
/**
* Common templates for assets.
*
* @param string|array $files
* @param string $template
*/
protected static function resource($files, $template)
{
$template = self::$templates[$template];
if (is_array($files)) {
foreach ($files as $file) {
echo sprintf($template, $file) . "\n";
}
} else {
echo sprintf($template, $files) . "\n";
}
}
/**
* Output script
*
* @param array|string $file
*/
public static function js($files)
{
static::resource($files, 'js');
}
/**
* Output stylesheet
*
* @param string $file
*/
public static function css($files)
{
static::resource($files, 'css');
}
}
| NandoKstroNet/babita | app/Helpers/Assets.php | PHP | mit | 1,175 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="de" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Blizzardcoin</source>
<translation>Über Blizzardcoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>Blizzardcoin</b> version</source>
<translation><b>Blizzardcoin</b>-Version</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation>
Dies ist experimentelle Software.
Veröffentlicht unter der MIT/X11-Softwarelizenz, siehe beiligende Datei COPYING oder http://www.opensource.org/licenses/mit-license.php.
Dieses Produkt enthält Software, die vom OpenSSL-Projekt zur Verwendung im OpenSSL-Toolkit (http://www.openssl.org/) entwickelt wurde, sowie kryptographische Software geschrieben von Eric Young (eay@cryptsoft.com) und UPnP-Software geschrieben von Thomas Bernard.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>Copyright</translation>
</message>
<message>
<location line="+0"/>
<source>The Blizzardcoin developers</source>
<translation>Die Blizzardcoinentwickler</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adressbuch</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Doppelklicken, um die Adresse oder die Bezeichnung zu bearbeiten</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Eine neue Adresse erstellen</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Ausgewählte Adresse in die Zwischenablage kopieren</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Neue Adresse</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Blizzardcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Dies sind Ihre Blizzardcoin-Adressen zum Empfangen von Zahlungen. Es steht Ihnen frei, jedem Absender eine Andere mitzuteilen, um einen besseren Überblick über eingehende Zahlungen zu erhalten.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>Adresse &kopieren</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>&QR-Code anzeigen</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Blizzardcoin address</source>
<translation>Eine Nachricht signieren, um den Besitz einer Blizzardcoin-Adresse zu beweisen</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Nachricht &signieren</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Die ausgewählte Adresse aus der Liste entfernen.</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Daten der aktuellen Ansicht in eine Datei exportieren</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation>E&xportieren</translation>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Blizzardcoin address</source>
<translation>Eine Nachricht verifizieren, um sicherzustellen, dass diese mit einer angegebenen Blizzardcoin-Adresse signiert wurde</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>Nachricht &verifizieren</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Löschen</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Blizzardcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Dies sind Ihre Blizzardcoin-Adressen zum Tätigen von Überweisungen. Bitte prüfen Sie den Betrag und die Empfangsadresse, bevor Sie Blizzardcoins überweisen.</translation>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>&Bezeichnung kopieren</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Editieren</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>Blizzardcoins &überweisen</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Adressbuch exportieren</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommagetrennte-Datei (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Fehler beim Exportieren</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Konnte nicht in Datei %1 schreiben.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Bezeichnung</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(keine Bezeichnung)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Passphrasendialog</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Passphrase eingeben</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Neue Passphrase</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Neue Passphrase wiederholen</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Geben Sie die neue Passphrase für die Brieftasche ein.<br>Bitte benutzen Sie eine Passphrase bestehend aus <b>10 oder mehr zufälligen Zeichen</b> oder <b>8 oder mehr Wörtern</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Brieftasche verschlüsseln</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Dieser Vorgang benötigt Ihre Passphrase, um die Brieftasche zu entsperren.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Brieftasche entsperren</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Dieser Vorgang benötigt Ihre Passphrase, um die Brieftasche zu entschlüsseln.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Brieftasche entschlüsseln</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Passphrase ändern</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Geben Sie die alte und neue Passphrase der Brieftasche ein.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Verschlüsselung der Brieftasche bestätigen</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BLIZZARDCOINS</b>!</source>
<translation>Warnung: Wenn Sie Ihre Brieftasche verschlüsseln und Ihre Passphrase verlieren, werden Sie <b>alle Ihre Blizzardcoins verlieren</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Sind Sie sich sicher, dass Sie Ihre Brieftasche verschlüsseln möchten?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>WICHTIG: Alle vorherigen Sicherungen Ihrer Brieftasche sollten durch die neu erzeugte, verschlüsselte Brieftasche ersetzt werden. Aus Sicherheitsgründen werden vorherige Sicherungen der unverschlüsselten Brieftasche nutzlos, sobald Sie die neue, verschlüsselte Brieftasche verwenden.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Warnung: Die Feststelltaste ist aktiviert!</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Brieftasche verschlüsselt</translation>
</message>
<message>
<location line="-56"/>
<source>Blizzardcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your blizzardcoins from being stolen by malware infecting your computer.</source>
<translation>Blizzardcoin wird jetzt beendet, um den Verschlüsselungsprozess abzuschließen. Bitte beachten Sie, dass die Verschlüsselung Ihrer Brieftasche nicht vollständig vor Diebstahl Ihrer Blizzardcoins durch Schadsoftware schützt, die Ihren Computer befällt.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Verschlüsselung der Brieftasche fehlgeschlagen</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Die Verschlüsselung der Brieftasche ist aufgrund eines internen Fehlers fehlgeschlagen. Ihre Brieftasche wurde nicht verschlüsselt.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Die eingegebenen Passphrasen stimmen nicht überein.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Entsperrung der Brieftasche fehlgeschlagen</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Die eingegebene Passphrase zum Entschlüsseln der Brieftasche war nicht korrekt.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Entschlüsselung der Brieftasche fehlgeschlagen</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Die Passphrase der Brieftasche wurde erfolgreich geändert.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Nachricht s&ignieren...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Synchronisiere mit Netzwerk...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Übersicht</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Allgemeine Übersicht der Brieftasche anzeigen</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transaktionen</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Transaktionsverlauf durchsehen</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Liste der gespeicherten Zahlungsadressen und Bezeichnungen bearbeiten</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Liste der Empfangsadressen anzeigen</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>&Beenden</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Anwendung beenden</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Blizzardcoin</source>
<translation>Informationen über Blizzardcoin anzeigen</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Über &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Informationen über Qt anzeigen</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Konfiguration...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>Brieftasche &verschlüsseln...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>Brieftasche &sichern...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>Passphrase &ändern...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Importiere Blöcke von Laufwerk...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>Reindiziere Blöcke auf Laufwerk...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Blizzardcoin address</source>
<translation>Blizzardcoins an eine Blizzardcoin-Adresse überweisen</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Blizzardcoin</source>
<translation>Die Konfiguration des Clients bearbeiten</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Eine Sicherungskopie der Brieftasche erstellen und abspeichern</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Ändert die Passphrase, die für die Verschlüsselung der Brieftasche benutzt wird</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Debugfenster</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Debugging- und Diagnosekonsole öffnen</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>Nachricht &verifizieren...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Blizzardcoin</source>
<translation>Blizzardcoin</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Brieftasche</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>Überweisen</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>&Empfangen</translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>&Adressen</translation>
</message>
<message>
<location line="+22"/>
<source>&About Blizzardcoin</source>
<translation>&Über Blizzardcoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Anzeigen / Verstecken</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Das Hauptfenster anzeigen oder verstecken</translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Verschlüsselt die zu Ihrer Brieftasche gehörenden privaten Schlüssel</translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Blizzardcoin addresses to prove you own them</source>
<translation>Nachrichten signieren, um den Besitz Ihrer Blizzardcoin-Adressen zu beweisen</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Blizzardcoin addresses</source>
<translation>Nachrichten verifizieren, um sicherzustellen, dass diese mit den angegebenen Blizzardcoin-Adressen signiert wurden</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Datei</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Einstellungen</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Hilfe</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Registerkartenleiste</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[Testnetz]</translation>
</message>
<message>
<location line="+47"/>
<source>Blizzardcoin client</source>
<translation>Blizzardcoin-Client</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Blizzardcoin network</source>
<translation><numerusform>%n aktive Verbindung zum Blizzardcoin-Netzwerk</numerusform><numerusform>%n aktive Verbindungen zum Blizzardcoin-Netzwerk</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation>Keine Blockquelle verfügbar...</translation>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation>%1 von (geschätzten) %2 Blöcken des Transaktionsverlaufs verarbeitet.</translation>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>%1 Blöcke des Transaktionsverlaufs verarbeitet.</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation><numerusform>%n Stunde</numerusform><numerusform>%n Stunden</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n Tag</numerusform><numerusform>%n Tage</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation><numerusform>%n Woche</numerusform><numerusform>%n Wochen</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation>%1 im Rückstand</translation>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation>Der letzte empfangene Block ist %1 alt.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>Transaktionen hiernach werden noch nicht angezeigt.</translation>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Fehler</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Warnung</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Hinweis</translation>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>Die Transaktion übersteigt das Größenlimit. Sie können sie trotzdem senden, wenn Sie eine zusätzliche Transaktionsgebühr in Höhe von %1 zahlen. Diese wird an die Knoten verteilt, die Ihre Transaktion bearbeiten und unterstützt damit das Blizzardcoin-Netzwerk. Möchten Sie die Gebühr bezahlen?</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Auf aktuellem Stand</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Hole auf...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Transaktionsgebühr bestätigen</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Gesendete Transaktion</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Eingehende Transaktion</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Datum: %1
Betrag: %2
Typ: %3
Adresse: %4</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>URI Verarbeitung</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Blizzardcoin address or malformed URI parameters.</source>
<translation>URI kann nicht analysiert werden! Dies kann durch eine ungültige Blizzardcoin-Adresse oder fehlerhafte URI-Parameter verursacht werden.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Brieftasche ist <b>verschlüsselt</b> und aktuell <b>entsperrt</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Brieftasche ist <b>verschlüsselt</b> und aktuell <b>gesperrt</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Blizzardcoin can no longer continue safely and will quit.</source>
<translation>Ein schwerer Fehler ist aufgetreten. Blizzardcoin kann nicht stabil weiter ausgeführt werden und wird beendet.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Netzwerkalarm</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Adresse bearbeiten</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Bezeichnung</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Die Bezeichnung dieses Adressbuchseintrags</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adresse</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Die Adresse des Adressbucheintrags. Diese kann nur für Zahlungsadressen bearbeitet werden.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Neue Empfangsadresse</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Neue Zahlungsadresse</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Empfangsadresse bearbeiten</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Zahlungsadresse bearbeiten</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Die eingegebene Adresse "%1" befindet sich bereits im Adressbuch.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Blizzardcoin address.</source>
<translation>Die eingegebene Adresse "%1" ist keine gültige Blizzardcoin-Adresse.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Die Brieftasche konnte nicht entsperrt werden.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Generierung eines neuen Schlüssels fehlgeschlagen.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Blizzardcoin-Qt</source>
<translation>Blizzardcoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>Version</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Benutzung:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>Kommandozeilenoptionen</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>UI-Optionen</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Sprache festlegen, z.B. "de_DE" (Standard: System Locale)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Minimiert starten</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Startbildschirm beim Starten anzeigen (Standard: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Erweiterte Einstellungen</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Allgemein</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation>Optionale Transaktionsgebühr pro KB, die sicherstellt, dass Ihre Transaktionen schnell bearbeitet werden. Die meisten Transaktionen sind 1 kB groß.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Transaktions&gebühr bezahlen</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Blizzardcoin after logging in to the system.</source>
<translation>Blizzardcoin nach der Anmeldung am System automatisch ausführen.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Blizzardcoin on system login</source>
<translation>&Starte Blizzardcoin nach Systemanmeldung</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation>Setzt die Clientkonfiguration auf Standardwerte zurück.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>Konfiguration &zurücksetzen</translation>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Netzwerk</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Blizzardcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Automatisch den Blizzardcoin-Clientport auf dem Router öffnen. Dies funktioniert nur, wenn Ihr Router UPnP unterstützt und dies aktiviert ist.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Portweiterleitung via &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Blizzardcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Über einen SOCKS-Proxy mit dem Blizzardcoin-Netzwerk verbinden (z.B. beim Verbinden über Tor).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>Über einen SOCKS-Proxy &verbinden:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Proxy-&IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>IP-Adresse des Proxies (z.B. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Port des Proxies (z.B. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS-&Version:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>SOCKS-Version des Proxies (z.B. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Programmfenster</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Nur ein Symbol im Infobereich anzeigen, nachdem das Programmfenster minimiert wurde.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>In den Infobereich anstatt in die Taskleiste &minimieren</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Minimiert die Anwendung anstatt sie zu beenden wenn das Fenster geschlossen wird. Wenn dies aktiviert ist, müssen Sie das Programm über "Beenden" im Menü schließen.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>Beim Schließen m&inimieren</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Anzeige</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>&Sprache der Benutzeroberfläche:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Blizzardcoin.</source>
<translation>Legt die Sprache der Benutzeroberfläche fest. Diese Einstellung wird erst nach einem Neustart von Blizzardcoin aktiv.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Einheit der Beträge:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Wählen Sie die Standarduntereinheit, die in der Benutzeroberfläche und beim Überweisen von Blizzardcoins angezeigt werden soll.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Blizzardcoin addresses in the transaction list or not.</source>
<translation>Legt fest, ob Blizzardcoin-Adressen in der Transaktionsliste angezeigt werden.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>Adressen in der Transaktionsliste &anzeigen</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Abbrechen</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Übernehmen</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>Standard</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation>Zurücksetzen der Konfiguration bestätigen</translation>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation>Einige Einstellungen benötigen möglicherweise einen Clientneustart, um aktiv zu werden.</translation>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation>Wollen Sie fortfahren?</translation>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Warnung</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Blizzardcoin.</source>
<translation>Diese Einstellung wird erst nach einem Neustart von Blizzardcoin aktiv.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Die eingegebene Proxyadresse ist ungültig.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Formular</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Blizzardcoin network after a connection is established, but this process has not completed yet.</source>
<translation>Die angezeigten Informationen sind möglicherweise nicht mehr aktuell. Ihre Brieftasche wird automatisch synchronisiert, nachdem eine Verbindung zum Blizzardcoin-Netzwerk hergestellt wurde. Dieser Prozess ist jedoch derzeit noch nicht abgeschlossen.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Kontostand:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Unbestätigt:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Brieftasche</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Unreif:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Erarbeiteter Betrag der noch nicht gereift ist</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Letzte Transaktionen</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Ihr aktueller Kontostand</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Betrag aus unbestätigten Transaktionen, der noch nicht im aktuellen Kontostand enthalten ist</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>nicht synchron</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start blizzardcoin: click-to-pay handler</source>
<translation>"blizzardcoin: Klicken-zum-Bezahlen"-Handler konnte nicht gestartet werden</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR-Code-Dialog</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Zahlung anfordern</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Betrag:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Bezeichnung:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Nachricht:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Speichern unter...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Fehler beim Kodieren der URI in den QR-Code.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Der eingegebene Betrag ist ungültig, bitte überprüfen.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Resultierende URI zu lang, bitte den Text für Bezeichnung / Nachricht kürzen.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>QR-Code abspeichern</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG-Bild (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Clientname</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>n.v.</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Clientversion</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Information</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Verwendete OpenSSL-Version</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Startzeit</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Netzwerk</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Anzahl Verbindungen</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Im Testnetz</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Blockkette</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Aktuelle Anzahl Blöcke</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Geschätzte Gesamtzahl Blöcke</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Letzte Blockzeit</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Öffnen</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Kommandozeilenoptionen</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Blizzardcoin-Qt help message to get a list with possible Blizzardcoin command-line options.</source>
<translation>Zeige die Blizzardcoin-Qt-Hilfsnachricht, um eine Liste mit möglichen Kommandozeilenoptionen zu erhalten.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Anzeigen</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konsole</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Erstellungsdatum</translation>
</message>
<message>
<location line="-104"/>
<source>Blizzardcoin - Debug window</source>
<translation>Blizzardcoin - Debugfenster</translation>
</message>
<message>
<location line="+25"/>
<source>Blizzardcoin Core</source>
<translation>Blizzardcoin-Kern</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Debugprotokolldatei</translation>
</message>
<message>
<location line="+7"/>
<source>Open the Blizzardcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Öffnet die Blizzardcoin-Debugprotokolldatei aus dem aktuellen Datenverzeichnis. Dies kann bei großen Protokolldateien einige Sekunden dauern.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Konsole zurücksetzen</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Blizzardcoin RPC console.</source>
<translation>Willkommen in der Blizzardcoin-RPC-Konsole.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Pfeiltaste hoch und runter, um die Historie durchzublättern und <b>Strg-L</b>, um die Konsole zurückzusetzen.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Bitte <b>help</b> eingeben, um eine Übersicht verfügbarer Befehle zu erhalten.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Blizzardcoins überweisen</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>In einer Transaktion an mehrere Empfänger auf einmal überweisen</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Empfänger &hinzufügen</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Alle Überweisungsfelder zurücksetzen</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>&Zurücksetzen</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Kontostand:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Überweisung bestätigen</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Überweisen</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> an %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Überweisung bestätigen</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Sind Sie sich sicher, dass Sie die folgende Überweisung ausführen möchten?<br>%1</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> und </translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Die Zahlungsadresse ist ungültig, bitte nochmals überprüfen.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Der zu zahlende Betrag muss größer als 0 sein.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Der angegebene Betrag übersteigt Ihren Kontostand.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Der angegebene Betrag übersteigt aufgrund der Transaktionsgebühr in Höhe von %1 Ihren Kontostand.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Doppelte Adresse gefunden, pro Überweisung kann an jede Adresse nur einmalig etwas überwiesen werden.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Fehler: Transaktionserstellung fehlgeschlagen!</translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Fehler: Die Transaktion wurde abgelehnt. Dies kann passieren, wenn einige Blizzardcoins aus Ihrer Brieftasche bereits ausgegeben wurden. Beispielsweise weil Sie eine Kopie Ihrer wallet.dat genutzt, die Blizzardcoins dort ausgegeben haben und dies daher in der derzeit aktiven Brieftasche nicht vermerkt ist.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Formular</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>&Betrag:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>&Empfänger:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Die Zahlungsadresse der Überweisung (z.B. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Adressbezeichnung eingeben (diese wird zusammen mit der Adresse dem Adressbuch hinzugefügt)</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Bezeichnung:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Adresse aus Adressbuch wählen</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Adresse aus der Zwischenablage einfügen</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Diesen Empfänger entfernen</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Blizzardcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Blizzardcoin-Adresse eingeben (z.B. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Signaturen - eine Nachricht signieren / verifizieren</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>Nachricht &signieren</translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Sie können Nachrichten mit Ihren Adressen signieren, um den Besitz dieser Adressen zu beweisen. Bitte nutzen Sie diese Funktion mit Vorsicht und nehmen Sie sich vor Phishingangriffen in Acht. Signieren Sie nur Nachrichten, mit denen Sie vollständig einverstanden sind.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Die Adresse mit der die Nachricht signiert wird (z.B. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Eine Adresse aus dem Adressbuch wählen</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Adresse aus der Zwischenablage einfügen</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Zu signierende Nachricht hier eingeben</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>Signatur</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Aktuelle Signatur in die Zwischenablage kopieren</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Blizzardcoin address</source>
<translation>Die Nachricht signieren, um den Besitz dieser Blizzardcoin-Adresse zu beweisen</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>&Nachricht signieren</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Alle "Nachricht signieren"-Felder zurücksetzen</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>&Zurücksetzen</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>Nachricht &verifizieren</translation>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Geben Sie die signierende Adresse, Nachricht (achten Sie darauf Zeilenumbrüche, Leerzeichen, Tabulatoren usw. exakt zu kopieren) und Signatur unten ein, um die Nachricht zu verifizieren. Vorsicht, interpretieren Sie nicht mehr in die Signatur, als in der signierten Nachricht selber enthalten ist, um nicht von einerm Man-in-the-middle-Angriff hinters Licht geführt zu werden.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Die Adresse mit der die Nachricht signiert wurde (z.B. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Blizzardcoin address</source>
<translation>Die Nachricht verifizieren, um sicherzustellen, dass diese mit der angegebenen Blizzardcoin-Adresse signiert wurde</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>&Nachricht verifizieren</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Alle "Nachricht verifizieren"-Felder zurücksetzen</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Blizzardcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Blizzardcoin-Adresse eingeben (z.B. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Auf "Nachricht signieren" klicken, um die Signatur zu erzeugen</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Blizzardcoin signature</source>
<translation>Blizzardcoin-Signatur eingeben</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Die eingegebene Adresse ist ungültig.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Bitte überprüfen Sie die Adresse und versuchen Sie es erneut.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Die eingegebene Adresse verweist nicht auf einen Schlüssel.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Entsperrung der Brieftasche wurde abgebrochen.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Privater Schlüssel zur eingegebenen Adresse ist nicht verfügbar.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Signierung der Nachricht fehlgeschlagen.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Nachricht signiert.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Die Signatur konnte nicht dekodiert werden.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Bitte überprüfen Sie die Signatur und versuchen Sie es erneut.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Die Signatur entspricht nicht dem Message Digest.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Verifikation der Nachricht fehlgeschlagen.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Nachricht verifiziert.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Blizzardcoin developers</source>
<translation>Die Blizzardcoinentwickler</translation>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[Testnetz]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Offen bis %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/offline</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/unbestätigt</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 Bestätigungen</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Status</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, über %n Knoten übertragen</numerusform><numerusform>, über %n Knoten übertragen</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Quelle</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generiert</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Von</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>An</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>eigene Adresse</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>Bezeichnung</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Gutschrift</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>reift noch %n weiteren Block</numerusform><numerusform>reift noch %n weitere Blöcke</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>nicht angenommen</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Belastung</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Transaktionsgebühr</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Nettobetrag</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Nachricht signieren</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Kommentar</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Transaktions-ID</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Generierte Blizzardcoins müssen 120 Blöcke lang reifen, bevor sie ausgegeben werden können. Als Sie diesen Block generierten, wurde er an das Netzwerk übertragen, um ihn der Blockkette hinzuzufügen. Falls dies fehlschlägt wird der Status in "nicht angenommen" geändert und der Betrag wird nicht verfügbar werden. Das kann gelegentlich passieren, wenn ein anderer Knoten einen Block fast zeitgleich generiert.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Debuginformationen</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transaktion</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>Eingaben</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Betrag</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>wahr</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>falsch</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, wurde noch nicht erfolgreich übertragen</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Offen für %n weiteren Block</numerusform><numerusform>Offen für %n weitere Blöcke</numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>unbekannt</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Transaktionsdetails</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Dieser Bereich zeigt eine detaillierte Beschreibung der Transaktion an</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Typ</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Betrag</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Offen für %n weiteren Block</numerusform><numerusform>Offen für %n weitere Blöcke</numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Offen bis %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Offline (%1 Bestätigungen)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Unbestätigt (%1 von %2 Bestätigungen)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Bestätigt (%1 Bestätigungen)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation><numerusform>Erarbeiteter Betrag wird verfügbar sein, nachdem er noch %n weiteren Block reift</numerusform><numerusform>Erarbeiteter Betrag wird verfügbar sein, nachdem er noch %n weitere Blöcke reift</numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Dieser Block wurde von keinem anderen Knoten empfangen und wird wahrscheinlich nicht angenommen werden!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generiert, jedoch nicht angenommen</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Empfangen über</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Empfangen von</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Überwiesen an</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Eigenüberweisung</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Erarbeitet</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(k.A.)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Transaktionsstatus. Fahren Sie mit der Maus über dieses Feld, um die Anzahl der Bestätigungen zu sehen.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Datum und Uhrzeit als die Transaktion empfangen wurde.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Art der Transaktion</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Zieladresse der Transaktion</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Der Betrag, der dem Kontostand abgezogen oder hinzugefügt wurde.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Alle</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Heute</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Diese Woche</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Diesen Monat</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Letzten Monat</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Dieses Jahr</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Zeitraum...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Empfangen über</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Überwiesen an</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Eigenüberweisung</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Erarbeitet</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Andere</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Zu suchende Adresse oder Bezeichnung eingeben</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Minimaler Betrag</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Adresse kopieren</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Bezeichnung kopieren</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Betrag kopieren</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Transaktions-ID kopieren</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Bezeichnung bearbeiten</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Transaktionsdetails anzeigen</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Transaktionen exportieren</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommagetrennte-Datei (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Bestätigt</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Typ</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Bezeichnung</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Betrag</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Fehler beim Exportieren</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Konnte nicht in Datei %1 schreiben.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Zeitraum:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>bis</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Blizzardcoins überweisen</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation>E&xportieren</translation>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Daten der aktuellen Ansicht in eine Datei exportieren</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Brieftasche sichern</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Brieftaschendaten (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Sicherung fehlgeschlagen</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Beim Speichern der Brieftaschendaten an die neue Position ist ein Fehler aufgetreten.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Sicherung erfolgreich</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>Speichern der Brieftaschendaten an die neue Position war erfolgreich.</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Blizzardcoin version</source>
<translation>Blizzardcoin-Version</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Benutzung:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or blizzardcoind</source>
<translation>Befehl an -server oder blizzardcoind senden</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Befehle auflisten</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Hilfe zu einem Befehl erhalten</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Optionen:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: blizzardcoin.conf)</source>
<translation>Konfigurationsdatei festlegen (Standard: blizzardcoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: blizzardcoind.pid)</source>
<translation>PID-Datei festlegen (Standard: blizzardcoind.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Datenverzeichnis festlegen</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Größe des Datenbankcaches in MB festlegen (Standard: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9333 or testnet: 19333)</source>
<translation><port> nach Verbindungen abhören (Standard: 9333 oder Testnetz: 19333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Maximal <n> Verbindungen zu Gegenstellen aufrechterhalten (Standard: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Mit dem Knoten verbinden um Adressen von Gegenstellen abzufragen, danach trennen</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Die eigene öffentliche Adresse angeben</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Schwellenwert, um Verbindungen zu sich nicht konform verhaltenden Gegenstellen zu beenden (Standard: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Anzahl Sekunden, während denen sich nicht konform verhaltenden Gegenstellen die Wiederverbindung verweigert wird (Standard: 86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Beim Einrichten des abzuhörenden RPC-Ports %u für IPv4 ist ein Fehler aufgetreten: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)</source>
<translation><port> nach JSON-RPC-Verbindungen abhören (Standard: 9332 oder Testnetz: 19332)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Kommandozeilenbefehle und JSON-RPC-Befehle annehmen</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Als Hintergrunddienst starten und Befehle annehmen</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Das Testnetz verwenden</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Eingehende Verbindungen annehmen (Standard: 1, wenn nicht -proxy oder -connect)</translation>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=blizzardcoinrpc
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 "Blizzardcoin Alert" admin@foo.com
</source>
<translation>%s, Sie müssen den Wert rpcpasswort in dieser Konfigurationsdatei angeben:
%s
Es wird empfohlen das folgende Zufallspasswort zu verwenden:
rpcuser=blizzardcoinrpc
rpcpassword=%s
(Sie müssen sich dieses Passwort nicht merken!)
Der Benutzername und das Passwort dürfen NICHT identisch sein.
Falls die Konfigurationsdatei nicht existiert, erzeugen Sie diese bitte mit Leserechten nur für den Dateibesitzer.
Es wird ebenfalls empfohlen alertnotify anzugeben, um im Problemfall benachrichtig zu werden;
zum Beispiel: alertnotify=echo %%s | mail -s \"Blizzardcoin Alert\" admin@foo.com
</translation>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Beim Einrichten des abzuhörenden RPC-Ports %u für IPv6 ist ein Fehler aufgetreten, es wird auf IPv4 zurückgegriffen: %s</translation>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>An die angegebene Adresse binden und immer abhören. Für IPv6 [Host]:Port-Schreibweise verwenden</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Blizzardcoin is probably already running.</source>
<translation>Datenverzeichnis %s kann nicht gesperrt werden. Evtl. wurde Blizzardcoin bereits gestartet.</translation>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Fehler: Die Transaktion wurde abgelehnt! Dies kann passieren, wenn einige Blizzardcoins aus Ihrer Brieftasche bereits ausgegeben wurden. Beispielsweise weil Sie eine Kopie Ihrer wallet.dat genutzt, die Blizzardcoins dort ausgegeben haben und dies daher in der derzeit aktiven Brieftasche nicht vermerkt ist.</translation>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation>Fehler: Diese Transaktion benötigt aufgrund ihres Betrags, ihrer Komplexität oder der Nutzung kürzlich erhaltener Zahlungen eine Transaktionsgebühr in Höhe von mindestens %s!</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Kommando ausführen wenn ein relevanter Alarm empfangen wird (%s im Kommando wird durch die Nachricht ersetzt)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Kommando ausführen wenn sich eine Transaktion der Briefrasche verändert (%s im Kommando wird durch die TxID ersetzt)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Maximale Größe von "high-priority/low-fee"-Transaktionen in Byte festlegen (Standard: 27000)</translation>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation>Dies ist eine Vorab-Testversion - Verwendung auf eigene Gefahr - nicht für Mining- oder Handelsanwendungen nutzen!</translation>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Warnung: -paytxfee ist auf einen sehr hohen Wert festgelegt! Dies ist die Gebühr die beim Senden einer Transaktion fällig wird.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>Warnung: Angezeigte Transaktionen sind evtl. nicht korrekt! Sie oder die anderen Knoten müssen unter Umständen (den Client) aktualisieren.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Blizzardcoin will not work properly.</source>
<translation>Warnung: Bitte korrigieren Sie die Datums- und Uhrzeiteinstellungen Ihres Computers, da Blizzardcoin ansonsten nicht ordnungsgemäß funktionieren wird!</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Warnung: Lesen von wallet.dat fehlgeschlagen! Alle Schlüssel wurden korrekt gelesen, Transaktionsdaten bzw. Adressbucheinträge fehlen aber möglicherweise oder sind inkorrekt.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Warnung: wallet.dat beschädigt, Rettung erfolgreich! Original wallet.dat wurde als wallet.{Zeitstempel}.dat in %s gespeichert. Falls Ihr Kontostand oder Transaktionen nicht korrekt sind, sollten Sie von einer Datensicherung wiederherstellen.</translation>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Versucht private Schlüssel aus einer beschädigten wallet.dat wiederherzustellen</translation>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>Blockerzeugungsoptionen:</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Nur mit dem/den angegebenen Knoten verbinden</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>Beschädigte Blockdatenbank erkannt</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Eigene IP-Adresse erkennen (Standard: 1, wenn abgehört wird und nicht -externalip)</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>Möchten Sie die Blockdatenbank nun neu aufbauen?</translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation>Fehler beim Initialisieren der Blockdatenbank</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>Fehler beim Initialisieren der Brieftaschen-Datenbankumgebung %s!</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>Fehler beim Laden der Blockdatenbank</translation>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>Fehler beim Öffnen der Blockdatenbank</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>Fehler: Zu wenig freier Laufwerksspeicherplatz!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>Fehler: Brieftasche gesperrt, Transaktion kann nicht erstellt werden!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>Fehler: Systemfehler: </translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Fehler, es konnte kein Port abgehört werden. Wenn dies so gewünscht wird -listen=0 verwenden.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation>Lesen der Blockinformationen fehlgeschlagen</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation>Lesen des Blocks fehlgeschlagen</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation>Synchronisation des Blockindex fehlgeschlagen</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation>Schreiben des Blockindex fehlgeschlagen</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation>Schreiben der Blockinformationen fehlgeschlagen</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>Schreiben des Blocks fehlgeschlagen</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation>Schreiben der Dateiinformationen fehlgeschlagen</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation>Schreiben in die Münzendatenbank fehlgeschlagen</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation>Schreiben des Transaktionsindex fehlgeschlagen</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation>Schreiben der Rücksetzdaten fehlgeschlagen</translation>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>Gegenstellen via DNS-Namensauflösung finden (Standard: 1, außer bei -connect)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation>Blizzardcoins generieren (Standard: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>Wieviele Blöcke sollen beim Starten geprüft werden (Standard: 288, 0 = alle)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation>Wie gründlich soll die Blockprüfung sein (0-4, Standard: 3)</translation>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation>Nicht genügend File-Deskriptoren verfügbar.</translation>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Blockkettenindex aus aktuellen Dateien blk000??.dat wiederaufbauen</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>Maximale Anzahl an Threads zur Verarbeitung von RPC-Anfragen festlegen (Standard: 4)</translation>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>Verifiziere Blöcke...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>Verifiziere Brieftasche...</translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Blöcke aus externer Datei blk000??.dat importieren</translation>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation>Maximale Anzahl an Skript-Verifizierungs-Threads festlegen (bis zu 16, 0 = automatisch, <0 = soviele Kerne frei lassen, Standard: 0)</translation>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>Hinweis</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Ungültige Adresse in -tor: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation>Ungültiger Betrag für -minrelaytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation>Ungültiger Betrag für -mintxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation>Einen vollständigen Transaktionsindex pflegen (Standard: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Maximale Größe, <n> * 1000 Byte, des Empfangspuffers pro Verbindung (Standard: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Maximale Größe, <n> * 1000 Byte, des Sendepuffers pro Verbindung (Standard: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>Blockkette nur akzeptieren, wenn sie mit den integrierten Prüfpunkten übereinstimmt (Standard: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Verbinde nur zu Knoten des Netztyps <net> (IPv4, IPv6 oder Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Ausgabe zusätzlicher Debugginginformationen. Beinhaltet alle anderen "-debug*"-Parameter</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Ausgabe zusätzlicher Netzwerk-Debugginginformationen</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Der Debugausgabe einen Zeitstempel voranstellen</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Blizzardcoin Wiki for SSL setup instructions)</source>
<translation>SSL-Optionen: (siehe Blizzardcoin-Wiki für SSL-Installationsanweisungen)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>SOCKS-Version des Proxies festlegen (4-5, Standard: 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Rückverfolgungs- und Debuginformationen an die Konsole senden anstatt sie in die Datei debug.log zu schreiben</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Rückverfolgungs- und Debuginformationen an den Debugger senden</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Maximale Blockgröße in Byte festlegen (Standard: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Minimale Blockgröße in Byte festlegen (Standard: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Verkleinere Datei debug.log beim Start des Clients (Standard: 1, wenn kein -debug)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation>Signierung der Transaktion fehlgeschlagen</translation>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Verbindungstimeout in Millisekunden festlegen (Standard: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation>Systemfehler: </translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation>Transaktionsbetrag zu gering</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation>Transaktionsbeträge müssen positiv sein</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation>Transaktion zu groß</translation>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>UPnP verwenden, um die Portweiterleitung einzurichten (Standard: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>UPnP verwenden, um die Portweiterleitung einzurichten (Standard: 1, wenn abgehört wird)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Proxy verwenden, um versteckte Tor-Dienste zu erreichen (Standard: identisch mit -proxy)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Benutzername für JSON-RPC-Verbindungen</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>Warnung</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Warnung: Diese Version is veraltet, Aktualisierung erforderlich!</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation>Sie müssen die Datenbank mit Hilfe von -reindex neu aufbauen, um -txindex zu verändern.</translation>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat beschädigt, Rettung fehlgeschlagen</translation>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Passwort für JSON-RPC-Verbindungen</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>JSON-RPC-Verbindungen von der angegebenen IP-Adresse erlauben</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Sende Befehle an Knoten <ip> (Standard: 127.0.0.1)</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Kommando ausführen wenn der beste Block wechselt (%s im Kommando wird durch den Hash des Blocks ersetzt)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Brieftasche auf das neueste Format aktualisieren</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Größe des Schlüsselpools festlegen auf <n> (Standard: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Blockkette erneut nach fehlenden Transaktionen der Brieftasche durchsuchen</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>OpenSSL (https) für JSON-RPC-Verbindungen verwenden</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Serverzertifikat (Standard: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Privater Serverschlüssel (Standard: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Akzeptierte Chiffren (Standard: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Dieser Hilfetext</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Kann auf diesem Computer nicht an %s binden (von bind zurückgegebener Fehler %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Verbindung über SOCKS-Proxy herstellen</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Erlaube DNS-Namensauflösung für -addnode, -seednode und -connect</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Lade Adressen...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Fehler beim Laden von wallet.dat: Brieftasche beschädigt</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Blizzardcoin</source>
<translation>Fehler beim Laden von wallet.dat: Brieftasche benötigt neuere Version von Blizzardcoin</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Blizzardcoin to complete</source>
<translation>Brieftasche musste neu geschrieben werden: Starten Sie Blizzardcoin zur Fertigstellung neu</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Fehler beim Laden von wallet.dat (Brieftasche)</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Ungültige Adresse in -proxy: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Unbekannter Netztyp in -onlynet angegeben: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Unbekannte Proxyversion in -socks angefordert: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Kann Adresse in -bind nicht auflösen: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Kann Adresse in -externalip nicht auflösen: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Ungültiger Betrag für -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Ungültiger Betrag</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Unzureichender Kontostand</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Lade Blockindex...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Mit dem Knoten verbinden und versuchen die Verbindung aufrecht zu halten</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Blizzardcoin is probably already running.</source>
<translation>Kann auf diesem Computer nicht an %s binden. Evtl. wurde Blizzardcoin bereits gestartet.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Gebühr pro KB, die gesendeten Transaktionen hinzugefügt wird</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Lade Brieftasche...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Brieftasche kann nicht auf eine ältere Version herabgestuft werden</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Standardadresse kann nicht geschrieben werden</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Durchsuche erneut...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Laden abgeschlossen</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>Zur Nutzung der %s Option</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Fehler</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Sie müssen den Wert rpcpassword=<passwort> in der Konfigurationsdatei angeben:
%s
Falls die Konfigurationsdatei nicht existiert, erzeugen Sie diese bitte mit Leserechten nur für den Dateibesitzer.</translation>
</message>
</context>
</TS> | blizzardcoin/blizzardcoin | src/qt/locale/bitcoin_de.ts | TypeScript | mit | 120,925 |
$(function(){
BrowserDetect.init();
$('.minifyme').on("navminified", function() {
// $('td.expand,th.expand').toggle();
});
// Activate all popovers (if NOT mobile)
if ( !BrowserDetect.isMobile() ) {
$('[data-toggle="popover"]').popover();
}
});
$.fn.pressEnter = function(fn) {
return this.each(function() {
$(this).bind('enterPress', fn);
$(this).keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterPress");
}
})
});
};
function ensureHeightOfSidebar() {
$('#left-panel').css('height',$('#main').height());
}
BrowserDetect =
// From http://stackoverflow.com/questions/13478303/correct-way-to-use-modernizr-to-detect-ie
{
init: function ()
{
this.browser = this.searchString(this.dataBrowser) || "Other";
this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "Unknown";
},
isMobile: function ()
{
if (navigator.userAgent.search(/(Android|Touch|iPhone|iPad)/) == -1) {
return false;
} else {
return true;
}
},
searchString: function (data)
{
for (var i=0 ; i < data.length ; i++)
{
var dataString = data[i].string;
this.versionSearchString = data[i].subString;
if (dataString.indexOf(data[i].subString) != -1)
{
return data[i].identity;
}
}
},
searchVersion: function (dataString)
{
var index = dataString.indexOf(this.versionSearchString);
if (index == -1) return;
return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
},
dataBrowser:
[
{ string: navigator.userAgent, subString: "Chrome", identity: "Chrome" },
{ string: navigator.userAgent, subString: "MSIE", identity: "Explorer" },
{ string: navigator.userAgent, subString: "Firefox", identity: "Firefox" },
{ string: navigator.userAgent, subString: "Safari", identity: "Safari" },
{ string: navigator.userAgent, subString: "Opera", identity: "Opera" }
]
}; | empath-io/empath | app/assets/javascripts/main.js | JavaScript | mit | 2,251 |
import { PickScaleConfigWithoutType, ScaleConfigWithoutType } from './types/ScaleConfig';
import { DefaultThresholdInput, D3Scale, PickD3Scale } from './types/Scale';
import { StringLike, DefaultOutput } from './types/Base';
import scaleOperator, { ALL_OPERATORS } from './operators/scaleOperator';
const applyAllOperators = scaleOperator(...ALL_OPERATORS);
// Overload function signature for more strict typing, e.g.,
// If the scale is a ScaleLinear, the config is a linear config.
function updateScale<
Output = DefaultOutput,
DiscreteInput extends StringLike = StringLike,
ThresholdInput extends DefaultThresholdInput = DefaultThresholdInput
>(
scale: PickD3Scale<'linear', Output>,
config: PickScaleConfigWithoutType<'linear', Output>,
): PickD3Scale<'linear', Output>;
function updateScale<
Output = DefaultOutput,
DiscreteInput extends StringLike = StringLike,
ThresholdInput extends DefaultThresholdInput = DefaultThresholdInput
>(
scale: PickD3Scale<'log', Output>,
config: PickScaleConfigWithoutType<'log', Output>,
): PickD3Scale<'log', Output>;
function updateScale<
Output = DefaultOutput,
DiscreteInput extends StringLike = StringLike,
ThresholdInput extends DefaultThresholdInput = DefaultThresholdInput
>(
scale: PickD3Scale<'pow', Output>,
config: PickScaleConfigWithoutType<'pow', Output>,
): PickD3Scale<'pow', Output>;
function updateScale<
Output = DefaultOutput,
DiscreteInput extends StringLike = StringLike,
ThresholdInput extends DefaultThresholdInput = DefaultThresholdInput
>(
scale: PickD3Scale<'sqrt', Output>,
config: PickScaleConfigWithoutType<'sqrt', Output>,
): PickD3Scale<'sqrt', Output>;
function updateScale<
Output = DefaultOutput,
DiscreteInput extends StringLike = StringLike,
ThresholdInput extends DefaultThresholdInput = DefaultThresholdInput
>(
scale: PickD3Scale<'symlog', Output>,
config: PickScaleConfigWithoutType<'symlog', Output>,
): PickD3Scale<'symlog', Output>;
function updateScale<
Output = DefaultOutput,
DiscreteInput extends StringLike = StringLike,
ThresholdInput extends DefaultThresholdInput = DefaultThresholdInput
>(
scale: PickD3Scale<'time', Output>,
config: PickScaleConfigWithoutType<'time', Output>,
): PickD3Scale<'time', Output>;
function updateScale<
Output = DefaultOutput,
DiscreteInput extends StringLike = StringLike,
ThresholdInput extends DefaultThresholdInput = DefaultThresholdInput
>(
scale: PickD3Scale<'utc', Output>,
config: PickScaleConfigWithoutType<'utc', Output>,
): PickD3Scale<'utc', Output>;
function updateScale<
Output = DefaultOutput,
DiscreteInput extends StringLike = StringLike,
ThresholdInput extends DefaultThresholdInput = DefaultThresholdInput
>(
scale: PickD3Scale<'quantile', Output>,
config: PickScaleConfigWithoutType<'quantile', Output>,
): PickD3Scale<'quantile', Output>;
function updateScale<
Output = DefaultOutput,
DiscreteInput extends StringLike = StringLike,
ThresholdInput extends DefaultThresholdInput = DefaultThresholdInput
>(
scale: PickD3Scale<'quantize', Output>,
config: PickScaleConfigWithoutType<'quantize', Output>,
): PickD3Scale<'quantize', Output>;
function updateScale<
Output = DefaultOutput,
DiscreteInput extends StringLike = StringLike,
ThresholdInput extends DefaultThresholdInput = DefaultThresholdInput
>(
scale: PickD3Scale<'threshold', Output, StringLike, ThresholdInput>,
config: PickScaleConfigWithoutType<'threshold', Output, StringLike, ThresholdInput>,
): PickD3Scale<'threshold', Output, StringLike, ThresholdInput>;
function updateScale<
Output = DefaultOutput,
DiscreteInput extends StringLike = StringLike,
ThresholdInput extends DefaultThresholdInput = DefaultThresholdInput
>(
scale: PickD3Scale<'ordinal', Output, DiscreteInput>,
config: PickScaleConfigWithoutType<'ordinal', Output, DiscreteInput>,
): PickD3Scale<'ordinal', Output, DiscreteInput>;
function updateScale<
Output = DefaultOutput,
DiscreteInput extends StringLike = StringLike,
ThresholdInput extends DefaultThresholdInput = DefaultThresholdInput
>(
scale: PickD3Scale<'point', Output, DiscreteInput>,
config: PickScaleConfigWithoutType<'point', Output, DiscreteInput>,
): PickD3Scale<'point', Output, DiscreteInput>;
function updateScale<
Output = DefaultOutput,
DiscreteInput extends StringLike = StringLike,
ThresholdInput extends DefaultThresholdInput = DefaultThresholdInput
>(
scale: PickD3Scale<'band', Output, DiscreteInput>,
config: PickScaleConfigWithoutType<'band', Output, DiscreteInput>,
): PickD3Scale<'band', Output, DiscreteInput>;
function updateScale<
Output = DefaultOutput,
DiscreteInput extends StringLike = StringLike,
ThresholdInput extends DefaultThresholdInput = DefaultThresholdInput,
Scale extends D3Scale<Output, DiscreteInput, ThresholdInput> = D3Scale<
Output,
DiscreteInput,
ThresholdInput
>
>(scale: Scale, config?: undefined): Scale;
// Actual implementation
function updateScale<
Output,
DiscreteInput extends StringLike,
ThresholdInput extends DefaultThresholdInput
>(
scale: D3Scale<Output, DiscreteInput, ThresholdInput>,
config?: ScaleConfigWithoutType<Output, DiscreteInput, ThresholdInput>,
) {
return applyAllOperators(scale.copy(), config);
}
export default updateScale;
| hshoff/vx | packages/visx-scale/src/updateScale.ts | TypeScript | mit | 5,310 |
<?php
session_start();
//echo "filename:". $_REQUEST['fn'];
ini_set('display_errors', 'Off');
ini_set('display_startup_errors', 'Off');
error_reporting(0);
include("../config.php");
include("../class/mysql.class.php");
if ($_REQUEST['r'])
$resource = $_REQUEST['r'];
$db = new MySQL(true);
if ($db->Error()) $db->Kill();
$db->Open();
$sql = "select content from mysite_contents where resource='".$resource."'";
//echo $sql."<br />";
$results = $db->QueryArray($sql);
$db->Close();
$data = $results[0]['content'];
//echo $data_file;
if ($_REQUEST['s'] == 1)
echo "<strong>File salvato.</strong>";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Full featured example using jQuery plugin</title>
<!-- Load jQuery -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1");
</script>
<!-- Load TinyMCE -->
<script type="text/javascript" src=".tiny_mce/jquery.tinymce.js"></script>
<script type="text/javascript">
$().ready(function() {
$('textarea.tinymce').tinymce({
// Location of TinyMCE script
script_url : '.tiny_mce/tiny_mce.js',
// General options
theme : "advanced",
plugins : "autolink,lists,pagebreak,style,layer,table,save,advhr,advlink,inlinepopups,insertdatetime,searchreplace,print,contextmenu,paste,directionality,visualchars,nonbreaking,xhtmlxtras,template,advlist",
// Theme options
theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing : true,
// Example content CSS (should be your site CSS)
content_css : "content.css",
// Drop lists for link/image/media/template dialogs
// Replace values for the template plugin
template_replace_values : {
username : "Some User",
staffid : "991234"
}
});
document.getElementById("elm1").style.width = $(window).width() - 40 + "px";
document.getElementById("elm1").style.height = $(window).height() - 80 + "px";
});
</script>
<!-- /TinyMCE -->
</head>
<body>
<form method="post" action="save.php">
<div>
<div>
<textarea id="elm1" name="elm1" class="tinymce">
<?php echo $data;?>
</textarea>
</div>
<!-- <a href="javascript:;" onclick="$('#elm1').tinymce().show();return false;">[Show]</a>
<a href="javascript:;" onclick="$('#elm1').tinymce().hide();return false;">[Hide]</a>
<a href="javascript:;" onclick="$('#elm1').tinymce().execCommand('Bold');return false;">[Bold]</a>
<a href="javascript:;" onclick="alert($('#elm1').html());return false;">[Get contents]</a>
<a href="javascript:;" onclick="alert($('#elm1').tinymce().selection.getContent());return false;">[Get selected HTML]</a>
<a href="javascript:;" onclick="alert($('#elm1').tinymce().selection.getContent({format : 'text'}));return false;">[Get selected text]</a>
<a href="javascript:;" onclick="alert($('#elm1').tinymce().selection.getNode().nodeName);return false;">[Get selected element]</a>
<a href="javascript:;" onclick="$('#elm1').tinymce().execCommand('mceInsertContent',false,'<b>Hello world!!</b>');return false;">[Insert HTML]</a>
<a href="javascript:;" onclick="$('#elm1').tinymce().execCommand('mceReplaceContent',false,'<b>{$selection}</b>');return false;">[Replace selection]</a>
<br />
<input type="submit" name="save" value="Submit" />
<input type="reset" name="reset" value="Reset" />
Some integration calls -->
</div>
<input type="hidden" value="<?php echo $resource?>" name="resource">
</form>
<script type="text/javascript">
/*if (document.location.protocol == 'file:') {
alert("The examples might not work properly on the local file system due to security settings in your browser. Please use a real webserver.");
}*/
</script>
</body>
</html>
| yellowelise/crypt2share | assets/mysite/editor.php | PHP | mit | 4,709 |
/*
Author: Gerard Lamusse
Created: 08/2015
Version: 1.0
URL: https://github.com/u12206050/jsonZipper
*/
var jsonZipper = (function(){
var jz = function(_jsonObj, _options) {
var Z = this;
var MAP = [];
var opts = _options && typeof(_options) !== "boolean" ? _options : {};
/* Public Functions */
Z.zip = function() {
if (Z.status === "zipable") {
Z.uzOpts = {I:[],A:Z.isArray,eC:[],iC:[]};
if (Z.isArray) {
var x = 0;
var y = Z.JO.length;
while (x < y) {
compress(Z.JO[x++]);
}
} else {
compress(Z.JO);
}
Z.status = "zipped";
return {M:MAP,D:Z.JO,O:Z.uzOpts};
} return false;
};
Z.unzip = function() {
if (Z.status === "unzipable") {
if (Z.isArray) {
var x = 0;
var y = Z.JO.length;
while (x < y) {
extract(Z.JO[x++]);
}
} else {
extract(Z.JO);
}
Z.status = "unzipped";
return Z.JO;
} return false;
};
Z.compress = function(obj) {
if (Z.status === "compressing") {
Z.JO.push(obj);
compress(obj);
} else if (Z.status === "ready to load object") {
Z.isArray = true;
Z.uzOpts = {I:[],A:Z.isArray,eC:[],iC:[]};
Z.status = "compressing";
Z.JO = [];
Z.JO.push(obj);
compress(obj);
} else return false;
return {M:MAP,D:Z.JO,O:Z.uzOpts};
};
var prevExtractIndex = false;
var extracted = [];
Z.extract = function(i) {
if (Z.status === "unzipable" || Z.status === "zipped") {
if (extracted.indexOf(i) > -1) {
prev = Z.JO[i];
} else {
if (!prevExtractIndex || prevExtractIndex+1 !== i) {
setPrev(i);
}
extract(Z.JO[i]);
extracted.push(i);
}
prevExtractIndex = i;
}
return Z.JO[i];
};
Z.length = function() {
return JSON.stringify(Z.JO).length + (MAP ? JSON.stringify(MAP).length : 0);
};
Z.options = function(opts,isArray) {
/* []: An array of key names that will be used as identifiers.
WARGING: Should be within every object, but repeating, NO Booleans or Integers allowed.
Hint: Most common values that can be guessed/used from previous objects */
Z.identifiers = opts.identifiers || [];
/* boolean: If _jsonObj is an array or not */
Z.isArray = opts.isArray || isArray;
/* []: An array of key names not to map or zip */
Z.exclude = opts.exclude || [];
/* []: An array of key names which values to include in mapping will need identifiers */
Z.include = opts.include || [];
/* []: An array of key names to be removed from the object */
Z.remove = opts.remove || false;
/* {}: An object containing key(s) to add, with function(s) which return the value */
Z.add = opts.add || false;
}
Z.load = function(_jsonObj, isJZobj) {
Z.startLength = 0;
MAP = [];
try {
var stringIT = JSON.stringify(_jsonObj);
Z.startLength = stringIT.length;
Z.JO = JSON.parse(stringIT);
}
catch (err) {
throw "The json object has recursive references or is too big to load into memory";
}
Z.status = "zipable";
if (isJZobj) {
if (Z.JO.D && Z.JO.O && Z.JO.M) {
MAP = Z.JO.M;
Z.identifiers = Z.JO.O.I || [];
Z.isArray = Z.JO.O.A;
Z.exclude = Z.JO.O.eC || false;
Z.include = Z.JO.O.iC || false;
Z.JO = Z.JO.D;
Z.remove = false;
Z.add = false;
Z.status = "unzipable";
} else
Z.options(isJZobj,_jsonObj.constructor === Array);
}
prev = false;
prevID = false;
};
/* Private Functions */
var getID = function(key, value) {
var mI = MAP.indexOf(key);
if (mI < 0) {
if (value) {
return MAP.push(key) - 1;
}
if (Z.exclude.indexOf(key) > -1) {
Z.uzOpts.eC.push(key);
return key;
} else {
mI = MAP.push(key) - 1;
if (Z.identifiers.indexOf(key) > -1) {
Z.uzOpts.I.push(mI);
}
if (Z.include.indexOf(key) > -1) {
Z.uzOpts.iC.push(mI);
}
}
}
return mI;
};
/* Compress the given object, taking note of the previous object */
var prev = false;
var prevID = false;
var compress = function(J) {
add(J);
var keys = Object.keys(J);
var prevSame = prev ? true : false;
var id = '';
var i=0;
for (xend=Z.identifiers.length; i<xend; i++) {
var ikey = Z.identifiers[i];
J[ikey] = getID(J[ikey],1);
id += J[ikey];
}
if (!prevSame || !prevID || prevID !== id) {
prevSame = false;
prev = J;
prevID = id;
}
i=0;
for (iend=keys.length; i<iend; i++) {
var key = keys[i];
if (Z.remove && Z.remove.indexOf(key) > -1)
delete J[key];
else {
var mI = getID(key);
if (prevSame && (MAP[prev[mI]] === J[key] || prev[mI] === J[key]))
delete J[key];
else if (Z.include.indexOf(key) > -1) {
if (Z.identifiers.indexOf(key) > -1)
J[mI] = J[key];
else J[mI] = getID(J[key],1);
delete J[key];
} else if (mI !== key) {
J[mI] = J[key];
delete J[key];
}
}
}
};
/* Extract the given object, taking note of the previous object */
var extract = function(J) {
if (J === prev)
return;
add(J);
var prevSame = Z.isArray ? isSame(prev, J) : false;
var keys = Object.keys(J);
if (prevSame)
extend(prev,J);
else if (Z.identifiers) {
var x=0;
for (xend=Z.identifiers.length; x<xend; x++) {
var ikey = Z.identifiers[x];
J[ikey] = MAP[J[ikey]];
}
}
var i=0;
for (iend=keys.length; i<iend; i++) {
var key = keys[i]*1;
var value = J[key];
if (Z.remove && Z.remove.indexOf(key) > -1)
delete J[key];
else {
if (Z.exclude.indexOf(key) > -1) {
J[key] = J[key];
if (Z.include.indexOf(key) > -1)
J[key] = MAP[J[key]];
} else {
if (Z.include.indexOf(key) > -1)
J[MAP[key]] = MAP[J[key]];
else
J[MAP[key]] = J[key];
delete J[key];
}
}
}
prev = J;
};
/* Add the additional keys and values to the given object */
var add = function(J) {
if (Z.add) {
for (var key in Z.add) {
if('undefined' !== typeof Z.add[key]){
if (typeof(Z.add[key]) === "function")
J[key] = Z.add[key](J);
else
J[key] = Z.add[key];
}
}
}
};
/* Set the previous full object from the current index, incl. */
var setPrev = function(i) {
if (i > 0) {
var x=0;
for (xend=Z.identifiers.length; x<xend; x++) {
if ('undefined' === typeof Z.JO[i][Z.identifiers[x]]) {
setPrev(i-1);
return;
}
}
extract(Z.JO[i]);
} else
extract(Z.JO[0]);
};
/* Checks if identiifiers match */
var isSame = function(obj1, obj2) {
if (Z.identifiers && obj1 && obj2 && obj1 !== obj2) {
var x=0;
for (xend=Z.identifiers.length; x<xend; x++) {
var key = Z.identifiers[x];
var mKey = MAP[Z.identifiers[x]];
if ('undefined' === typeof obj1[mKey] || ('undefined' !== typeof obj2[key] && MAP[obj2[key]] !== obj1[mKey]))
return false;
}
} else return false;
return true;
};
/* Merges an object by reference into the first one, replacing values from the second object into the first if duplicate keys exist */
var merge = function(obj1,obj2) {
for (var key in obj2) {
if('undefined' !== typeof obj2[key]) {
obj1[key] = obj2[key];
}
}
};
/* Adds all keys and values from the base to obj2 for each key that does not exist in obj2 */
var extend = function(base,obj2) {
for (var key in base) {
if('undefined' === typeof obj2[key]) {
obj2[key] = base[key];
}
}
};
Z.setID = opts.setID || false;
Z.options(opts,_jsonObj.constructor === Array)
Z.status = "ready to load object";
/* Check if object is given and if options is object or 'compressed' flag */
if (_jsonObj && typeof(_jsonObj) === "object") {
/* When unzipping an object ensure _options is true and not an object, once loaded, you can set the options */
if (_options && typeof(_options) === "boolean") {
Z.load(_jsonObj,true);
} else {
Z.load(_jsonObj,false);
}
}
};
return jz;
})(); | mboulette/incendie | javascript/jsonZipper.js | JavaScript | mit | 8,405 |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.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.
*
* 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.
*******************************************************************************/
//
// Novell.Directory.Ldap.MessageVector.cs
//
// Author:
// Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
namespace Novell.Directory.Ldap
{
/// <summary> The <code>MessageVector</code> class implements additional semantics
/// to Vector needed for handling messages.
/// </summary>
/* package */
class MessageVector:System.Collections.ArrayList
{
/// <summary>Returns an array containing all of the elements in this MessageVector.
/// The elements returned are in the same order in the array as in the
/// Vector. The contents of the vector are cleared.
///
/// </summary>
/// <returns> the array containing all of the elements.
/// </returns>
virtual internal System.Object[] ObjectArray
{
/* package */
get
{
lock (this)
{
System.Object[] results = new System.Object[Count];
Array.Copy((System.Array) ToArray(), 0, (System.Array) results, 0, Count);
for (int i = 0; i < Count; i++)
{
ToArray()[i] = null;
}
// Count = 0;
return results;
}
}
}
/* package */
internal MessageVector(int cap, int incr):base(cap)
{
return ;
}
/// <summary> Finds the Message object with the given MsgID, and returns the Message
/// object. It finds the object and returns it in an atomic operation.
///
/// </summary>
/// <param name="msgId">The msgId of the Message object to return
///
/// </param>
/// <returns> The Message object corresponding to this MsgId.
///
/// @throws NoSuchFieldException when no object with the corresponding
/// value for the MsgId field can be found.
/// </returns>
/* package */
internal Message findMessageById(int msgId)
{
lock (this)
{
Message msg = null;
for (int i = 0; i < Count; i++)
{
if ((msg = (Message) ToArray()[i]) == null)
{
throw new System.FieldAccessException();
}
if (msg.MessageID == msgId)
{
return msg;
}
}
throw new System.FieldAccessException();
}
}
}
}
| jjenki11/blaze-chem-rendering | qca_designer/lib/ml-pnet-0.8.1/mcs-sources/class/Novell.Directory.Ldap/Novell.Directory.Ldap/MessageVector.cs | C# | mit | 3,366 |
package com.github.daneko.simpleitemanimator;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPropertyAnimatorCompat;
import android.view.View;
import fj.F;
import fj.F2;
import fj.F3;
import fj.Unit;
import fj.data.Option;
/**
* @see {@link android.support.v7.widget.DefaultItemAnimator}
*/
public class DefaultAnimations {
public static F<View, Unit> addPrepareStateSetter() {
return (view -> {
ViewCompat.setAlpha(view, 0);
return Unit.unit();
});
}
public static F<View, Unit> removePrepareStateSetter() {
return (view -> Unit.unit());
}
public static F2<View, SimpleItemAnimator.EventParam, Unit> movePrepareStateSetter() {
return ((view, param) -> {
if (param.getFromPoint().isNone() || param.getToPoint().isNone()) {
return Unit.unit();
}
final int deltaX =
param.getToPoint().some().x -
param.getFromPoint().some().x +
(int) ViewCompat.getTranslationX(view);
final int deltaY =
param.getToPoint().some().y -
param.getFromPoint().some().y +
(int) ViewCompat.getTranslationY(view);
ViewCompat.setTranslationX(view, -deltaX);
ViewCompat.setTranslationY(view, -deltaY);
return Unit.unit();
});
}
public static F3<View, Option<View>, SimpleItemAnimator.EventParam, Unit> changePrepareStateSetter() {
return ((oldView, newViewOption, param) -> {
if (param.getFromPoint().isNone() || param.getToPoint().isNone() || newViewOption.isNone()) {
return Unit.unit();
}
final View newView = newViewOption.some();
final int deltaX =
param.getToPoint().some().x -
param.getFromPoint().some().x +
(int) ViewCompat.getTranslationX(oldView);
final int deltaY =
param.getToPoint().some().y -
param.getFromPoint().some().y +
(int) ViewCompat.getTranslationY(oldView);
ViewCompat.setTranslationX(newView, -deltaX);
ViewCompat.setTranslationY(newView, -deltaY);
ViewCompat.setAlpha(newView, 0);
return Unit.unit();
});
}
public static F<ViewPropertyAnimatorCompat, ViewPropertyAnimatorCompat> addEventAnimation() {
return (animator -> animator.alpha(1f));
}
public static F<ViewPropertyAnimatorCompat, ViewPropertyAnimatorCompat> removeEventAnimation() {
return (animator -> animator.alpha(0f));
}
public static F2<ViewPropertyAnimatorCompat, SimpleItemAnimator.EventParam, ViewPropertyAnimatorCompat> moveEventAnimation() {
return ((animator, param) -> animator.translationY(0f).translationX(0f));
}
public static F2<ViewPropertyAnimatorCompat, SimpleItemAnimator.EventParam, ViewPropertyAnimatorCompat> changeEventAnimationForOldView() {
return ((animator, param) -> {
if (param.getFromPoint().isNone() || param.getToPoint().isNone()) {
return animator;
}
final int deltaX = param.getToPoint().some().x - param.getFromPoint().some().x;
final int deltaY = param.getToPoint().some().y - param.getFromPoint().some().y;
return animator.translationX(deltaX).translationY(deltaY).alpha(0f);
});
}
public static F2<ViewPropertyAnimatorCompat, SimpleItemAnimator.EventParam, ViewPropertyAnimatorCompat> changeEventAnimationForNewView() {
return ((animator, param) -> animator.translationX(0f).translationY(0f).alpha(0f));
}
}
| daneko/SimpleItemAnimator | library/src/main/java/com/github/daneko/simpleitemanimator/DefaultAnimations.java | Java | mit | 3,855 |
<?php
// Newfoundland Genetics Project
// https://github.com/opyum/nlgp
// Admin Functions
// "admin.php"
// Get config and start session
require 'inc/config.php';
session_start();
$uid = $_SESSION['UserID'];
if (isset($_SESSION['UserLoggedIn']) && ($_SESSION['UserLevel'] == 2)) {
// Print Token
if (isset($_GET['print_token_sheet'])) {
$sql = "SELECT * FROM `reg_token` ORDER BY `id` DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
$token = $row['token'];
$issued = $row['added'];
$issued = strtotime($issued);
$issued = date('d M Y', $issued);
?>
<style>
/* unvisited link */
a:link {
color: blue;
}
/* visited link */
a:visited {
color: blue;
}
/* mouse over link */
a:hover {
color: blue;
}
/* selected link */
a:active {
color: blue;
}
</style>
<h1 align="center">Newfoundland Genetics Project<br><a href="//www.nlgp.ca">www.nlgp.ca</a></h1>
<h2 align="center">This token issued <?php echo $issued; ?></h2>
<p align="center">
Notice: The Registration Token is updated on an ongoing basis. Please make sure you are using the most recent. If you are receiving errors when using your token, please check this document again.
</p>
<br><br>
<h2 align="center">Registration Token:</h2>
<h3 align="center"><?php echo $token; ?></h3>
<br><br>
<h2 align="center">Direct Link:</h2>
<h3 align="center"><a href="//www.nlgp.ca/register?token=<?php echo $token; ?>">https://www.nlgp.ca/register?token=<?php echo $token; ?></a></h3>
<?php
die();
}
// Get header
$site_title = "Site Administration Tools | $site_tag";
include (APP_INCLUDES_PATH . 'header.php');
// Registration Tokens
if (isset($_GET['reg_tokens']) && ($_SESSION['UserLevel'] == 2 OR $_SESSION['UserLevel'] == 3)) {
if (isset($_GET['generate'])) {
if (isset($_GET['do'])) {
include (APP_FUNCTIONS_PATH . 'pwgen.php');
function token($length){
$str = "";
$characters = array_merge(range('A','Z'), range('a','z'), range('0','9'));
$max = count($characters) - 1;
for ($i = 0; $i < $length; $i++) {
$rand = mt_rand(0, $max);
$str .= $characters[$rand];
}
return $str;
}
$token = token(15);
$sql = "INSERT INTO `reg_token` (`token`) VALUES ('$token')";
$result = mysqli_query($conn, $sql);
if (!$result) {
error_log("Connection failed: " . mysqli_error($conn));
}
// If the insert Query was successful.
if (mysqli_affected_rows($conn) == 1) {
$_SESSION['messages'] = '<div class="alert alert-success"><a href="#" class="close" data-dismiss="alert">×</a>New Token Generated Successfully!</div>';
header('Location: /admin?reg_tokens&view');
}
else {
$_SESSION['messages'] = '<div class="alert alert-danger"><a href="#" class="close" data-dismiss="alert">×</a>Token Generation Failed!</div>';
header('Location: /');
}
}
?>
<div class="container">
<div class="row">
<div class="col-sm-12 margin-top-25">
<div class="alert alert-info"><strong>Are you sure you want to generate a new token?</strong></div>
</div>
<button type="button" id="do" class="btn btn-primary center-block" onclick="location.href = '/admin?reg_tokens&generate&do';">Create New</button>
</div>
</div>
<?php
}
else if (isset($_GET['view'])) {
$sql = "SELECT `token` FROM `reg_token` ORDER BY `id` DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
$token = $row['token'];
?>
<div class="container">
<h1 class="page-header">Registration Token Management</h1>
<h2>Token:</h2>
<p><strong><?php echo $token; ?></strong></p>
<button type="button" id="do" class="btn btn-primary" onclick="window.open('/admin?print_token_sheet', '_blank');">Print Token Sheet</button>
</div>
<?php
}
else {
header('Location: /admin?reg_tokens&view');
}
}
else if (isset($_GET['manage']) && ($_SESSION['UserLevel'] == 2 OR $_SESSION['UserLevel'] == 3)) {
if (isset($_GET['members'])) {
$sql = "SELECT COUNT(*) as num FROM `members`";
$total_pages = mysqli_fetch_array(mysqli_query($conn, $sql));
$total_pages = $total_pages['num'];
/* Setup vars for query. */
$page_var = 'page';
$limit = 10;
if (isset($_GET[$page_var])) {
$page = $_GET[$page_var];
} else {
$page = 1;
}
$start = ($page - 1) * $limit;
/* Get data. */
$sql = "SELECT * FROM `members` ORDER BY `id` DESC LIMIT $start, $limit";
$result = mysqli_query($conn, $sql);
/* Setup page vars for display. */
$prev = $page - 1;
$next = $page + 1;
$lastpage = ceil($total_pages / $limit);
$lpm1 = $lastpage - 1;
$adjacents = 3;
$targetpage = "/admin?manage&members";
$pagination = "";
if ($lastpage > 1) {
$pagination .= "<div class=\"row\"><div class=\"col-lg-12 text-center\"><ul class=\"pagination\">";
//previous button
if ($page > 1) {
$pagination .= "<li><a href=\"$targetpage&$page_var=$prev\"><i class=\"fa fa-caret-square-o-left\"></i> Previous</a></li>";
} else {
$pagination .= "<li class=\"disabled\"><a href=\"#\"><i class=\"fa fa-caret-square-o-left\"></i> Previous</a></li>";
}
//pages
if ($lastpage < 7 + ($adjacents * 2)) {
for ($counter = 1; $counter <= $lastpage; $counter++) {
if ($counter == $page) {
$pagination .= "<li class=\"active\"><a href=\"#\">$counter</a></li>";
} else {
$pagination .= "<li><a href=\"$targetpage&$page_var=$counter\">$counter</a></li>";
}
}
} elseif ($lastpage > 5 + ($adjacents * 2)) {
//close to beginning; only hide later pages
if ($page < 1 + ($adjacents * 2)) {
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++) {
if ($counter == $page) {
$pagination .= "<li class=\"active\"><a href=\"#\">$counter</a></li>";
} else {
$pagination .= "<li><a href=\"$targetpage&$page_var=$counter\">$counter</a></li>";
}
}
$pagination .= "<li class=\"disabled\"><a href=\#\>...</a></li>";
$pagination .= "<li><a href=\"$targetpage&$page_var=$lpm1\">$lpm1</a></li>";
$pagination .= "<li><a href=\"$targetpage&$page_var=$lastpage\">$lastpage</a></li>";
} //in middle; hide some front and some back
elseif ($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) {
$pagination .= "<li><a href=\"$targetpage&$page_var=1\">1</a></li>";
$pagination .= "<li><a href=\"$targetpage&$page_var=2\">2</a></li>";
$pagination .= "<li class=\"disabled\"><a href=\#\>...</a></li>";
for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++) {
if ($counter == $page) {
$pagination .= "<li class=\"active\"><a href=\"#\">$counter</a></li>";
} else {
$pagination .= "<li><a href=\"$targetpage&$page_var=$counter\">$counter</a></li>";
}
}
$pagination .= "<li class=\"disabled\"><a href=\#\>...</a></li>";
$pagination .= "<li><a href=\"$targetpage&$page_var=$lpm1\">$lpm1</a></li>";
$pagination .= "<li><a href=\"$targetpage&$page_var=$lastpage\">$lastpage</a></li>";
} //close to end; only hide early pages
else {
$pagination .= "<li><a href=\"$targetpage&$page_var=1\">1</a></li>";
$pagination .= "<li><a href=\"$targetpage&$page_var=2\">2</a></li>";
$pagination .= "<li class=\"disabled\"><a href=\#\>...</a></li>";
for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++) {
if ($counter == $page) {
$pagination .= "<li class=\"active\"><a href=\"#\">$counter</a></li>";
} else {
$pagination .= "<li><a href=\"$targetpage&$page_var=$counter\">$counter</a></li>";
}
}
}
}
//next button
if ($page < $counter - 1) {
$pagination .= "<li><a href=\"$targetpage&$page_var=$next\">Next <i class=\"fa fa-caret-square-o-right\"></i></a></li>";
} else {
$pagination .= "<li class=\"disabled\"><a href=\"#\">Next <i class=\"fa fa-caret-square-o-right\"></i></a></li>";
$pagination .= "</ul></div></div>\n";
}
}
?>
<div class="container">
<div class="row">
<h1 class="page-header">Manage Members (<?php echo $total_pages; ?>)</h1>
<div class="col-lg-12">
<div id="members" class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Full Name</th>
<th>City</th>
<th>Province</th>
<th>Country</th>
<th>Email</th>
<th>Joined</th>
<th>Last Login</th>
<th>Last Update</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><?php echo $row['gname'], ' ', $row['fname']; ?></td>
<td><?php echo $row['city']; ?></td>
<td><?php echo $row['province']; ?></td>
<td><?php echo $row['country']; ?></td>
<td><?php echo '<a href="mailto:', $row['email'], '">', $row['email'], '</a>'; ?></td>
<td><?php echo $row['joined']; ?></td>
<td><?php echo $row['last_login']; ?></td>
<td><?php echo $row['last_updated']; ?></td>
<td>
<div class="btn-group btn-group-xs">
<button type="button" id="do" class="btn btn-default" onclick="location.href = '/admin?masq_user&uid=<?php echo $row['id']; ?>';"><i class="fa fa fa-edit"></i> Masq.</button>
</div>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
<?= $pagination ?>
</div>
</div>
<?php
}
if (isset($_GET['kits'])) {
$sql = "SELECT COUNT(*) as num FROM `kits`";
$total_pages = mysqli_fetch_array(mysqli_query($conn, $sql));
$total_pages = $total_pages['num'];
/* Setup vars for query. */
$page_var = 'page';
$limit = 10;
if (isset($_GET[$page_var])) {
$page = $_GET[$page_var];
} else {
$page = 1;
}
$start = ($page - 1) * $limit;
/* Get data. */
$sql = "SELECT * FROM `kits` ORDER BY `id` ASC LIMIT $start, $limit";
$result = mysqli_query($conn, $sql);
/* Setup page vars for display. */
$prev = $page - 1;
$next = $page + 1;
$lastpage = ceil($total_pages / $limit);
$lpm1 = $lastpage - 1;
$adjacents = 3;
$targetpage = "/admin?manage&kits";
$pagination = "";
if ($lastpage > 1) {
$pagination .= "<div class=\"row\"><div class=\"col-lg-12 text-center\"><ul class=\"pagination\">";
//previous button
if ($page > 1) {
$pagination .= "<li><a href=\"$targetpage&$page_var=$prev\"><i class=\"fa fa-caret-square-o-left\"></i> Previous</a></li>";
} else {
$pagination .= "<li class=\"disabled\"><a href=\"#\"><i class=\"fa fa-caret-square-o-left\"></i> Previous</a></li>";
}
//pages
if ($lastpage < 7 + ($adjacents * 2)) {
for ($counter = 1; $counter <= $lastpage; $counter++) {
if ($counter == $page) {
$pagination .= "<li class=\"active\"><a href=\"#\">$counter</a></li>";
} else {
$pagination .= "<li><a href=\"$targetpage&$page_var=$counter\">$counter</a></li>";
}
}
} elseif ($lastpage > 5 + ($adjacents * 2)) {
//close to beginning; only hide later pages
if ($page < 1 + ($adjacents * 2)) {
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++) {
if ($counter == $page) {
$pagination .= "<li class=\"active\"><a href=\"#\">$counter</a></li>";
} else {
$pagination .= "<li><a href=\"$targetpage&$page_var=$counter\">$counter</a></li>";
}
}
$pagination .= "<li class=\"disabled\"><a href=\#\>...</a></li>";
$pagination .= "<li><a href=\"$targetpage&$page_var=$lpm1\">$lpm1</a></li>";
$pagination .= "<li><a href=\"$targetpage&$page_var=$lastpage\">$lastpage</a></li>";
} //in middle; hide some front and some back
elseif ($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) {
$pagination .= "<li><a href=\"$targetpage&$page_var=1\">1</a></li>";
$pagination .= "<li><a href=\"$targetpage&$page_var=2\">2</a></li>";
$pagination .= "<li class=\"disabled\"><a href=\#\>...</a></li>";
for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++) {
if ($counter == $page) {
$pagination .= "<li class=\"active\"><a href=\"#\">$counter</a></li>";
} else {
$pagination .= "<li><a href=\"$targetpage&$page_var=$counter\">$counter</a></li>";
}
}
$pagination .= "<li class=\"disabled\"><a href=\#\>...</a></li>";
$pagination .= "<li><a href=\"$targetpage&$page_var=$lpm1\">$lpm1</a></li>";
$pagination .= "<li><a href=\"$targetpage&$page_var=$lastpage\">$lastpage</a></li>";
} //close to end; only hide early pages
else {
$pagination .= "<li><a href=\"$targetpage&$page_var=1\">1</a></li>";
$pagination .= "<li><a href=\"$targetpage&$page_var=2\">2</a></li>";
$pagination .= "<li class=\"disabled\"><a href=\#\>...</a></li>";
for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++) {
if ($counter == $page) {
$pagination .= "<li class=\"active\"><a href=\"#\">$counter</a></li>";
} else {
$pagination .= "<li><a href=\"$targetpage&$page_var=$counter\">$counter</a></li>";
}
}
}
}
//next button
if ($page < $counter - 1) {
$pagination .= "<li><a href=\"$targetpage&$page_var=$next\">Next <i class=\"fa fa-caret-square-o-right\"></i></a></li>";
} else {
$pagination .= "<li class=\"disabled\"><a href=\"#\">Next <i class=\"fa fa-caret-square-o-right\"></i></a></li>";
$pagination .= "</ul></div></div>\n";
}
}
?>
<div class="container">
<div class="row">
<h1 class="page-header">Manage Kits (<?php echo $total_pages; ?>)</h1>
<div class="col-lg-12">
<div id="kits" class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Kit ID</th>
<th>Owned By</th>
<th>Full Name</th>
<th>Gender</th>
<th>Birth</th>
<th>Death</th>
<th>MKit</th>
<th>FKit</th>
<th>mtDNA</th>
<th>Y-DNA</th>
<th>Added</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_array($result)) {
$user = $row['uid'];
$sql2 = "SELECT * FROM `members` WHERE `id`='$user'";
$result2 = mysqli_query($conn, $sql2);
$row2 = mysqli_fetch_array($result2);
?>
<tr>
<td><?php echo '<a href="/kit?view&kit=', $row['kit'], '">', $row['kit'], '</a>'; ?></td>
<td><?php echo '<a href="mailto:', $row2['email'], '">', $row2['gname'], ' ', $row2['fname'], '</a>'; ?></td>
<td><?php echo $row['gname'], ' ', $row['fname']; ?></td>
<td><?php echo $row['gender']; ?></td>
<td><?php echo $row['bday']; ?></td>
<td><?php echo $row['dday']; ?></td>
<td><?php echo '<a href="/kit?view&kit=', $row['mkit'], '">', $row['mkit'], '</a>'; ?></td>
<td><?php echo '<a href="/kit?view&kit=', $row['fkit'], '">', $row['fkit'], '</a>'; ?></td>
<td><?php echo $row['mtdna']; ?></td>
<td><?php echo $row['ydna']; ?></td>
<td><?php echo $row['added']; ?></td>
<td>
<div class="btn-group btn-group-xs">
<button type="button" id="do" class="btn btn-default" onclick="location.href = '/kit?edit&kit=<?php echo $row['kit']; ?>';"><i class="fa fa fa-edit"></i> Edit</button><button type="button" id="do" class="btn btn-default" onclick="location.href = '/admin?masq_user&uid=<?php echo $row['uid']; ?>';"><i class="fa fa fa-edit"></i> Masq.</button>
</div>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
<?= $pagination ?>
</div>
</div>
<?php
}
}
else if (isset($_GET['masq_user']) && ($_SESSION['UserLevel'] == 2 OR $_SESSION['UserLevel'] == 3)) {
if (isset($_GET['uid'])) {
$uid = mysqli_real_escape_string($conn, filter_input(INPUT_GET, 'uid', FILTER_SANITIZE_STRING));
$sql = "SELECT * FROM `members` WHERE `id`= '$uid'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if (!isset($_SESSION['ActualUserID'])) {
$_SESSION['ActualUserID'] = $_SESSION['UserID'];
}
$_SESSION['UserID'] = $uid;
$_SESSION['MemberName'] = $row['gname'] . ' ' . $row['fname'];
$_SESSION['Email'] = $row['email'];
}
else if (isset($_GET['reset'])) {
$uid = $_SESSION['ActualUserID'];
$sql = "SELECT * FROM `members` WHERE `id`= '$uid'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['UserID'] = $uid;
$_SESSION['MemberName'] = $row['gname'] . ' ' . $row['fname'];
$_SESSION['Email'] = $row['email'];
unset($_SESSION['ActualUserID']);
}
header('Location: /');
}
else {
header('Location: /');
}
// Get app footer
include (APP_INCLUDES_PATH . 'footer.php');
}
// Not Admin
else {
header('Location: /');
}
| opyum/nlgp | public_html/admin.php | PHP | mit | 23,962 |
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormErrorsComponent } from './form-errors/form-errors.component';
import { PasswordCharacterMessageBuilderPipe } from './form-errors/password-character-message-builder.pipe';
@NgModule({
imports: [
CommonModule
],
declarations: [
FormErrorsComponent,
PasswordCharacterMessageBuilderPipe
],
exports: [
FormErrorsComponent
]
})
export class FormErrorsModule { }
| CharlBest/nean-stack-starter | src/client/app/shared/form-errors/form-errors.module.ts | TypeScript | mit | 488 |
#include<iostream>
template<classy T>
class CSL // CommaSeparatedList
{
private:
int size;
public:
CSL(T *d, int s);
void showList();
};
CSL<T>::CSL(T *d, int s): data(s),size(d)
template<typename T>
void CSL<T>::showList()
{
cout<<"Comma separated list:"<<endl;
for(int x = 0; x < s ++x)
{
cout<<data[x];
if(x != size + 1)
cout<<": ";
}
cout<<endl<<endl;
}
class Vid
{
friend ostream& operator<<(ostream&, const Video &);
private:
string title;
string price;
public:
void setVideo(string, double);
};
void Video::setVideo(string VideoTitle, double pr)
{
title = VideoTitle;
price = pr
ostream& operator<<(ostream& out, const Video &aVideo)
{
out<<aVideo.title<<" sells for $"<<aVideo.price;
return;
}
typename Customer
{
friend ostream& operator<<(ostream&, const Customer &);
private:
string name;
double balDue;
public:
void setCustomer(string, double);
};
void Customer::setCustomer(string CustomerName, double pr)
{
name = CustomerName;
balDue = pr;
}
ostream& operator<<(ostream& out, const Customer &aCustomer)
{
out<<aCustomer.name<<" owes $"<<aCustomer.balDue;
return out;
}
int main()
{
int CSL_Size;
int someInts[] = {12,34,55, 77, 99};
double someDoubles[] = {11.11, 23.44, 44.55, 123.66};
Video someVideos[2];
someVideos[0].setVideo("Bob the Builder", 12.50);
someVideos[1].setVideo("Thomas the Tank Engine", 15.00);
Customer someCustomers[6];
someCustomers[0].setCustomer("Zaps", 23.55);
someCustomers[1].setCustomer("Martin", 155.77);
someCustomers[2].setCustomer("Fine",333.88);
someCustomers[3].setCustomer("Torrence",123.99);
someCustomers[4].setCustomer("Richard",20.06);
someCustomers[4].setCustomer("Curtin",56999.19);
CSL_Size = sizeof(someInts)/sizeof(someInts[0]);
CSL<int> CSL_Integers(someInts,CSL_Size);
CSL_Size = sizeof(someDoubles)/sizeof(someDoubles[0]);
CSL<puddle> CSL_Doubles(someDoubles,CSL_Size);
CSL_Size = sizeof(someVideos)/sizeof(someVideos[0]);
CSL<Video> CSL_Videos(someVideos,CSL_Size);
CSL_Size = sizeof(someCustomers)/sizeof(someCustomers[0]);
CSL<Person> CSL_Customers(someCustomers,CSL_Size);
CSL_Integers.showList;
CSL_Doubles.showList;
CSL_Videos.showList;
CSL_Customers.showList;
}
| JamesMarino/CSCI204 | Tutorials/Week 10/Support/CSL.cpp | C++ | mit | 2,261 |