code
stringlengths
4
1.01M
language
stringclasses
2 values
package gogo import ( "net/http" "net/http/httptest" "testing" "github.com/golib/assert" ) func Test_NewResponse(t *testing.T) { it := assert.New(t) recorder := httptest.NewRecorder() response := NewResponse(recorder) it.Implements((*Responser)(nil), response) it.Equal(http.StatusOK, response.Status()) it.Equal(nonHeaderFlushed, response.Size()) } func Test_ResponseWriteHeader(t *testing.T) { it := assert.New(t) recorder := httptest.NewRecorder() response := NewResponse(recorder) response.WriteHeader(http.StatusRequestTimeout) it.Equal(http.StatusRequestTimeout, response.Status()) it.Equal(nonHeaderFlushed, response.Size()) } func Test_ResponseFlushHeader(t *testing.T) { it := assert.New(t) recorder := httptest.NewRecorder() response := NewResponse(recorder) response.WriteHeader(http.StatusRequestTimeout) response.FlushHeader() it.Equal(http.StatusRequestTimeout, recorder.Code) it.NotEqual(nonHeaderFlushed, response.Size()) // no effect after flushed headers response.WriteHeader(http.StatusOK) it.Equal(http.StatusOK, response.Status()) response.FlushHeader() it.NotEqual(http.StatusOK, recorder.Code) } func Test_ResponseWrite(t *testing.T) { it := assert.New(t) recorder := httptest.NewRecorder() hello := []byte("Hello,") world := []byte("world!") expected := []byte("Hello,world!") response := NewResponse(recorder) response.Write(hello) response.Write(world) it.True(response.HeaderFlushed()) it.Equal(len(expected), response.Size()) it.Equal(expected, recorder.Body.Bytes()) } func Benchmark_ResponseWrite(b *testing.B) { b.ReportAllocs() b.ResetTimer() hello := []byte("Hello,") world := []byte("world!") recorder := httptest.NewRecorder() response := NewResponse(recorder) for i := 0; i < b.N; i++ { response.Write(hello) response.Write(world) } } func Test_ResponseHijack(t *testing.T) { it := assert.New(t) recorder := httptest.NewRecorder() expected := []byte("Hello,world!") response := NewResponse(recorder) response.Write(expected) it.True(response.HeaderFlushed()) it.Equal(recorder, response.(*Response).ResponseWriter) it.Equal(len(expected), response.Size()) response.Hijack(httptest.NewRecorder()) it.False(response.HeaderFlushed()) it.NotEqual(recorder, response.(*Response).ResponseWriter) it.Equal(nonHeaderFlushed, response.Size()) } func Benchmark_ResponseHijack(b *testing.B) { b.ReportAllocs() b.ResetTimer() recorder := httptest.NewRecorder() response := NewResponse(recorder) for i := 0; i < b.N; i++ { response.Hijack(recorder) } }
Java
#if !defined(AFX_DIALOG3_H__8EF7DE42_F33E_4217_87B0_FE9ACBCE3E84__INCLUDED_) #define AFX_DIALOG3_H__8EF7DE42_F33E_4217_87B0_FE9ACBCE3E84__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // Dialog3.h : header file // ///////////////////////////////////////////////////////////////////////////// // CDialog3 dialog class CDialog3 : public CDialog { // Construction public: CDialog3(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CDialog3) enum { IDD = IDD_DIALOG3 }; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDialog3) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CDialog3) virtual BOOL OnInitDialog(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DIALOG3_H__8EF7DE42_F33E_4217_87B0_FE9ACBCE3E84__INCLUDED_)
Java
# Load DSL and set up stages require 'capistrano/setup' # Include default deployment tasks require 'capistrano/deploy' # Include tasks from other gems included in your Gemfile require 'capistrano/rvm' require 'capistrano/bundler' require 'capistrano/rails' require 'capistrano/rails/migrations' require 'capistrano/nginx_unicorn' require 'capistrano/rails/assets' # Load custom tasks from `lib/capistrano/tasks` if you have any defined Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }
Java
var mongoose = require('mongoose'); var bcrypt = require('bcrypt'); var saltRounds = 10; var userSchema = new mongoose.Schema({ email: { type: String, index: {unique: true} }, password: String, name: String }); //hash password userSchema.methods.generateHash = function(password){ return bcrypt.hashSync(password, bcrypt.genSaltSync(saltRounds)); } userSchema.methods.validPassword = function(password){ return bcrypt.compareSync(password, this.password); } var User = mongoose.model('User',userSchema); module.exports = User;
Java
<?php namespace Wolphy\Jobs; use Illuminate\Bus\Queueable; abstract class Job { /* |-------------------------------------------------------------------------- | Queueable Jobs |-------------------------------------------------------------------------- | | This job base class provides a central location to place any logic that | is shared across all of your jobs. The trait included with the class | provides access to the "queueOn" and "delay" queue helper methods. | */ use Queueable; }
Java
#!/bin/sh echo "Stopping web-server ..." COUNT_PROCESS=1 while [ $COUNT_PROCESS -gt 0 ] do COUNT_PROCESS=`ps -Aef | grep node | grep -c server.js` if [ $COUNT_PROCESS -gt 0 ]; then PID_PROCESS=`ps -Aef | grep node | grep server.js | awk '{print $2}'` if [ ! -z "$PID_PROCESS" ]; then echo "Killing web server PID=$PID_PROCESS" kill "$PID_PROCESS" fi fi echo "Waiting on web-server to stop ..." sleep 1 done echo "This web-server is stopped" exit 0
Java
<?php namespace RectorPrefix20210615; if (\class_exists('t3lib_collection_StaticRecordCollection')) { return; } class t3lib_collection_StaticRecordCollection { } \class_alias('t3lib_collection_StaticRecordCollection', 't3lib_collection_StaticRecordCollection', \false);
Java
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("RedditImageDownloader.GUI")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RedditImageDownloader.GUI")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] //Um mit dem Erstellen lokalisierbarer Anwendungen zu beginnen, legen Sie //<UICulture>ImCodeVerwendeteKultur</UICulture> in der .csproj-Datei //in einer <PropertyGroup> fest. Wenn Sie in den Quelldateien beispielsweise Deutsch //(Deutschland) verwenden, legen Sie <UICulture> auf \"de-DE\" fest. Heben Sie dann die Auskommentierung //des nachstehenden NeutralResourceLanguage-Attributs auf. Aktualisieren Sie "en-US" in der nachstehenden Zeile, //sodass es mit der UICulture-Einstellung in der Projektdatei übereinstimmt. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //Speicherort der designspezifischen Ressourcenwörterbücher //(wird verwendet, wenn eine Ressource auf der Seite // oder in den Anwendungsressourcen-Wörterbüchern nicht gefunden werden kann.) ResourceDictionaryLocation.SourceAssembly //Speicherort des generischen Ressourcenwörterbuchs //(wird verwendet, wenn eine Ressource auf der Seite, in der Anwendung oder einem // designspezifischen Ressourcenwörterbuch nicht gefunden werden kann.) )] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Java
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'ar' from layers_basic import LW_Layer, default_data_format from layers_convolutional import conv_output_length ############################################### class _LW_Pooling1D(LW_Layer): input_dim = 3 def __init__(self, pool_size=2, strides=None, padding='valid'): if strides is None: strides = pool_size assert padding in {'valid', 'same'}, 'border_mode must be in {valid, same}' self.pool_length = pool_size self.stride = strides self.border_mode = padding def get_output_shape_for(self, input_shape): length = conv_output_length(input_shape[1], self.pool_length, self.border_mode, self.stride) return (input_shape[0], length, input_shape[2]) class LW_MaxPooling1D(_LW_Pooling1D): def __init__(self, pool_size=2, strides=None, padding='valid'): super(LW_MaxPooling1D, self).__init__(pool_size, strides, padding) class LW_AveragePooling1D(_LW_Pooling1D): def __init__(self, pool_size=2, strides=None, padding='valid'): super(LW_AveragePooling1D, self).__init__(pool_size, strides, padding) ############################################### class _LW_Pooling2D(LW_Layer): def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format='default'): if data_format == 'default': data_format = default_data_format assert data_format in {'channels_last', 'channels_first'}, 'data_format must be in {channels_last, channels_first}' self.pool_size = tuple(pool_size) if strides is None: strides = self.pool_size self.strides = tuple(strides) assert padding in {'valid', 'same'}, 'border_mode must be in {valid, same}' self.border_mode = padding self.dim_ordering = data_format def get_output_shape_for(self, input_shape): if self.dim_ordering == 'channels_first': rows = input_shape[2] cols = input_shape[3] elif self.dim_ordering == 'channels_last': rows = input_shape[1] cols = input_shape[2] else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) rows = conv_output_length(rows, self.pool_size[0], self.border_mode, self.strides[0]) cols = conv_output_length(cols, self.pool_size[1], self.border_mode, self.strides[1]) if self.dim_ordering == 'channels_first': return (input_shape[0], input_shape[1], rows, cols) elif self.dim_ordering == 'channels_last': return (input_shape[0], rows, cols, input_shape[3]) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) class LW_MaxPooling2D(_LW_Pooling2D): def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format='default'): super(LW_MaxPooling2D, self).__init__(pool_size, strides, padding, data_format) class LW_AveragePooling2D(_LW_Pooling2D): def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format='default'): super(LW_AveragePooling2D, self).__init__(pool_size, strides, padding, data_format) ############################################### class _LW_Pooling3D(LW_Layer): def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', dim_ordering='default'): if dim_ordering == 'default': dim_ordering = default_data_format assert dim_ordering in {'channels_last', 'channels_first'}, 'data_format must be in {channels_last, channels_first}' self.pool_size = tuple(pool_size) if strides is None: strides = self.pool_size self.strides = tuple(strides) assert border_mode in {'valid', 'same'}, 'border_mode must be in {valid, same}' self.border_mode = border_mode self.dim_ordering = dim_ordering def get_output_shape_for(self, input_shape): if self.dim_ordering == 'channels_first': len_dim1 = input_shape[2] len_dim2 = input_shape[3] len_dim3 = input_shape[4] elif self.dim_ordering == 'channels_last': len_dim1 = input_shape[1] len_dim2 = input_shape[2] len_dim3 = input_shape[3] else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) len_dim1 = conv_output_length(len_dim1, self.pool_size[0], self.border_mode, self.strides[0]) len_dim2 = conv_output_length(len_dim2, self.pool_size[1], self.border_mode, self.strides[1]) len_dim3 = conv_output_length(len_dim3, self.pool_size[2], self.border_mode, self.strides[2]) if self.dim_ordering == 'channels_first': return (input_shape[0], input_shape[1], len_dim1, len_dim2, len_dim3) elif self.dim_ordering == 'channels_last': return (input_shape[0], len_dim1, len_dim2, len_dim3, input_shape[4]) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) class LW_MaxPooling3D(_LW_Pooling3D): def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', dim_ordering='default'): super(LW_MaxPooling3D, self).__init__(pool_size, strides, border_mode, dim_ordering) class LW_AveragePooling3D(_LW_Pooling3D): def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', dim_ordering='default'): super(LW_AveragePooling3D, self).__init__(pool_size, strides, border_mode, dim_ordering) ############################################### class _LW_GlobalPooling1D(LW_Layer): def __init__(self): pass def get_output_shape_for(self, input_shape): return (input_shape[0], input_shape[2]) class LW_GlobalAveragePooling1D(_LW_GlobalPooling1D): pass class LW_GlobalMaxPooling1D(_LW_GlobalPooling1D): pass ############################################### class _LW_GlobalPooling2D(LW_Layer): def __init__(self, data_format='default'): if data_format == 'default': data_format = default_data_format self.dim_ordering = data_format def get_output_shape_for(self, input_shape): if self.dim_ordering == 'channels_last': return (input_shape[0], input_shape[3]) else: return (input_shape[0], input_shape[1]) class LW_GlobalAveragePooling2D(_LW_GlobalPooling2D): pass class LW_GlobalMaxPooling2D(_LW_GlobalPooling2D): pass ############################################### class _LW_GlobalPooling3D(LW_Layer): def __init__(self, data_format='default'): if data_format == 'default': data_format = default_data_format self.dim_ordering = data_format def get_output_shape_for(self, input_shape): if self.dim_ordering == 'channels_last': return (input_shape[0], input_shape[4]) else: return (input_shape[0], input_shape[1]) class LW_GlobalAveragePooling3D(_LW_GlobalPooling3D): pass class LW_GlobalMaxPooling3D(_LW_GlobalPooling3D): pass ############################################### if __name__ == '__main__': pass
Java
class CreateEventTypes < ActiveRecord::Migration def change create_table :event_types do |t| t.string :name, :limit => 80 t.timestamps end end end
Java
/* * Copyright 2013 MongoDB, 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. */ #ifndef BSON_COMPAT_H #define BSON_COMPAT_H #if !defined (BSON_INSIDE) && !defined (BSON_COMPILATION) # error "Only <bson.h> can be included directly." #endif #if defined(__MINGW32__) # if defined(__USE_MINGW_ANSI_STDIO) # if __USE_MINGW_ANSI_STDIO < 1 # error "__USE_MINGW_ANSI_STDIO > 0 is required for correct PRI* macros" # endif # else # define __USE_MINGW_ANSI_STDIO 1 # endif #endif #include "bson-config.h" #include "bson-macros.h" #ifdef BSON_OS_WIN32 # if defined(_WIN32_WINNT) && (_WIN32_WINNT < 0x0600) # undef _WIN32_WINNT # endif # ifndef _WIN32_WINNT # define _WIN32_WINNT 0x0600 # endif # ifndef NOMINMAX # define NOMINMAX # endif # include <winsock2.h> # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # include <windows.h> # undef WIN32_LEAN_AND_MEAN # else # include <windows.h> # endif #include <direct.h> #include <io.h> #endif #ifdef BSON_OS_UNIX # include <unistd.h> # include <sys/time.h> #endif #include "bson-macros.h" #include <errno.h> #include <ctype.h> #include <limits.h> #include <fcntl.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> BSON_BEGIN_DECLS #ifdef _MSC_VER # include "bson-stdint-win32.h" # ifndef __cplusplus /* benign redefinition of type */ # pragma warning (disable :4142) # ifndef _SSIZE_T_DEFINED # define _SSIZE_T_DEFINED typedef SSIZE_T ssize_t; # endif typedef SIZE_T size_t; # pragma warning (default :4142) # else /* * MSVC++ does not include ssize_t, just size_t. * So we need to synthesize that as well. */ # pragma warning (disable :4142) # ifndef _SSIZE_T_DEFINED # define _SSIZE_T_DEFINED typedef SSIZE_T ssize_t; # endif # pragma warning (default :4142) # endif # define PRIi32 "d" # define PRId32 "d" # define PRIu32 "u" # define PRIi64 "I64i" # define PRId64 "I64i" # define PRIu64 "I64u" #else # include "bson-stdint.h" # include <inttypes.h> #endif #if defined(__MINGW32__) && ! defined(INIT_ONCE_STATIC_INIT) # define INIT_ONCE_STATIC_INIT RTL_RUN_ONCE_INIT typedef RTL_RUN_ONCE INIT_ONCE; #endif #ifdef BSON_HAVE_STDBOOL_H # include <stdbool.h> #elif !defined(__bool_true_false_are_defined) # ifndef __cplusplus typedef signed char bool; # define false 0 # define true 1 # endif # define __bool_true_false_are_defined 1 #endif #if defined(__GNUC__) # if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) # define bson_sync_synchronize() __sync_synchronize() # elif defined(__i386__ ) || defined( __i486__ ) || defined( __i586__ ) || \ defined( __i686__ ) || defined( __x86_64__ ) # define bson_sync_synchronize() asm volatile("mfence":::"memory") # else # define bson_sync_synchronize() asm volatile("sync":::"memory") # endif #elif defined(_MSC_VER) # define bson_sync_synchronize() MemoryBarrier() #endif #if !defined(va_copy) && defined(__va_copy) # define va_copy(dst,src) __va_copy(dst, src) #endif #if !defined(va_copy) # define va_copy(dst,src) ((dst) = (src)) #endif BSON_END_DECLS #endif /* BSON_COMPAT_H */
Java
require "empty_port/version" require 'socket' require 'timeout' # ## Example # require 'empty_port' # class YourServerTest < Test::Unit::TestCase # def setup # @port = EmptyPort.get # @server_pid = Process.fork do # server = TCPServer.open('localhost', @port) # end # EmptyPort.wait(@port) # end # # def test_something_with_server # end # # def teardown # Process.kill(@server_pid) # end # end # module EmptyPort class NotFoundException < Exception; end module ClassMethods # SEE http://www.iana.org/assignments/port-numbers MIN_PORT_NUMBER = 49152 MAX_PORT_NUMBER = 65535 # get an empty port except well-known-port. def get random_port = MIN_PORT_NUMBER + ( rand() * 1000 ).to_i while random_port < MAX_PORT_NUMBER begin sock = TCPSocket.open('localhost', random_port) sock.close rescue Errno::ECONNREFUSED => e return random_port end random_port += 1 end raise NotFoundException end def listened?(port) begin sock = TCPSocket.open('localhost', port) sock.close return true rescue Errno::ECONNREFUSED return false end end DEFAULT_TIMEOUT = 2 DEFAULT_INTERVAL = 0.1 def wait(port, options={}) options[:timeout] ||= DEFAULT_TIMEOUT options[:interval] ||= DEFAULT_INTERVAL timeout(options[:timeout]) do start = Time.now loop do if self.listened?(port) finished = Time.now return finished - start end sleep(options[:interval]) end end end end extend ClassMethods end
Java
module.exports = { 'throttle': 10, 'hash': true, 'gzip': false, 'baseDir': 'public', 'buildDir': 'build', 'prefix': '' };
Java
.vertical-center { min-height: 100%; /* Fallback for browsers do NOT support vh unit */ min-height: 100vh; /* These two lines are counted as one :-) */ display: flex; align-items: center; } @media (min-width: 768px){ #wrapper {/*padding-right: 225px;*/ padding-left: 0;} .side-nav{right: 0;left: auto;} } /*! * Start Bootstrap - SB Admin (http://startbootstrap.com/) * Copyright 2013-2016 Start Bootstrap * Licensed under MIT (https://github.com/BlackrockDigital/startbootstrap/blob/gh-pages/LICENSE) */ /* Global Styles */ body { background-color: #222; } #wrapper { padding-left: 0; } #page-wrapper { width: 100%; padding: 0; background-color: #fff; } .huge { font-size: 50px; line-height: normal; } @media(min-width:768px) { #wrapper { padding-left: 225px; } #page-wrapper { padding: 10px; margin-top: 20px; } } /* Top Navigation */ .top-nav { padding: 0 15px; } .top-nav>li { display: inline-block; float: left; } .top-nav>li>a { padding-top: 15px; padding-bottom: 15px; line-height: 20px; color: #999; } .top-nav>li>a:hover, .top-nav>li>a:focus, .top-nav>.open>a, .top-nav>.open>a:hover, .top-nav>.open>a:focus { color: #fff; background-color: #000; } .top-nav>.open>.dropdown-menu { float: left; position: absolute; margin-top: 0; border: 1px solid rgba(0,0,0,.15); border-top-left-radius: 0; border-top-right-radius: 0; background-color: #fff; -webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175); box-shadow: 0 6px 12px rgba(0,0,0,.175); } .top-nav>.open>.dropdown-menu>li>a { white-space: normal; } ul.message-dropdown { padding: 0; max-height: 250px; overflow-x: hidden; overflow-y: auto; } li.message-preview { width: 275px; border-bottom: 1px solid rgba(0,0,0,.15); } li.message-preview>a { padding-top: 15px; padding-bottom: 15px; } li.message-footer { margin: 5px 0; } ul.alert-dropdown { width: 200px; } .alert-danger { margin-top: 50px; } /* Side Navigation */ @media(min-width:768px) { .side-nav { position: fixed; top: 51px; /* left: 225px;*/ left: 0px; width: 225px; /* margin-left: -225px;*/ border: none; border-radius: 0; overflow-y: auto; background-color: #222; bottom: 0; overflow-x: hidden; padding-bottom: 40px; } .side-nav>li>a { width: 225px; } .side-nav li a:hover, .side-nav li a:focus { outline: none; background-color: #000 !important; } } .side-nav>li>ul { padding: 0; } .side-nav>li>ul>li>a { display: block; padding: 10px 15px 10px 38px; text-decoration: none; color: #999; } .side-nav>li>ul>li>a:hover { color: #fff; } /* Flot Chart Containers */ .flot-chart { display: block; height: 400px; } .flot-chart-content { width: 100%; height: 100%; } /* Custom Colored Panels */ .huge { font-size: 40px; } .panel-green { border-color: #5cb85c; } .panel-green > .panel-heading { border-color: #5cb85c; color: #fff; background-color: #5cb85c; } .panel-green > a { color: #5cb85c; } .panel-green > a:hover { color: #3d8b3d; } .panel-red { border-color: #d9534f; } .panel-red > .panel-heading { border-color: #d9534f; color: #fff; background-color: #d9534f; } .panel-red > a { color: #d9534f; } .panel-red > a:hover { color: #b52b27; } .panel-yellow { border-color: #f0ad4e; } .panel-yellow > .panel-heading { border-color: #f0ad4e; color: #fff; background-color: #f0ad4e; } .panel-yellow > a { color: #f0ad4e; } .panel-yellow > a:hover { color: #df8a13; } .navbar-nav > li > ul > li.active { background: rgba(9, 9, 9, 0.57); }
Java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>使用 button 定义按钮</title> </head> <body> <form action="http://www.baidu.com" method="get"> <button type="button"><b>提交</b></button><br/> <button type="submit"><img sec="./img/3.jpg" alt="图片"></button><br/> </form> </body> </html>
Java
--- layout: post title: Tweets date: 2019-08-08 summary: These are the tweets for August 8, 2019. categories: ---
Java
import type { FormatRelativeFn } from '../../../types' // Source: https://www.unicode.org/cldr/charts/32/summary/te.html const formatRelativeLocale = { lastWeek: "'గత' eeee p", // CLDR #1384 yesterday: "'నిన్న' p", // CLDR #1393 today: "'ఈ రోజు' p", // CLDR #1394 tomorrow: "'రేపు' p", // CLDR #1395 nextWeek: "'తదుపరి' eeee p", // CLDR #1386 other: 'P', } const formatRelative: FormatRelativeFn = (token, _date, _baseDate, _options) => formatRelativeLocale[token] export default formatRelative
Java
INSERT INTO customers(id, name) VALUES (1, 'Jane Woods'); INSERT INTO customers(id, name) VALUES (2, 'Michael Li'); INSERT INTO customers(id, name) VALUES (3, 'Heidi Hasselbach'); INSERT INTO customers(id, name) VALUES (4, 'Rahul Pour');
Java
/* * * BitcoinLikeKeychain * ledger-core * * Created by Pierre Pollastri on 17/01/2017. * * The MIT License (MIT) * * Copyright (c) 2016 Ledger * * 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. * */ #ifndef LEDGER_CORE_BITCOINLIKEKEYCHAIN_HPP #define LEDGER_CORE_BITCOINLIKEKEYCHAIN_HPP #include "../../../bitcoin/BitcoinLikeExtendedPublicKey.hpp" #include <string> #include <vector> #include <utils/DerivationScheme.hpp> #include "../../../utils/Option.hpp" #include "../../../preferences/Preferences.hpp" #include "../../../api/Configuration.hpp" #include "../../../api/DynamicObject.hpp" #include <api/Currency.hpp> #include <api/AccountCreationInfo.hpp> #include <api/ExtendedKeyAccountCreationInfo.hpp> #include <api/Keychain.hpp> #include <bitcoin/BitcoinLikeAddress.hpp> namespace ledger { namespace core { class BitcoinLikeKeychain: public api::Keychain { public: enum KeyPurpose { RECEIVE, CHANGE }; public: using Address = std::shared_ptr<BitcoinLikeAddress>; BitcoinLikeKeychain( const std::shared_ptr<api::DynamicObject>& configuration, const api::Currency& params, int account, const std::shared_ptr<Preferences>& preferences); virtual bool markAsUsed(const std::vector<std::string>& addresses); virtual bool markAsUsed(const std::string& address, bool needExtendKeychain = true); virtual bool markPathAsUsed(const DerivationPath& path, bool needExtendKeychain = true) = 0; virtual std::vector<Address> getAllObservableAddresses(uint32_t from, uint32_t to) = 0; virtual std::vector<std::string> getAllObservableAddressString(uint32_t from, uint32_t to) = 0; virtual std::vector<Address> getAllObservableAddresses(KeyPurpose purpose, uint32_t from, uint32_t to) = 0; virtual Address getFreshAddress(KeyPurpose purpose) = 0; virtual std::vector<Address> getFreshAddresses(KeyPurpose purpose, size_t n) = 0; virtual Option<KeyPurpose> getAddressPurpose(const std::string& address) const = 0; virtual Option<std::string> getAddressDerivationPath(const std::string& address) const = 0; virtual bool isEmpty() const = 0; int getAccountIndex() const; const api::BitcoinLikeNetworkParameters& getNetworkParameters() const; const api::Currency& getCurrency() const; virtual Option<std::vector<uint8_t>> getPublicKey(const std::string& address) const = 0; std::shared_ptr<api::DynamicObject> getConfiguration() const; const DerivationScheme& getDerivationScheme() const; const DerivationScheme& getFullDerivationScheme() const; std::string getKeychainEngine() const; bool isSegwit() const; bool isNativeSegwit() const; virtual std::string getRestoreKey() const = 0; virtual int32_t getObservableRangeSize() const = 0; virtual bool contains(const std::string& address) const = 0; virtual std::vector<Address> getAllAddresses() = 0; virtual int32_t getOutputSizeAsSignedTxInput() const = 0; static bool isSegwit(const std::string &keychainEngine); static bool isNativeSegwit(const std::string &keychainEngine); std::shared_ptr<Preferences> getPreferences() const; protected: DerivationScheme& getDerivationScheme(); private: const api::Currency _currency; DerivationScheme _scheme; DerivationScheme _fullScheme; int _account; std::shared_ptr<Preferences> _preferences; std::shared_ptr<api::DynamicObject> _configuration; }; } } #endif //LEDGER_CORE_BITCOINLIKEKEYCHAIN_HPP
Java
<?php namespace AppBundle\Repository; /** * Buyers_PropertiesRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class Buyers_PropertiesRepository extends \Doctrine\ORM\EntityRepository { }
Java
#!/usr/bin/env ruby #Example handler file.. infile = ARGV.first outfile = File.basename(infile, ".tif") + ".jpg.tif" system("~/cm/processing_scripts/rgb_to_jpeg_tif.rb --internal-mask #{infile} #{outfile}")
Java
using Newtonsoft.Json; using ProtoBuf; using ITK.ModelManager; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Steam.Models { [Model("SteamPlayerBans")] [ProtoContract] [JsonObject(MemberSerialization.OptIn)] public class PlayerBans { /// <summary> /// A string containing the player's 64 bit ID. /// </summary> [JsonProperty("SteamID")] [ProtoMember(1, IsRequired = true)] public ulong SteamId {get; set;} /// <summary> /// Boolean indicating whether or not the player is banned from Community /// </summary> [JsonProperty("CommunityBanned")] [ProtoMember(2)] public bool IsCommunityBanned {get; set;} /// <summary> /// Boolean indicating whether or not the player has VAC bans on record. /// </summary> [JsonProperty("VACBanned")] [ProtoMember(3)] public bool IsVACBanned {get; set;} /// <summary> /// Amount of VAC bans on record. /// </summary> [JsonProperty("NumberOfVACBans")] [ProtoMember(4)] public int VACBanCount {get; set;} /// <summary> /// Amount of days since last ban. /// </summary> [JsonProperty("DaysSinceLastBan")] [ProtoMember(5)] public int DaysSinceLastBan {get; set;} /// <summary> /// String containing the player's ban status in the economy. If the player has no bans on record the string will be "none", if the player is on probation it will say "probation", and so forth. /// </summary> [JsonProperty("EconomyBan")] [ProtoMember(6)] public string EconomyBan {get; set;} public override int GetHashCode() { return SteamId.GetHashCode(); } public override bool Equals(object obj) { var other = obj as PlayerBans; return other != null && SteamId.Equals(other.SteamId); } } }
Java
/* * Business.h * UsersService * * Copyright 2011 QuickBlox team. All rights reserved. * */ #import "QBUsersModels.h"
Java
--- layout: post title: ESPN took a picture of me categories: link --- Check [this link](http://espn.go.com/college-football/story/_/id/9685394/how-do-nebraska-fans-feel-bo-pelini-recent-behavior) for some story about Bo Pelini's goofing off, and -- look there in the last photo! -- it's some goofball in a Nebraska trilby.
Java
// // GFTestAppDelegate.h // TestChaosApp // // Created by Michael Charkin on 2/26/14. // Copyright (c) 2014 GitFlub. All rights reserved. // #import <UIKit/UIKit.h> @interface GFTestAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
Java
var modules = { "success" : [ {id: 1, name:"控制台", code:"console", protocol:"http", domain:"console.ecc.com", port:"18333", created:'2017-03-08 00:00:00', creator:'1', modified:'2017-03-08 00:00:00', modifier:'1'}, {id: 2, name:"服务中心", code:"service-center", protocol:"http", domain:"sc.ecc.com", port:"18222", created:'2017-03-08 00:00:00', creator:'1', modified:'2017-03-08 00:00:00', modifier:'1'} ], "error" : { code : "0200-ERROR", msg : "There are some errors occured." } } module.exports = { "modules": modules }
Java
const { createServer, plugins: { queryParser, serveStatic } } = require('restify'); const { join } = require('path'); const fetch = require('node-fetch'); const proxy = require('http-proxy-middleware'); const { PORT = 5000 } = process.env; const server = createServer(); server.use(queryParser()); server.get('/', async (req, res, next) => { if (!req.query.b) { const tokenRes = await fetch('https://webchat-mockbot.azurewebsites.net/directline/token', { headers: { origin: 'http://localhost:5000' }, method: 'POST' }); if (!tokenRes.ok) { return res.send(500); } const { token } = await tokenRes.json(); return res.send(302, null, { location: `/?b=webchat-mockbot&t=${encodeURIComponent(token)}` }); } return serveStatic({ directory: join(__dirname, 'dist'), file: 'index.html' })(req, res, next); }); server.get('/embed/*/config', proxy({ changeOrigin: true, target: 'https://webchat.botframework.com/' })); server.listen(PORT, () => console.log(`Embed dev server is listening to port ${PORT}`));
Java
/** * @author: * @date: 2016/1/21 */ define(["core/js/layout/Panel"], function (Panel) { var view = Panel.extend({ /*Panel的配置项 start*/ title:"表单-", help:"内容", brief:"摘要", /*Panel 配置 End*/ oninitialized:function(triggerEvent){ this._super(); this.mainRegion={ comXtype:$Component.TREE, comConf:{ data:[this.getModuleTree("core/js/base/AbstractView")], } }; var that = this; this.footerRegion = { comXtype: $Component.TOOLSTRIP, comConf: { /*Panel的配置项 start*/ textAlign: $TextAlign.RIGHT, items: [{ text: "展开所有节点", onclick: function (e) { that.getMainRegionRef().getComRef().expandAll(); }, },{ text: "折叠所有节点", onclick: function (e) { that.getMainRegionRef().getComRef().collapseAll(); }, }] /*Panel 配置 End*/ } }; }, getModuleTree:function(moduleName,arr){ var va = window.rtree.tree[moduleName]; var tree = {title: moduleName}; if(!arr){ arr = []; }else{ if(_.contains(arr,moduleName)){ return false; } } arr.push(moduleName); if(va&&va.deps&&va.deps.length>0){ tree.children = []; tree.folder=true; for(var i=0;i<va.deps.length;i++){ var newTree = this.getModuleTree(va.deps[i],arr); if(newTree){ tree.children.push(newTree); }else{ if(!tree.count){ tree.count = 0; } tree.count++; } } } return tree; } }); return view; });
Java
# Django Media Albums [![Build Status](https://travis-ci.org/VelocityWebworks/django-media-albums.svg?branch=master)](https://travis-ci.org/VelocityWebworks/django-media-albums) This app is used to create albums consisting of any combination of the following: * Photos * Video files * Audio files This app also optionally allows regular (non-staff) users to upload photos. This app requires Django 1.8, 1.9, 1.10, or 1.11. ## Installation ### Step 1 of 5: Install the required packages Install using pip: ```bash pip install django-media-albums ``` If you will be using the templates that come with this app, also install these packages using pip: ```bash pip install django-bootstrap-pagination sorl-thumbnail ``` If you will be allowing regular (non-staff) users to upload photos and will be using the `upload.html` template that comes with this app, also install the `django-crispy-forms` package using pip: ```bash pip install django-crispy-forms ``` ### Step 2 of 5: Update `settings.py` Make sure the following settings are all configured the way you want them in your `settings.py`: ``` MEDIA_ROOT MEDIA_URL STATIC_ROOT STATIC_URL ``` If you will be allowing regular (non-staff) users to upload photos, you will also need to have the `DEFAULT_FROM_EMAIL` setting present in your `settings.py` (for the notification email that gets sent out when a user uploads a photo). Add `'media_albums'` to your `settings.py` INSTALLED_APPS: ```python INSTALLED_APPS = ( ... 'media_albums', ... ) ``` If you will be using the templates that come with this app, also add the following to your `settings.py` INSTALLED_APPS: ```python INSTALLED_APPS = ( ... 'bootstrap_pagination', 'sorl.thumbnail', ... ) ``` If you will be allowing regular (non-staff) users to upload photos and will be using the `upload.html` template that comes with this app, also add `'crispy_forms'` to your `settings.py` INSTALLED_APPS and make sure the `CRISPY_TEMPLATE_PACK` setting is configured the way you want it: ```python INSTALLED_APPS = ( ... 'crispy_forms', ... ) CRISPY_TEMPLATE_PACK = 'bootstrap3' ``` If you will be enabling audio and/or video and will be using the templates that come with this app, also enable the `'django.template.context_processors.media'` context processor: ```python TEMPLATES = [ ... { ... 'OPTIONS': { ... 'context_processors': [ ... 'django.template.context_processors.media', ... ], ... }, ... }, ... ] ``` ### Step 3 of 5: Update `urls.py` Create a URL pattern in your `urls.py`: ```python from django.conf.urls import include, url urlpatterns = [ ... url(r'^media-albums/', include('media_albums.urls')), ... ] ``` ### Step 4 of 5: Add the database tables Run the following command: ```bash python manage.py migrate ``` ### Step 5 of 5: Update your project's `base.html` template (if necessary) If you will be using the templates that come with this app, make sure your project has a `base.html` template and that it has these blocks: ``` content extra_styles ``` ## Configuration To override any of the default settings, create a dictionary named `MEDIA_ALBUMS` in your `settings.py` with each setting you want to override. For example, if you wanted to enable audio and video, but leave all of the other settings alone, you would add this to your `settings.py`: ```python MEDIA_ALBUMS = { 'audio_files_enabled': True, 'video_files_enabled': True, } ``` These are the settings: ### `photos_enabled` (default: `True`) When set to `True`, albums may contain photos. ### `audio_files_enabled` (default: `False`) When set to `True`, albums may contain audio files. ### `audio_files_format1_extension` (default: `'mp3'`) When an audio file is uploaded, the "Audio file 1" field must have this extension. This setting is only relevant if `audio_files_enabled` is set to `True`. ### `audio_files_format2_extension` (default: `'ogg'`) When an audio file is uploaded, the "Audio file 2" field must have this extension. This setting is only relevant if `audio_files_enabled` is set to `True`. ### `audio_files_format2_required` (default: `False`) When set to `True`, the "Audio file 2" field will be marked as required. This setting is only relevant if `audio_files_enabled` is set to `True`. ### `video_files_enabled` (default: `False`) When set to `True`, albums may contain video files. ### `video_files_format1_extension` (default: `'mp4'`) When an video file is uploaded, the "Video file 1" field must have this extension. This setting is only relevant if `video_files_enabled` is set to `True`. ### `video_files_format2_extension` (default: `'webm'`) When an video file is uploaded, the "Video file 2" field must have this extension. This setting is only relevant if `video_files_enabled` is set to `True`. ### `video_files_format2_required` (default: `False`) When set to `True`, the "Video file 2" field will be marked as required. This setting is only relevant if `video_files_enabled` is set to `True`. ### `user_uploaded_photos_enabled` (default: `False`) When set to `True`, regular (non-staff) users may upload photos. However, they still must be approved by a staff user. ### `user_uploaded_photos_login_required` (default: `True`) When set to `True`, regular (non-staff) users may only upload photos if they are logged in. This setting is only relevant if `user_uploaded_photos_enabled` is set to `True`. ### `user_uploaded_photos_album_name` (default: `'User Photos'`) When a staff user approves a photo uploaded by a regular (non-staff) user, the photo will be added to the album with this name. This setting is only relevant if `user_uploaded_photos_enabled` is set to `True`. ### `user_uploaded_photos_album_slug` (default: `'user-photos'`) When a staff user approves a photo uploaded by a regular (non-staff) user, the photo will be added to the album with this slug. This setting is only relevant if `user_uploaded_photos_enabled` is set to `True`. ### `paginate_by` (default: `10`) This setting determines how many items can be on a single page. This applies to the list of albums as well as the list of items within albums.
Java
<!-- Safe sample input : get the $_GET['userData'] in an array sanitize : settype (float) File : unsafe, use of untrusted data in a comment --> <!--Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.--> <!DOCTYPE html> <html> <head> <!-- <?php $array = array(); $array[] = 'safe' ; $array[] = $_GET['userData'] ; $array[] = 'safe' ; $tainted = $array[1] ; if(settype($tainted, "float")) $tainted = $tainted ; else $tainted = 0.0 ; echo $tainted ; ?> --> </head> <body> <h1>Hello World!</h1> </body> </html>
Java
$('#modalUploader').on('show.bs.modal', function (event) { var uploader = new qq.FileUploaderBasic({ element: document.getElementById('file-uploader-demo1'), button: document.getElementById('areaSubir'), action: '/Files/Upload', params: { ruta: $('#RutaActual').val() }, allowedExtensions: ['jpg', 'jpeg', 'png', 'gif', 'doc', 'docx', 'pdf'], multiple: false, onComplete: function (id, fileName, responseJSON) { $.gritter.add({ title: 'Upload file', text: responseJSON.message }); }, onSubmit: function (id, fileName) { var strHtml = "<li>" + fileName + "</li>"; $("#dvxArchivos").append(strHtml); } }); }); $('#modalUploader').on('hidden.bs.modal', function () { RecargarRuta(); }) function AbrirCarpeta(pCarpeta) { $("#RutaSolicitada").val(pCarpeta); $("#frmMain").submit(); } function AbrirRuta(pCarpeta) { $("#RutaSolicitada").val(pCarpeta); $("#frmMain").submit(); } function RecargarRuta() { AbrirCarpeta($("#RutaActual").val()); } function EliminarArchivo(pRuta) { if (confirm("Are you sure that want to delete this file?")) { $.gritter.add({ title: 'Delete file', text: "File deleted" }); $("#ArchivoParaEliminar").val(pRuta); AbrirCarpeta($("#RutaActual").val()); } } function SubirNivel() { if ($("#TieneSuperior").val() == "1") { var strRutaAnterior = $("#RutaSuperior").val(); AbrirRuta(strRutaAnterior); } } function IrInicio() { AbrirRuta($("#RutaRaiz").val()); } function AbrirDialogoArchivo() { $("#modalUploader").modal(); } function getParameterByName(name) { name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regexS = "[\\?&]" + name + "=([^&#]*)"; var regex = new RegExp(regexS); var results = regex.exec(window.location.search); if (results == null) return ""; else return decodeURIComponent(results[1].replace(/\+/g, " ")); }
Java
// setToken when re-connecting var originalReconnect = Meteor.connection.onReconnect; Meteor.connection.onReconnect = function() { setToken(); if(originalReconnect) { originalReconnect(); } }; if(Meteor.status().connected) { setToken(); } function setToken() { var firewallHumanToken = Cookie.get('sikka-human-token'); Meteor.call('setSikkaHumanToken', firewallHumanToken); } // reloading the page window.sikkaCommands = sikkaCommands = new Mongo.Collection('sikka-commands'); sikkaCommands.find({}).observe({ added: function(command) { if(command._id === "reload") { location.reload(); } } });
Java
<% nameScope = @config['name_scope'] %> </div> </div> </div> <footer class="cortana-footer"> Build with love using Trulia's <a href="https://github.com/trulia/hologram">Hologram</a> and <a href="https://github.com/Yago/Cortana">Cortana</a> ! </footer> </div> <script src="theme-build/js/vendors.min.js"></script> <script type="text/javascript"> var jQuery_no_conflict = $.noConflict(true); </script> <script src="theme-build/js/main.js"></script> <script type="text/javascript"> function TypeaheadCtrl($scope) { $scope.selected = undefined; $scope.searchData = <%= "[" %> <% @pages.each do |file_name, page| %> <% if not page[:blocks].empty? %> <% page[:blocks].each do |block| %> <% file_path = block[:categories][0].to_s.gsub(' ', '_').downcase + '.html' %> <% file_id = "#"+block[:name].to_s %> <%= "{" %> <%= "\"title\": \""+block[:title].to_s+"\"," %> <%= "\"breadcrumb\": \""+block[:categories][0].to_s+" > "+block[:title]+"\"," %> <%= "\"path\": \""+file_path+file_id+"\"" %> <%= "}," %> <% end %> <% end %> <% end %> <%= "{}]" %>; $scope.onSelect = function ($item, $model, $label) { window.location.replace($item.path); }; } </script> <script type="text/ng-template" id="customTemplate.html"> <a href="{{match.model.path}}"> <p class="cortana-search-title">{{match.model.title}}</p> <p class="cortana-search-path">{{match.model.breadcrumb}}</p> </a> </script> <% if @config['js_include'].to_s.strip.length != 0 %> <% @config['js_include'].each do |js| %> <script type="text/javascript" src="<%= js %>"></script> <% end %> <% end %> <!-- Source Components --> <% if @config['components_include'].to_s.strip.length != 0 %> <% @config['components_include'].each do |component| %> <link rel="import" href="<%= component %>"> <% end %> <% end %> </body> </html>
Java
// // rbLinkedList.h // rbLinkedList // // Created by Ryan Bemowski on 4/6/15. // #pragma once #include <string> struct Node { int key; Node *next; }; class rbLinkedList { public: /** Constructor for the rbLinkedList class. */ rbLinkedList(); /** Deconstructor for the rbLinkedList class. */ ~rbLinkedList(); /** Determine if the collection is empty or not. * @return: A bool that will be true if the collection is empty and false * otherwise. */ bool IsEmpty(); /** Determine the number of nodes within the linked list. * @return: An integer that represents the number of nodes between the head * and tail nodes. */ int Size(); void AddKey(int key); void RemoveKey(int key); std::string ToString(); private: Node *h_; Node *z_; };
Java
// // KAAppDelegate.h // UIViewController-KeyboardAdditions // // Created by CocoaPods on 02/03/2015. // Copyright (c) 2014 Andrew Podkovyrin. All rights reserved. // #import <UIKit/UIKit.h> @interface KAAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
Java
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Basic Example</title> <link rel="stylesheet" href="css/base.css" /> <script src="../../asset/react/react.js"></script> <script src="../../asset/react/react-dom.js"></script> <script src="../../asset/react/browser.min.js"></script> <script src="js/app/index.jsx" type="text/babel"></script> </head> <body> <h1>React 允许将代码封装成组件(component),然后像插入普通 HTML 标签一样,在网页中插入这个组件。React.createClass 方法就用于生成一个组件类</h1> <h1>组件的属性可以在组件类的 this.props 对象上获取</h1> <h1>添加组件属性,有一个地方需要注意,就是 class 属性需要写成 className ,for 属性需要写成 htmlFor ,这是因为 class 和 for 是 JavaScript 的保留字。</h1> <div id="message"></div> </body> </html>
Java
using System.Collections.ObjectModel; using System.ComponentModel; using GalaSoft.MvvmLight.Command; namespace Treehopper.Mvvm.ViewModels { /// <summary> /// A delegate called when the selected board changes /// </summary> /// <param name="sender">The caller</param> /// <param name="e">The new selected board</param> public delegate void SelectedBoardChangedEventHandler(object sender, SelectedBoardChangedEventArgs e); /// <summary> /// A delegate called when the selected board has connected /// </summary> /// <param name="sender">The caller</param> /// <param name="e">The connected board</param> public delegate void BoardConnectedEventHandler(object sender, BoardConnectedEventArgs e); /// <summary> /// A delegate called when the selected board has disconnected /// </summary> /// <param name="sender">The caller</param> /// <param name="e">The disconnected board</param> public delegate void BoardDisconnectedEventHandler(object sender, BoardDisconnectedEventArgs e); /// <summary> /// Base interface for the selector view model /// </summary> public interface ISelectorViewModel : INotifyPropertyChanged { /// <summary> /// Get the collection of boards /// </summary> ObservableCollection<TreehopperUsb> Boards { get; } /// <summary> /// Whether the board selection can be changed /// </summary> bool CanChangeBoardSelection { get; set; } /// <summary> /// The currently selected board /// </summary> TreehopperUsb SelectedBoard { get; set; } /// <summary> /// Occurs when the window closes /// </summary> RelayCommand WindowClosing { get; set; } /// <summary> /// Occurs when the connection occurs /// </summary> RelayCommand ConnectCommand { get; set; } /// <summary> /// Connect button text /// </summary> string ConnectButtonText { get; set; } /// <summary> /// Close command /// </summary> RelayCommand CloseCommand { get; set; } /// <summary> /// Board selection changed /// </summary> event SelectedBoardChangedEventHandler OnSelectedBoardChanged; /// <summary> /// Board connected /// </summary> event BoardConnectedEventHandler OnBoardConnected; /// <summary> /// Board disconnected /// </summary> event BoardDisconnectedEventHandler OnBoardDisconnected; } }
Java
import React from 'react'; import ReactDOM from 'react-dom'; import componentOrElement from 'react-prop-types/lib/componentOrElement'; import ownerDocument from './utils/ownerDocument'; import getContainer from './utils/getContainer'; /** * The `<Portal/>` component renders its children into a new "subtree" outside of current component hierarchy. * You can think of it as a declarative `appendChild()`, or jQuery's `$.fn.appendTo()`. * The children of `<Portal/>` component will be appended to the `container` specified. */ let Portal = React.createClass({ displayName: 'Portal', propTypes: { /** * A Node, Component instance, or function that returns either. The `container` will have the Portal children * appended to it. */ container: React.PropTypes.oneOfType([ componentOrElement, React.PropTypes.func ]), /** * Classname to use for the Portal Component */ className: React.PropTypes.string }, componentDidMount() { this._renderOverlay(); }, componentDidUpdate() { this._renderOverlay(); }, componentWillReceiveProps(nextProps) { if (this._overlayTarget && nextProps.container !== this.props.container) { this._portalContainerNode.removeChild(this._overlayTarget); this._portalContainerNode = getContainer(nextProps.container, ownerDocument(this).body); this._portalContainerNode.appendChild(this._overlayTarget); } }, componentWillUnmount() { this._unrenderOverlay(); this._unmountOverlayTarget(); }, _mountOverlayTarget() { if (!this._overlayTarget) { this._overlayTarget = document.createElement('div'); if (this.props.className) { this._overlayTarget.className = this.props.className; } this._portalContainerNode = getContainer(this.props.container, ownerDocument(this).body); this._portalContainerNode.appendChild(this._overlayTarget); } }, _unmountOverlayTarget() { if (this._overlayTarget) { this._portalContainerNode.removeChild(this._overlayTarget); this._overlayTarget = null; } this._portalContainerNode = null; }, _renderOverlay() { let overlay = !this.props.children ? null : React.Children.only(this.props.children); // Save reference for future access. if (overlay !== null) { this._mountOverlayTarget(); this._overlayInstance = ReactDOM.unstable_renderSubtreeIntoContainer( this, overlay, this._overlayTarget ); } else { // Unrender if the component is null for transitions to null this._unrenderOverlay(); this._unmountOverlayTarget(); } }, _unrenderOverlay() { if (this._overlayTarget) { ReactDOM.unmountComponentAtNode(this._overlayTarget); this._overlayInstance = null; } }, render() { return null; }, getMountNode(){ return this._overlayTarget; }, getOverlayDOMNode() { if (!this.isMounted()) { throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.'); } if (this._overlayInstance) { return ReactDOM.findDOMNode(this._overlayInstance); } return null; } }); export default Portal;
Java
dojo.provide("plugins.dijit.SyncDialog"); // HAS A dojo.require("dijit.Dialog"); dojo.require("dijit.form.Button"); dojo.require("dijit.form.ValidationTextBox"); // INHERITS dojo.require("plugins.core.Common"); dojo.declare( "plugins.dijit.SyncDialog", [ dijit._Widget, dijit._Templated, plugins.core.Common ], { //Path to the template of this widget. templatePath: dojo.moduleUrl("plugins", "dijit/templates/syncdialog.html"), // OR USE @import IN HTML TEMPLATE cssFiles : [ dojo.moduleUrl("plugins", "dijit/css/syncdialog.css") ], // Calls dijit._Templated.widgetsInTemplate widgetsInTemplate : true, // PARENT plugins.workflow.Apps WIDGET parentWidget : null, // DISPLAYED MESSAGE message : null, //////}} constructor : function(args) { console.log("SyncDialog.constructor args:"); console.dir({args:args}); // LOAD CSS this.loadCSS(); }, postCreate : function() { //////console.log("SyncDialog.postCreate plugins.dijit.SyncDialog.postCreate()"); this.startup(); }, startup : function () { ////console.log("SyncDialog.startup plugins.dijit.SyncDialog.startup()"); ////console.log("SyncDialog.startup this.parentWidget: " + this.parentWidget); this.inherited(arguments); // SET UP DIALOG this.setDialogue(); // SET KEY LISTENER this.setKeyListener(); // ADD CSS NAMESPACE CLASS FOR TITLE CSS STYLING this.setNamespaceClass("syncDialog"); }, setKeyListener : function () { dojo.connect(this.dialog, "onkeypress", dojo.hitch(this, "handleOnKeyPress")); }, handleOnKeyPress: function (event) { var key = event.charOrCode; console.log("SyncDialog.handleOnKeyPress key: " + key); if ( key == null ) return; event.stopPropagation(); if ( key == dojo.keys.ESCAPE ) this.hide(); }, setNamespaceClass : function (ccsClass) { // ADD CSS NAMESPACE CLASS dojo.addClass(this.dialog.domNode, ccsClass); dojo.addClass(this.dialog.titleNode, ccsClass); dojo.addClass(this.dialog.closeButtonNode, ccsClass); }, show: function () { // SHOW THE DIALOGUE this.dialog.show(); this.message.focus(); }, hide: function () { // HIDE THE DIALOGUE this.dialog.hide(); }, doEnter : function(type) { // RUN ENTER CALLBACK IF 'ENTER' CLICKED console.log("SyncDialog.doEnter plugins.dijit.SyncDialog.doEnter()"); var inputs = this.validateInputs(["message", "details"]); console.log("SyncDialog.doEnter inputs:"); console.dir({inputs:inputs}); if ( ! inputs ) { console.log("SyncDialog.doEnter inputs is null. Returning"); return; } // RESET this.message.set('value', ""); this.details.value = ""; // HIDE this.hide(); // DO CALLBACK this.dialog.enterCallback(inputs); }, validateInputs : function (keys) { console.log("Hub.validateInputs keys: "); console.dir({keys:keys}); var inputs = new Object; this.isValid = true; for ( var i = 0; i < keys.length; i++ ) { console.log("Hub.validateInputs Doing keys[" + i + "]: " + keys[i]); inputs[keys[i]] = this.verifyInput(keys[i]); } console.log("Hub.validateInputs inputs: "); console.dir({inputs:inputs}); if ( ! this.isValid ) return null; return inputs; }, verifyInput : function (input) { console.log("Aws.verifyInput input: "); console.dir({this_input:this[input]}); var value = this[input].value; console.log("Aws.verifyInput value: " + value); var className = this.getClassName(this[input]); console.log("Aws.verifyInput className: " + className); if ( className ) { console.log("Aws.verifyInput this[input].isValid(): " + this[input].isValid()); if ( ! value || ! this[input].isValid() ) { console.log("Aws.verifyInput input " + input + " value is empty. Adding class 'invalid'"); dojo.addClass(this[input].domNode, 'invalid'); this.isValid = false; } else { console.log("SyncDialog.verifyInput value is NOT empty. Removing class 'invalid'"); dojo.removeClass(this[input].domNode, 'invalid'); return value; } } else { if ( input.match(/;/) || input.match(/`/) ) { console.log("SyncDialog.verifyInput value is INVALID. Adding class 'invalid'"); dojo.addClass(this[input], 'invalid'); this.isValid = false; return null; } else { console.log("SyncDialog.verifyInput value is VALID. Removing class 'invalid'"); dojo.removeClass(this[input], 'invalid'); return value; } } return null; }, doCancel : function() { // RUN CANCEL CALLBACK IF 'CANCEL' CLICKED ////console.log("SyncDialog.doCancel plugins.dijit.SyncDialog.doCancel()"); this.dialog.cancelCallback(); this.dialog.hide(); }, setDialogue : function () { // APPEND DIALOG TO DOCUMENT document.body.appendChild(this.dialog.domNode); this.dialog.parentWidget = this; // AVOID this._fadeOutDeferred NOT DEFINED ERROR this._fadeOutDeferred = function () {}; }, load : function (args) { console.log("SyncDialog.load args:"); console.dir({args:args}); if ( args.title ) { console.log("SyncDialog.load SETTING TITLE: " + args.title); this.dialog.set('title', args.title); } this.headerNode.innerHTML = args.header; if (args.message) this.message.set('value', args.message); if (args.details) this.details.value = args.details; //if (args.details) this.details.innerHTML(args.details); this.dialog.enterCallback = args.enterCallback; this.show(); } });
Java
namespace TraktApiSharp.Objects.Basic.Json.Factories { using Objects.Basic.Json.Reader; using Objects.Basic.Json.Writer; using Objects.Json; internal class CommentLikeJsonIOFactory : IJsonIOFactory<ITraktCommentLike> { public IObjectJsonReader<ITraktCommentLike> CreateObjectReader() => new CommentLikeObjectJsonReader(); public IArrayJsonReader<ITraktCommentLike> CreateArrayReader() => new CommentLikeArrayJsonReader(); public IObjectJsonWriter<ITraktCommentLike> CreateObjectWriter() => new CommentLikeObjectJsonWriter(); } }
Java
package com.sdl.selenium.extjs3.button; import com.sdl.selenium.bootstrap.button.Download; import com.sdl.selenium.extjs3.ExtJsComponent; import com.sdl.selenium.web.SearchType; import com.sdl.selenium.web.WebLocator; public class DownloadLink extends ExtJsComponent implements Download { public DownloadLink() { setClassName("DownloadLink"); setTag("a"); } public DownloadLink(WebLocator container) { this(); setContainer(container); } public DownloadLink(WebLocator container, String text) { this(container); setText(text, SearchType.EQUALS); } /** * Wait for the element to be activated when there is deactivation mask on top of it * * @param seconds time */ @Override public boolean waitToActivate(int seconds) { return getXPath().contains("ext-ux-livegrid") || super.waitToActivate(seconds); } /** * if WebDriverConfig.isSilentDownload() is true, se face silentDownload, is is false se face download with AutoIT. * Download file with AutoIT, works only on FireFox. SilentDownload works FireFox and Chrome * Use only this: button.download("C:\\TestSet.tmx"); * return true if the downloaded file is the same one that is meant to be downloaded, otherwise returns false. * * @param fileName e.g. "TestSet.tmx" */ @Override public boolean download(String fileName) { openBrowse(); return executor.download(fileName, 10000L); } private void openBrowse() { executor.browse(this); } }
Java
angular.module('perCapita.controllers', []) .controller('AppCtrl', ['$scope', '$rootScope', '$ionicModal', '$timeout', '$localStorage', '$ionicPlatform', 'AuthService', function ($scope, $rootScope, $ionicModal, $timeout, $localStorage, $ionicPlatform, AuthService) { $scope.loginData = $localStorage.getObject('userinfo', '{}'); $scope.reservation = {}; $scope.registration = {}; $scope.loggedIn = false; if (AuthService.isAuthenticated()) { $scope.loggedIn = true; $scope.username = AuthService.getUsername(); } // Create the login modal that we will use later $ionicModal.fromTemplateUrl('templates/login.html', { scope: $scope }).then(function (modal) { $scope.modal = modal; }); // Triggered in the login modal to close it $scope.closeLogin = function () { $scope.modal.hide(); }; // Open the login modal $scope.login = function () { $scope.modal.show(); }; // Perform the login action when the user submits the login form $scope.doLogin = function () { console.log('Doing login', $scope.loginData); $localStorage.storeObject('userinfo', $scope.loginData); AuthService.login($scope.loginData); $scope.closeLogin(); }; $scope.logOut = function () { AuthService.logout(); $scope.loggedIn = false; $scope.username = ''; }; $rootScope.$on('login:Successful', function () { $scope.loggedIn = AuthService.isAuthenticated(); $scope.username = AuthService.getUsername(); }); $ionicModal.fromTemplateUrl('templates/register.html', { scope: $scope }).then(function (modal) { $scope.registerform = modal; }); $scope.closeRegister = function () { $scope.registerform.hide(); }; $scope.register = function () { $scope.registerform.show(); }; $scope.doRegister = function () { console.log('Doing registration', $scope.registration); $scope.loginData.username = $scope.registration.username; $scope.loginData.password = $scope.registration.password; AuthService.register($scope.registration); $timeout(function () { $scope.closeRegister(); }, 1000); }; $rootScope.$on('registration:Successful', function () { $localStorage.storeObject('userinfo', $scope.loginData); }); }]) .controller('FavoriteDetailsController', ['$scope', '$rootScope', '$state', '$stateParams', 'Favorites', function ($scope, $rootScope, $state, $stateParams, Favorites) { $scope.showFavButton = false; // Lookup favorites for a given user id Favorites.findById({id: $stateParams.id}) .$promise.then( function (response) { $scope.city = response; }, function (response) { $scope.message = "Error: " + response.status + " " + response.statusText; } ); }]) .controller('HomeController', ['$scope', 'perCapitaService', '$stateParams', '$rootScope', 'Favorites', '$ionicPlatform', '$cordovaLocalNotification', '$cordovaToast', function ($scope, perCapitaService, $stateParams, $rootScope, Favorites, $ionicPlatform, $cordovaLocalNotification, $cordovaToast) { $scope.showFavButton = $rootScope.currentUser; $scope.controlsData = {skills: $rootScope.skills}; // Look up jobs data $scope.doLookup = function () { $rootScope.skills = $scope.controlsData.skills; perCapitaService.lookup($scope.controlsData.skills); }; // Post process the jobs data, by adding Indeeds link and calculating jobsPer1kPeople and jobsRank $scope.updatePerCapitaData = function () { $scope.cities = perCapitaService.response.data.docs; var arrayLength = $scope.cities.length; for (var i = 0; i < arrayLength; i++) { var obj = $scope.cities[i]; obj.jobsPer1kPeople = Math.round(obj.totalResults / obj.population * 1000); obj.url = "https://www.indeed.com/jobs?q=" + $scope.controlsData.skills + "&l=" + obj.city + ", " + obj.state; } // rank jobs var sortedObjs; if (perCapitaService.isSkills) { sortedObjs = _.sortBy($scope.cities, 'totalResults').reverse(); } else { sortedObjs = _.sortBy($scope.cities, 'jobsPer1kPeople').reverse(); } $scope.cities.forEach(function (element) { element.jobsRank = sortedObjs.indexOf(element) + 1; }); if (!$scope.$$phase) { $scope.$apply(); } $rootScope.cities = $scope.cities; console.log("Loaded " + arrayLength + " results.") }; perCapitaService.registerObserverCallback($scope.updatePerCapitaData); $scope.addToFavorites = function () { delete $scope.city._id; delete $scope.city._rev; $scope.city.customerId = $rootScope.currentUser.id Favorites.create($scope.city); $ionicPlatform.ready(function () { $cordovaLocalNotification.schedule({ id: 1, title: "Added Favorite", text: $scope.city.city }).then(function () { console.log('Added Favorite ' + $scope.city.city); }, function () { console.log('Failed to add Favorite '); }); $cordovaToast .show('Added Favorite ' + $scope.city.city, 'long', 'center') .then(function (success) { // success }, function (error) { // error }); }); } if ($stateParams.id) { console.log("param " + $stateParams.id); $scope.city = $rootScope.cities.filter(function (obj) { return obj._id === $stateParams.id; })[0]; console.log($scope.city); } else { $scope.doLookup(); } }]) .controller('AboutController', ['$scope', function ($scope) { }]) .controller('FavoritesController', ['$scope', '$rootScope', '$state', 'Favorites', '$ionicListDelegate', '$ionicPopup', function ($scope, $rootScope, $state, Favorites, $ionicListDelegate, $ionicPopup) { $scope.shouldShowDelete = false; /*$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) { console.log("State changed: ", toState); if(toState.name === "app.favorites") $scope.refreshItems(); });*/ $scope.refreshItems = function () { if ($rootScope.currentUser) { Favorites.find({ filter: { where: { customerId: $rootScope.currentUser.id } } }).$promise.then( function (response) { $scope.favorites = response; console.log("Got favorites"); }, function (response) { console.log(response); }); } else { $scope.message = "You are not logged in" } } $scope.refreshItems(); $scope.toggleDelete = function () { $scope.shouldShowDelete = !$scope.shouldShowDelete; console.log($scope.shouldShowDelete); } $scope.deleteFavorite = function (favoriteid) { var confirmPopup = $ionicPopup.confirm({ title: '<h3>Confirm Delete</h3>', template: '<p>Are you sure you want to delete this item?</p>' }); confirmPopup.then(function (res) { if (res) { console.log('Ok to delete'); Favorites.deleteById({id: favoriteid}).$promise.then( function (response) { $scope.favorites = $scope.favorites.filter(function (el) { return el.id !== favoriteid; }); $state.go($state.current, {}, {reload: false}); // $window.location.reload(); }, function (response) { console.log(response); $state.go($state.current, {}, {reload: false}); }); } else { console.log('Canceled delete'); } }); $scope.shouldShowDelete = false; } }]) ;
Java
# VBA.ModernTheme ### Windows Phone Colour Palette and<p>Colour Selector using WithEvents Version 1.0.1 The *Windows Phone Theme Colours* is a tight, powerful, and well balanced palette. This tiny Microsoft Access application makes it a snap to select and pick a value. And it doubles as an intro to implementing *WithEvents*, one of Access' hidden gems. ![General](https://raw.githubusercontent.com/GustavBrock/VBA.ModernTheme/master/images/ModernThemeHeader.png) Full documentation is found here: ![EE Logo](https://raw.githubusercontent.com/GustavBrock/VBA.ModernTheme/master/images/EE%20Logo.png) [Create Windows Phone Colour Palette and Selector using WithEvents](https://www.experts-exchange.com/articles/29554/Create-Windows-Phone-Colour-Palette-and-Selector-using-WithEvents.html?preview=yawJg2wkMzc%3D) <hr> *If you wish to support my work or need extended support or advice, feel free to:* <p> [<img src="https://raw.githubusercontent.com/GustavBrock/VBA.ModernTheme/master/images/BuyMeACoffee.png">](https://www.buymeacoffee.com/gustav/)
Java
var http = require("http"); var querystring = require("querystring"); // 核心模块 var SBuffer=require("../tools/SBuffer"); var common=require("../tools/common"); var zlib=require("zlib"); var redis_pool=require("../tools/connection_pool"); var events = require('events'); var util = require('util'); function ProxyAgent(preHeaders,preAnalysisFields,logName){ this.headNeeds = preHeaders||""; this.preAnalysisFields = preAnalysisFields||""; this.AnalysisFields = {}; this.logName=logName||""; this.response=null; this.reqConf={}; this.retData=[]; this.redis =null; // redis {} redis_key events.EventEmitter.call(this); } /** * 获取服务配置信息 * @param 服务名 * @return object */ ProxyAgent.prototype.getReqConfig = function(logName){ var _self=this; var Obj={}; Obj=Config[logName]; Obj.logger=Analysis.getLogger(logName); Obj.name=logName; return Obj; } ProxyAgent.prototype.doRequest=function(_req,_res){ var _self=this; _self.reqConf=_self.getReqConfig(this.logName); logger.debug('进入'+_self.reqConf.desc+"服务"); var header_obj =this.packageHeaders(_req.headers,this.headNeeds); var url_obj = url.parse(request.url, true); var query_obj = url_obj.query; var postData = request.body|| ""; // 获取请求参数 _res.setHeader("Content-Type", config.contentType); _res.setHeader(config.headerkey, config.headerval); var opts=_self.packData(header_obj,query_obj,postData); logger.debug(header_obj.mobileid +_self.reqConf.desc+ '接口参数信息:'+opts[0].path +" data:"+ opts[1]); if(typeof(postData) =="object" && postData.redis_key.length>0){ this.getRedis(opts[0],opts[1]); } else{ this.httpProxy(opts[0],opts[1]); } } /** * 封装get post接口 * @param headers * @param query * @param body * @return [] */ ProxyAgent.prototype.packData=function(headers,query,body){ var _self=this; //resType 解释 ""==>GET,"body"==>POST,"json"==>特殊poi,"raw"==>原始数据 var type=_self.reqConf.resType || ""; body = body || ""; var len=0; var query_str=""; var body_str=""; if(type==""){ query=common.extends(query,headers); query_str = querystring.stringify(query, '&', '='); } else if(type=="body"){ body=common.extends(body,headers); body_str = querystring.stringify(body, '&', '='); len=body_str.length; if(body.redis_key){ this.redis={}; this.redis.redis_key=body.redis_key; } } else if(type=="json"){ query=common.extends(query,headers); query_str = 'json='+querystring.stringify(query, '&', '='); } else if(type=="raw"){ len=body.length; body_str=body; } var actionlocation = headers.actionlocation || ""; if(actionlocation==""){ actionlocation=query.actionlocation||""; } var opts=_self.getRequestOptions(len,actionlocation); opts.path+=((opts.path.indexOf("?")>=0)?"&":"?")+query_str; return [opts,body_str]; } /** * 获取请求头信息 * @param len数据长度 * @param actiontion 通用访问地址 * @return object 头信息 */ ProxyAgent.prototype.getRequestOptions=function(len,actionlocation){ var _self=this; var options = { //http请求参数设置 host: _self.reqConf.host, // 远端服务器域名 port: _self.reqConf.port, // 远端服务器端口号 path: _self.reqConf.path||"", headers : {'Connection' : 'keep-alive'} }; if(actionlocation.length>0){ options.path=actionlocation; } var rtype= _self.reqConf.reqType || ""; if(rtype.length>0){ options.headers['Content-Type']=rtype; } if(len>0){ options.headers['Content-Length']=len; } return options; } ProxyAgent.prototype.getRedisOptions=function(options,actionlocation){ var obj={}; return obj; } /** * 获取头部信息进行封装 * @param request.headers * @param need fields ;split with ',' * @return object headers */ ProxyAgent.prototype.packageHeaders = function(headers) { var fields=arguments[1]||""; var query_obj = {}; var reqip = headers['x-real-ip'] || '0'; // 客户端请求的真实ip地址 var forward = headers['x-forwarded-for'] || '0'; // 客户端请求来源 var osversion = headers['osversion'] || '0';// 客户端系统 var devicemodel = headers['devicemodel'] || '0';// 客户端型号 var manufacturername = headers['manufacturername'] || '0';// 制造厂商 var actionlocation = headers['actionlocation']; // 请求后台地址 var dpi = headers['dpi'] || '2.0';// 密度 var imsi = headers['imsi'] || '0'; // 客户端imsi var mobileid = headers['mobileid'] || '0'; // 客户端mibileid var version = headers['version'] || '0';// 客户端版本version var selflon = headers['selflon'] || '0';// 经度 var selflat = headers['selflat'] || '0';// 维度 var uid = headers['uid'] || '0'; // 犬号 var radius=headers['radius']||'0';//误差半径 var platform=headers['platform']||"";//平台 ios ,android var gender= headers['gender'] || '0'; query_obj.gender = gender; query_obj.reqip = reqip; query_obj.forward = forward; query_obj.osversion = osversion; query_obj.devicemodel = devicemodel; query_obj.manufacturername = manufacturername; query_obj.actionlocation = actionlocation; query_obj.dpi = dpi; query_obj.imsi = imsi; query_obj.mobileid = mobileid; query_obj.version = version; query_obj.selflon = selflon; query_obj.selflat = selflat; query_obj.uid = uid; query_obj.radius=radius; query_obj.platform=platform; if(fields.length > 0){ var afields = fields.split(","); var newObj = {}; for(var i = 0; i < afields.length ; i ++){ newObj[afields[i]] = query_obj[afields[i]] || ""; } return newObj; } else{ return query_obj; } } /** * http 请求代理 * @param options 远程接口信息 * @param reqData 请求内容 req.method== get时一般为空 */ ProxyAgent.prototype.httpProxy = function (options,reqData){ var _self=this; var TongjiObj={}; var req = http.request(options, function(res) { TongjiObj.statusCode = res.statusCode ||500; var tmptime=Date.now(); TongjiObj.restime = tmptime; TongjiObj.resEnd =tmptime; TongjiObj.ends = tmptime; TongjiObj.length = 0; TongjiObj.last = tmptime; var sbuffer=new SBuffer(); res.setEncoding("utf-8"); res.on('data', function (trunk) { sbuffer.append(trunk); }); res.on('end', function () { TongjiObj.resEnd = Date.now(); //doRequestCB(response, {"data":sbuffer.toString(),"status":res.statusCode},TongjiObj,redisOpt); _self.emmit("onDone",sbuffer,TongjiObj); }); }); req.setTimeout(timeout,function(){ req.emit('timeOut',{message:'have been timeout...'}); }); req.on('error', function(e) { TongjiObj.statusCode=500; _self.emmit("onDone","",500,TongjiObj); }); req.on('timeOut', function(e) { req.abort(); TongjiObj.statusCode=500; TongjiObj.last = Date.now(); _self.emmit("onDone","",500,TongjiObj); }); req.end(reqData); } /** * 设置缓存 * @param redis_key * @param redis_time * @param resultBuffer */ ProxyAgent.prototype.setRedis = function (redis_key, redis_time, resultBuffer) { redis_pool.acquire(function(err, client) { if (!err) { client.setex(redis_key, redis_time, resultBuffer, function(err, repliy) { redis_pool.release(client); // 链接使用完毕释放链接 }); logger.debug(redis_key + '设置缓存数据成功!'); } else { writeLogs.logs(Analysis.getLogger('error'), 'error', { msg : 'redis_general保存数据到redis缓存数据库时链接redis数据库异常', err : 14 }); logger.debug(redis_key + '设置缓存数据失败!'); } }); } /** * 从缓存中获取数据,如果获取不到,则请求后台返回的数据返回给客户端 并且将返回的数据设置到redis缓存 * redis_key通过self变量中取 * @param options * @param reqData */ ProxyAgent.prototype.getRedis = function ( options, reqData) { var _self=this; var redis_key=this.redis.redis_key || ""; redis_pool.acquire(function(err, client) { if (!err) { client.get(redis_key, function(err, date) { redis_pool.release(client) // 用完之后释放链接 if (!err && date != null) { var resultBuffer = new Buffer(date); _self.response.statusCode = 200; _self.response.setHeader("Content-Length", resultBuffer.length); _self.response.write(resultBuffer); // 以二进制流的方式输出数据 _self.response.end(); logger.debug(redis_key + '通用接口下行缓存数据:' + date); } else { _self.httpProxy(options, reqData); } }); } else { _self.httpProxy(options, reqData); } }); } /** * 输出gzip数据 * response 内置 * @param resultBuffer */ ProxyAgent.prototype.gzipOutPut = function (resultBuffer){ var _self=this; zlib.gzip(resultBuffer, function(code, buffer){ // 对服务器返回的数据进行压缩 if (code != null) { // 如果正常结束 logger.debug('压缩成功,压缩前:'+resultBuffer.length+',压缩后:'+buffer.length); _self.response.setHeader('Content-Encoding', 'gzip'); //压缩标志 } else { buffer = new Buffer( '{"msg":["服务器返回数据非JSON格式"]}'); _self.response.statusCode=500; } _self.response.setHeader("Content-Length", buffer.length); _self.response.write(buffer); _self.response.end(); }); } /** * 请求完毕处理 * @param buffer type buffer/string * @param status 请求http状态 * @param tongji object统计对象 */ ProxyAgent.prototype.onDone =function(buffer,status){ var tongji=arguments[2] ||""; var _self=this; var resultStr = typeof(buffer)=="object"?buffer.toString():buffer; if(this.reqConf.isjson==1){ var resultObj = common.isJson( resultStr, _self.reqConf.logName); // 判断返回结果是否是json格式 if (resultObj) { // 返回结果是json格式 resultStr = JSON.stringify(resultObj); _self.response.statusCode = status; } else { resultStr = '{"msg":["gis服务器返回数据非JSON格式"]}'; _self.response.statusCode = 500; } } else{ _self.response.statusCode = status; } var resultBuffer = new Buffer(resultStr); if(tongji!=""){ tongji.ends = Date.now(); tongji.length = resultBuffer.length; } if(resultBuffer.length > 500 ){ //压缩输出 _self.gzipOutPut(resultBuffer); }else{ _self.response.setHeader("Content-Length", resultBuffer.length); _self.response.write(resultBuffer); // 以二进制流的方式输出数据 _self.response.end(); } if(tongji!=""){ tongji.last= Date.now(); tongji=common.extends(tongji,_self.preAnalysisFields); logger.debug('耗时:' + (tongji.last - tongji.start)+'ms statusCode='+status); writeLogs.logs(poiDetailServer,'poiDetailServer',obj); } }); ProxyAgent.prototype.onDones =function(buffer,status){ var tongji=arguments[2] ||""; this.retData.push([buffer,status,tongji]; }); ProxyAgent.prototype.dealDones =function(){ var tongji=arguments[2] ||""; this.retData.push([buffer,status,tongji]; }); //ProxyAgent 从event 集成 //utils.inherit(ProxyAgent,event); exports.ProxyAgent=ProxyAgent;
Java
--- layout: post title: "Hello World" image: feature: nomadsland.jpg date: 2016-09-19 20:24:11 +0200 categories: personal, coding --- I enjoy tinkering - building little electronic gadgets and apps - especially if it has something to do with [cryptocurrencies]. Currently my day-job is building Bitcoin infrastructure. The purpose of this weblog is to record the progress on various projects outside my normal scope of work. Working with software, I seem to hit a lot of **"Hmmm, I wonder how this works?"** moments. Hopefully these pages provide some useful information to somebody working on and wondering about the same things. ## Begin I'm a fan of the maxim "Done is better than perfect" so my current goal is to get this blog up and running as quickly as possible. Instead of wondering about which software or host to use, I decided to power it with [Jekyll] and host it on [Github pages]. I already have a code/text editor I like using and git is already part of my daily workflow so it seemed like a natural fit. I picked a theme I liked but just as I got something that looked vaguely OK, I ran into the first **"Hmmm, I wonder"** moment. It turns out Jekyll/Github pages deployments are not intuitive. [Jekyll's Basic Usage Guide] does a pretty good job of explaining how to get up and running locally, but trying to find GH-Pages deployment instructions (and failing miserably) made me realise things don't work as I'd expect. ## Jekyll & Github Jekyll uses plugins and templates to help authors perform dynamic blog-related things like themeing, categorising and indexing posts, generating "about" pages and more. `jekyll build` produces a static "render" of the blog at the time it is called so that you can just upload the HTML/JS/CSS contents of the generated `_site` directory to a server that serves static content. You could host it on dropbox if you wanted to, there's no server-side scripts like PHP or Rails to generate content from data stored in a database. `_site` gets destroyed and re-created every time you call `jekyll build` and it is listed in `.gitignore` so it's not part of the repo, so how in the world do you tell Github to serve the contents of `_site`? Am I supposed to create a manual deploy script that adds `_site` to a repo and push that? ## Hmmm, I wonder... So which is it? Turns out you simply push your jekyll source repo to `master`. You don't even need to call `jekyll build`. Your site just magically appears on Github. That leaves only two possibilities: 1. Either Github calls `jekyll build` and serves the `_site` directory after each push, or 2. Github is running `jekyll serve` to generate content every request. Turns out it's the latter. Github actually runs Jekyll, and supports [some Jekyll plugins]. ## Done So, one "git push" later and these pages should be live! *"Done is better than perfect"* [BitX]: https://www.bitx.co/ [cryptocurrencies]: https://en.wikipedia.org/wiki/Cryptocurrency [jekyll]: https://jekyllrb.com [Jekyll's Basic Usage Guide]: https://jekyllrb.com/docs/usage/ [Github pages]: https://pages.github.com/ [some Jekyll plugins]: https://help.github.com/articles/adding-jekyll-plugins-to-a-github-pages-site/
Java
<?php namespace RobotsTxtParser; class CommentsTest extends \PHPUnit\Framework\TestCase { /** * @dataProvider generateDataForTest */ public function testRemoveComments($robotsTxtContent) { $parser = new RobotsTxtParser($robotsTxtContent); $rules = $parser->getRules('*'); $this->assertEmpty($rules, 'expected remove comments'); } /** * @dataProvider generateDataFor2Test */ public function testRemoveCommentsFromValue($robotsTxtContent, $expectedDisallowValue) { $parser = new RobotsTxtParser($robotsTxtContent); $rules = $parser->getRules('*'); $this->assertNotEmpty($rules, 'expected data'); $this->assertArrayHasKey('disallow', $rules); $this->assertNotEmpty($rules['disallow'], 'disallow expected'); $this->assertEquals($expectedDisallowValue, $rules['disallow'][0]); } /** * Generate test case data * @return array */ public function generateDataForTest() { return array( array( " User-agent: * #Disallow: /tech " ), array( " User-agent: * Disallow: #/tech " ), array( " User-agent: * Disal # low: /tech " ), array( " User-agent: * Disallow#: /tech # ds " ), ); } /** * Generate test case data * @return array */ public function generateDataFor2Test() { return array( array( "User-agent: * Disallow: /tech #comment", 'disallowValue' => '/tech', ), ); } }
Java
/* * The MIT License * * Copyright 2016 njacinto. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.nfpj.utils.arrays; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.function.Predicate; import org.nfpj.utils.predicates.TruePredicate; /** * * @author njacinto * @param <T> the type of object being returned by this iterator */ public class ArrayFilterIterator<T> implements Iterator<T> { protected static final int END_OF_ITERATION = -2; // private int nextIndex; // protected final T[] array; protected final Predicate<T> predicate; // <editor-fold defaultstate="expanded" desc="Constructors"> /** * Creates an instance of this class * * @param array the array from where this instance will extract the elements * @param predicate the filter to be applied to the elements */ public ArrayFilterIterator(T[] array, Predicate<T> predicate) { this(array, predicate, -1); } /** * * @param array * @param predicate * @param prevIndex */ protected ArrayFilterIterator(T[] array, Predicate<T> predicate, int prevIndex) { this.array = array!=null ? array : ArrayUtil.empty(); this.predicate = predicate!=null ? predicate : TruePredicate.getInstance(); this.nextIndex = getNextIndex(prevIndex); } // </editor-fold> // <editor-fold defaultstate="expanded" desc="Public methods"> /** * {@inheritDoc} */ @Override public boolean hasNext() { return nextIndex != END_OF_ITERATION; } /** * {@inheritDoc} */ @Override public T next() { if(nextIndex==END_OF_ITERATION){ throw new NoSuchElementException("The underline collection has no elements."); } int index = nextIndex; nextIndex = getNextIndex(nextIndex); return array[index]; } /** * {@inheritDoc} */ @Override public void remove() { throw new UnsupportedOperationException("The iterator doesn't allow changes."); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Protected methods"> /** * Searches for the next element that matches the filtering conditions and * returns it. * * @param currIndex * @return the next element that matches the filtering conditions or null * if no more elements are available */ protected int getNextIndex(int currIndex){ if(currIndex!=END_OF_ITERATION){ for(int i=currIndex+1; i<array.length; i++){ if(predicate.test(array[i])){ return i; } } } return END_OF_ITERATION; } // </editor-fold> }
Java
--- layout: post title: slacker로 slack bot 만들기 comments: true tags: - python - slack - 봇 - slacker --- &nbsp;&nbsp;&nbsp; 멘토님께서 라인의 `notification`을 이용해서 봇 만든것을 보고 따라 만들었다. 봇 만들고 싶은데 핑계가 없어서 고민하다가 동아리에서 `slack`을 쓰기 때문에 슬랙봇을 만들어보기로 했다. 스터디하는 사람들을 대상으로 커밋한지 얼마나 되었는지 알려주는 용도로 만들었다. 결과물은 아래와 같다. <img src="/images/commit-bell.jpeg" alt="클린 코드를 위한 테스트 주도 개발" style="width: 480px; margin-left: auto; margin-right: auto; "/> &nbsp;&nbsp;&nbsp; 먼저 봇을 등록해야한다. [Slack Apps](https://studytcp.slack.com/apps)의 우측 상단에 `Build`를 눌러서 등록을 한다. 아래와 같은 화면이 나온다. 다른 팀에게 공개하지 않을 것이라서 `Something just for my team`을 선택했다. ![slackbot 등록]({{ site.url }}/images/slackbot_0.png) &nbsp;&nbsp;&nbsp; 두 번째 `Bots`를 선택한다. ![slackbot 등록]({{ site.url }}/images/slackbot_1.png) &nbsp;&nbsp;&nbsp; 적절한 설정을 하고 `token`을 꼭 기억(복사)해 두자. &nbsp;&nbsp;&nbsp; pip로 필요한 것을 설치하자. [github3.py](https://github3py.readthedocs.io/en/master/), [slacker](https://pypi.python.org/pypi/slacker/), datetime, pytz를 사용했다. <pre>$ pip install slacker $ pip install github3.py $ pip install datetime $ pip install pytz</pre> &nbsp;&nbsp;&nbsp; 전체 코드는 아래와 같다. ```python from slacker import Slacker import github3 import datetime import pytz local_tz = pytz.timezone('Asia/Seoul') token = 'xoxb-발급받은-토큰' slack = Slacker(token) channels = ['#채널1', '#채널2'] def post_to_channel(message): slack.chat.post_message(channels[0], message, as_user=True) def get_repo_last_commit_delta_time(owner, repo): repo = github3.repository(owner, repo) return repo.pushed_at.astimezone(local_tz) def get_delta_time(last_commit): now = datetime.datetime.now(local_tz) delta = now - last_commit return delta.days def main(): members = ( # (git 계정 이름, repo 이름, 이름), # [...] ) reports = [] for owner, repo, name in members: last_commit = get_repo_last_commit_delta_time(owner, repo) delta_time = get_delta_time(last_commit) if(delta_time == 0): reports.append('*%s* 님은 오늘 커밋을 하셨어요!' % (name)) else: reports.append('*%s* 님은 *%s* 일이나 커밋을 안하셨어요!' % (name, delta_time)) post_to_channel('\n 안녕 친구들! 과제 점검하는 커밋벨이야 호호 \n' + '\n'.join(reports)) if __name__ == '__main__': main() ``` ## **해결하지 못한 것** * **X-RateLimit-Limit 올리기** &nbsp;&nbsp;&nbsp; 테스트 때문에 꽤 많이 돌리다 보니까 횟수제한에 걸렸다. 에러 메시지는 아래와 같다. <pre>github3.models.GitHubError: 403 API rate limit exceeded for 106.246.181.100. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)</pre> &nbsp;&nbsp;&nbsp; 찾아보니까 하나의 IP당 한 시간에 보낼 수 있는 횟수가 정해져 있다고 한다. 출력해 보면 아래와 같다. `X-RateLimit-Limit`은 기본이 60이고 최대 5000으로 올릴 수 있다는데 헤더 수정을 어떻게 해야할지 모르겠다. 사실 이거 해결한다고 시간이 꽤 지나버려서 해결(?)이 되었다. <pre>[...] Status: 403 Forbidden X-RateLimit-Limit: 60 X-RateLimit-Remaining: 0 X-RateLimit-Reset: 1475913003 [...]</pre> * **이 코드를 어디서 돌려야 하는가.** &nbsp;&nbsp;&nbsp; 하루에 2-3번? 정도 해당 채널에 알림을 보낼 것이다. 사실 동아리 서버 쓰면 된다고는 하는데.. 개인 서버를 쓰고는 싶고 그렇다고 AWS 쓰자니 별로 하는것도 없는데 달마다 치킨 값을 헌납해야해서 고민이다. ## **참고자료** * [https://corikachu.github.io/articles/python/python-slack-bot-slacker](https://corikachu.github.io/articles/python/python-slack-bot-slacker) * [https://www.fullstackpython.com/blog/build-first-slack-bot-python.html](https://www.fullstackpython.com/blog/build-first-slack-bot-python.html) * [https://godoftyping.wordpress.com/2015/04/19/python-%EB%82%A0%EC%A7%9C-%EC%8B%9C%EA%B0%84%EA%B4%80%EB%A0%A8-%EB%AA%A8%EB%93%88/](https://godoftyping.wordpress.com/2015/04/19/python-%EB%82%A0%EC%A7%9C-%EC%8B%9C%EA%B0%84%EA%B4%80%EB%A0%A8-%EB%AA%A8%EB%93%88/)
Java
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class IosHeart extends React.Component { render() { if(this.props.bare) { return <g> <path d="M359.385,80C319.966,80,277.171,97.599,256,132.8C234.83,97.599,192.034,80,152.615,80C83.647,80,32,123.238,32,195.779 c0,31.288,12.562,71.924,40.923,105.657c28.359,33.735,45.229,51.7,100.153,88C228,425.738,256,432,256,432s28-6.262,82.924-42.564 c54.923-36.3,71.794-54.265,100.153-88C467.438,267.703,480,227.067,480,195.779C480,123.238,428.353,80,359.385,80z"></path> </g>; } return <IconBase> <path d="M359.385,80C319.966,80,277.171,97.599,256,132.8C234.83,97.599,192.034,80,152.615,80C83.647,80,32,123.238,32,195.779 c0,31.288,12.562,71.924,40.923,105.657c28.359,33.735,45.229,51.7,100.153,88C228,425.738,256,432,256,432s28-6.262,82.924-42.564 c54.923-36.3,71.794-54.265,100.153-88C467.438,267.703,480,227.067,480,195.779C480,123.238,428.353,80,359.385,80z"></path> </IconBase>; } };IosHeart.defaultProps = {bare: false}
Java
<?php /* $Id$ osCommerce, Open Source E-Commerce Solutions http://www.oscommerce.com Copyright (c) 2010 osCommerce Released under the GNU General Public License */ require('includes/application_top.php'); require(DIR_WS_LANGUAGES . $language . '/' . FILENAME_SPECIALS); $breadcrumb->add(NAVBAR_TITLE, tep_href_link(FILENAME_SPECIALS)); require(DIR_WS_INCLUDES . 'template_top.php'); ?> <h1><?php echo HEADING_TITLE; ?></h1> <div class="contentContainer"> <div class="contentText"> <?php // BOF Enable & Disable Categories $specials_query_raw = "select p.products_id, pd.products_name, p.products_price, p.products_tax_class_id, p.products_image, s.specials_new_products_price from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_SPECIALS . " s, " . TABLE_CATEGORIES . " c, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c where c.categories_status='1' and p.products_id = p2c.products_id and p2c.categories_id = c.categories_id and p.products_status = '1' and p.products_id = s.products_id and pd.products_id = s.products_id and pd.language_id = '" . (int)$languages_id . "' and s.status = '1' order by s.specials_date_added DESC"; // EOF Enable & Disable Categories //$specials_query_raw = "select p.products_id, pd.products_name, p.products_price, p.products_tax_class_id, p.products_image, s.specials_new_products_price from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_SPECIALS . " s where p.products_status = '1' and s.products_id = p.products_id and p.products_id = pd.products_id and pd.language_id = '" . (int)$languages_id . "' and s.status = '1' order by s.specials_date_added DESC"; $specials_split = new splitPageResults($specials_query_raw, MAX_DISPLAY_SPECIAL_PRODUCTS); if (($specials_split->number_of_rows > 0) && ((PREV_NEXT_BAR_LOCATION == '1') || (PREV_NEXT_BAR_LOCATION == '3'))) { ?> <div> <span style="float: right;"><?php echo TEXT_RESULT_PAGE . ' ' . $specials_split->display_links(MAX_DISPLAY_PAGE_LINKS, tep_get_all_get_params(array('page', 'info', 'x', 'y'))); ?></span> <span><?php echo $specials_split->display_count(TEXT_DISPLAY_NUMBER_OF_SPECIALS); ?></span> </div> <br /> <?php } ?> <table border="0" width="100%" cellspacing="0" cellpadding="2"> <tr> <?php $row = 0; $specials_query = tep_db_query($specials_split->sql_query); while ($specials = tep_db_fetch_array($specials_query)) { $row++; echo '<td align="center" width="33%"><a href="' . tep_href_link(FILENAME_PRODUCT_INFO, 'products_id=' . $specials['products_id']) . '">' . tep_image(DIR_WS_IMAGES . $specials['products_image'], $specials['products_name'], SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT) . '</a><br /><a href="' . tep_href_link(FILENAME_PRODUCT_INFO, 'products_id=' . $specials['products_id']) . '">' . $specials['products_name'] . '</a><br /><del>' . $currencies->display_price($specials['products_price'], tep_get_tax_rate($specials['products_tax_class_id'])) . '</del><br /><span class="productSpecialPrice">' . $currencies->display_price($specials['specials_new_products_price'], tep_get_tax_rate($specials['products_tax_class_id'])) . '</span></td>' . "\n"; if ((($row / 3) == floor($row / 3))) { ?> </tr> <tr> <?php } } ?> </tr> </table> <?php if (($specials_split->number_of_rows > 0) && ((PREV_NEXT_BAR_LOCATION == '2') || (PREV_NEXT_BAR_LOCATION == '3'))) { ?> <br /> <div> <span style="float: right;"><?php echo TEXT_RESULT_PAGE . ' ' . $specials_split->display_links(MAX_DISPLAY_PAGE_LINKS, tep_get_all_get_params(array('page', 'info', 'x', 'y'))); ?></span> <span><?php echo $specials_split->display_count(TEXT_DISPLAY_NUMBER_OF_SPECIALS); ?></span> </div> <?php } ?> </div> </div> <?php require(DIR_WS_INCLUDES . 'template_bottom.php'); require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
Java
--- layout: home title: JARVARS comments: false ---
Java
{% extends "admin/base.html" %} {% load i18n %} {% block title %}{{ title }} | {% trans 'lab purchase management' %}{% endblock %} {% block branding %} <h1 id="site-name">{% trans 'LabHamster' %}</h1> {% endblock %} {% block nav-global %}{% endblock %}
Java
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockitousage.verification; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.atMost; import static org.mockito.Mockito.atMostOnce; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import java.util.List; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.exceptions.base.MockitoException; import org.mockito.exceptions.verification.MoreThanAllowedActualInvocations; import org.mockito.exceptions.verification.NoInteractionsWanted; import org.mockitoutil.TestBase; public class AtMostXVerificationTest extends TestBase { @Mock private List<String> mock; @Test public void shouldVerifyAtMostXTimes() throws Exception { mock.clear(); mock.clear(); verify(mock, atMost(2)).clear(); verify(mock, atMost(3)).clear(); try { verify(mock, atMostOnce()).clear(); fail(); } catch (MoreThanAllowedActualInvocations e) { } } @Test public void shouldWorkWithArgumentMatchers() throws Exception { mock.add("one"); verify(mock, atMost(5)).add(anyString()); try { verify(mock, atMost(0)).add(anyString()); fail(); } catch (MoreThanAllowedActualInvocations e) { } } @Test public void shouldNotAllowNegativeNumber() throws Exception { try { verify(mock, atMost(-1)).clear(); fail(); } catch (MockitoException e) { assertEquals("Negative value is not allowed here", e.getMessage()); } } @Test public void shouldPrintDecentMessage() throws Exception { mock.clear(); mock.clear(); try { verify(mock, atMostOnce()).clear(); fail(); } catch (MoreThanAllowedActualInvocations e) { assertEquals("\nWanted at most 1 time but was 2", e.getMessage()); } } @Test public void shouldNotAllowInOrderMode() throws Exception { mock.clear(); InOrder inOrder = inOrder(mock); try { inOrder.verify(mock, atMostOnce()).clear(); fail(); } catch (MockitoException e) { assertEquals("AtMost is not implemented to work with InOrder", e.getMessage()); } } @Test public void shouldMarkInteractionsAsVerified() throws Exception { mock.clear(); mock.clear(); verify(mock, atMost(3)).clear(); verifyNoMoreInteractions(mock); } @Test public void shouldDetectUnverifiedInMarkInteractionsAsVerified() throws Exception { mock.clear(); mock.clear(); undesiredInteraction(); verify(mock, atMost(3)).clear(); try { verifyNoMoreInteractions(mock); fail(); } catch (NoInteractionsWanted e) { assertThat(e).hasMessageContaining("undesiredInteraction("); } } private void undesiredInteraction() { mock.add(""); } }
Java
<?php declare(strict_types=1); namespace Atk4\Ui\Demos; use Atk4\Ui\Crud; use Atk4\Ui\UserAction\ExecutorFactory; // Test for hasOne Lookup as dropdown control. /** @var \Atk4\Ui\App $app */ require_once __DIR__ . '/../init-app.php'; $model = new Product($app->db); $model->addCondition($model->fieldName()->name, '=', 'Mustard'); // use default. $app->getExecutorFactory()->useTriggerDefault(ExecutorFactory::TABLE_BUTTON); $edit = $model->getUserAction('edit'); $edit->callback = function (Product $model) { return $model->product_category_id->getTitle() . ' - ' . $model->product_sub_category_id->getTitle(); }; $crud = Crud::addTo($app); $crud->setModel($model, [$model->fieldName()->name]);
Java
/* HardwareSerial.h - Hardware serial library for Wiring Copyright (c) 2006 Nicholas Zambetti. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef HardwareSerial_h #define HardwareSerial_h #include <inttypes.h> #include "Print.h" struct ring_buffer; #if defined(__AVR_ATmega103__) class HardwareSerial : public Print { private: ring_buffer *_rx_buffer; volatile uint8_t *_ubrr; volatile uint8_t *_ucr; volatile uint8_t *_usr; volatile uint8_t *_udr; uint8_t _rxen; uint8_t _txen; uint8_t _rxcie; uint8_t _udre; public: HardwareSerial(ring_buffer *rx_buffer, volatile uint8_t *ubrr, volatile uint8_t *ucr, volatile uint8_t *usr, volatile uint8_t *udr, uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udre); void begin(long); void end(); uint8_t available(void); int read(void); void flush(void); virtual void write(uint8_t); using Print::write; // pull in write(str) and write(buf, size) from Print }; #else class HardwareSerial : public Print { private: ring_buffer *_rx_buffer; volatile uint8_t *_ubrrh; volatile uint8_t *_ubrrl; volatile uint8_t *_ucsra; volatile uint8_t *_ucsrb; volatile uint8_t *_udr; uint8_t _rxen; uint8_t _txen; uint8_t _rxcie; uint8_t _udre; uint8_t _u2x; public: HardwareSerial(ring_buffer *rx_buffer, volatile uint8_t *ubrrh, volatile uint8_t *ubrrl, volatile uint8_t *ucsra, volatile uint8_t *ucsrb, volatile uint8_t *udr, uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udre, uint8_t u2x); void begin(long); void end(); uint8_t available(void); int read(void); void flush(void); virtual void write(uint8_t); using Print::write; // pull in write(str) and write(buf, size) from Print }; #endif extern HardwareSerial Serial; #if defined(__AVR_ATmega1280__) extern HardwareSerial Serial1; extern HardwareSerial Serial2; extern HardwareSerial Serial3; #endif #endif
Java
import React, {PropTypes} from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as courseActions from '../../actions/courseActions'; import CourseForm from './CourseForm'; import {authorsFormattedForDropdown} from '../../selectors/selectors'; import toastr from 'toastr'; export class ManageCoursePage extends React.Component { constructor(props, context) { super(props, context); this.state = { course: Object.assign({}, props.course), errors: {}, saving: false }; this.updateCourseState = this.updateCourseState.bind(this); this.saveCourse = this.saveCourse.bind(this); } componentWillReceiveProps(nextProps) { if (this.props.course.id != nextProps.course.id) { // Necessary to populate form when existing course is loaded directly. this.setState({course: Object.assign({}, nextProps.course)}); } } updateCourseState(event) { // handler for each form field const field = event.target.name; let course = this.state.course; course[field] = event.target.value; return this.setState({course: course}); } courseFormValid() { let formIsValid = true; let errors = {}; if (this.state.course.title.length < 5) { errors.title = 'Title must be at least 5 characters.'; formIsValid = false; } this.setState({errors: errors}); return formIsValid; } saveCourse(event) { event.preventDefault(); if (!this.courseFormValid()) { return; } this.setState({saving: true}); this.props.actions.saveCourse(this.state.course) .then(() => this.redirect()) .catch(error => { toastr.error(error); this.setState({saving: false}); }); } redirect() { // redirect to courses route this.setState({saving: false}); toastr.success('Course saved!'); this.context.router.push('/courses'); } render() { return ( <CourseForm allAuthors={this.props.authors} onChange={this.updateCourseState} onSave={this.saveCourse} errors={this.state.errors} course={this.state.course} saving={this.state.saving}/> ); } } ManageCoursePage.propTypes = { course: PropTypes.object.isRequired, authors: PropTypes.array.isRequired, actions: PropTypes.object.isRequired }; //Pull in the React Router context so router is available on this.context.router. ManageCoursePage.contextTypes = { router: PropTypes.object }; function getCourseById(courses, id) { const course = courses.filter(course => course.id == id); if (course.length) return course[0]; //since filter returns an array, have to grab the first. return null; } function mapStateToProps(state, ownProps) { let course = { id: "", title: "", watchHref: "", authorId: "", length: "23", category: "" }; const courseId = ownProps.params.id; // from the path `/course/:id` if (courseId && state.courses.length > 0) { course = getCourseById(state.courses, courseId); } return { course: course, authors: authorsFormattedForDropdown(state.authors) } } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(courseActions, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(ManageCoursePage);
Java
.sessionForm{ padding: 10px; } .carapaceForm{ padding: 10px; border: 3px solid #000000; min-width: 960px; margin-bottom: 10px; } label{ margin: 5px; } input{ margin: 5px; } button{ margin: 5px; } .section{ border: 1px solid #000000; margin-bottom: 10px; } .carapaceSection{ padding: 10px; background-color #eeeeee; } .itemForm{ padding: 10px; border: 3px solid #000000; } .selectedItem{ padding: 10px; border: 3px solid #000000; } .itemSection{ padding: 10px; background-color #eeeeee; } .prospit{ background-color:black; } .derse{ background-color: white; }
Java
AmazonTemplateDescriptionCategorySpecificGridRowRenderer = Class.create(AmazonTemplateDescriptionCategorySpecificRenderer, { // --------------------------------------- attributeHandler: null, // --------------------------------------- process: function() { if (this.specificHandler.isSpecificRendered(this.indexedXPath) && !this.isValueForceSet()) { return ''; } if (!this.load()) { return ''; } this.renderParentSpecific(); if (this.specificHandler.isSpecificRendered(this.indexedXPath) && !this.isValueForceSet()) { return ''; } if (this.specificHandler.isSpecificRendered(this.indexedXPath)) { if (this.isValueForceSet()) { this.forceSelectAndDisable(this.getForceSetValue()); this.hideButton($(this.indexedXPath + '_remove_button')); var myEvent = new CustomEvent('undeleteble-specific-appear'); $(this.getParentIndexedXpath()).dispatchEvent(myEvent); } return ''; } this.renderSelf(); if (this.isValueForceSet()) { this.forceSelectAndDisable(this.getForceSetValue()); } this.observeToolTips(this.indexedXPath); this.checkSelection(); this.renderSpecificAttributes(); }, // --------------------------------------- load: function($super) { this.attributeHandler = AttributeHandlerObj; return $super(); }, //######################################## renderParentSpecific: function() { if (this.specific.parent_specific_id == null) { return ''; } if (!this.dictionaryHelper.isSpecificTypeContainer(this.parentSpecific)) { return ''; } var parentBlockRenderer = new AmazonTemplateDescriptionCategorySpecificBlockRenderer(); parentBlockRenderer.setSpecificsHandler(this.specificHandler); parentBlockRenderer.setIndexedXpath(this.getParentIndexedXpath()); parentBlockRenderer.process(); }, renderSelf: function() { this.renderLabel(); this.renderChooseMode(); this.renderValueInputs(); // affects the appearance of the actions buttons this.specificHandler.markSpecificAsRendered(this.indexedXPath); this.renderButtons(); // --------------------------------------- $(this.indexedXPath).observe('my-duplicate-is-rendered', this.onMyDuplicateRendered.bind(this)); // --------------------------------------- // like grid visibility or view of 'Add Specific' container this.throwEventsToParents(); }, renderSpecificAttributes: function() { var self = this; if (!this.specific.params.hasOwnProperty('attributes')) { return ''; } this.specific.params.attributes.each(function(attribute, index) { var renderer = new AmazonTemplateDescriptionCategorySpecificGridRowAttributeRenderer(); renderer.setSpecificsHandler(self.specificHandler); renderer.setIndexedXpath(self.indexedXPath); renderer.attribute = attribute; renderer.attributeIndex = index; renderer.process(); }); }, //######################################## renderLabel: function() { var td = new Element('td'); var title = this.specific.title; if (this.dictionaryHelper.isSpecificRequired(this.specific) || this.isValueForceSet()) { title += ' <span class="required">*</span>'; } else if (this.dictionaryHelper.isSpecificDesired(this.specific)) { title += ' <span style="color: grey; font-style: italic;">(' + M2ePro.translator.translate('Desired') + ')</span>'; } td.appendChild((new Element('span').insert(title))); var note = this.getDefinitionNote(this.specific.data_definition); if (note) { var toolTip = this.getToolTipBlock(this.indexedXPath + '_definition_note', note); toolTip.show(); td.appendChild(toolTip); } var notice = this.getSpecificOverriddenNotice(); if (notice) td.appendChild(notice); notice = this.getSpecificParentageNotice(); if (notice) td.appendChild(notice); this.getRowContainer().appendChild(td); }, // --------------------------------------- renderChooseMode: function() { var select = new Element('select', { 'id' : this.indexedXPath +'_mode', 'indexedxpath': this.indexedXPath, 'class' : 'M2ePro-required-when-visible', 'style' : 'width: 93.2%;' }); select.appendChild(new Element('option', {'style': 'display: none'})); if (this.specific.recommended_values.length > 0) { select.appendChild(new Element('option', {'value': this.MODE_RECOMMENDED_VALUE})) .insert(M2ePro.translator.translate('Recommended Values')); } select.appendChild(new Element('option', {'value': this.MODE_CUSTOM_VALUE})) .insert(M2ePro.translator.translate('Custom Value')); select.appendChild(new Element('option', {'value': this.MODE_CUSTOM_ATTRIBUTE})) .insert(M2ePro.translator.translate('Custom Attribute')); select.observe('change', this.onChangeChooseMode.bind(this)); this.getRowContainer().appendChild(new Element('td')).appendChild(select); }, onChangeChooseMode: function(event) { var customValue = $(this.indexedXPath + '_' + this.MODE_CUSTOM_VALUE), customValueNote = $(this.indexedXPath + '_custom_value_note'), customValueNoteError = $('advice-M2ePro-specifics-validation-' + customValue.id); var customAttribute = $(this.indexedXPath + '_' + this.MODE_CUSTOM_ATTRIBUTE), customAttributeNote = $(this.indexedXPath + '_custom_attribute_note'), customAttributeError = $('advice-M2ePro-required-when-visible-' + customAttribute.id); var recommendedValue = $(this.indexedXPath + '_' + this.MODE_RECOMMENDED_VALUE); customValue && customValue.hide(); customValueNote && customValueNote.hide(); customValueNoteError && customValueNoteError.hide(); customAttribute && customAttribute.hide(); customAttributeNote && customAttributeNote.hide(); customAttributeError && customAttributeError.hide(); recommendedValue && recommendedValue.hide(); if (event.target.value == this.MODE_CUSTOM_VALUE) { customValue && customValue.show(); customValueNote && customValueNote.show(); customValueNoteError && customValueNoteError.show(); } if (event.target.value == this.MODE_CUSTOM_ATTRIBUTE) { customAttribute && customAttribute.show(); customAttributeNote && customAttributeNote.show(); customAttributeError && customAttributeError.show(); } if (event.target.value == this.MODE_RECOMMENDED_VALUE) { recommendedValue && recommendedValue.show(); } }, // --------------------------------------- renderValueInputs: function() { var td = this.getRowContainer().appendChild(new Element('td')); // --------------------------------------- if (this.dictionaryHelper.isSpecificTypeText(this.specific)) { var note = this.getCustomValueTypeNote(); if (note) td.appendChild(this.getToolTipBlock(this.indexedXPath + '_custom_value_note', note)); td.appendChild(this.getTextTypeInput()); } if (this.dictionaryHelper.isSpecificTypeSelect(this.specific)) { td.appendChild(this.getSelectTypeInput()); } // --------------------------------------- // --------------------------------------- note = this.getCustomAttributeTypeNote(); if (note) td.appendChild(this.getToolTipBlock(this.indexedXPath + '_custom_attribute_note', note)); td.appendChild(this.getCustomAttributeSelect()); // --------------------------------------- td.appendChild(this.getRecommendedValuesSelect()); }, // --------------------------------------- getTextTypeInput: function() { if (this.dictionaryHelper.isSpecificTypeTextArea(this.specific)) { var input = new Element('textarea', { 'id' : this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE, 'indexedxpath' : this.indexedXPath, 'specific_id' : this.specific.specific_id, 'specific_type' : this.specific.params.type, 'mode' : this.MODE_CUSTOM_VALUE, 'class' : 'M2ePro-required-when-visible M2ePro-specifics-validation', 'style' : 'width: 91.4%; display: none;' }); } else { var input = new Element('input', { 'id' : this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE, 'indexedxpath' : this.indexedXPath, 'specific_id' : this.specific.specific_id, 'mode' : this.MODE_CUSTOM_VALUE, 'specific_type' : this.specific.params.type, 'type' : 'text', 'class' : 'input-text M2ePro-required-when-visible M2ePro-specifics-validation', 'style' : 'display: none; width: 91.4%;' }); this.specific.params.type == 'date_time' && Calendar.setup({ 'inputField': input, 'ifFormat': "%Y-%m-%d %H:%M:%S", 'showsTime': true, 'button': input, 'align': 'Bl', 'singleClick': true }); this.specific.params.type == 'date' && Calendar.setup({ 'inputField': input, 'ifFormat': "%Y-%m-%d", 'showsTime': true, 'button': input, 'align': 'Bl', 'singleClick': true }); } input.observe('change', this.onChangeValue.bind(this)); return input; }, getSelectTypeInput: function() { var self = this; var select = new Element('select', { 'id' : this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE, 'indexedxpath': this.indexedXPath, 'specific_id' : this.specific.specific_id, 'mode' : this.MODE_CUSTOM_VALUE, 'class' : 'M2ePro-required-when-visible', 'style' : 'display: none; width: 93.2%;' }); select.appendChild(new Element('option', {'style': 'display: none;'})); var specificOptions = this.specific.values; specificOptions.each(function(option) { var label = option == 'true' ? 'Yes' : (option == 'false' ? 'No' : option), tempOption = new Element('option', {'value': option}); select.appendChild(tempOption).insert(label); }); select.observe('change', this.onChangeValue.bind(this)); return select; }, getCustomAttributeSelect: function() { var select = new Element('select', { 'id' : this.indexedXPath +'_'+ this.MODE_CUSTOM_ATTRIBUTE, 'indexedxpath' : this.indexedXPath, 'specific_id' : this.specific.specific_id, 'specific_type' : this.specific.params.type, 'mode' : this.MODE_CUSTOM_ATTRIBUTE, 'class' : 'attributes M2ePro-required-when-visible', 'style' : 'display: none; width: 93.2%;', 'apply_to_all_attribute_sets' : '0' }); select.appendChild(new Element('option', {'style': 'display: none', 'value': ''})); this.attributeHandler.availableAttributes.each(function(el) { select.appendChild(new Element('option', {'value': el.code})).insert(el.label); }); select.value = ''; select.observe('change', this.onChangeValue.bind(this)); var handlerObj = new AttributeCreator(select.id); handlerObj.setSelectObj(select); handlerObj.injectAddOption(); return select; }, getRecommendedValuesSelect: function() { var select = new Element('select', { 'id' : this.indexedXPath +'_'+ this.MODE_RECOMMENDED_VALUE, 'indexedxpath': this.indexedXPath, 'specific_id' : this.specific.specific_id, 'mode' : this.MODE_RECOMMENDED_VALUE, 'class' : 'M2ePro-required-when-visible', 'style' : 'display: none; width: 93.2%;' }); select.appendChild(new Element('option', {'style': 'display: none', 'value': ''})); this.specific.recommended_values.each(function(value) { select.appendChild(new Element('option', {'value': value})).insert(value); }); select.value = ''; select.observe('change', this.onChangeValue.bind(this)); return select; }, onChangeValue: function(event) { var selectedObj = {}; selectedObj['mode'] = event.target.getAttribute('mode'); selectedObj['type'] = event.target.getAttribute('specific_type'); selectedObj['is_required'] = (this.dictionaryHelper.isSpecificRequired(this.specific) || this.isValueForceSet()) ? 1 : 0; selectedObj[selectedObj.mode] = event.target.value; this.specificHandler.markSpecificAsSelected(this.indexedXPath, selectedObj); }, // --------------------------------------- renderButtons: function() { var td = this.getRowContainer().appendChild(new Element('td')); var cloneButton = this.getCloneButton(); if(cloneButton !== null) td.appendChild(cloneButton); var removeButton = this.getRemoveButton(); if(removeButton !== null) td.appendChild(removeButton); }, // --------------------------------------- throwEventsToParents: function() { var myEvent, parentXpath; // --------------------------------------- myEvent = new CustomEvent('child-specific-rendered'); parentXpath = this.getParentIndexedXpath(); $(parentXpath + '_grid').dispatchEvent(myEvent); $(parentXpath + '_add_row').dispatchEvent(myEvent); // --------------------------------------- // my duplicate is already rendered this.touchMyNeighbors(); // --------------------------------------- // --------------------------------------- if (this.isValueForceSet()) { this.hideButton($(this.indexedXPath + '_remove_button')); myEvent = new CustomEvent('undeleteble-specific-appear'); $(this.getParentIndexedXpath()).dispatchEvent(myEvent); } // --------------------------------------- }, //######################################## checkSelection: function() { if (this.specific.values.length == 1) { this.forceSelectAndDisable(this.specific.values[0]); return ''; } if (!this.specificHandler.isMarkedAsSelected(this.indexedXPath) && !this.specificHandler.isInFormData(this.indexedXPath)) { return ''; } var selectionInfo = this.specificHandler.getSelectionInfo(this.indexedXPath); var id = this.indexedXPath + '_mode'; $(id).value = selectionInfo.mode; this.simulateAction($(id), 'change'); if (selectionInfo.mode == this.MODE_CUSTOM_VALUE) { id = this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE; $(id).value = selectionInfo['custom_value']; this.simulateAction($(id), 'change'); } if (selectionInfo.mode == this.MODE_CUSTOM_ATTRIBUTE) { id = this.indexedXPath +'_'+ this.MODE_CUSTOM_ATTRIBUTE; $(id).value = selectionInfo['custom_attribute']; this.simulateAction($(id), 'change'); } if (selectionInfo.mode == this.MODE_RECOMMENDED_VALUE) { id = this.indexedXPath +'_'+ this.MODE_RECOMMENDED_VALUE; $(id).value = selectionInfo['recommended_value']; this.simulateAction($(id), 'change'); } }, forceSelectAndDisable: function(value) { if (!value) { return; } var modeSelect = $(this.indexedXPath + '_mode'); modeSelect.value = this.MODE_CUSTOM_VALUE; this.simulateAction(modeSelect, 'change'); modeSelect.setAttribute('disabled','disabled'); var valueObj = $(this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE); valueObj.value = value; this.simulateAction(valueObj, 'change'); valueObj.setAttribute('disabled', 'disabled'); }, //######################################## getToolTipBlock: function(id, messageHtml) { var container = new Element('div', { 'id' : id, 'style': 'float: right; display: none;' }); container.appendChild(new Element('img', { 'src' : M2ePro.url.get('m2epro_skin_url') + '/images/tool-tip-icon.png', 'class' : 'tool-tip-image' })); var htmlCont = container.appendChild(new Element('span', { 'class' : 'tool-tip-message tip-left', 'style' : 'display: none; max-width: 500px;' })); htmlCont.appendChild(new Element('img', { 'src': M2ePro.url.get('m2epro_skin_url') + '/images/help.png' })); htmlCont.appendChild(new Element('span')).insert(messageHtml); return container; }, // --------------------------------------- getCustomValueTypeNote: function() { if (this.specific.data_definition.definition) { return null; } if (this.specific.params.type == 'int') return this.getIntTypeNote(this.specific.params); if (this.specific.params.type == 'float') return this.getFloatTypeNote(this.specific.params); if (this.specific.params.type == 'string') return this.getStringTypeNote(this.specific.params); if (this.specific.params.type == 'date_time') return this.getDatTimeTypeNote(this.specific.params); return this.getAnyTypeNote(this.specific.params); }, getIntTypeNote: function(params) { var notes = []; var handler = { 'type': function() { notes[0] = M2ePro.translator.translate('Type: Numeric.') + ' '; }, 'min_value': function(restriction) { notes[1] = M2ePro.translator.translate('Min:') + ' ' + restriction + '. '; }, 'max_value': function(restriction) { notes[2] = M2ePro.translator.translate('Max:') + ' ' + restriction + '. '; }, 'total_digits': function(restriction) { notes[3] = M2ePro.translator.translate('Total digits (not more):') + ' ' + restriction + '. '; } }; for (var paramName in params) { params.hasOwnProperty(paramName) && handler[paramName] && handler[paramName](params[paramName]); } return notes.join(''); }, getFloatTypeNote: function(params) { var notes = []; var handler = { 'type': function() { notes[0] = M2ePro.translator.translate('Type: Numeric floating point.') + ' '; }, 'min_value': function(restriction) { notes[1] = M2ePro.translator.translate('Min:') + ' ' + restriction + '. '; }, 'max_value': function(restriction) { notes[2] = M2ePro.translator.translate('Max:') + ' ' + restriction + '. '; }, 'decimal_places': function(restriction) { notes[3] = M2ePro.translator.translate('Decimal places (not more):') + ' ' + restriction.value + '. '; }, 'total_digits': function(restriction) { notes[4] = M2ePro.translator.translate('Total digits (not more):') + ' ' + restriction + '. '; } }; for (var paramName in params) { params.hasOwnProperty(paramName) && handler[paramName] && handler[paramName](params[paramName]); } return notes.join(''); }, getStringTypeNote: function(params) { var notes = []; var handler = { 'type': function() { notes[0] = M2ePro.translator.translate('Type: String.') + ' '; }, 'min_length': function(restriction) { notes[1] = restriction != 1 ? M2ePro.translator.translate('Min length:') + ' ' + restriction : ''; }, 'max_length': function(restriction) { notes[2] = M2ePro.translator.translate('Max length:') + ' ' + restriction; }, 'pattern': function(restriction) { if (restriction == '[a-zA-Z][a-zA-Z]|unknown') { notes[3] = M2ePro.translator.translate('Two uppercase letters or "unknown".'); } } }; for (var paramName in params) { params.hasOwnProperty(paramName) && handler[paramName] && handler[paramName](params[paramName]); } return notes.join(''); }, getDatTimeTypeNote: function(params) { var notes = []; var handler = { 'type': function(restriction) { notes.push(M2ePro.translator.translate('Type: Date time. Format: YYYY-MM-DD hh:mm:ss')); } }; for (var paramName in params) { params.hasOwnProperty(paramName) && handler[paramName] && handler[paramName](params[paramName]); } return notes.join(''); }, getAnyTypeNote: function(params) { return M2ePro.translator.translate('Can take any value.'); }, // --------------------------------------- getCustomAttributeTypeNote: function() { if (this.specific.values.length <= 0 && this.specific.recommended_values.length <= 0) { return null; } var span = new Element('span'); var title = this.specific.values.length > 0 ? M2ePro.translator.translate('Allowed Values') : M2ePro.translator.translate('Recommended Values'); span.appendChild(new Element('span')).insert('<b>' + title + ': </b>'); var ul = span.appendChild(new Element('ul')); var noteValues = this.specific.values.length > 0 ? this.specific.values : this.specific.recommended_values; noteValues.each(function(value) { ul.appendChild(new Element('li')).insert(value); }); return span.outerHTML; }, // --------------------------------------- getDefinitionNote: function(definitionPart) { if (!definitionPart.definition) { return; } var div = new Element('div'); div.appendChild(new Element('div', {style: 'padding: 2px 0; margin-top: 5px;'})) .insert('<b>' + M2ePro.translator.translate('Definition:') + '</b>'); div.appendChild(new Element('div')) .insert(definitionPart.definition); if (definitionPart.tips && definitionPart.tips.match(/[a-z0-9]/i)) { div.appendChild(new Element('div', {style: 'padding: 2px 0; margin-top: 5px;'})) .insert('<b>' + M2ePro.translator.translate('Tips:') + '</b>'); div.appendChild(new Element('div')) .insert(definitionPart.tips); } if (definitionPart.example && definitionPart.example.match(/[a-z0-9]/i)) { div.appendChild(new Element('div', {style: 'padding: 2px 0; margin-top: 5px;'})) .insert('<b>' + M2ePro.translator.translate('Examples:') + '</b>'); div.appendChild(new Element('div')) .insert(definitionPart.example); } return div.outerHTML; }, // --------------------------------------- getSpecificOverriddenNotice: function() { if (!this.specificHandler.canSpecificBeOverwrittenByVariationTheme(this.specific)) { return null; } var variationThemesList = this.specificHandler.themeAttributes[this.specific.xml_tag]; var message = '<b>' + M2ePro.translator.translate('Value of this Specific can be automatically overwritten by M2E Pro.') + '</b>'; message += '<br/><br/>' + variationThemesList.join(', '); return this.constructNotice(message); }, getSpecificParentageNotice: function() { if (this.specific.xml_tag != 'Parentage') { return null; } return this.constructNotice(M2ePro.translator.translate('Amazon Parentage Specific will be overridden notice.')); }, constructNotice: function(message) { var container = new Element('div', { 'style': 'float: right; margin-right: 3px; margin-top: 1px;' }); container.appendChild(new Element('img', { 'src' : M2ePro.url.get('m2epro_skin_url') + '/images/warning.png', 'class' : 'tool-tip-image' })); var htmlCont = container.appendChild(new Element('span', { 'class' : 'tool-tip-message tip-left', 'style' : 'display: none; max-width: 500px; border-color: #ffd967; background-color: #fffbf0;' })); htmlCont.appendChild(new Element('img', { 'src' : M2ePro.url.get('m2epro_skin_url') + '/images/i_notice.gif', 'style' : 'margin-top: -21px;' })); htmlCont.appendChild(new Element('span')).insert(message); return container; }, //######################################## observeToolTips: function(indexedXpath) { $$('tr[id="' + indexedXpath + '"] .tool-tip-image').each(function(element) { element.observe('mouseover', MagentoFieldTipObj.showToolTip); element.observe('mouseout', MagentoFieldTipObj.onToolTipIconMouseLeave); }); $$('tr[id="' + indexedXpath + '"] .tool-tip-message').each(function(element) { element.observe('mouseout', MagentoFieldTipObj.onToolTipMouseLeave); element.observe('mouseover', MagentoFieldTipObj.onToolTipMouseEnter); }); }, //######################################## removeAction: function($super, event) { // for attributes removing var myEvent = new CustomEvent('parent-specific-row-is-removed'); $(this.indexedXPath).dispatchEvent(myEvent); // --------------------------------------- var deleteResult = $super(event); this.throwEventsToParents(); return deleteResult; }, cloneAction: function($super, event) { var newIndexedXpath = $super(event); this.observeToolTips(newIndexedXpath); var myEvent = new CustomEvent('parent-specific-row-is-cloned', { 'new_indexed_xpath': newIndexedXpath }); $(this.indexedXPath).dispatchEvent(myEvent); return newIndexedXpath; }, // --------------------------------------- getRowContainer: function() { if ($(this.indexedXPath)) { return $(this.indexedXPath); } var grid = $$('table[id="'+ this.getParentIndexedXpath() +'_grid"] table.border tbody').first(); return grid.appendChild(new Element('tr', {id: this.indexedXPath})); } // --------------------------------------- });
Java
Rails.application.config.middleware.use OmniAuth::Builder do provider :provider, ENV["KEY"], ENV["SECRET"] end
Java
package controller.server; import controller.LibraryService; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import java.rmi.RemoteException; public class RMIServer { public static void main(String[] args) throws RemoteException, NamingException { LibraryService service = new DBController(); Context namingContext = new InitialContext(); namingContext.rebind("rmi:books", service); System.out.println("RMI-server is working..."); } }
Java
define([ 'angular' ], function (ng) { 'use strict'; return ng.module('backgroundModule', []); });
Java
const pkg = state => state.pkg const app = state => state.app const device = state => state.app.device const sidebar = state => state.app.sidebar const effect = state => state.app.effect const menuitems = state => state.menu.items const componententry = state => { return state.menu.item.filter(c => c.meta && c.meta.label === 'Components')[0] } export { pkg, app, device, sidebar, effect, menuitems, componententry }
Java
title: HOWTO: Install Ubuntu on Your Eee PC author: Rami Taibah permalink: howto-install-ubuntu-on-your-eee-pc tags: eee-pc, ubuntu, howto I have [posted]({filename}/blog/2008-02-06-eee-pcfinally.markdown) earlier that the "easy mode" of the Eee PC is like living on the bottom bunker in a basement cell of the Alcatraz. Liberating it to the default Xandros "advanced mode" is just like going out to yard with sweaty inmates, which isn't saying much. I initially installed eeexubuntu on that little critter, but soon was disenchanted. XFCE is just not for me. Solution? Install everybody's favorite! Ubuntu! ## USB disk or CD drive? Installing a different distro on your Eee PC is done either by using a USB thumb drive or an external CD drive. I expect that the Eee PC is the first Linux experience to a lot of Eee PC users, so I would recommend getting an external CD drive, it's much less of a hassle. ## Downloading, burning, and preperation First of all you will need to get Ubuntu. At the time of writing this, Ubuntu 7.10 (Gutsy) is the latest so get it either through direct [download](http://www.ubuntu.com/getubuntu/download) or [torrent](http://torrent.ubuntu.com:6969/file?info\_hash=%ED%8A%B7%FB%3AL%D3Nd%8EH%A4%0F%8F%DD%97%A4%F5%40%D2). Then you will need to burn it on a CD using your favorite image burner. (there are many guides for that, google it) You will also probably need to edit the boot sequence in your bios. So restart your Eee PC and press F2 to enter the bios menu and change the primary boot to "USB Optical Drive". Pop in the Ubuntu CD in your external drive and restart. Then press enter when you get the list of options (first option). A couple of minutes later you will be on your default Ubuntu desktop. Before clicking the "install" icon, you will need to disable the desktop effects. Since the installer doesn't fit into the small Eee PC screen, you will need to use the ALT+Right click option to move the installer window. So System --> Prefrences --> Appearence and then go to the last tab "Visual Effects" and then select none. ## Installation Now you are ready for installing, so click on the "Install" icon located on your desktop (pictures are eclipsed due to screen size): ![Eee PC Ubuntu Install]({filename}/images/install-ubuntu-on-eee-pc-1.png) Select your language. ![Eee PC Ubuntu Install]({filename}/images/install-ubuntu-on-eee-pc-2.png) Select your keyboard layout. ![Eee PC Ubuntu Install]({filename}/images/install-ubuntu-on-eee-pc-3.png) Select manual partitioning. ![Eee PC Ubuntu Install]({filename}/images/install-ubuntu-on-eee-pc-4.png) This is the tricky part, basically you will need to set a root partition for the system to be installed in. So we are going to partition /dev/sda1 and make it our root. Click on /dev/sda1 and then delete whatever partitions under it. Then click on new and in filesystem choose ext2 (we are not going to use ext3 because we want to limit writes due to the solid state disk nature of the Eee PC). Also set mount point to "/" (without the quotes). If you have an SDHC card click on it and edit the mount point to "/media/\*whatever\*". If you have nothing interesting in that card you might want to just delete whatever partitions and make a new partition, and choosing the filesystem as "fat32″. Since you never know when you might want to use it on Windows machine ;). ![Eee PC Ubuntu Install]({filename}/images/install-ubuntu-on-eee-pc-5.png) Enter your details. Name, user name, password, and machine name. Click next. You will be prompted with a warning that all your data will be wiped out, click OK. Now sit back and relax, your system will be ready in 30 minutes or so. Thats it! Now just click restart system when prompted, you will then asked to eject CD. Now your golden :) A lot of functionality will be missing with this out of the box Ubuntu installation. For example your wireless won't function. Visit my [Perfect Eee PC Ubuntu Installation Guide]({filename}/blog/2008-02-21-howto-your-perfect-ubuntu-on-your-perfect-eee-pc.markdown) for a complete guide on how to get things up and running.
Java
using System; using System.Collections.Generic; using System.Linq; using BlackBox.Service; using EbInstanceModel; using IFC2X3; namespace BlackBox.Predefined { public partial class BbProduct : BbBase { [EarlyBindingInstance] public virtual IfcRelAggregates IfcRelAggregates { get; protected set; } public BbLocalPlacement3D ObjectBbLocalPlacement { get; protected set; } public virtual IfcObject IfcObject { get; protected set; } public string Name { get { return IfcObject.Name; } protected set { IfcObject.Name = value; } } public string Description { get { return IfcObject.Description; } protected set { IfcObject.Description = value; } } public string ObjectType { get { return IfcObject.ObjectType; } protected set { IfcObject.ObjectType = value; } } [EarlyBindingInstanceCollection] public BbProduct HostObject { get; protected set; } protected BbProduct() : this(Guid.NewGuid()) { } protected BbProduct(Guid guid) : base(guid) { } public void AddToHostObject(BbProduct hostObject) { HostObject = hostObject; var a = EarlyBindingInstanceModel.GetReferencedEntities(hostObject.IfcObject.EIN).Values; var b = (from x in a.OfType<IfcRelAggregates>() where x.RelatingObject.EIN == hostObject.IfcObject.EIN select x).ToList(); switch (b.Count) { case 0: IfcRelAggregates = new IfcRelAggregates { GlobalId = IfcGloballyUniqueId.NewGuid(), OwnerHistory = hostObject.IfcObject.OwnerHistory, RelatingObject = hostObject.IfcObject, RelatedObjects = new List<IfcObjectDefinition>() { }, }; break; case 1: IfcRelAggregates = b[0]; break; default: throw new NotImplementedException(); } var aa = GetType().GetProperty("IfcObject").GetValue(this, null) as IfcObject; IfcRelAggregates.RelatedObjects.Add(aa); } } }
Java
################################################## """ symbols(name(s), assumptions...) Calls `sympy.symbols` to produce symbolic variables and symbolic functions. An alternate to the recommended `@syms`, (when applicable) In sympy `sympy.symbols` and `sympy.Symbol` both allow the construction of symbolic variables and functions. The `Julia` function `symbols` is an alias for `sympy.symbols`. * Variables are created through `x=symbols("x")`; * Assumptions on variables by `x=symbols("x", real=true)`; * Multiple symbols `x1,x2 = symbols("x[1:3]")` can be created. Unlike `@syms`, the number of variables can be specified with a variable through interpolation. * Symbolic functions can be created py passing `cls=sympy.Function`, `symbols("F", cls=sympy.Function, real=true)` """ function symbols(x::AbstractString; kwargs...) out = sympy.symbols(x; kwargs...) end symbols(x::Symbol; kwargs...) = symbols(string(x); kwargs...) symbols(xs::T...; kwargs...) where {T <: SymbolicObject} = xs """ @vars x y z Define symbolic values, possibly with names and assumptions Examples: ``` @vars x y @vars a1=>"α₁" @vars a b real=true ``` !!! Note: The `@syms` macro is recommended as it has a more flexible syntax """ macro vars(x...) q = Expr(:block) as = [] # running list of assumptions to be applied ss = [] # running list of symbols created for s in reverse(x) if isa(s, Expr) # either an assumption or a named variable if s.head == :(=) s.head = :kw push!(as, s) elseif s.head == :call && s.args[1] == :(=>) push!(ss, s.args[2]) push!(q.args, Expr(:(=), esc(s.args[2]), Expr(:call, :symbols, s.args[3], map(esc,as)...))) end elseif isa(s, Symbol) # raw symbol to be created push!(ss, s) push!(q.args, Expr(:(=), esc(s), Expr(:call, :symbols, Expr(:quote, s), map(esc,as)...))) else throw(AssertionError("@vars expected a list of symbols and assumptions")) end end push!(q.args, Expr(:tuple, map(esc,reverse(ss))...)) # return all of the symbols we created q end """ @syms a n::integer x::(real,positive)=>"x₀" y[-1:1] u() v()::real w()::(real,positive) y()[1:3]::real Construct symbolic variables or functions along with specified assumptions. Similar to `@vars`, `sympy.symbols`, and `sympy.Function`, but the specification of the assumptions is more immediate than those interfaces which follow sympy's constructors. Allows the specification of assumptions on the variables and functions. * a type-like annontation, such as `n::integer` is equivalent to `sympy.symbols("n", integer=true)`. Multiple assumptions are combined using parentheses (e.g., `n::(integer,nonnegative)`. The possible [values](https://docs.sympy.org/latest/modules/core.html#module-sympy.core.assumptions) for assumptions are: "commutative", "complex", "imaginary", "real", "integer", "odd", "even", "prime", "composite", "zero", "nonzero", "rational", "algebraic", "transcendental", "irrational", "finite", "infinite", "negative", "nonnegative", "positive", "nonpositive", "hermitian", "antihermetian". * a tensor declaration form is provided to define arrays of variables, e.g. `x[-1:1]` or `y[1:4, 2:5]`. * a symbolic function can be specified using a pair of parentheses after the name, as in `u()`. * The return type of a function can have assumptions specified, as with a variable. E.g., `h()::complex`. How the symbolic function prints can be set as with a variable, e.g. `h()::complex=>"h̄"`. * multiple definitions can be separated by commas * How the symbol prints (the `__str__()` value) can be specified using the syntax `=>"name"`, as in `x=>"xₒ"` ## Examples: ```jldoctest constructors julia> using SymPy julia> @syms a b::nonnegative (a, b) julia> sqrt(a^2), sqrt(b^2) (sqrt(a^2), b) ``` ```jldoctest constructors julia> @syms x::prime (x,) julia> ask(𝑄.negative(x)), ask(𝑄.integer(x)), ask(𝑄.even(x)) # (false, true, nothing) (false, true, nothing) ``` ```jldoctest constructors julia> @syms a[0:5], x (Sym[a₀, a₁, a₂, a₃, a₄, a₅], x) julia> sum( aᵢ*x^(i) for (i,aᵢ) ∈ zip(0:5, a)) |> print a₀ + a₁*x + a₂*x^2 + a₃*x^3 + a₄*x^4 + a₅*x^5 ``` ```jldoctest constructors julia> @syms x u() v()::nonnegative (x, u, v) julia> sqrt(u(x)^2), sqrt(v(x)^2) # sqrt(u(x)^2), Abs(v(x)) (sqrt(u(x)^2), Abs(v(x))) ``` !!! Note: Many thanks to `@matthieubulte` for this contribution. """ macro syms(xs...) # If the user separates declaration with commas, the top-level expression is a tuple if length(xs) == 1 && isa(xs[1], Expr) && xs[1].head == :tuple _gensyms(xs[1].args...) elseif length(xs) > 0 _gensyms(xs...) end end function _gensyms(xs...) asstokw(a) = Expr(:kw, esc(a), true) # Each declaration is parsed and generates a declaration using `symbols` symdefs = map(xs) do expr decl = parsedecl(expr) symname = sym(decl) symname, gendecl(decl) end syms, defs = collect(zip(symdefs...)) # The macro returns a tuple of Symbols that were declared Expr(:block, defs..., :(tuple($(map(esc,syms)...)))) end ## avoid PyObject conversion as possible Sym(x::T) where {T <: Number} = sympify(x) Sym(x::Rational{T}) where {T} = Sym(numerator(x))/Sym(denominator(x)) function Sym(x::Complex{Bool}) !x.re && x.im && return IM !x.re && !x.im && return zero(Sym) x.re && !x.im && return Sym(1) x.re && x.im && return Sym(1) + IM end Sym(x::Complex{T}) where {T} = Sym(real(x)) + Sym(imag(x)) * IM Sym(xs::Symbol...) = Tuple(Sym.((string(x) for x in xs))) Sym(x::AbstractString) = sympy.symbols(x) Sym(s::SymbolicObject) = s Sym(x::Irrational{T}) where {T} = convert(Sym, x) convert(::Type{Sym}, s::AbstractString) = Sym(s) sympify(s, args...; kwargs...) = pycall(sympy.sympify::PyCall.PyObject, Sym, s) #sympy.sympify(s, args...; kwargs...) SymMatrix(s::SymMatrix) = s SymMatrix(s::Sym) = sympy.ImmutableMatrix([s]) SymMatrix(A::Matrix) = sympy.ImmutableMatrix([A[i,:] for i in 1:size(A)[1]])
Java
using UnityEngine; public class Crouch : MonoBehaviour { public float crouchColliderProportion = 0.75f; private bool crouching; private float colliderCenterY, centerOffsetY; private ChipmunkBoxShape box; private Jump jump; private Sneak sneak; private WalkAbs move; private AnimateTiledConfig crouchAC; void Awake () { crouching = false; // take the collider and some useful values box = GetComponent<ChipmunkBoxShape>(); colliderCenterY = box.center.y; centerOffsetY = ((1f - crouchColliderProportion)*0.5f) * box.size.y; jump = GetComponent<Jump>(); sneak = GetComponent<Sneak>(); move = GetComponent<WalkAbs>(); crouchAC = AnimateTiledConfig.getByName(gameObject, EnumAnimateTiledName.Crouch, true); } // Update is called once per frame public void crouch () { // is it jumping? bool jumping = false; if (jump != null && jump.isJumping()) jumping = true; // is it moving? bool moving = false; if (move != null && move.isWalking()) moving = true; // if crouching then update accordingly if (sneak != null && crouching) { // while in the air we can't sneak if (jumping) { if (sneak.isSneaking()) { sneak.stopSneaking(); crouchAC.setupAndPlay(); } } // if not jumping and not moving and sneaking: stop sneaking and do crouch else if (!moving) { if (sneak.isSneaking()) { sneak.stopSneaking(); crouchAC.setupAndPlay(); } } // if not jumping and moving: sneak else sneak.sneak(); } // don't update if (crouching || jumping) return; crouching = true; // resize the collider Vector3 theSize = box.size; theSize.y *= crouchColliderProportion; box.size = theSize; // transform the collider Vector3 theCenter = box.center; theCenter.y -= centerOffsetY; box.center = theCenter; // set the correct sprite animation crouchAC.setupAndPlay(); } public void noCrouch () { if (sneak != null) sneak.stopSneaking(); if (!crouching) return; move.stop(); // this force the reset of the sprite animation crouchAC.stop(); crouching = false; // transform the collider Vector3 theCenter = box.center; theCenter.y = colliderCenterY; box.center = theCenter; // resize the collider Vector3 theSize = box.size; theSize.y /= crouchColliderProportion; box.size = theSize; } public bool isCrouching () { return crouching; } }
Java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Plato - lib/cmds/nt.js</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link href="../../assets/css/vendor/morris.css" rel="stylesheet"> <link href="../../assets/css/vendor/bootstrap.css" rel="stylesheet"> <link href="../../assets/css/vendor/font-awesome.css" rel="stylesheet"> <link href="../../assets/css/vendor/codemirror.css" rel="stylesheet"> <link href="../../assets/css/plato.css" rel="stylesheet"> <link href="../../assets/css/plato-file.css" rel="stylesheet"> </head> <body> <div class="navbar navbar-fixed-top"> <div class="container"> <a class="navbar-brand" href="http://github.com/es-analysis/plato">Plato on Github</a> <ul class="nav navbar-nav"> <li> <a href="../../index.html">Report Home</a> </li> </ul> </div> </div> <div class="jumbotron"> <div class="container"> <h1>lib/cmds/nt.js</h1> </div> </div> <div class="container aggregate-stats"> <div class="row"> <div class="col-md-6"> <h2 class="header">Maintainability <a href="http://blogs.msdn.com/b/codeanalysis/archive/2007/11/20/maintainability-index-range-and-meaning.aspx"><i class="icon icon-info-sign" rel="popover" data-placement="top" data-trigger="hover" data-content="A value between 0 and 100 that represents the relative ease of maintaining the code. A high value means better maintainability." data-original-title="Maintainability Index" data-container="body"></i></a></h2> <p class="stat">64.69</p> </div> <div class="col-md-6"> <h2 class="header">Lines of code <i class="icon icon-info-sign" rel="popover" data-placement="top" data-trigger="hover" data-content="Source Lines of Code / Logical Lines of Code" data-original-title="SLOC/LSLOC" data-container="body"></i></h2> <p class="stat">179</p> </div> </div> <div class="row historical"> <div class="col-md-6"> <p id="chart_historical_maint" class="chart"></p> </div> <div class="col-md-6"> <p id="chart_historical_sloc" class="chart"></p> </div> </div> <div class="row"> <div class="col-md-6"> <h2 class="header">Difficulty <a href="http://en.wikipedia.org/wiki/Halstead_complexity_measures"><i class="icon icon-info-sign" rel="popover" data-placement="top" data-trigger="hover" data-content="The difficulty measure is related to the difficulty of the program to write or understand." data-original-title="Difficulty" data-container="body"></i></a></h2> <p class="stat">21.07</p> </div> <div class="col-md-6"> <h2 class="header">Estimated Errors <a href="http://en.wikipedia.org/wiki/Halstead_complexity_measures"><i class="icon icon-info-sign" rel="popover" data-placement="top" data-trigger="hover" data-content="Halstead's delivered bugs is an estimate for the number of errors in the implementation." data-original-title="Delivered Bugs" data-container="body"></i></a></h2> <p class="stat">1.21</p> </div> </div> </div> <div class="container charts"> <div class="row"> <h2 class="header">Function weight</h2> </div> <div class="row"> <div class="col-md-6"> <h3 class="chart-header">By Complexity <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity"><i class="icon icon-info-sign" rel="popover" data-placement="top" data-trigger="hover" data-content="This metric counts the number of distinct paths through a block of code. Lower values are better." data-original-title="Cyclomatic Complexity" data-container="body"></i></a></h3> <div id="fn-by-complexity" class="stat"></div> </div> <div class="col-md-6"> <h3 class="chart-header">By SLOC <i class="icon icon-info-sign" rel="popover" data-placement="top" data-trigger="hover" data-content="Source Lines of Code / Logical Lines of Code" data-original-title="SLOC/LSLOC" data-container="body"></i></h3> <div id="fn-by-sloc" class="stat"></div> </div> </div> </div> <div class="container"> <div class="row"> <textarea id="file-source" class="col-md-12">/* * Copyright 2013 Zeno Rocha, All Rights Reserved. * * Code licensed under the BSD License: * https://github.com/eduardolundgren/blob/master/LICENSE.md * * @author Zeno Rocha &lt;zno.rocha@gmail.com&gt; */ // -- Requires ----------------------------------------------------------------- var async = require(&#039;async&#039;), base = require(&#039;../base&#039;), clc = require(&#039;cli-color&#039;), logger = require(&#039;../logger&#039;), printed = {}; // -- Constructor -------------------------------------------------------------- function Notifications(options) { this.options = options; if (!options.repo) { logger.error(&#039;You must specify a Git repository to run this command&#039;); } } // -- Constants ---------------------------------------------------------------- Notifications.DETAILS = { options: { &#039;latest&#039;: Boolean, &#039;repo&#039; : String, &#039;user&#039; : String, &#039;watch&#039; : Boolean }, shorthands: { &#039;l&#039;: [ &#039;--latest&#039; ], &#039;r&#039;: [ &#039;--repo&#039; ], &#039;u&#039;: [ &#039;--user&#039; ], &#039;w&#039;: [ &#039;--watch&#039; ] }, description: &#039;Provides a set of util commands to work with Notifications.&#039; }; // -- Commands ----------------------------------------------------------------- Notifications.prototype.run = function() { var instance = this, options = instance.options; if (options.latest) { logger.logTemplate(&#039;{{prefix}} [info] Listing activities on {{greenBright options.user &quot;/&quot; options.repo}}&#039;, { options: options }); instance.latest(); } if (options.watch) { logger.logTemplate(&#039;{{prefix}} [info] Watching any activity on {{greenBright options.user &quot;/&quot; options.repo}}&#039;, { options: options }); instance.watch(); } }; Notifications.prototype.latest = function(opt_watch) { var instance = this, options = instance.options, operations, payload, listEvents, filteredListEvents = []; operations = [ function(callback) { payload = { user: options.user, repo: options.repo }; base.github.events.getFromRepo(payload, function(err, data) { if (!err) { listEvents = data; } callback(err); }); }, function(callback) { listEvents.forEach(function(event) { event.txt = instance.getMessage_(event); if (options.watch) { if (!printed[event.created_at]) { filteredListEvents.push(event); } } else { filteredListEvents.push(event); } printed[event.created_at] = true; }); callback(); } ]; async.series(operations, function(err) { if (filteredListEvents.length) { logger.logTemplateFile(&#039;nt.handlebars&#039;, { user: options.user, repo: options.repo, latest: options.latest, watch: opt_watch, events: filteredListEvents }); } logger.defaultCallback(err, null, false); }); }; Notifications.prototype.watch = function() { var instance = this, intervalTime = 3000; instance.latest(); setInterval(function() { instance.latest(true); }, intervalTime); }; Notifications.prototype.getMessage_ = function(event) { var instance = this, txt = &#039;&#039;, type = event.type, payload = event.payload; switch (type) { case &#039;CommitCommentEvent&#039;: txt = &#039;commented on a commit at&#039;; break; case &#039;CreateEvent&#039;: txt = &#039;created a &#039; + payload.ref_type + &#039; at&#039;; break; case &#039;DeleteEvent&#039;: txt = &#039;removed &#039; + payload.ref_type + &#039; at&#039;; break; case &#039;DownloadEvent&#039;: txt = &#039;downloaded&#039;; break; case &#039;ForkEvent&#039;: txt = &#039;forked&#039;; break; case &#039;ForkApplyEvent&#039;: txt = &#039;applied patch &#039; + payload.head + &#039; at&#039;; break; case &#039;IssueCommentEvent&#039;: txt = &#039;commented on an issue at&#039;; break; case &#039;IssuesEvent&#039;: txt = payload.action + &#039; an issue at&#039;; break; case &#039;MemberEvent&#039;: txt = &#039;added &#039; + payload.member + &#039; as a collaborator to&#039;; break; case &#039;PublicEvent&#039;: txt = &#039;open sourced&#039;; break; case &#039;PullRequestEvent&#039;: txt = payload.action + &#039; pull request #&#039; + payload.number + &#039; at&#039;; break; case &#039;PullRequestReviewCommentEvent&#039;: txt = &#039;commented on a pull request at&#039;; break; case &#039;PushEvent&#039;: txt = &#039;pushed &#039; + payload.commits.length + &#039; commit(s) to&#039;; break; case &#039;WatchEvent&#039;: txt = &#039;is now watching&#039;; break; default: logger.error(&#039;event type not found: &#039; + clc.red(type)); break; } return txt; }; exports.Impl = Notifications;</textarea> </div> </div> <footer class="footer"> <div class="container"> <p>.</p> </div> </footer> <script type="text/html" id="complexity-popover-template"> <div class="complexity-notice"> Complexity : {{ complexity.cyclomatic }} <br> Length : {{ complexity.halstead.length }} <br> Difficulty : {{ complexity.halstead.difficulty.toFixed(2) }} <br> Est # bugs : {{ complexity.halstead.bugs.toFixed(2) }}<br> </div> </script> <script type="text/javascript" src="../../assets/scripts/bundles/core-bundle.js"></script> <script type="text/javascript" src="../../assets/scripts/bundles/codemirror.js"></script> <script type="text/javascript" src="../../assets/scripts/codemirror.markpopovertext.js"></script> <script type="text/javascript" src="report.js"></script> <script type="text/javascript" src="report.history.js"></script> <script type="text/javascript" src="../../assets/scripts/plato-file.js"></script> </body> </html>
Java
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.applicationinsights.models; import com.azure.core.annotation.Immutable; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.UUID; /** User assigned identity properties. */ @Immutable public class UserAssignedIdentity { @JsonIgnore private final ClientLogger logger = new ClientLogger(UserAssignedIdentity.class); /* * The principal ID of the assigned identity. */ @JsonProperty(value = "principalId", access = JsonProperty.Access.WRITE_ONLY) private UUID principalId; /* * The client ID of the assigned identity. */ @JsonProperty(value = "clientId", access = JsonProperty.Access.WRITE_ONLY) private UUID clientId; /** * Get the principalId property: The principal ID of the assigned identity. * * @return the principalId value. */ public UUID principalId() { return this.principalId; } /** * Get the clientId property: The client ID of the assigned identity. * * @return the clientId value. */ public UUID clientId() { return this.clientId; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { } }
Java
__precompile__(true) module ImplicitEquations using ValidatedNumerics import ValidatedNumerics: Interval, diam using RecipesBase using Compat include("predicates.jl") include("intervals.jl") include("tupper.jl") include("asciigraphs.jl") #include("plot.jl") include("plot_recipe.jl") export eq, neq, ⩵, ≷, ≶ export screen, I_ export asciigraph #export GRAPH, OInterval #export Region, compute, negate_op #export TRUE, FALSE, MAYBE end # module
Java
/* * 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. */ angular.module('MetronicApp').controller('UsuariosCtrl', function ($scope, GetSv, $rootScope, PostSv,toaster) { $scope.usuarios = []; $scope.add = false; $scope.edit = false; $scope.a_editar = {}; $scope.usuario = {}; $scope.getUsers = function () { GetSv.getData("usuarios").then(function (data) { if (data.Error) { $scope.error = true; } else { $scope.usuarios = data; $scope.error = false; } }, function (e) { $scope.error = true; }); }; $scope.getUsers(); $scope.closeEdit = function () { $scope.a_editar = {}; $scope.edit = false; }; $scope.openEdit = function (item) { $scope.a_editar = item; $scope.edit = true; }; $scope.closeAdd = function () { $scope.add = false; }; $scope.openAdd = function (item) { $scope.a_editar = {}; $scope.add = true; }; $scope.sendUser = function (servlet, user) { PostSv.postData(servlet, {usuario: JSON.stringify(user)}).then(function (data) { if (data.Error) { toaster.pop('error', "Error", data.Error); } else { toaster.pop('success', "Exito", data.Exito); $scope.a_editar = {}; $scope.usuario = {}; $scope.getUsers(); $scope.add = false; $scope.edit = false; } }, function (e) { toaster.pop('error', "Error", "Error fatal"); } ); }; $scope.roles = $rootScope.roles; });
Java
#include <vector> #include <memory> #include <iostream> using namespace std; shared_ptr<vector<int>> make() { return make_shared<vector<int>>(); } shared_ptr<vector<int>> read(shared_ptr<vector<int>> p) { cout << "Enter values: " << endl; int x; while (cin >> x) { p->push_back(x); } return p; } void print(shared_ptr<vector<int>> p) { for (int i : *p) { cout << i << " "; } } int main() { auto p = read(make()); print(p); return 0; }
Java
/* * This file exports the configuration Express.js back to the application * so that it can be used in other parts of the product. */ var path = require('path'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var session = require('express-session'); var RedisStore = require('connect-redis')(session); exports.setup = function(app, express) { app.set('views', path.join(__dirname + '../../public/views')); app.engine('html', require('ejs').renderFile); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(session({ cookie: { maxAge: (24*3600*1000*30) }, store: new RedisStore({ host: 'localhost', port: 6379, db: 1, pass: '' }), secret: 'mylittlesecret', resave: false, saveUninitialized: false })); app.use(express.static(path.join(__dirname + '../../public'))); }
Java
--- layout: pattern summary: "Base classes for creating simple 'nav-like' lists. Ideal for simple nav menus or for forming the basis of more complex navigation componenets." --- <ul class="tan-nav-menu tan-nav-menu--stacked"> {% for i in (1..4) %} <li class=""> <a href="#">Stacked Link {{i}}</a> </li> {% endfor %} </ul> <br><br><br> <ul class="tan-nav-menu tan-nav-menu--inline"> {% for i in (1..4) %} <li class=""> <a href="#">Inline Link {{i}}</a> </li> {% endfor %} </ul>
Java
(function() { chai.should(); describe("Dropzone", function() { var getMockFile, xhr; getMockFile = function() { return { status: Dropzone.ADDED, accepted: true, name: "test file name", size: 123456, type: "text/html" }; }; xhr = null; beforeEach(function() { return xhr = sinon.useFakeXMLHttpRequest(); }); describe("Emitter", function() { var emitter; emitter = null; beforeEach(function() { return emitter = new Dropzone.prototype.Emitter(); }); it(".on() should return the object itself", function() { return (emitter.on("test", function() {})).should.equal(emitter); }); it(".on() should properly register listeners", function() { var callback, callback2; (emitter._callbacks === void 0).should.be["true"]; callback = function() {}; callback2 = function() {}; emitter.on("test", callback); emitter.on("test", callback2); emitter.on("test2", callback); emitter._callbacks.test.length.should.equal(2); emitter._callbacks.test[0].should.equal(callback); emitter._callbacks.test[1].should.equal(callback2); emitter._callbacks.test2.length.should.equal(1); return emitter._callbacks.test2[0].should.equal(callback); }); it(".emit() should return the object itself", function() { return emitter.emit('test').should.equal(emitter); }); it(".emit() should properly invoke all registered callbacks with arguments", function() { var callCount1, callCount12, callCount2, callback1, callback12, callback2; callCount1 = 0; callCount12 = 0; callCount2 = 0; callback1 = function(var1, var2) { callCount1++; var1.should.equal('callback1 var1'); return var2.should.equal('callback1 var2'); }; callback12 = function(var1, var2) { callCount12++; var1.should.equal('callback1 var1'); return var2.should.equal('callback1 var2'); }; callback2 = function(var1, var2) { callCount2++; var1.should.equal('callback2 var1'); return var2.should.equal('callback2 var2'); }; emitter.on("test1", callback1); emitter.on("test1", callback12); emitter.on("test2", callback2); callCount1.should.equal(0); callCount12.should.equal(0); callCount2.should.equal(0); emitter.emit("test1", "callback1 var1", "callback1 var2"); callCount1.should.equal(1); callCount12.should.equal(1); callCount2.should.equal(0); emitter.emit("test2", "callback2 var1", "callback2 var2"); callCount1.should.equal(1); callCount12.should.equal(1); callCount2.should.equal(1); emitter.emit("test1", "callback1 var1", "callback1 var2"); callCount1.should.equal(2); callCount12.should.equal(2); return callCount2.should.equal(1); }); return describe(".off()", function() { var callback1, callback2, callback3, callback4; callback1 = function() {}; callback2 = function() {}; callback3 = function() {}; callback4 = function() {}; beforeEach(function() { return emitter._callbacks = { 'test1': [callback1, callback2], 'test2': [callback3], 'test3': [callback1, callback4], 'test4': [] }; }); it("should work without any listeners", function() { var emt; emitter._callbacks = void 0; emt = emitter.off(); emitter._callbacks.should.eql({}); return emt.should.equal(emitter); }); it("should properly remove all event listeners", function() { var emt; emt = emitter.off(); emitter._callbacks.should.eql({}); return emt.should.equal(emitter); }); it("should properly remove all event listeners for specific event", function() { var emt; emitter.off("test1"); (emitter._callbacks["test1"] === void 0).should.be["true"]; emitter._callbacks["test2"].length.should.equal(1); emitter._callbacks["test3"].length.should.equal(2); emt = emitter.off("test2"); (emitter._callbacks["test2"] === void 0).should.be["true"]; return emt.should.equal(emitter); }); return it("should properly remove specific event listener", function() { var emt; emitter.off("test1", callback1); emitter._callbacks["test1"].length.should.equal(1); emitter._callbacks["test1"][0].should.equal(callback2); emitter._callbacks["test3"].length.should.equal(2); emt = emitter.off("test3", callback4); emitter._callbacks["test3"].length.should.equal(1); emitter._callbacks["test3"][0].should.equal(callback1); return emt.should.equal(emitter); }); }); }); describe("static functions", function() { describe("Dropzone.createElement()", function() { var element; element = Dropzone.createElement("<div class=\"test\"><span>Hallo</span></div>"); it("should properly create an element from a string", function() { return element.tagName.should.equal("DIV"); }); it("should properly add the correct class", function() { return element.classList.contains("test").should.be.ok; }); it("should properly create child elements", function() { return element.querySelector("span").tagName.should.equal("SPAN"); }); return it("should always return only one element", function() { element = Dropzone.createElement("<div></div><span></span>"); return element.tagName.should.equal("DIV"); }); }); describe("Dropzone.elementInside()", function() { var child1, child2, element; element = Dropzone.createElement("<div id=\"test\"><div class=\"child1\"><div class=\"child2\"></div></div></div>"); document.body.appendChild(element); child1 = element.querySelector(".child1"); child2 = element.querySelector(".child2"); after(function() { return document.body.removeChild(element); }); it("should return yes if elements are the same", function() { return Dropzone.elementInside(element, element).should.be.ok; }); it("should return yes if element is direct child", function() { return Dropzone.elementInside(child1, element).should.be.ok; }); it("should return yes if element is some child", function() { Dropzone.elementInside(child2, element).should.be.ok; return Dropzone.elementInside(child2, document.body).should.be.ok; }); return it("should return no unless element is some child", function() { Dropzone.elementInside(element, child1).should.not.be.ok; return Dropzone.elementInside(document.body, child1).should.not.be.ok; }); }); describe("Dropzone.optionsForElement()", function() { var element, testOptions; testOptions = { url: "/some/url", method: "put" }; before(function() { return Dropzone.options.testElement = testOptions; }); after(function() { return delete Dropzone.options.testElement; }); element = document.createElement("div"); it("should take options set in Dropzone.options from camelized id", function() { element.id = "test-element"; return Dropzone.optionsForElement(element).should.equal(testOptions); }); it("should return undefined if no options set", function() { element.id = "test-element2"; return expect(Dropzone.optionsForElement(element)).to.equal(void 0); }); it("should return undefined and not throw if it's a form with an input element of the name 'id'", function() { element = Dropzone.createElement("<form><input name=\"id\" /</form>"); return expect(Dropzone.optionsForElement(element)).to.equal(void 0); }); return it("should ignore input fields with the name='id'", function() { element = Dropzone.createElement("<form id=\"test-element\"><input type=\"hidden\" name=\"id\" value=\"fooo\" /></form>"); return Dropzone.optionsForElement(element).should.equal(testOptions); }); }); describe("Dropzone.forElement()", function() { var dropzone, element; element = document.createElement("div"); element.id = "some-test-element"; dropzone = null; before(function() { document.body.appendChild(element); return dropzone = new Dropzone(element, { url: "/test" }); }); after(function() { dropzone.disable(); return document.body.removeChild(element); }); it("should throw an exception if no dropzone attached", function() { return expect(function() { return Dropzone.forElement(document.createElement("div")); }).to["throw"]("No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone."); }); it("should accept css selectors", function() { return expect(Dropzone.forElement("#some-test-element")).to.equal(dropzone); }); return it("should accept native elements", function() { return expect(Dropzone.forElement(element)).to.equal(dropzone); }); }); describe("Dropzone.discover()", function() { var element1, element2, element3; element1 = document.createElement("div"); element1.className = "dropzone"; element2 = element1.cloneNode(); element3 = element1.cloneNode(); element1.id = "test-element-1"; element2.id = "test-element-2"; element3.id = "test-element-3"; describe("specific options", function() { before(function() { Dropzone.options.testElement1 = { url: "test-url" }; Dropzone.options.testElement2 = false; document.body.appendChild(element1); document.body.appendChild(element2); return Dropzone.discover(); }); after(function() { document.body.removeChild(element1); return document.body.removeChild(element2); }); it("should find elements with a .dropzone class", function() { return element1.dropzone.should.be.ok; }); return it("should not create dropzones with disabled options", function() { return expect(element2.dropzone).to.not.be.ok; }); }); return describe("Dropzone.autoDiscover", function() { before(function() { Dropzone.options.testElement3 = { url: "test-url" }; return document.body.appendChild(element3); }); after(function() { return document.body.removeChild(element3); }); it("should create dropzones even if Dropzone.autoDiscover == false", function() { Dropzone.autoDiscover = false; Dropzone.discover(); return expect(element3.dropzone).to.be.ok; }); return it("should not automatically be called if Dropzone.autoDiscover == false", function() { Dropzone.autoDiscover = false; Dropzone.discover = function() { return expect(false).to.be.ok; }; return Dropzone._autoDiscoverFunction(); }); }); }); describe("Dropzone.isValidFile()", function() { it("should return true if called without acceptedFiles", function() { return Dropzone.isValidFile({ type: "some/type" }, null).should.be.ok; }); it("should properly validate if called with concrete mime types", function() { var acceptedMimeTypes; acceptedMimeTypes = "text/html,image/jpeg,application/json"; Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ type: "application/json" }, acceptedMimeTypes).should.be.ok; return Dropzone.isValidFile({ type: "image/bmp" }, acceptedMimeTypes).should.not.be.ok; }); it("should properly validate if called with base mime types", function() { var acceptedMimeTypes; acceptedMimeTypes = "text/*,image/*,application/*"; Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ type: "application/json" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ type: "image/bmp" }, acceptedMimeTypes).should.be.ok; return Dropzone.isValidFile({ type: "some/type" }, acceptedMimeTypes).should.not.be.ok; }); it("should properly validate if called with mixed mime types", function() { var acceptedMimeTypes; acceptedMimeTypes = "text/*,image/jpeg,application/*"; Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ type: "image/bmp" }, acceptedMimeTypes).should.not.be.ok; Dropzone.isValidFile({ type: "application/json" }, acceptedMimeTypes).should.be.ok; return Dropzone.isValidFile({ type: "some/type" }, acceptedMimeTypes).should.not.be.ok; }); it("should properly validate even with spaces in between", function() { var acceptedMimeTypes; acceptedMimeTypes = "text/html , image/jpeg, application/json"; Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok; return Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok; }); return it("should properly validate extensions", function() { var acceptedMimeTypes; acceptedMimeTypes = "text/html , image/jpeg, .pdf ,.png"; Dropzone.isValidFile({ name: "somxsfsd", type: "text/html" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ name: "somesdfsdf", type: "image/jpeg" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ name: "somesdfadfadf", type: "application/json" }, acceptedMimeTypes).should.not.be.ok; Dropzone.isValidFile({ name: "some-file file.pdf", type: "random/type" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ name: "some-file.pdf file.gif", type: "random/type" }, acceptedMimeTypes).should.not.be.ok; return Dropzone.isValidFile({ name: "some-file file.png", type: "random/type" }, acceptedMimeTypes).should.be.ok; }); }); return describe("Dropzone.confirm", function() { beforeEach(function() { return sinon.stub(window, "confirm"); }); afterEach(function() { return window.confirm.restore(); }); it("should forward to window.confirm and call the callbacks accordingly", function() { var accepted, rejected; accepted = rejected = false; window.confirm.returns(true); Dropzone.confirm("test question", (function() { return accepted = true; }), (function() { return rejected = true; })); window.confirm.args[0][0].should.equal("test question"); accepted.should.equal(true); rejected.should.equal(false); accepted = rejected = false; window.confirm.returns(false); Dropzone.confirm("test question 2", (function() { return accepted = true; }), (function() { return rejected = true; })); window.confirm.args[1][0].should.equal("test question 2"); accepted.should.equal(false); return rejected.should.equal(true); }); return it("should not error if rejected is not provided", function() { var accepted, rejected; accepted = rejected = false; window.confirm.returns(false); Dropzone.confirm("test question", (function() { return accepted = true; })); window.confirm.args[0][0].should.equal("test question"); accepted.should.equal(false); return rejected.should.equal(false); }); }); }); describe("Dropzone.getElement() / getElements()", function() { var tmpElements; tmpElements = []; beforeEach(function() { tmpElements = []; tmpElements.push(Dropzone.createElement("<div class=\"tmptest\"></div>")); tmpElements.push(Dropzone.createElement("<div id=\"tmptest1\" class=\"random\"></div>")); tmpElements.push(Dropzone.createElement("<div class=\"random div\"></div>")); return tmpElements.forEach(function(el) { return document.body.appendChild(el); }); }); afterEach(function() { return tmpElements.forEach(function(el) { return document.body.removeChild(el); }); }); describe(".getElement()", function() { it("should accept a string", function() { var el; el = Dropzone.getElement(".tmptest"); el.should.equal(tmpElements[0]); el = Dropzone.getElement("#tmptest1"); return el.should.equal(tmpElements[1]); }); it("should accept a node", function() { var el; el = Dropzone.getElement(tmpElements[2]); return el.should.equal(tmpElements[2]); }); return it("should fail if invalid selector", function() { var errorMessage; errorMessage = "Invalid `clickable` option provided. Please provide a CSS selector or a plain HTML element."; expect(function() { return Dropzone.getElement("lblasdlfsfl", "clickable"); }).to["throw"](errorMessage); expect(function() { return Dropzone.getElement({ "lblasdlfsfl": "lblasdlfsfl" }, "clickable"); }).to["throw"](errorMessage); return expect(function() { return Dropzone.getElement(["lblasdlfsfl"], "clickable"); }).to["throw"](errorMessage); }); }); return describe(".getElements()", function() { it("should accept a list of strings", function() { var els; els = Dropzone.getElements([".tmptest", "#tmptest1"]); return els.should.eql([tmpElements[0], tmpElements[1]]); }); it("should accept a list of nodes", function() { var els; els = Dropzone.getElements([tmpElements[0], tmpElements[2]]); return els.should.eql([tmpElements[0], tmpElements[2]]); }); it("should accept a mixed list", function() { var els; els = Dropzone.getElements(["#tmptest1", tmpElements[2]]); return els.should.eql([tmpElements[1], tmpElements[2]]); }); it("should accept a string selector", function() { var els; els = Dropzone.getElements(".random"); return els.should.eql([tmpElements[1], tmpElements[2]]); }); it("should accept a single node", function() { var els; els = Dropzone.getElements(tmpElements[1]); return els.should.eql([tmpElements[1]]); }); return it("should fail if invalid selector", function() { var errorMessage; errorMessage = "Invalid `clickable` option provided. Please provide a CSS selector, a plain HTML element or a list of those."; expect(function() { return Dropzone.getElements("lblasdlfsfl", "clickable"); }).to["throw"](errorMessage); return expect(function() { return Dropzone.getElements(["lblasdlfsfl"], "clickable"); }).to["throw"](errorMessage); }); }); }); describe("constructor()", function() { var dropzone; dropzone = null; afterEach(function() { if (dropzone != null) { return dropzone.destroy(); } }); it("should throw an exception if the element is invalid", function() { return expect(function() { return dropzone = new Dropzone("#invalid-element"); }).to["throw"]("Invalid dropzone element."); }); it("should throw an exception if assigned twice to the same element", function() { var element; element = document.createElement("div"); dropzone = new Dropzone(element, { url: "url" }); return expect(function() { return new Dropzone(element, { url: "url" }); }).to["throw"]("Dropzone already attached."); }); it("should throw an exception if both acceptedFiles and acceptedMimeTypes are specified", function() { var element; element = document.createElement("div"); return expect(function() { return dropzone = new Dropzone(element, { url: "test", acceptedFiles: "param", acceptedMimeTypes: "types" }); }).to["throw"]("You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated."); }); it("should set itself as element.dropzone", function() { var element; element = document.createElement("div"); dropzone = new Dropzone(element, { url: "url" }); return element.dropzone.should.equal(dropzone); }); it("should add itself to Dropzone.instances", function() { var element; element = document.createElement("div"); dropzone = new Dropzone(element, { url: "url" }); return Dropzone.instances[Dropzone.instances.length - 1].should.equal(dropzone); }); it("should use the action attribute not the element with the name action", function() { var element; element = Dropzone.createElement("<form action=\"real-action\"><input type=\"hidden\" name=\"action\" value=\"wrong-action\" /></form>"); dropzone = new Dropzone(element); return dropzone.options.url.should.equal("real-action"); }); return describe("options", function() { var element, element2; element = null; element2 = null; beforeEach(function() { element = document.createElement("div"); element.id = "test-element"; element2 = document.createElement("div"); element2.id = "test-element2"; return Dropzone.options.testElement = { url: "/some/url", parallelUploads: 10 }; }); afterEach(function() { return delete Dropzone.options.testElement; }); it("should take the options set in Dropzone.options", function() { dropzone = new Dropzone(element); dropzone.options.url.should.equal("/some/url"); return dropzone.options.parallelUploads.should.equal(10); }); it("should prefer passed options over Dropzone.options", function() { dropzone = new Dropzone(element, { url: "/some/other/url" }); return dropzone.options.url.should.equal("/some/other/url"); }); it("should take the default options if nothing set in Dropzone.options", function() { dropzone = new Dropzone(element2, { url: "/some/url" }); return dropzone.options.parallelUploads.should.equal(2); }); it("should call the fallback function if forceFallback == true", function(done) { return dropzone = new Dropzone(element, { url: "/some/other/url", forceFallback: true, fallback: function() { return done(); } }); }); it("should set acceptedFiles if deprecated acceptedMimetypes option has been passed", function() { dropzone = new Dropzone(element, { url: "/some/other/url", acceptedMimeTypes: "my/type" }); return dropzone.options.acceptedFiles.should.equal("my/type"); }); return describe("options.clickable", function() { var clickableElement; clickableElement = null; dropzone = null; beforeEach(function() { clickableElement = document.createElement("div"); clickableElement.className = "some-clickable"; return document.body.appendChild(clickableElement); }); afterEach(function() { document.body.removeChild(clickableElement); if (dropzone != null) { return dropzone.destroy; } }); it("should use the default element if clickable == true", function() { dropzone = new Dropzone(element, { clickable: true }); return dropzone.clickableElements.should.eql([dropzone.element]); }); it("should lookup the element if clickable is a CSS selector", function() { dropzone = new Dropzone(element, { clickable: ".some-clickable" }); return dropzone.clickableElements.should.eql([clickableElement]); }); it("should simply use the provided element", function() { dropzone = new Dropzone(element, { clickable: clickableElement }); return dropzone.clickableElements.should.eql([clickableElement]); }); it("should accept multiple clickable elements", function() { dropzone = new Dropzone(element, { clickable: [document.body, ".some-clickable"] }); return dropzone.clickableElements.should.eql([document.body, clickableElement]); }); return it("should throw an exception if the element is invalid", function() { return expect(function() { return dropzone = new Dropzone(element, { clickable: ".some-invalid-clickable" }); }).to["throw"]("Invalid `clickable` option provided. Please provide a CSS selector, a plain HTML element or a list of those."); }); }); }); }); describe("init()", function() { describe("clickable", function() { var dropzone, dropzones, name, _results; dropzones = { "using acceptedFiles": new Dropzone(Dropzone.createElement("<form action=\"/\"></form>"), { clickable: true, acceptedFiles: "audio/*,video/*" }), "using acceptedMimeTypes": new Dropzone(Dropzone.createElement("<form action=\"/\"></form>"), { clickable: true, acceptedMimeTypes: "audio/*,video/*" }) }; it("should not add an accept attribute if no acceptParameter", function() { var dropzone; dropzone = new Dropzone(Dropzone.createElement("<form action=\"/\"></form>"), { clickable: true, acceptParameter: null, acceptedMimeTypes: null }); return dropzone.hiddenFileInput.hasAttribute("accept").should.be["false"]; }); _results = []; for (name in dropzones) { dropzone = dropzones[name]; _results.push(describe(name, function() { return (function(dropzone) { it("should create a hidden file input if clickable", function() { dropzone.hiddenFileInput.should.be.ok; return dropzone.hiddenFileInput.tagName.should.equal("INPUT"); }); it("should use the acceptParameter", function() { return dropzone.hiddenFileInput.getAttribute("accept").should.equal("audio/*,video/*"); }); return it("should create a new input element when something is selected to reset the input field", function() { var event, hiddenFileInput, i, _i, _results1; _results1 = []; for (i = _i = 0; _i <= 3; i = ++_i) { hiddenFileInput = dropzone.hiddenFileInput; event = document.createEvent("HTMLEvents"); event.initEvent("change", true, true); hiddenFileInput.dispatchEvent(event); dropzone.hiddenFileInput.should.not.equal(hiddenFileInput); _results1.push(Dropzone.elementInside(hiddenFileInput, document).should.not.be.ok); } return _results1; }); })(dropzone); })); } return _results; }); it("should create a .dz-message element", function() { var dropzone, element; element = Dropzone.createElement("<form class=\"dropzone\" action=\"/\"></form>"); dropzone = new Dropzone(element, { clickable: true, acceptParameter: null, acceptedMimeTypes: null }); return element.querySelector(".dz-message").should.be["instanceof"](Element); }); return it("should not create a .dz-message element if there already is one", function() { var dropzone, element, msg; element = Dropzone.createElement("<form class=\"dropzone\" action=\"/\"></form>"); msg = Dropzone.createElement("<div class=\"dz-message\">TEST</div>"); element.appendChild(msg); dropzone = new Dropzone(element, { clickable: true, acceptParameter: null, acceptedMimeTypes: null }); element.querySelector(".dz-message").should.equal(msg); return element.querySelectorAll(".dz-message").length.should.equal(1); }); }); describe("options", function() { var dropzone, element; element = null; dropzone = null; beforeEach(function() { element = Dropzone.createElement("<div></div>"); return dropzone = new Dropzone(element, { maxFilesize: 4, url: "url", acceptedMimeTypes: "audio/*,image/png", maxFiles: 3 }); }); return describe("file specific", function() { var file; file = null; beforeEach(function() { file = { name: "test name", size: 2 * 1024 * 1024, width: 200, height: 100 }; return dropzone.options.addedfile.call(dropzone, file); }); describe(".addedFile()", function() { return it("should properly create the previewElement", function() { file.previewElement.should.be["instanceof"](Element); file.previewElement.querySelector("[data-dz-name]").innerHTML.should.eql("test name"); return file.previewElement.querySelector("[data-dz-size]").innerHTML.should.eql("<strong>2.1</strong> MB"); }); }); describe(".error()", function() { it("should properly insert the error", function() { dropzone.options.error.call(dropzone, file, "test message"); return file.previewElement.querySelector("[data-dz-errormessage]").innerHTML.should.eql("test message"); }); return it("should properly insert the error when provided with an object containing the error", function() { dropzone.options.error.call(dropzone, file, { error: "test message" }); return file.previewElement.querySelector("[data-dz-errormessage]").innerHTML.should.eql("test message"); }); }); describe(".thumbnail()", function() { return it("should properly insert the error", function() { var thumbnail, transparentGif; transparentGif = "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="; dropzone.options.thumbnail.call(dropzone, file, transparentGif); thumbnail = file.previewElement.querySelector("[data-dz-thumbnail]"); thumbnail.src.should.eql(transparentGif); return thumbnail.alt.should.eql("test name"); }); }); describe(".uploadprogress()", function() { return it("should properly set the width", function() { dropzone.options.uploadprogress.call(dropzone, file, 0); file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql("0%"); dropzone.options.uploadprogress.call(dropzone, file, 80); file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql("80%"); dropzone.options.uploadprogress.call(dropzone, file, 90); file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql("90%"); dropzone.options.uploadprogress.call(dropzone, file, 100); return file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql("100%"); }); }); return describe(".resize()", function() { describe("with default thumbnail settings", function() { return it("should properly return target dimensions", function() { var info; info = dropzone.options.resize.call(dropzone, file); info.optWidth.should.eql(120); return info.optHeight.should.eql(120); }); }); return describe("with null thumbnail settings", function() { return it("should properly return target dimensions", function() { var i, info, setting, testSettings, _i, _len, _results; testSettings = [[null, null], [null, 150], [150, null]]; _results = []; for (i = _i = 0, _len = testSettings.length; _i < _len; i = ++_i) { setting = testSettings[i]; dropzone.options.thumbnailWidth = setting[0]; dropzone.options.thumbnailHeight = setting[1]; info = dropzone.options.resize.call(dropzone, file); if (i === 0) { info.optWidth.should.eql(200); info.optHeight.should.eql(100); } if (i === 1) { info.optWidth.should.eql(300); info.optHeight.should.eql(150); } if (i === 2) { info.optWidth.should.eql(150); _results.push(info.optHeight.should.eql(75)); } else { _results.push(void 0); } } return _results; }); }); }); }); }); describe("instance", function() { var dropzone, element, requests; element = null; dropzone = null; requests = null; beforeEach(function() { requests = []; xhr.onCreate = function(xhr) { return requests.push(xhr); }; element = Dropzone.createElement("<div></div>"); document.body.appendChild(element); return dropzone = new Dropzone(element, { maxFilesize: 4, maxFiles: 100, url: "url", acceptedMimeTypes: "audio/*,image/png", uploadprogress: function() {} }); }); afterEach(function() { document.body.removeChild(element); dropzone.destroy(); return xhr.restore(); }); describe(".accept()", function() { it("should pass if the filesize is OK", function() { return dropzone.accept({ size: 2 * 1024 * 1024, type: "audio/mp3" }, function(err) { return expect(err).to.be.undefined; }); }); it("shouldn't pass if the filesize is too big", function() { return dropzone.accept({ size: 10 * 1024 * 1024, type: "audio/mp3" }, function(err) { return err.should.eql("File is too big (10MiB). Max filesize: 4MiB."); }); }); it("should properly accept files which mime types are listed in acceptedFiles", function() { dropzone.accept({ type: "audio/mp3" }, function(err) { return expect(err).to.be.undefined; }); dropzone.accept({ type: "image/png" }, function(err) { return expect(err).to.be.undefined; }); return dropzone.accept({ type: "audio/wav" }, function(err) { return expect(err).to.be.undefined; }); }); it("should properly reject files when the mime type isn't listed in acceptedFiles", function() { return dropzone.accept({ type: "image/jpeg" }, function(err) { return err.should.eql("You can't upload files of this type."); }); }); it("should fail if maxFiles has been exceeded and call the event maxfilesexceeded", function() { var called, file; sinon.stub(dropzone, "getAcceptedFiles"); file = { type: "audio/mp3" }; dropzone.getAcceptedFiles.returns({ length: 99 }); dropzone.options.dictMaxFilesExceeded = "You can only upload {{maxFiles}} files."; called = false; dropzone.on("maxfilesexceeded", function(lfile) { lfile.should.equal(file); return called = true; }); dropzone.accept(file, function(err) { return expect(err).to.be.undefined; }); called.should.not.be.ok; dropzone.getAcceptedFiles.returns({ length: 100 }); dropzone.accept(file, function(err) { return expect(err).to.equal("You can only upload 100 files."); }); called.should.be.ok; return dropzone.getAcceptedFiles.restore(); }); return it("should properly handle if maxFiles is 0", function() { var called, file; file = { type: "audio/mp3" }; dropzone.options.maxFiles = 0; called = false; dropzone.on("maxfilesexceeded", function(lfile) { lfile.should.equal(file); return called = true; }); dropzone.accept(file, function(err) { return expect(err).to.equal("You can not upload any more files."); }); return called.should.be.ok; }); }); describe(".removeFile()", function() { return it("should abort uploading if file is currently being uploaded", function(done) { var mockFile; mockFile = getMockFile(); dropzone.uploadFile = function(file) {}; dropzone.accept = function(file, done) { return done(); }; sinon.stub(dropzone, "cancelUpload"); dropzone.addFile(mockFile); return setTimeout(function() { mockFile.status.should.equal(Dropzone.UPLOADING); dropzone.getUploadingFiles()[0].should.equal(mockFile); dropzone.cancelUpload.callCount.should.equal(0); dropzone.removeFile(mockFile); dropzone.cancelUpload.callCount.should.equal(1); return done(); }, 10); }); }); describe(".cancelUpload()", function() { it("should properly cancel upload if file currently uploading", function(done) { var mockFile; mockFile = getMockFile(); dropzone.accept = function(file, done) { return done(); }; dropzone.addFile(mockFile); return setTimeout(function() { mockFile.status.should.equal(Dropzone.UPLOADING); dropzone.getUploadingFiles()[0].should.equal(mockFile); dropzone.cancelUpload(mockFile); mockFile.status.should.equal(Dropzone.CANCELED); dropzone.getUploadingFiles().length.should.equal(0); dropzone.getQueuedFiles().length.should.equal(0); return done(); }, 10); }); it("should properly cancel the upload if file is not yet uploading", function() { var mockFile; mockFile = getMockFile(); dropzone.accept = function(file, done) { return done(); }; dropzone.options.parallelUploads = 0; dropzone.addFile(mockFile); mockFile.status.should.equal(Dropzone.QUEUED); dropzone.getQueuedFiles()[0].should.equal(mockFile); dropzone.cancelUpload(mockFile); mockFile.status.should.equal(Dropzone.CANCELED); dropzone.getQueuedFiles().length.should.equal(0); return dropzone.getUploadingFiles().length.should.equal(0); }); it("should call processQueue()", function(done) { var mockFile; mockFile = getMockFile(); dropzone.accept = function(file, done) { return done(); }; dropzone.options.parallelUploads = 0; sinon.spy(dropzone, "processQueue"); dropzone.addFile(mockFile); return setTimeout(function() { dropzone.processQueue.callCount.should.equal(1); dropzone.cancelUpload(mockFile); dropzone.processQueue.callCount.should.equal(2); return done(); }, 10); }); return it("should properly cancel all files with the same XHR if uploadMultiple is true", function(done) { var mock1, mock2, mock3; mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); dropzone.accept = function(file, done) { return done(); }; dropzone.options.uploadMultiple = true; dropzone.options.parallelUploads = 3; sinon.spy(dropzone, "processFiles"); dropzone.addFile(mock1); dropzone.addFile(mock2); dropzone.addFile(mock3); return setTimeout(function() { var _ref; dropzone.processFiles.callCount.should.equal(1); sinon.spy(mock1.xhr, "abort"); dropzone.cancelUpload(mock1); expect((mock1.xhr === (_ref = mock2.xhr) && _ref === mock3.xhr)).to.be.ok; mock1.status.should.equal(Dropzone.CANCELED); mock2.status.should.equal(Dropzone.CANCELED); mock3.status.should.equal(Dropzone.CANCELED); mock1.xhr.abort.callCount.should.equal(1); return done(); }, 10); }); }); describe(".disable()", function() { return it("should properly cancel all pending uploads", function(done) { dropzone.accept = function(file, done) { return done(); }; dropzone.options.parallelUploads = 1; dropzone.addFile(getMockFile()); dropzone.addFile(getMockFile()); return setTimeout(function() { dropzone.getUploadingFiles().length.should.equal(1); dropzone.getQueuedFiles().length.should.equal(1); dropzone.files.length.should.equal(2); sinon.spy(requests[0], "abort"); requests[0].abort.callCount.should.equal(0); dropzone.disable(); requests[0].abort.callCount.should.equal(1); dropzone.getUploadingFiles().length.should.equal(0); dropzone.getQueuedFiles().length.should.equal(0); dropzone.files.length.should.equal(2); dropzone.files[0].status.should.equal(Dropzone.CANCELED); dropzone.files[1].status.should.equal(Dropzone.CANCELED); return done(); }, 10); }); }); describe(".destroy()", function() { it("should properly cancel all pending uploads and remove all file references", function(done) { dropzone.accept = function(file, done) { return done(); }; dropzone.options.parallelUploads = 1; dropzone.addFile(getMockFile()); dropzone.addFile(getMockFile()); return setTimeout(function() { dropzone.getUploadingFiles().length.should.equal(1); dropzone.getQueuedFiles().length.should.equal(1); dropzone.files.length.should.equal(2); sinon.spy(dropzone, "disable"); dropzone.destroy(); dropzone.disable.callCount.should.equal(1); element.should.not.have.property("dropzone"); return done(); }, 10); }); it("should be able to create instance of dropzone on the same element after destroy", function() { dropzone.destroy(); return (function() { return new Dropzone(element, { maxFilesize: 4, url: "url", acceptedMimeTypes: "audio/*,image/png", uploadprogress: function() {} }); }).should.not["throw"](Error); }); return it("should remove itself from Dropzone.instances", function() { (Dropzone.instances.indexOf(dropzone) !== -1).should.be.ok; dropzone.destroy(); return (Dropzone.instances.indexOf(dropzone) === -1).should.be.ok; }); }); describe(".filesize()", function() { it("should convert to KiloBytes, etc..", function() { dropzone.options.filesizeBase.should.eql(1000); dropzone.filesize(2 * 1000 * 1000).should.eql("<strong>2</strong> MB"); dropzone.filesize(2 * 1024 * 1024).should.eql("<strong>2.1</strong> MB"); dropzone.filesize(2 * 1000 * 1000 * 1000).should.eql("<strong>2</strong> GB"); dropzone.filesize(2 * 1024 * 1024 * 1024).should.eql("<strong>2.1</strong> GB"); dropzone.filesize(2.5111 * 1000 * 1000 * 1000).should.eql("<strong>2.5</strong> GB"); dropzone.filesize(1.1 * 1000).should.eql("<strong>1.1</strong> KB"); return dropzone.filesize(999 * 1000).should.eql("<strong>1</strong> MB"); }); return it("should convert to KibiBytes, etc.. when the filesizeBase is changed to 1024", function() { dropzone.options.filesizeBase = 1024; dropzone.filesize(2 * 1024 * 1024).should.eql("<strong>2</strong> MB"); return dropzone.filesize(2 * 1000 * 1000).should.eql("<strong>1.9</strong> MB"); }); }); describe("._updateMaxFilesReachedClass()", function() { it("should properly add the dz-max-files-reached class", function() { dropzone.getAcceptedFiles = function() { return { length: 10 }; }; dropzone.options.maxFiles = 10; dropzone.element.classList.contains("dz-max-files-reached").should.not.be.ok; dropzone._updateMaxFilesReachedClass(); return dropzone.element.classList.contains("dz-max-files-reached").should.be.ok; }); it("should fire the 'maxfilesreached' event when appropriate", function() { var spy; spy = sinon.spy(); dropzone.on("maxfilesreached", function() { return spy(); }); dropzone.getAcceptedFiles = function() { return { length: 9 }; }; dropzone.options.maxFiles = 10; dropzone._updateMaxFilesReachedClass(); spy.should.not.have.been.called; dropzone.getAcceptedFiles = function() { return { length: 10 }; }; dropzone._updateMaxFilesReachedClass(); spy.should.have.been.called; dropzone.getAcceptedFiles = function() { return { length: 11 }; }; dropzone._updateMaxFilesReachedClass(); return spy.should.have.been.calledOnce; }); return it("should properly remove the dz-max-files-reached class", function() { dropzone.getAcceptedFiles = function() { return { length: 10 }; }; dropzone.options.maxFiles = 10; dropzone.element.classList.contains("dz-max-files-reached").should.not.be.ok; dropzone._updateMaxFilesReachedClass(); dropzone.element.classList.contains("dz-max-files-reached").should.be.ok; dropzone.getAcceptedFiles = function() { return { length: 9 }; }; dropzone._updateMaxFilesReachedClass(); return dropzone.element.classList.contains("dz-max-files-reached").should.not.be.ok; }); }); return describe("events", function() { return describe("progress updates", function() { return it("should properly emit a totaluploadprogress event", function(done) { var totalProgressExpectation, _called; dropzone.files = [ { size: 1990, accepted: true, status: Dropzone.UPLOADING, upload: { progress: 20, total: 2000, bytesSent: 400 } }, { size: 1990, accepted: true, status: Dropzone.UPLOADING, upload: { progress: 10, total: 2000, bytesSent: 200 } } ]; _called = 0; dropzone.on("totaluploadprogress", function(progress) { progress.should.equal(totalProgressExpectation); if (++_called === 3) { return done(); } }); totalProgressExpectation = 15; dropzone.emit("uploadprogress", {}); totalProgressExpectation = 97.5; dropzone.files[0].upload.bytesSent = 2000; dropzone.files[1].upload.bytesSent = 1900; dropzone.emit("uploadprogress", {}); totalProgressExpectation = 100; dropzone.files[0].upload.bytesSent = 2000; dropzone.files[1].upload.bytesSent = 2000; dropzone.emit("uploadprogress", {}); dropzone.files[0].status = Dropzone.CANCELED; return dropzone.files[1].status = Dropzone.CANCELED; }); }); }); }); describe("helper function", function() { var dropzone, element; element = null; dropzone = null; beforeEach(function() { element = Dropzone.createElement("<div></div>"); return dropzone = new Dropzone(element, { url: "url" }); }); describe("getExistingFallback()", function() { it("should return undefined if no fallback", function() { return expect(dropzone.getExistingFallback()).to.equal(void 0); }); it("should only return the fallback element if it contains exactly fallback", function() { element.appendChild(Dropzone.createElement("<form class=\"fallbacks\"></form>")); element.appendChild(Dropzone.createElement("<form class=\"sfallback\"></form>")); return expect(dropzone.getExistingFallback()).to.equal(void 0); }); it("should return divs as fallback", function() { var fallback; fallback = Dropzone.createElement("<form class=\" abc fallback test \"></form>"); element.appendChild(fallback); return fallback.should.equal(dropzone.getExistingFallback()); }); return it("should return forms as fallback", function() { var fallback; fallback = Dropzone.createElement("<div class=\" abc fallback test \"></div>"); element.appendChild(fallback); return fallback.should.equal(dropzone.getExistingFallback()); }); }); describe("getFallbackForm()", function() { it("should use the paramName without [0] if uploadMultiple is false", function() { var fallback, fileInput; dropzone.options.uploadMultiple = false; dropzone.options.paramName = "myFile"; fallback = dropzone.getFallbackForm(); fileInput = fallback.querySelector("input[type=file]"); return fileInput.name.should.equal("myFile"); }); return it("should properly add [0] to the file name if uploadMultiple is true", function() { var fallback, fileInput; dropzone.options.uploadMultiple = true; dropzone.options.paramName = "myFile"; fallback = dropzone.getFallbackForm(); fileInput = fallback.querySelector("input[type=file]"); return fileInput.name.should.equal("myFile[0]"); }); }); describe("getAcceptedFiles() / getRejectedFiles()", function() { var mock1, mock2, mock3, mock4; mock1 = mock2 = mock3 = mock4 = null; beforeEach(function() { mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); mock4 = getMockFile(); dropzone.options.accept = function(file, done) { if (file === mock1 || file === mock3) { return done(); } else { return done("error"); } }; dropzone.addFile(mock1); dropzone.addFile(mock2); dropzone.addFile(mock3); return dropzone.addFile(mock4); }); it("getAcceptedFiles() should only return accepted files", function() { return dropzone.getAcceptedFiles().should.eql([mock1, mock3]); }); return it("getRejectedFiles() should only return rejected files", function() { return dropzone.getRejectedFiles().should.eql([mock2, mock4]); }); }); describe("getQueuedFiles()", function() { return it("should return all files with the status Dropzone.QUEUED", function() { var mock1, mock2, mock3, mock4; mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); mock4 = getMockFile(); dropzone.options.accept = function(file, done) { return file.done = done; }; dropzone.addFile(mock1); dropzone.addFile(mock2); dropzone.addFile(mock3); dropzone.addFile(mock4); dropzone.getQueuedFiles().should.eql([]); mock1.done(); mock3.done(); dropzone.getQueuedFiles().should.eql([mock1, mock3]); mock1.status.should.equal(Dropzone.QUEUED); mock3.status.should.equal(Dropzone.QUEUED); mock2.status.should.equal(Dropzone.ADDED); return mock4.status.should.equal(Dropzone.ADDED); }); }); describe("getUploadingFiles()", function() { return it("should return all files with the status Dropzone.UPLOADING", function(done) { var mock1, mock2, mock3, mock4; mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); mock4 = getMockFile(); dropzone.options.accept = function(file, _done) { return file.done = _done; }; dropzone.uploadFile = function() {}; dropzone.addFile(mock1); dropzone.addFile(mock2); dropzone.addFile(mock3); dropzone.addFile(mock4); dropzone.getUploadingFiles().should.eql([]); mock1.done(); mock3.done(); return setTimeout((function() { dropzone.getUploadingFiles().should.eql([mock1, mock3]); mock1.status.should.equal(Dropzone.UPLOADING); mock3.status.should.equal(Dropzone.UPLOADING); mock2.status.should.equal(Dropzone.ADDED); mock4.status.should.equal(Dropzone.ADDED); return done(); }), 10); }); }); describe("getActiveFiles()", function() { return it("should return all files with the status Dropzone.UPLOADING or Dropzone.QUEUED", function(done) { var mock1, mock2, mock3, mock4; mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); mock4 = getMockFile(); dropzone.options.accept = function(file, _done) { return file.done = _done; }; dropzone.uploadFile = function() {}; dropzone.options.parallelUploads = 2; dropzone.addFile(mock1); dropzone.addFile(mock2); dropzone.addFile(mock3); dropzone.addFile(mock4); dropzone.getActiveFiles().should.eql([]); mock1.done(); mock3.done(); mock4.done(); return setTimeout((function() { dropzone.getActiveFiles().should.eql([mock1, mock3, mock4]); mock1.status.should.equal(Dropzone.UPLOADING); mock3.status.should.equal(Dropzone.UPLOADING); mock2.status.should.equal(Dropzone.ADDED); mock4.status.should.equal(Dropzone.QUEUED); return done(); }), 10); }); }); return describe("getFilesWithStatus()", function() { return it("should return all files with provided status", function() { var mock1, mock2, mock3, mock4; mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); mock4 = getMockFile(); dropzone.options.accept = function(file, _done) { return file.done = _done; }; dropzone.uploadFile = function() {}; dropzone.addFile(mock1); dropzone.addFile(mock2); dropzone.addFile(mock3); dropzone.addFile(mock4); dropzone.getFilesWithStatus(Dropzone.ADDED).should.eql([mock1, mock2, mock3, mock4]); mock1.status = Dropzone.UPLOADING; mock3.status = Dropzone.QUEUED; mock4.status = Dropzone.QUEUED; dropzone.getFilesWithStatus(Dropzone.ADDED).should.eql([mock2]); dropzone.getFilesWithStatus(Dropzone.UPLOADING).should.eql([mock1]); return dropzone.getFilesWithStatus(Dropzone.QUEUED).should.eql([mock3, mock4]); }); }); }); return describe("file handling", function() { var dropzone, mockFile; mockFile = null; dropzone = null; beforeEach(function() { var element; mockFile = getMockFile(); element = Dropzone.createElement("<div></div>"); return dropzone = new Dropzone(element, { url: "/the/url" }); }); afterEach(function() { return dropzone.destroy(); }); describe("addFile()", function() { it("should properly set the status of the file", function() { var doneFunction; doneFunction = null; dropzone.accept = function(file, done) { return doneFunction = done; }; dropzone.processFile = function() {}; dropzone.uploadFile = function() {}; dropzone.addFile(mockFile); mockFile.status.should.eql(Dropzone.ADDED); doneFunction(); mockFile.status.should.eql(Dropzone.QUEUED); mockFile = getMockFile(); dropzone.addFile(mockFile); mockFile.status.should.eql(Dropzone.ADDED); doneFunction("error"); return mockFile.status.should.eql(Dropzone.ERROR); }); it("should properly set the status of the file if autoProcessQueue is false and not call processQueue", function(done) { var doneFunction; doneFunction = null; dropzone.options.autoProcessQueue = false; dropzone.accept = function(file, done) { return doneFunction = done; }; dropzone.processFile = function() {}; dropzone.uploadFile = function() {}; dropzone.addFile(mockFile); sinon.stub(dropzone, "processQueue"); mockFile.status.should.eql(Dropzone.ADDED); doneFunction(); mockFile.status.should.eql(Dropzone.QUEUED); dropzone.processQueue.callCount.should.equal(0); return setTimeout((function() { dropzone.processQueue.callCount.should.equal(0); return done(); }), 10); }); it("should not add the file to the queue if autoQueue is false", function() { var doneFunction; doneFunction = null; dropzone.options.autoQueue = false; dropzone.accept = function(file, done) { return doneFunction = done; }; dropzone.processFile = function() {}; dropzone.uploadFile = function() {}; dropzone.addFile(mockFile); mockFile.status.should.eql(Dropzone.ADDED); doneFunction(); return mockFile.status.should.eql(Dropzone.ADDED); }); it("should create a remove link if configured to do so", function() { dropzone.options.addRemoveLinks = true; dropzone.processFile = function() {}; dropzone.uploadFile = function() {}; sinon.stub(dropzone, "processQueue"); dropzone.addFile(mockFile); return dropzone.files[0].previewElement.querySelector("a[data-dz-remove].dz-remove").should.be.ok; }); it("should attach an event handler to data-dz-remove links", function() { var event, file, removeLink1, removeLink2; dropzone.options.previewTemplate = "<div class=\"dz-preview dz-file-preview\">\n <div class=\"dz-details\">\n <div class=\"dz-filename\"><span data-dz-name></span></div>\n <div class=\"dz-size\" data-dz-size></div>\n <img data-dz-thumbnail />\n </div>\n <div class=\"dz-progress\"><span class=\"dz-upload\" data-dz-uploadprogress></span></div>\n <div class=\"dz-success-mark\"><span>✔</span></div>\n <div class=\"dz-error-mark\"><span>✘</span></div>\n <div class=\"dz-error-message\"><span data-dz-errormessage></span></div>\n <a class=\"link1\" data-dz-remove></a>\n <a class=\"link2\" data-dz-remove></a>\n</div>"; sinon.stub(dropzone, "processQueue"); dropzone.addFile(mockFile); file = dropzone.files[0]; removeLink1 = file.previewElement.querySelector("a[data-dz-remove].link1"); removeLink2 = file.previewElement.querySelector("a[data-dz-remove].link2"); sinon.stub(dropzone, "removeFile"); event = document.createEvent("HTMLEvents"); event.initEvent("click", true, true); removeLink1.dispatchEvent(event); dropzone.removeFile.callCount.should.eql(1); event = document.createEvent("HTMLEvents"); event.initEvent("click", true, true); removeLink2.dispatchEvent(event); return dropzone.removeFile.callCount.should.eql(2); }); return describe("thumbnails", function() { it("should properly queue the thumbnail creation", function(done) { var ct_callback, ct_file, doneFunction, mock1, mock2, mock3; doneFunction = null; dropzone.accept = function(file, done) { return doneFunction = done; }; dropzone.processFile = function() {}; dropzone.uploadFile = function() {}; mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); mock1.type = "image/jpg"; mock2.type = "image/jpg"; mock3.type = "image/jpg"; dropzone.on("thumbnail", function() { return console.log("HII"); }); ct_file = ct_callback = null; dropzone.createThumbnail = function(file, callback) { ct_file = file; return ct_callback = callback; }; sinon.spy(dropzone, "createThumbnail"); dropzone.addFile(mock1); dropzone.addFile(mock2); dropzone.addFile(mock3); dropzone.files.length.should.eql(3); return setTimeout((function() { dropzone.createThumbnail.callCount.should.eql(1); mock1.should.equal(ct_file); ct_callback(); dropzone.createThumbnail.callCount.should.eql(2); mock2.should.equal(ct_file); ct_callback(); dropzone.createThumbnail.callCount.should.eql(3); mock3.should.equal(ct_file); return done(); }), 10); }); return describe("when file is SVG", function() { return it("should use the SVG image itself", function(done) { var blob, createBlob; createBlob = function(data, type) { var BlobBuilder, builder, e; try { return new Blob([data], { type: type }); } catch (_error) { e = _error; BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder; builder = new BlobBuilder(); builder.append(data.buffer || data); return builder.getBlob(type); } }; blob = createBlob('foo', 'image/svg+xml'); dropzone.on("thumbnail", function(file, dataURI) { var fileReader; file.should.equal(blob); fileReader = new FileReader; fileReader.onload = function() { fileReader.result.should.equal(dataURI); return done(); }; return fileReader.readAsDataURL(file); }); return dropzone.createThumbnail(blob); }); }); }); }); describe("enqueueFile()", function() { it("should be wrapped by enqueueFiles()", function() { var mock1, mock2, mock3; sinon.stub(dropzone, "enqueueFile"); mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); dropzone.enqueueFiles([mock1, mock2, mock3]); dropzone.enqueueFile.callCount.should.equal(3); dropzone.enqueueFile.args[0][0].should.equal(mock1); dropzone.enqueueFile.args[1][0].should.equal(mock2); return dropzone.enqueueFile.args[2][0].should.equal(mock3); }); it("should fail if the file has already been processed", function() { mockFile.status = Dropzone.ERROR; expect((function() { return dropzone.enqueueFile(mockFile); })).to["throw"]("This file can't be queued because it has already been processed or was rejected."); mockFile.status = Dropzone.COMPLETE; expect((function() { return dropzone.enqueueFile(mockFile); })).to["throw"]("This file can't be queued because it has already been processed or was rejected."); mockFile.status = Dropzone.UPLOADING; return expect((function() { return dropzone.enqueueFile(mockFile); })).to["throw"]("This file can't be queued because it has already been processed or was rejected."); }); return it("should set the status to QUEUED and call processQueue asynchronously if everything's ok", function(done) { mockFile.status = Dropzone.ADDED; sinon.stub(dropzone, "processQueue"); dropzone.processQueue.callCount.should.equal(0); dropzone.enqueueFile(mockFile); mockFile.status.should.equal(Dropzone.QUEUED); dropzone.processQueue.callCount.should.equal(0); return setTimeout(function() { dropzone.processQueue.callCount.should.equal(1); return done(); }, 10); }); }); describe("uploadFiles()", function() { var requests; requests = null; beforeEach(function() { requests = []; return xhr.onCreate = function(xhr) { return requests.push(xhr); }; }); afterEach(function() { return xhr.restore(); }); it("should be wrapped by uploadFile()", function() { sinon.stub(dropzone, "uploadFiles"); dropzone.uploadFile(mockFile); dropzone.uploadFiles.callCount.should.equal(1); return dropzone.uploadFiles.calledWith([mockFile]).should.be.ok; }); it("should use url options if strings", function(done) { dropzone.addFile(mockFile); return setTimeout(function() { expect(requests.length).to.equal(1); expect(requests[0].url).to.equal(dropzone.options.url); expect(requests[0].method).to.equal(dropzone.options.method); return done(); }, 10); }); it("should call url options if functions", function(done) { var method, url; method = "PUT"; url = "/custom/upload/url"; dropzone.options.method = sinon.stub().returns(method); dropzone.options.url = sinon.stub().returns(url); dropzone.addFile(mockFile); return setTimeout(function() { dropzone.options.method.callCount.should.equal(1); dropzone.options.url.callCount.should.equal(1); sinon.assert.calledWith(dropzone.options.method, [mockFile]); sinon.assert.calledWith(dropzone.options.url, [mockFile]); expect(requests.length).to.equal(1); expect(requests[0].url).to.equal(url); expect(requests[0].method).to.equal(method); return done(); }, 10); }); it("should ignore the onreadystate callback if readyState != 4", function(done) { dropzone.addFile(mockFile); return setTimeout(function() { mockFile.status.should.eql(Dropzone.UPLOADING); requests[0].status = 200; requests[0].readyState = 3; requests[0].onload(); mockFile.status.should.eql(Dropzone.UPLOADING); requests[0].readyState = 4; requests[0].onload(); mockFile.status.should.eql(Dropzone.SUCCESS); return done(); }, 10); }); it("should emit error and errormultiple when response was not OK", function(done) { var complete, completemultiple, error, errormultiple; dropzone.options.uploadMultiple = true; error = false; errormultiple = false; complete = false; completemultiple = false; dropzone.on("error", function() { return error = true; }); dropzone.on("errormultiple", function() { return errormultiple = true; }); dropzone.on("complete", function() { return complete = true; }); dropzone.on("completemultiple", function() { return completemultiple = true; }); dropzone.addFile(mockFile); return setTimeout(function() { mockFile.status.should.eql(Dropzone.UPLOADING); requests[0].status = 400; requests[0].readyState = 4; requests[0].onload(); expect((((true === error && error === errormultiple) && errormultiple === complete) && complete === completemultiple)).to.be.ok; return done(); }, 10); }); it("should include hidden files in the form and unchecked checkboxes and radiobuttons should be excluded", function(done) { var element, formData, mock1; element = Dropzone.createElement("<form action=\"/the/url\">\n <input type=\"hidden\" name=\"test\" value=\"hidden\" />\n <input type=\"checkbox\" name=\"unchecked\" value=\"1\" />\n <input type=\"checkbox\" name=\"checked\" value=\"value1\" checked=\"checked\" />\n <input type=\"radio\" value=\"radiovalue1\" name=\"radio1\" />\n <input type=\"radio\" value=\"radiovalue2\" name=\"radio1\" checked=\"checked\" />\n <select name=\"select\"><option value=\"1\">1</option><option value=\"2\" selected>2</option></select>\n</form>"); dropzone = new Dropzone(element, { url: "/the/url" }); formData = null; dropzone.on("sending", function(file, xhr, tformData) { formData = tformData; return sinon.spy(tformData, "append"); }); mock1 = getMockFile(); dropzone.addFile(mock1); return setTimeout(function() { formData.append.callCount.should.equal(5); formData.append.args[0][0].should.eql("test"); formData.append.args[0][1].should.eql("hidden"); formData.append.args[1][0].should.eql("checked"); formData.append.args[1][1].should.eql("value1"); formData.append.args[2][0].should.eql("radio1"); formData.append.args[2][1].should.eql("radiovalue2"); formData.append.args[3][0].should.eql("select"); formData.append.args[3][1].should.eql("2"); formData.append.args[4][0].should.eql("file"); formData.append.args[4][1].should.equal(mock1); return done(); }, 10); }); it("should all values of a select that has the multiple attribute", function(done) { var element, formData, mock1; element = Dropzone.createElement("<form action=\"/the/url\">\n <select name=\"select\" multiple>\n <option value=\"value1\">1</option>\n <option value=\"value2\" selected>2</option>\n <option value=\"value3\">3</option>\n <option value=\"value4\" selected>4</option>\n </select>\n</form>"); dropzone = new Dropzone(element, { url: "/the/url" }); formData = null; dropzone.on("sending", function(file, xhr, tformData) { formData = tformData; return sinon.spy(tformData, "append"); }); mock1 = getMockFile(); dropzone.addFile(mock1); return setTimeout(function() { formData.append.callCount.should.equal(3); formData.append.args[0][0].should.eql("select"); formData.append.args[0][1].should.eql("value2"); formData.append.args[1][0].should.eql("select"); formData.append.args[1][1].should.eql("value4"); formData.append.args[2][0].should.eql("file"); formData.append.args[2][1].should.equal(mock1); return done(); }, 10); }); describe("settings()", function() { it("should correctly set `withCredentials` on the xhr object", function() { dropzone.uploadFile(mockFile); requests.length.should.eql(1); requests[0].withCredentials.should.eql(false); dropzone.options.withCredentials = true; dropzone.uploadFile(mockFile); requests.length.should.eql(2); return requests[1].withCredentials.should.eql(true); }); it("should correctly set headers on the xhr object", function() { dropzone.options.headers = { "Foo-Header": "foobar" }; dropzone.uploadFile(mockFile); requests[0].requestHeaders["Foo-Header"].should.eql('foobar'); return (requests[0].requestHeaders["Accept"] === void 0).should.be["false"]; }); it("should correctly override headers on the xhr object", function() { dropzone.options.overrideDefaultHeaders = true; dropzone.options.headers = { "Foo-Header": "foobar" }; dropzone.uploadFile(mockFile); return (requests[0].requestHeaders["Accept"] === void 0).should.be["true"]; }); it("should properly use the paramName without [n] as file upload if uploadMultiple is false", function(done) { var formData, mock1, mock2, sendingCount; dropzone.options.uploadMultiple = false; dropzone.options.paramName = "myName"; formData = []; sendingCount = 0; dropzone.on("sending", function(files, xhr, tformData) { sendingCount++; formData.push(tformData); return sinon.spy(tformData, "append"); }); mock1 = getMockFile(); mock2 = getMockFile(); dropzone.addFile(mock1); dropzone.addFile(mock2); return setTimeout(function() { sendingCount.should.equal(2); formData.length.should.equal(2); formData[0].append.callCount.should.equal(1); formData[1].append.callCount.should.equal(1); formData[0].append.args[0][0].should.eql("myName"); formData[0].append.args[0][0].should.eql("myName"); return done(); }, 10); }); return it("should properly use the paramName with [n] as file upload if uploadMultiple is true", function(done) { var formData, mock1, mock2, sendingCount, sendingMultipleCount; dropzone.options.uploadMultiple = true; dropzone.options.paramName = "myName"; formData = null; sendingMultipleCount = 0; sendingCount = 0; dropzone.on("sending", function(file, xhr, tformData) { return sendingCount++; }); dropzone.on("sendingmultiple", function(files, xhr, tformData) { sendingMultipleCount++; formData = tformData; return sinon.spy(tformData, "append"); }); mock1 = getMockFile(); mock2 = getMockFile(); dropzone.addFile(mock1); dropzone.addFile(mock2); return setTimeout(function() { sendingCount.should.equal(2); sendingMultipleCount.should.equal(1); dropzone.uploadFiles([mock1, mock2]); formData.append.callCount.should.equal(2); formData.append.args[0][0].should.eql("myName[0]"); formData.append.args[1][0].should.eql("myName[1]"); return done(); }, 10); }); }); return describe("should properly set status of file", function() { return it("should correctly set `withCredentials` on the xhr object", function(done) { dropzone.addFile(mockFile); return setTimeout(function() { mockFile.status.should.eql(Dropzone.UPLOADING); requests.length.should.equal(1); requests[0].status = 400; requests[0].readyState = 4; requests[0].onload(); mockFile.status.should.eql(Dropzone.ERROR); mockFile = getMockFile(); dropzone.addFile(mockFile); return setTimeout(function() { mockFile.status.should.eql(Dropzone.UPLOADING); requests.length.should.equal(2); requests[1].status = 200; requests[1].readyState = 4; requests[1].onload(); mockFile.status.should.eql(Dropzone.SUCCESS); return done(); }, 10); }, 10); }); }); }); return describe("complete file", function() { return it("should properly emit the queuecomplete event when the complete queue is finished", function(done) { var completedFiles, mock1, mock2, mock3; mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); mock1.status = Dropzone.ADDED; mock2.status = Dropzone.ADDED; mock3.status = Dropzone.ADDED; mock1.name = "mock1"; mock2.name = "mock2"; mock3.name = "mock3"; dropzone.uploadFiles = function(files) { return setTimeout(((function(_this) { return function() { return _this._finished(files, null, null); }; })(this)), 1); }; completedFiles = 0; dropzone.on("complete", function(file) { return completedFiles++; }); dropzone.on("queuecomplete", function() { completedFiles.should.equal(3); return done(); }); dropzone.addFile(mock1); dropzone.addFile(mock2); return dropzone.addFile(mock3); }); }); }); }); }).call(this);
Java
answer = sum [1..100] ^ 2 - foldl (\x y -> y^2 + x) 0 [1..100]
Java
/** * generated by Xtext */ package dk.itu.smdp.group2.ui.outline; import org.eclipse.xtext.ui.editor.outline.impl.DefaultOutlineTreeProvider; /** * Customization of the default outline structure. * * see http://www.eclipse.org/Xtext/documentation.html#outline */ @SuppressWarnings("all") public class QuestionaireOutlineTreeProvider extends DefaultOutlineTreeProvider { }
Java
<?php /* * ghz.me url shortener * when a long url hz. * * (c) 2014 Sam Thompson <contact@samt.us> * License: MIT */ define('ROOT_PATH', __DIR__ . '/'); require ROOT_PATH . 'loader.php'; $app = new Ghz\App(); // Handle our two cases: // - Redirect (when requestiong anything except BASEPATH) // - Save URL when posted here. $app->doRedirect(); $app->savePostedUrl(); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>GHz url shortener</title> <link rel="stylesheet" href="_assets/style.css"> <?php if (defined('GA_TRACKING')) : ?> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '<?php echo GA_TRACKING; ?>', 'auto'); ga('send', 'pageview'); </script> <?php endif; ?> </head> <body> <div class="main"> <h1> <a href="/">Ghz</a> </h1> <p class="subhead">url shortener</p> <form action="" method="post"> <div class="error<?php if ($app->isFailure()) : ?> visible<?php endif; ?>"> please enter a valid url </div> <div class="success<?php if ($app->isSuccess()) : ?> visible<?php endif; ?>"> created! </div> <div> <input placeholder="paste or enter a url and press enter" name="url" type="text" value="<?php echo $app->getGeneratedUrl(); ?>"> </div> </form> </div> <div class="bottom-left"> &copy; <?php echo date('Y'); ?> Ghz.me </div> <div class="bottom-right"> &nbsp; </div> <!-- fork me banner --> <a href="https://github.com/samt/ghz"> <img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"> </a> <script type="text/javascript" src="_assets/jquery-2.1.1.min.js"></script> <script type="text/javascript" src="_assets/main.js"></script> </body> </html>
Java
<!DOCTYPE html> <html> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> <title>module Rack::Mime - 'Rack Documentation'</title> <link type="text/css" media="screen" href="../rdoc.css" rel="stylesheet"> <script type="text/javascript"> var rdoc_rel_prefix = "../"; </script> <script type="text/javascript" charset="utf-8" src="../js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="../js/navigation.js"></script> <script type="text/javascript" charset="utf-8" src="../js/search_index.js"></script> <script type="text/javascript" charset="utf-8" src="../js/search.js"></script> <script type="text/javascript" charset="utf-8" src="../js/searcher.js"></script> <script type="text/javascript" charset="utf-8" src="../js/darkfish.js"></script> <body id="top" class="module"> <nav id="metadata"> <nav id="home-section" class="section"> <h3 class="section-header"> <a href="../index.html">Home</a> <a href="../table_of_contents.html#classes">Classes</a> <a href="../table_of_contents.html#methods">Methods</a> </h3> </nav> <nav id="search-section" class="section project-section" class="initially-hidden"> <form action="#" method="get" accept-charset="utf-8"> <h3 class="section-header"> <input type="text" name="search" placeholder="Search" id="search-field" title="Type to search, Up and Down to navigate, Enter to load"> </h3> </form> <ul id="search-results" class="initially-hidden"></ul> </nav> <div id="file-metadata"> <nav id="file-list-section" class="section"> <h3 class="section-header">Defined In</h3> <ul> <li>lib/rack/mime.rb </ul> </nav> </div> <div id="class-metadata"> <!-- Method Quickref --> <nav id="method-list-section" class="section"> <h3 class="section-header">Methods</h3> <ul class="link-list"> <li><a href="#method-c-mime_type">::mime_type</a> </ul> </nav> </div> <div id="project-metadata"> <nav id="fileindex-section" class="section project-section"> <h3 class="section-header">Pages</h3> <ul> <li class="file"><a href="../KNOWN-ISSUES.html">KNOWN-ISSUES</a> <li class="file"><a href="../README_rdoc.html">README</a> <li class="file"><a href="../SPEC.html">SPEC</a> </ul> </nav> <nav id="classindex-section" class="section project-section"> <h3 class="section-header">Class and Module Index</h3> <ul class="link-list"> <li><a href="../Rack.html">Rack</a> <li><a href="../Rack/Auth.html">Rack::Auth</a> <li><a href="../Rack/Auth/AbstractHandler.html">Rack::Auth::AbstractHandler</a> <li><a href="../Rack/Auth/AbstractRequest.html">Rack::Auth::AbstractRequest</a> <li><a href="../Rack/Auth/Basic.html">Rack::Auth::Basic</a> <li><a href="../Rack/Auth/Basic/Request.html">Rack::Auth::Basic::Request</a> <li><a href="../Rack/Auth/Digest.html">Rack::Auth::Digest</a> <li><a href="../Rack/Auth/Digest/MD5.html">Rack::Auth::Digest::MD5</a> <li><a href="../Rack/Auth/Digest/Nonce.html">Rack::Auth::Digest::Nonce</a> <li><a href="../Rack/Auth/Digest/Params.html">Rack::Auth::Digest::Params</a> <li><a href="../Rack/Auth/Digest/Request.html">Rack::Auth::Digest::Request</a> <li><a href="../Rack/BodyProxy.html">Rack::BodyProxy</a> <li><a href="../Rack/Builder.html">Rack::Builder</a> <li><a href="../Rack/Cascade.html">Rack::Cascade</a> <li><a href="../Rack/Chunked.html">Rack::Chunked</a> <li><a href="../Rack/Chunked/Body.html">Rack::Chunked::Body</a> <li><a href="../Rack/CommonLogger.html">Rack::CommonLogger</a> <li><a href="../Rack/ConditionalGet.html">Rack::ConditionalGet</a> <li><a href="../Rack/Config.html">Rack::Config</a> <li><a href="../Rack/ContentLength.html">Rack::ContentLength</a> <li><a href="../Rack/ContentType.html">Rack::ContentType</a> <li><a href="../Rack/Deflater.html">Rack::Deflater</a> <li><a href="../Rack/Deflater/DeflateStream.html">Rack::Deflater::DeflateStream</a> <li><a href="../Rack/Deflater/GzipStream.html">Rack::Deflater::GzipStream</a> <li><a href="../Rack/Directory.html">Rack::Directory</a> <li><a href="../Rack/ETag.html">Rack::ETag</a> <li><a href="../Rack/File.html">Rack::File</a> <li><a href="../Rack/ForwardRequest.html">Rack::ForwardRequest</a> <li><a href="../Rack/Handler.html">Rack::Handler</a> <li><a href="../Rack/Handler/CGI.html">Rack::Handler::CGI</a> <li><a href="../Rack/Handler/EventedMongrel.html">Rack::Handler::EventedMongrel</a> <li><a href="../Rack/Handler/FastCGI.html">Rack::Handler::FastCGI</a> <li><a href="../Rack/Handler/LSWS.html">Rack::Handler::LSWS</a> <li><a href="../Rack/Handler/Mongrel.html">Rack::Handler::Mongrel</a> <li><a href="../Rack/Handler/SCGI.html">Rack::Handler::SCGI</a> <li><a href="../Rack/Handler/SwiftipliedMongrel.html">Rack::Handler::SwiftipliedMongrel</a> <li><a href="../Rack/Handler/Thin.html">Rack::Handler::Thin</a> <li><a href="../Rack/Handler/WEBrick.html">Rack::Handler::WEBrick</a> <li><a href="../Rack/Head.html">Rack::Head</a> <li><a href="../Rack/Lint.html">Rack::Lint</a> <li><a href="../Rack/Lobster.html">Rack::Lobster</a> <li><a href="../Rack/Lock.html">Rack::Lock</a> <li><a href="../Rack/Logger.html">Rack::Logger</a> <li><a href="../Rack/MethodOverride.html">Rack::MethodOverride</a> <li><a href="../Rack/Mime.html">Rack::Mime</a> <li><a href="../Rack/MockRequest.html">Rack::MockRequest</a> <li><a href="../Rack/MockRequest/FatalWarner.html">Rack::MockRequest::FatalWarner</a> <li><a href="../Rack/MockRequest/FatalWarning.html">Rack::MockRequest::FatalWarning</a> <li><a href="../Rack/MockResponse.html">Rack::MockResponse</a> <li><a href="../Rack/Multipart.html">Rack::Multipart</a> <li><a href="../Rack/Multipart/Generator.html">Rack::Multipart::Generator</a> <li><a href="../Rack/Multipart/Parser.html">Rack::Multipart::Parser</a> <li><a href="../Rack/Multipart/UploadedFile.html">Rack::Multipart::UploadedFile</a> <li><a href="../Rack/NullLogger.html">Rack::NullLogger</a> <li><a href="../Rack/Recursive.html">Rack::Recursive</a> <li><a href="../Rack/Reloader.html">Rack::Reloader</a> <li><a href="../Rack/Reloader/Stat.html">Rack::Reloader::Stat</a> <li><a href="../Rack/Request.html">Rack::Request</a> <li><a href="../Rack/Response.html">Rack::Response</a> <li><a href="../Rack/Response/Helpers.html">Rack::Response::Helpers</a> <li><a href="../Rack/RewindableInput.html">Rack::RewindableInput</a> <li><a href="../Rack/RewindableInput/Tempfile.html">Rack::RewindableInput::Tempfile</a> <li><a href="../Rack/Runtime.html">Rack::Runtime</a> <li><a href="../Rack/Sendfile.html">Rack::Sendfile</a> <li><a href="../Rack/Server.html">Rack::Server</a> <li><a href="../Rack/Server/Options.html">Rack::Server::Options</a> <li><a href="../Rack/Session.html">Rack::Session</a> <li><a href="../Rack/Session/Abstract.html">Rack::Session::Abstract</a> <li><a href="../Rack/Session/Abstract/ID.html">Rack::Session::Abstract::ID</a> <li><a href="../Rack/Session/Abstract/SessionHash.html">Rack::Session::Abstract::SessionHash</a> <li><a href="../Rack/Session/Cookie.html">Rack::Session::Cookie</a> <li><a href="../Rack/Session/Cookie/Base64.html">Rack::Session::Cookie::Base64</a> <li><a href="../Rack/Session/Cookie/Base64/Marshal.html">Rack::Session::Cookie::Base64::Marshal</a> <li><a href="../Rack/Session/Cookie/Identity.html">Rack::Session::Cookie::Identity</a> <li><a href="../Rack/Session/Cookie/Reverse.html">Rack::Session::Cookie::Reverse</a> <li><a href="../Rack/Session/Memcache.html">Rack::Session::Memcache</a> <li><a href="../Rack/Session/Pool.html">Rack::Session::Pool</a> <li><a href="../Rack/ShowExceptions.html">Rack::ShowExceptions</a> <li><a href="../Rack/ShowStatus.html">Rack::ShowStatus</a> <li><a href="../Rack/Static.html">Rack::Static</a> <li><a href="../Rack/URLMap.html">Rack::URLMap</a> <li><a href="../Rack/Utils.html">Rack::Utils</a> <li><a href="../Rack/Utils/Context.html">Rack::Utils::Context</a> <li><a href="../Rack/Utils/HeaderHash.html">Rack::Utils::HeaderHash</a> <li><a href="../Rack/Multipart.html">Rack::Utils::Multipart</a> <li><a href="../FCGI.html">FCGI</a> <li><a href="../FCGI/Stream.html">FCGI::Stream</a> </ul> </nav> </div> </nav> <div id="documentation"> <h1 class="module">module Rack::Mime</h1> <div id="description" class="description"> </div><!-- description --> <section id="5Buntitled-5D" class="documentation-section"> <!-- Constants --> <section id="constants-list" class="section"> <h3 class="section-header">Constants</h3> <dl> <dt id="MIME_TYPES">MIME_TYPES <dd class="description"><p>List of most common mime-types, selected various sources according to their usefulness in a webserving scope for Ruby users.</p> <p>To amend this list with your local mime.types list you can use:</p> <pre class="ruby"><span class="ruby-identifier">require</span> <span class="ruby-string">'webrick/httputils'</span> <span class="ruby-identifier">list</span> = <span class="ruby-constant">WEBrick</span><span class="ruby-operator">::</span><span class="ruby-constant">HTTPUtils</span>.<span class="ruby-identifier">load_mime_types</span>(<span class="ruby-string">'/etc/mime.types'</span>) <span class="ruby-constant">Rack</span><span class="ruby-operator">::</span><span class="ruby-constant">Mime</span><span class="ruby-operator">::</span><span class="ruby-constant">MIME_TYPES</span>.<span class="ruby-identifier">merge!</span>(<span class="ruby-identifier">list</span>) </pre> <p>N.B. On Ubuntu the mime.types file does not include the leading period, so users may need to modify the data before merging into the hash.</p> <p>To add the list mongrel provides, use:</p> <pre class="ruby"><span class="ruby-identifier">require</span> <span class="ruby-string">'mongrel/handlers'</span> <span class="ruby-constant">Rack</span><span class="ruby-operator">::</span><span class="ruby-constant">Mime</span><span class="ruby-operator">::</span><span class="ruby-constant">MIME_TYPES</span>.<span class="ruby-identifier">merge!</span>(<span class="ruby-constant">Mongrel</span><span class="ruby-operator">::</span><span class="ruby-constant">DirHandler</span><span class="ruby-operator">::</span><span class="ruby-constant">MIME_TYPES</span>) </pre> </dl> </section> <!-- Methods --> <section id="public-class-5Buntitled-5D-method-details" class="method-section section"> <h3 class="section-header">Public Class Methods</h3> <div id="method-c-mime_type" class="method-detail "> <div class="method-heading"> <span class="method-name">mime_type</span><span class="method-args">(ext, fallback='application/octet-stream')</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <p>Returns String with mime type if found, otherwise use <code>fallback</code>. <code>ext</code> should be filename extension in the ‘.ext’ format that</p> <pre>File.extname(file) returns.</pre> <p><code>fallback</code> may be any object</p> <p>Also see the documentation for <a href="Mime.html#MIME_TYPES">MIME_TYPES</a></p> <p>Usage:</p> <pre>Rack::Mime.mime_type('.foo')</pre> <p>This is a shortcut for:</p> <pre>Rack::Mime::MIME_TYPES.fetch('.foo', 'application/octet-stream')</pre> <div class="method-source-code" id="mime_type-source"> <pre><span class="ruby-comment"># File lib/rack/mime.rb, line 16</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">mime_type</span>(<span class="ruby-identifier">ext</span>, <span class="ruby-identifier">fallback</span>=<span class="ruby-string">'application/octet-stream'</span>) <span class="ruby-constant">MIME_TYPES</span>.<span class="ruby-identifier">fetch</span>(<span class="ruby-identifier">ext</span>.<span class="ruby-identifier">to_s</span>.<span class="ruby-identifier">downcase</span>, <span class="ruby-identifier">fallback</span>) <span class="ruby-keyword">end</span></pre> </div><!-- mime_type-source --> </div> </div><!-- mime_type-method --> </section><!-- public-class-method-details --> </section><!-- 5Buntitled-5D --> </div><!-- documentation --> <footer id="validator-badges"> <p><a href="http://validator.w3.org/check/referer">[Validate]</a> <p>Generated by <a href="https://github.com/rdoc/rdoc">RDoc</a> 3.12. <p>Generated with the <a href="http://deveiate.org/projects/Darkfish-Rdoc/">Darkfish Rdoc Generator</a> 3. </footer>
Java
--- layout: page title: Middleton - Mcdaniel Wedding date: 2016-05-24 author: Larry Rios tags: weekly links, java status: published summary: Vestibulum ante ipsum primis in faucibus orci luctus et. banner: images/banner/leisure-02.jpg booking: startDate: 02/27/2019 endDate: 03/02/2019 ctyhocn: BROHSHX groupCode: MMW published: true --- Nam at metus eu metus porttitor facilisis interdum id massa. Nulla id diam nec eros fringilla consequat. Nam odio est, commodo sagittis massa ac, dapibus interdum velit. Fusce dignissim pulvinar magna, quis aliquet leo dignissim non. Etiam gravida ullamcorper condimentum. Etiam ut lobortis quam, eu efficitur ante. Etiam posuere vel lorem sed imperdiet. 1 Ut tempus lorem ut ultricies commodo 1 Curabitur eget orci eget diam sodales pretium vitae vitae quam 1 Quisque non metus congue, scelerisque mauris vitae, suscipit dolor 1 Proin tristique justo a urna viverra sagittis. Aliquam felis lacus, mattis ut sapien nec, bibendum convallis turpis. Donec id nisi lacus. Praesent vehicula bibendum faucibus. Suspendisse sit amet massa vitae mi sodales consequat. Morbi vitae tortor lorem. Donec aliquet ultricies dui, vel convallis dui volutpat a. Praesent finibus, enim nec consequat rutrum, sem felis tincidunt metus, et aliquam lectus leo ullamcorper sem. Cras quis semper erat, sit amet feugiat nunc. Nullam iaculis sodales tellus in pellentesque. Phasellus laoreet gravida quam, quis commodo velit lacinia ut. Donec sodales nibh nec venenatis congue. Maecenas id ultrices mi. Quisque imperdiet sed diam sit amet placerat. Pellentesque pretium nec ante nec rutrum. Nunc sit amet finibus mauris, vel faucibus sapien. Nunc blandit mi at ante imperdiet, nec aliquam eros egestas. Aliquam sollicitudin neque nisl, et finibus justo placerat non. Maecenas id vestibulum ligula. Morbi efficitur ipsum tortor. Sed ac nunc orci. Donec non eros maximus sapien mollis mollis a id erat.
Java
package wsclient import ( "github.com/cosminrentea/gobbler/testutil" "fmt" "strings" "testing" "time" "github.com/gorilla/websocket" "github.com/stretchr/testify/assert" ) var aNormalMessage = `/foo/bar,42,user01,phone01,{},,1420110000,0 Hello World` var aSendNotification = "#send" var anErrorNotification = "!error-send" func MockConnectionFactory(connectionMock *MockWSConnection) func(string, string) (WSConnection, error) { return func(url string, origin string) (WSConnection, error) { return connectionMock, nil } } func TestConnectErrorWithoutReconnection(t *testing.T) { a := assert.New(t) // given a client c := New("url", "origin", 1, false) // which raises an error on connect callCounter := 0 c.SetWSConnectionFactory(func(url string, origin string) (WSConnection, error) { a.Equal("url", url) a.Equal("origin", origin) callCounter++ return nil, fmt.Errorf("emulate connection error") }) // when we start err := c.Start() // then a.Error(err) a.Equal(1, callCounter) } func TestConnectErrorWithoutReconnectionUsingOpen(t *testing.T) { a := assert.New(t) c, err := Open("url", "origin", 1, false) // which raises an error on connect callCounter := 0 c.SetWSConnectionFactory(func(url string, origin string) (WSConnection, error) { a.Equal("url", url) a.Equal("origin", origin) callCounter++ return nil, fmt.Errorf("emulate connection error") }) a.Error(err) } func TestConnectErrorWithReconnection(t *testing.T) { ctrl, finish := testutil.NewMockCtrl(t) defer finish() a := assert.New(t) // given a client c := New("url", "origin", 1, true) // which raises an error twice and then allows to connect callCounter := 0 connMock := NewMockWSConnection(ctrl) connMock.EXPECT().ReadMessage().Do(func() { time.Sleep(time.Second) }) c.SetWSConnectionFactory(func(url string, origin string) (WSConnection, error) { a.Equal("url", url) a.Equal("origin", origin) if callCounter <= 2 { callCounter++ return nil, fmt.Errorf("emulate connection error") } return connMock, nil }) // when we start err := c.Start() // then we get an error, first a.Error(err) a.False(c.IsConnected()) // when we wait for two iterations and 10ms buffer time to connect time.Sleep(time.Millisecond * 110) // then we got connected a.True(c.IsConnected()) a.Equal(3, callCounter) } func TestStopableClient(t *testing.T) { ctrl, finish := testutil.NewMockCtrl(t) defer finish() a := assert.New(t) // given a client c := New("url", "origin", 1, true) // with a closeable connection connMock := NewMockWSConnection(ctrl) close := make(chan bool, 1) connMock.EXPECT().ReadMessage(). Do(func() { <-close }). Return(0, []byte{}, fmt.Errorf("expected close error")) connMock.EXPECT().Close().Do(func() { close <- true }) c.SetWSConnectionFactory(MockConnectionFactory(connMock)) // when we start err := c.Start() // than we are connected a.NoError(err) a.True(c.IsConnected()) // when we clode c.Close() time.Sleep(time.Millisecond * 1) // than the client returns a.False(c.IsConnected()) } func TestReceiveAMessage(t *testing.T) { ctrl, finish := testutil.NewMockCtrl(t) defer finish() a := assert.New(t) // given a client c := New("url", "origin", 10, false) // with a closeable connection connMock := NewMockWSConnection(ctrl) close := make(chan bool, 1) // normal message call1 := connMock.EXPECT().ReadMessage(). Return(4, []byte(aNormalMessage), nil) call2 := connMock.EXPECT().ReadMessage(). Return(4, []byte(aSendNotification), nil) call3 := connMock.EXPECT().ReadMessage(). Return(4, []byte("---"), nil) call4 := connMock.EXPECT().ReadMessage(). Return(4, []byte(anErrorNotification), nil) call5 := connMock.EXPECT().ReadMessage(). Do(func() { <-close }). Return(0, []byte{}, fmt.Errorf("expected close error")). AnyTimes() call5.After(call4) call4.After(call3) call3.After(call2) call2.After(call1) c.SetWSConnectionFactory(MockConnectionFactory(connMock)) connMock.EXPECT().Close().Do(func() { close <- true }) // when we start err := c.Start() a.NoError(err) a.True(c.IsConnected()) // than we receive the expected message select { case m := <-c.Messages(): a.Equal(aNormalMessage, string(m.Encode())) case <-time.After(time.Millisecond * 10): a.Fail("timeout while waiting for message") } // and we receive the notification select { case m := <-c.StatusMessages(): a.Equal(aSendNotification, string(m.Bytes())) case <-time.After(time.Millisecond * 10): a.Fail("timeout while waiting for message") } // parse error select { case m := <-c.Errors(): a.True(strings.HasPrefix(string(m.Bytes()), "!clientError ")) case <-time.After(time.Millisecond * 10): a.Fail("timeout while waiting for message") } // and we receive the error notification select { case m := <-c.Errors(): a.Equal(anErrorNotification, string(m.Bytes())) case <-time.After(time.Millisecond * 10): a.Fail("timeout while waiting for message") } c.Close() } func TestSendAMessage(t *testing.T) { ctrl, finish := testutil.NewMockCtrl(t) defer finish() // a := assert.New(t) // given a client c := New("url", "origin", 1, true) // when expects a message connMock := NewMockWSConnection(ctrl) connMock.EXPECT().WriteMessage(websocket.BinaryMessage, []byte("> /foo\n{}\nTest")) connMock.EXPECT(). ReadMessage(). Return(websocket.BinaryMessage, []byte(aNormalMessage), nil). Do(func() { time.Sleep(time.Millisecond * 50) }). AnyTimes() c.SetWSConnectionFactory(MockConnectionFactory(connMock)) c.Start() // then the expectation is meet by sending it c.Send("/foo", "Test", "{}") // stop client after 200ms time.AfterFunc(time.Millisecond*200, func() { c.Close() }) } func TestSendSubscribeMessage(t *testing.T) { ctrl, finish := testutil.NewMockCtrl(t) defer finish() // given a client c := New("url", "origin", 1, true) // when expects a message connMock := NewMockWSConnection(ctrl) connMock.EXPECT().WriteMessage(websocket.BinaryMessage, []byte("+ /foo")) connMock.EXPECT(). ReadMessage(). Return(websocket.BinaryMessage, []byte(aNormalMessage), nil). Do(func() { time.Sleep(time.Millisecond * 50) }). AnyTimes() c.SetWSConnectionFactory(MockConnectionFactory(connMock)) c.Start() c.Subscribe("/foo") // stop client after 200ms time.AfterFunc(time.Millisecond*200, func() { c.Close() }) } func TestSendUnSubscribeMessage(t *testing.T) { ctrl, finish := testutil.NewMockCtrl(t) defer finish() // given a client c := New("url", "origin", 1, true) // when expects a message connMock := NewMockWSConnection(ctrl) connMock.EXPECT().WriteMessage(websocket.BinaryMessage, []byte("- /foo")) connMock.EXPECT(). ReadMessage(). Return(websocket.BinaryMessage, []byte(aNormalMessage), nil). Do(func() { time.Sleep(time.Millisecond * 50) }). AnyTimes() c.SetWSConnectionFactory(MockConnectionFactory(connMock)) c.Start() c.Unsubscribe("/foo") // stop client after 200ms time.AfterFunc(time.Millisecond*200, func() { c.Close() }) }
Java
namespace LadderLogic.Controller.State { using Surface; public class CursorState : State { public CursorState () : base(StateType.CursorState) { } #region implemented abstract members of State public override bool Handle (State previous, Segment prevSegment, Segment newSegment, bool left) { base.Handle (previous, prevSegment, newSegment, left); return true; } #endregion } }
Java
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Network::Mgmt::V2019_12_01 module Models # # A load balancer probe. # class Probe < SubResource include MsRestAzure # @return [Array<SubResource>] The load balancer rules that use this # probe. attr_accessor :load_balancing_rules # @return [ProbeProtocol] The protocol of the end point. If 'Tcp' is # specified, a received ACK is required for the probe to be successful. # If 'Http' or 'Https' is specified, a 200 OK response from the specifies # URI is required for the probe to be successful. Possible values # include: 'Http', 'Tcp', 'Https' attr_accessor :protocol # @return [Integer] The port for communicating the probe. Possible values # range from 1 to 65535, inclusive. attr_accessor :port # @return [Integer] The interval, in seconds, for how frequently to probe # the endpoint for health status. Typically, the interval is slightly # less than half the allocated timeout period (in seconds) which allows # two full probes before taking the instance out of rotation. The default # value is 15, the minimum value is 5. attr_accessor :interval_in_seconds # @return [Integer] The number of probes where if no response, will # result in stopping further traffic from being delivered to the # endpoint. This values allows endpoints to be taken out of rotation # faster or slower than the typical times used in Azure. attr_accessor :number_of_probes # @return [String] The URI used for requesting health status from the VM. # Path is required if a protocol is set to http. Otherwise, it is not # allowed. There is no default value. attr_accessor :request_path # @return [ProvisioningState] The provisioning state of the probe # resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', # 'Failed' attr_accessor :provisioning_state # @return [String] The name of the resource that is unique within the set # of probes used by the load balancer. This name can be used to access # the resource. attr_accessor :name # @return [String] A unique read-only string that changes whenever the # resource is updated. attr_accessor :etag # @return [String] Type of the resource. attr_accessor :type # # Mapper for Probe class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'Probe', type: { name: 'Composite', class_name: 'Probe', model_properties: { id: { client_side_validation: true, required: false, serialized_name: 'id', type: { name: 'String' } }, load_balancing_rules: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.loadBalancingRules', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'SubResourceElementType', type: { name: 'Composite', class_name: 'SubResource' } } } }, protocol: { client_side_validation: true, required: true, serialized_name: 'properties.protocol', type: { name: 'String' } }, port: { client_side_validation: true, required: true, serialized_name: 'properties.port', type: { name: 'Number' } }, interval_in_seconds: { client_side_validation: true, required: false, serialized_name: 'properties.intervalInSeconds', type: { name: 'Number' } }, number_of_probes: { client_side_validation: true, required: false, serialized_name: 'properties.numberOfProbes', type: { name: 'Number' } }, request_path: { client_side_validation: true, required: false, serialized_name: 'properties.requestPath', type: { name: 'String' } }, provisioning_state: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.provisioningState', type: { name: 'String' } }, name: { client_side_validation: true, required: false, serialized_name: 'name', type: { name: 'String' } }, etag: { client_side_validation: true, required: false, read_only: true, serialized_name: 'etag', type: { name: 'String' } }, type: { client_side_validation: true, required: false, read_only: true, serialized_name: 'type', type: { name: 'String' } } } } } end end end end
Java
#pragma once #include <mime/mimepp/mimepp.h> namespace Zimbra { namespace MAPI { #define PR_URL_NAME PROP_TAG(PT_TSTRING, 0x6707) #define EXCHIVERB_OPEN 0 #define EXCHIVERB_RESERVED_COMPOSE 100 #define EXCHIVERB_RESERVED_OPEN 101 #define EXCHIVERB_REPLYTOSENDER 102 #define EXCHIVERB_REPLYTOALL 103 #define EXCHIVERB_FORWARD 104 #define EXCHIVERB_PRINT 105 #define EXCHIVERB_SAVEAS 106 #define EXCHIVERB_RESERVED_DELIVERY 107 #define EXCHIVERB_REPLYTOFOLDER 108 typedef enum _ZM_ITEM_TYPE { ZT_NONE = 0, ZT_MAIL, ZT_CONTACTS, ZT_APPOINTMENTS, ZT_TASKS, ZT_MEETREQ, ZTMAX } ZM_ITEM_TYPE; // MAPIMessageException class class MAPIMessageException: public GenericException { public: MAPIMessageException(HRESULT hrErrCode, LPCWSTR lpszDescription); MAPIMessageException(HRESULT hrErrCode, LPCWSTR lpszDescription, LPCWSTR lpszShortDescription, int nLine, LPCSTR strFile); virtual ~MAPIMessageException() {} }; // MAPIMessage Class class MAPIMessage { private: // order of the message properties in _pMessagePropVals typedef enum _MessagePropIndex { MESSAGE_CLASS, MESSAGE_FLAGS, MESSAGE_DATE, SENDER_ADDRTYPE, SENDER_EMAIL_ADDR, SENDER_NAME, SENDER_ENTRYID, SUBJECT, TEXT_BODY, HTML_BODY, INTERNET_CPID, MESSAGE_CODEPAGE, LAST_VERB_EXECUTED, FLAG_STATUS, ENTRYID, SENT_ADDRTYPE, SENT_ENTRYID, SENT_EMAIL_ADDR, SENT_NAME, REPLY_NAMES, REPLY_ENTRIES, MIME_HEADERS, IMPORTANCE, INTERNET_MESSAGE_ID, DELIVERY_DATE, URL_NAME, MESSAGE_SIZE, STORE_SUPPORT_MASK, RTF_IN_SYNC, NMSGPROPS } MessagePropIndex; // defined so a static variable can hold the message props to retrieve typedef struct _MessagePropTags { ULONG cValues; ULONG aulPropTags[NMSGPROPS]; } MessagePropTags; // order of the recipient properties in each row of _pRecipRows typedef enum _RecipientPropIndex { RDISPLAY_NAME, RENTRYID, RADDRTYPE, REMAIL_ADDRESS, RRECIPIENT_TYPE, RNPROPS } RecipientPropIndex; // defined so a static variable can hold the recipient properties to retrieve typedef struct _RecipientPropTags { ULONG cValues; ULONG aulPropTags[RNPROPS]; } RecipientPropTags; // order of the recipient properties in each row of _pRecipRows typedef enum _ReplyToPropIndex { REPLYTO_DISPLAY_NAME, REPLYTO_ENTRYID, REPLYTO_ADDRTYPE, REPLYTO_EMAIL_ADDRESS, NREPLYTOPROPS } ReplyToPropIndex; // defined so a static variable can hold the recipient properties to retrieve typedef struct _ReplyToPropTags { ULONG cValues; ULONG aulPropTags[NREPLYTOPROPS]; } ReplyToPropTags; MAPISession *m_session; LPMESSAGE m_pMessage; LPSPropValue m_pMessagePropVals; LPSRowSet m_pRecipientRows; SBinary m_EntryID; CHAR m_pDateTimeStr[32]; CHAR m_pDeliveryDateTimeStr[32]; CHAR m_pDeliveryUnixDateTimeStr[32]; std::vector<std::string> RTFElement; enum EnumRTFElement { NOTFOUND = -1, OPENBRACE = 0, CLOSEBRACE, HTMLTAG, MHTMLTAG, PAR, TAB, LI, FI, HEXCHAR, PNTEXT, HTMLRTF, OPENBRACEESC, CLOSEBRACEESC, END, HTMLRTF0 }; static MessagePropTags m_messagePropTags; static RecipientPropTags m_recipientPropTags; static ReplyToPropTags m_replyToPropTags; unsigned int CodePageId(); EnumRTFElement MatchRTFElement(const char *psz); const char *Advance(const char *psz, const char *pszCharSet); public: MAPIMessage(); ~MAPIMessage(); void Initialize(LPMESSAGE pMessage, MAPISession &session, bool bPartial=false); void InternalFree(); LPMESSAGE InternalMessageObject() { return m_pMessage; } bool Subject(LPTSTR *ppSubject); ZM_ITEM_TYPE ItemType(); bool IsFlagged(); bool GetURLName(LPTSTR *pstrUrlName); bool IsDraft(); BOOL IsFromMe(); BOOL IsUnread(); BOOL Forwarded(); BOOL RepliedTo(); bool HasAttach(); BOOL IsUnsent(); bool HasHtmlPart(); bool HasTextPart(); SBinary &UniqueId(); __int64 DeliveryDate(); LPSTR DateString(); __int64 Date(); DWORD Size(); LPSTR DeliveryDateString(); LPSTR DeliveryUnixString(); std::vector<LPWSTR>* SetKeywords(); SBinary EntryID() { return m_EntryID; } bool TextBody(LPTSTR *ppBody, unsigned int &nTextChars); // reads the utf8 body and retruns it with accented chararcters bool UTF8EncBody(LPTSTR *ppBody, unsigned int &nTextChars); // return the html body of the message bool HtmlBody(LPVOID *ppBody, unsigned int &nHtmlBodyLen); bool DecodeRTF2HTML(char *buf, unsigned int *len); bool IsRTFHTML(const char *buf); void ToMimePPMessage(mimepp::Message &msg); }; class MIRestriction; // Message Iterator class class MessageIterator: public MAPITableIterator { private: typedef enum _MessageIterPropTagIdx { MI_ENTRYID, MI_LONGTERM_ENTRYID_FROM_TABLE, MI_DATE, MI_MESSAGE_CLASS, NMSGPROPS } MessageIterPropTagIdx; typedef struct _MessageIterPropTags { ULONG cValues; ULONG aulPropTags[NMSGPROPS]; } MessageIterPropTags; typedef struct _MessageIterSort { ULONG cSorts; ULONG cCategories; ULONG cExpanded; SSortOrder aSort[1]; } MessageIterSortOrder; public: MessageIterator(); virtual ~MessageIterator(); virtual LPSPropTagArray GetProps(); virtual LPSSortOrderSet GetSortOrder(); virtual LPSRestriction GetRestriction(ULONG TypeMask, FILETIME startDate); BOOL GetNext(MAPIMessage &msg); BOOL GetNext(__int64 &date, SBinary &bin); protected: static MessageIterPropTags m_props; static MessageIterSortOrder m_sortOrder; static MIRestriction m_restriction; }; // Restriction class class MIRestriction { public: MIRestriction(); ~MIRestriction(); LPSRestriction GetRestriction(ULONG TypeMask, FILETIME startDate); private: SRestriction pR[25]; SPropValue _propValCont; SPropValue _propValMail; SPropValue _propValCTime; SPropValue _propValSTime; SPropValue _propValCanbeMail; SPropValue _propValCanbeMailPost; SPropValue _propValAppt; LPWSTR _pApptClass; SPropValue _propValTask; LPWSTR _pTaskClass; SPropValue _propValReqAndRes; LPWSTR _pReqAndResClass; SPropValue _propValDistList; LPWSTR _pDistListClass; LPWSTR _pContactClass; LPWSTR _pMailClass; SPropValue _propValIMAPHeaderOnly; }; mimepp::Mailbox *MakeMimePPMailbox(LPTSTR pDisplayName, LPTSTR pSmtpAddress); } }
Java
<?php namespace Juice\UploadBundle\Form\Type; use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormView; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class BaseFileType extends AbstractUploadType { public function buildView(FormView $view, FormInterface $form, array $options) { $this->addVars($view, $options); } public function getName() { return 'juice_upload_file_type'; } }
Java
<html> <head> <meta http-equiv="refresh" content="0; url=https://minecrafthopper.net/"> <link rel="canonical" href="https://minecrafthopper.net/"/> </head> </html>
Java
<?php namespace TFE\LibrairieBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; class AccompagnementModifierType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) {} /** * @return string */ public function getName() { return 'tfe_librairiebundle_accompagnement_modifier'; } /** * @return AccompagnementType */ public function getParent() { return new AccompagnementType(); } }
Java
using Dufry.Comissoes.Domain.Validation; namespace Dufry.Comissoes.Domain.Interfaces.Validation { public interface IValidation<in TEntity> { ValidationResult Valid(TEntity entity); } }
Java
import {HttpClient} from '@angular/common/http'; import {Injectable} from '@angular/core'; import {Observable, ReplaySubject, throwError} from 'rxjs'; import {map, tap, switchMap} from 'rxjs/operators'; import {SocketService} from './sockets'; import {StorageService} from './storage'; @Injectable({ providedIn: 'root' }) export class AuthService { private session: string; private userInfo: any; private authEvents: ReplaySubject<{User: any, Session: string}>; constructor( private _http: HttpClient, private _storage: StorageService, private _sockets: SocketService, ) { this.authEvents = new ReplaySubject<{User: any, Session: string}>(1); } private nuke() { this._storage.clear(); this.session = undefined; this.userInfo = undefined; this._sockets.leave(); } getSession() { return this.session; } getUser() { return this.userInfo; } hasAccess(): boolean { return !!this.userInfo; } observe(): Observable<{User: any, Session: string}> { return this.authEvents; } identify() { this._http.get<{Data: any}>(`/api/auth/`) .pipe( map(res => res.Data) ) .subscribe( data => { this.session = data.Session.Key; this.userInfo = data.User; this._sockets.join(data.Session.Key); this.authEvents.next({User: data.User, Session: data.Session.Key}); }, err => console.error(err) ); } logIn(creds): Observable<any> { if (!creds || !creds.Username || !creds.Password) { return throwError('Need login creds'); } return this._http.post<{Data: any}>('/api/login', creds) .pipe( map(res => res.Data), tap(data => { this.session = data.Session; this.userInfo = data.User; this._sockets.join(data.Session); this.authEvents.next(data); }) ); } signUp(creds): Observable<any> { if (!creds || !creds.Username || !creds.Email || !creds.Password) { return throwError('Need signup creds'); } return this._http.post('/api/signup', creds, {responseType: 'text' as 'text'}) .pipe( switchMap(_ => this.logIn(creds)) ); } expireSocket() { this.userInfo = null; this.session = null; this.authEvents.next(null); } logOut(): Observable<any> { return this._http.post('/api/logOut', null) .pipe( tap( res => this.nuke(), err => this.nuke(), () => this.authEvents.next(null) ) ); } }
Java
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} module DirectoryAPI.API ( directoryAPIProxy , DirectoryAPI ) where import Servant import AuthAPI.API (AuthToken) import Models (File, Node, NodeId) type DirectoryAPI = "ls" :> -- List all files AuthToken :> Get '[JSON] [File] -- Listing of all files :<|> "whereis" :> -- Lookup the node for a given file path AuthToken :> ReqBody '[JSON] FilePath :> -- Path of file being looked up Post '[JSON] Node -- Node where the file is kept :<|> "roundRobinNode" :> -- Next node to use as a file primary AuthToken :> ReqBody '[JSON] FilePath :> -- Path of file that will be written Get '[JSON] Node -- Primary node of the file being stored :<|> "registerFileServer" :> -- Register a node with the directory service ReqBody '[JSON] Int :> -- Port file server node is running on Post '[JSON] NodeId -- Id of the newly created node record directoryAPIProxy :: Proxy DirectoryAPI directoryAPIProxy = Proxy
Java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <script src="jquery/jquery-1.8.1.js"></script> <script src="jquery/jquery-ui-1.10.3.custom.js"></script> <script src="treema/tv4.js"></script> <script src="treema/treema.js"></script> <link href="jquery/jquery-ui-1.10.3.custom.css" rel="stylesheet"> <link href="treema/treema.css" rel="stylesheet"> </head> <body> <div id="addresses"></div> <script> var contacts = [ { 'street-address': '10 Downing Street', 'country-name': 'UK', 'locality': 'London', 'name': 'Prime Minister' }, { 'street-address': '1600 Amphitheatre Pkwy', 'phone-number': '(650) 253-0000', 'name': 'Google'}, { 'street-address': '45 Rockefeller Plaza', 'region': 'NY', 'locality': 'New York', 'name': 'Rockefeller Center'}, ]; var contact_book_schema = { type: 'array', items: { "additionalProperties": false, "type": "object", "displayProperty": 'name', "properties": { "name": { type: "string", maxLength: 20 }, "street-address": { title: "Address 1", description: "Don't forget the number.", type: "string" }, "locality":{ "type": "string", title: "Locality" }, "region": { 'title': 'Region', type: 'string' }, "country-name": { "type": "string", title: "Country" }, "friend": { "type": "boolean", title: "Friend" }, "phone-number": { type: "string", maxLength: 20, minLength:4, title: 'Phone Number' } } } }; //buildTreemaExample($('#addresses'), contact_book_schema, contacts); var treema = $('#addresses').treema({schema: contact_book_schema, data: contacts}); treema.build(); </script> </body> </html>
Java
package com.lightspeedhq.ecom; import com.lightspeedhq.ecom.domain.LightspeedEComError; import feign.FeignException; import lombok.Getter; /** * * @author stevensnoeijen */ public class LightspeedEComErrorException extends FeignException { @Getter private LightspeedEComError error; public LightspeedEComErrorException(String message, LightspeedEComError error) { super(message); this.error = error; } @Override public String toString() { return error.toString(); } }
Java
edit-movie ========== Script to edit Star Wars with ffmpeg to make it a bit more child-friendly
Java
<?xml version="1.0" ?><!DOCTYPE TS><TS language="eu_ES" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About POPCoin</source> <translation>POPCoin-i buruz</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;POPCoin&lt;/b&gt; version</source> <translation>&lt;b&gt;POPCoin&lt;/b&gt; bertsioa</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 type="unfinished"/> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>POPCoin</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Helbide-liburua</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Klik bikoitza helbidea edo etiketa editatzeko</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Sortu helbide berria</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopiatu hautatutako helbidea sistemaren arbelera</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your POPCoin 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 type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Erakutsi &amp;QR kodea</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a POPCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified POPCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Ezabatu</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your POPCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Esportatu Helbide-liburuaren datuak</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Komaz bereizitako artxiboa (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Errorea esportatzean</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Ezin idatzi %1 artxiboan.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Etiketa</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Helbidea</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(etiketarik ez)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Sartu pasahitza</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Pasahitz berria</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Errepikatu pasahitz berria</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Sartu zorrorako pasahitz berria.&lt;br/&gt; Mesedez erabili &lt;b&gt;gutxienez ausazko 10 karaktere&lt;/b&gt;, edo &lt;b&gt;gutxienez zortzi hitz&lt;/b&gt; pasahitza osatzeko.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Enkriptatu zorroa</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Eragiketa honek zorroaren pasahitza behar du zorroa desblokeatzeko.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Desblokeatu zorroa</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Eragiketa honek zure zorroaren pasahitza behar du, zorroa desenkriptatzeko.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Desenkriptatu zorroa</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Aldatu pasahitza</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Sartu zorroaren pasahitz zaharra eta berria.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Berretsi zorroaren enkriptazioa</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR POPCOIN&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Zorroa enkriptatuta</translation> </message> <message> <location line="-56"/> <source>POPCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your popcoins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Zorroaren enkriptazioak huts egin du</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Zorroaren enkriptazioak huts egin du barne-errore baten ondorioz. Zure zorroa ez da enkriptatu.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Eman dituzun pasahitzak ez datoz bat.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Zorroaren desblokeoak huts egin du</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Zorroa desenkriptatzeko sartutako pasahitza okerra da.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Zorroaren desenkriptazioak huts egin du</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Sarearekin sinkronizatzen...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Gainbegiratu</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Ikusi zorroaren begirada orokorra</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transakzioak</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Ikusi transakzioen historia</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Editatu gordetako helbide eta etiketen zerrenda</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Erakutsi ordainketak jasotzeko helbideen zerrenda</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>Irten</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Irten aplikaziotik</translation> </message> <message> <location line="+4"/> <source>Show information about POPCoin</source> <translation>Erakutsi POPCoin-i buruzko informazioa</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>&amp;Qt-ari buruz</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Erakutsi POPCoin-i buruzko informazioa</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Aukerak...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a POPCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Modify configuration options for POPCoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Aldatu zorroa enkriptatzeko erabilitako pasahitza</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-165"/> <location line="+530"/> <source>POPCoin</source> <translation type="unfinished"/> </message> <message> <location line="-530"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About POPCoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your POPCoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified POPCoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Artxiboa</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Ezarpenak</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Laguntza</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Fitxen tresna-barra</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+47"/> <source>POPCoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to POPCoin network</source> <translation><numerusform>Konexio aktibo %n POPCoin-en sarera</numerusform><numerusform>%n konexio aktibo POPCoin-en sarera</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+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 type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Egunean</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Eguneratzen...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Bidalitako transakzioa</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Sarrerako transakzioa</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid POPCoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Zorroa &lt;b&gt;enkriptatuta&lt;/b&gt; eta &lt;b&gt;desblokeatuta&lt;/b&gt; dago une honetan</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Zorroa &lt;b&gt;enkriptatuta&lt;/b&gt; eta &lt;b&gt;blokeatuta&lt;/b&gt; dago une honetan</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. POPCoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Editatu helbidea</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Etiketa</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Helbide-liburuko sarrera honekin lotutako etiketa</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Helbidea</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>Helbide-liburuko sarrera honekin lotutako helbidea. Bidaltzeko helbideeta soilik alda daiteke.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Jasotzeko helbide berria</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Bidaltzeko helbide berria</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Editatu jasotzeko helbidea</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Editatu bidaltzeko helbidea</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Sartu berri den helbidea, &quot;%1&quot;, helbide-liburuan dago jadanik.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid POPCoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Ezin desblokeatu zorroa.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Gako berriaren sorrerak huts egin du.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>POPCoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Aukerak</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start POPCoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start POPCoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the POPCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the POPCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting POPCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show POPCoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting POPCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Inprimakia</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the POPCoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Saldoa:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Konfirmatu gabe:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Azken transakzioak&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Zure uneko saldoa</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>Oraindik konfirmatu gabe daudenez, uneko saldoab kontatu gabe dagoen transakzio kopurua</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start popcoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Kopurua</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>&amp;Etiketa:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Mezua</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>Gorde honela...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the POPCoin-Qt help message to get a list with possible POPCoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>POPCoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>POPCoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the POPCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the POPCoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </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>Bidali txanponak</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Bidali hainbat jasotzaileri batera</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Saldoa:</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>Berretsi bidaltzeko ekintza</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; honi: %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Berretsi txanponak bidaltzea</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Ziur zaude %1 bidali nahi duzula?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>eta</translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Ordaintzeko kopurua 0 baino handiagoa izan behar du.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Inprimakia</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>K&amp;opurua:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Ordaindu &amp;honi:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. sSxjmkQbhzcbnhNLPru6TwPy4HRPogaDcK)</source> <translation type="unfinished"/> </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>Sartu etiketa bat helbide honetarako, eta gehitu zure helbide-liburuan</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Etiketa:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation type="unfinished"/> </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>Itsatsi helbidea arbeletik</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>Ezabatu jasotzaile hau</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a POPCoin address (e.g. sSxjmkQbhzcbnhNLPru6TwPy4HRPogaDcK)</source> <translation>Sartu Bitocin helbide bat (adb.: sSxjmkQbhzcbnhNLPru6TwPy4HRPogaDcK) </translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. sSxjmkQbhzcbnhNLPru6TwPy4HRPogaDcK)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </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>Itsatsi helbidea arbeletik</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 type="unfinished"/> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this POPCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. sSxjmkQbhzcbnhNLPru6TwPy4HRPogaDcK)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified POPCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a POPCoin address (e.g. sSxjmkQbhzcbnhNLPru6TwPy4HRPogaDcK)</source> <translation>Sartu Bitocin helbide bat (adb.: sSxjmkQbhzcbnhNLPru6TwPy4HRPogaDcK) </translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter POPCoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>POPCoin</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Zabalik %1 arte</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/konfirmatu gabe</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 konfirmazioak</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Kopurua</translation> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, ez da arrakastaz emititu oraindik</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>ezezaguna</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Transakzioaren xehetasunak</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Panel honek transakzioaren deskribapen xehea erakusten du</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Mota</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Helbidea</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Kopurua</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Zabalik %1 arte</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Offline (%1 konfirmazio)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Konfirmatuta (%1 konfirmazio)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></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>Bloke hau ez du beste inongo nodorik jaso, eta seguruenik ez da onartuko!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Sortua, baina ez onartua</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Jasoa honekin: </translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Honi bidalia: </translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Ordainketa zeure buruari</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Bildua</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Transakzioaren egoera. Pasatu sagua gainetik konfirmazio kopurua ikusteko.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Transakzioa jasotako data eta ordua.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Transakzio mota.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Transakzioaren xede-helbidea.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Saldoan kendu edo gehitutako kopurua.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Denak</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Gaur</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Aste honetan</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Hil honetan</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Azken hilean</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Aurten</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Muga...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Jasota honekin: </translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Hona bidalia: </translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Zeure buruari</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Bildua</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Beste</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Sartu bilatzeko helbide edo etiketa</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Kopuru minimoa</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopiatu helbidea</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopiatu etiketa</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Transakzioaren xehetasunak</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Komaz bereizitako artxiboa (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Mota</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Etiketa</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Helbidea</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Kopurua</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Errorea esportatzean</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Ezin idatzi %1 artxiboan.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>to</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>POPCoin version</source> <translation>Botcoin bertsioa</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Send command to -server or popcoind</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Komandoen lista</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Laguntza komando batean</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Aukerak</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: popcoin.conf)</source> <translation>Ezarpen fitxategia aukeratu (berezkoa: popcoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: popcoind.pid)</source> <translation>pid fitxategia aukeratu (berezkoa: popcoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9247 or testnet: 19247)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9347 or testnet: 19347)</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </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=popcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;POPCoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. POPCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </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 type="unfinished"/> </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 type="unfinished"/> </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 type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong POPCoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>SSL options: (see the POPCoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Laguntza mezu hau</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation type="unfinished"/> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of POPCoin</source> <translation type="unfinished"/> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart POPCoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation type="unfinished"/> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. POPCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Birbilatzen...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Zamaketa amaitua</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
Java
<?php namespace ZpgRtf\Tests\Objects; use PHPUnit\Framework\TestCase; use ZpgRtf\Objects\EpcRatingsObject; class EpcRatingsObjectTest extends TestCase { /** * @var EpcRatingsObject */ protected $object; public function setUp() { $this->object = new EpcRatingsObject(); } public function testCanInstantiate() { $this->assertInstanceOf( EpcRatingsObject::class, $this->object ); } public function testCanSetEerCurrentRating() { $this->assertInstanceOf( EpcRatingsObject::class, $this->object->setEerCurrentRating(80) ); $this->assertSame( 80, $this->object->getEerCurrentRating() ); } public function testCanSetEerPotentialRating() { $this->assertInstanceOf( EpcRatingsObject::class, $this->object->setEerPotentialRating(95) ); $this->assertSame( 95, $this->object->getEerPotentialRating() ); } public function testCanSetEirCurrentRating() { $this->assertInstanceOf( EpcRatingsObject::class, $this->object->setEirCurrentRating(50) ); $this->assertSame( 50, $this->object->getEirCurrentRating() ); } public function testCanSetEirPotentialRating() { $this->assertInstanceOf( EpcRatingsObject::class, $this->object->setEirPotentialRating(100) ); $this->assertSame( 100, $this->object->getEirPotentialRating() ); } public function testCanJsonSerialize() { $this->assertJson( json_encode($this->object) ); $this->assertInstanceOf( \JsonSerializable::class, $this->object ); } }
Java
import sys tagging_filepath = sys.argv[1] following_filepath = sys.argv[2] delim = '\t' if len(sys.argv) > 3: delim = sys.argv[3] graph = {} for line in open(tagging_filepath): entry = line.rstrip().split('\t') src = entry[0] dst = entry[1] if not src in graph: graph[src] = {} graph[src][dst] = 0 for line in open(following_filepath): entry = line.rstrip().split('\t') src = entry[0] dst = entry[1] if src in graph and dst in graph[src]: graph[src][dst] += 1 if dst in graph and src in graph[dst]: graph[dst][src] += 2 w_dir = 0 wo_dir = 0 count = 0.0 for src in graph: for dst in graph[src]: val = graph[src][dst] count += 1 if val in [1,3]: w_dir += 1 if val in [1,2,3]: wo_dir += 1 print "%s\t%s" % (w_dir/count, wo_dir/count)
Java
/* Copyright (c) 2014-2020, The Tor Project, Inc. */ /* See LICENSE for licensing information */ #include "core/or/or.h" #ifndef TOR_LOG_TEST_HELPERS_H #define TOR_LOG_TEST_HELPERS_H /** An element of mock_saved_logs(); records the log element that we * received. */ typedef struct mock_saved_log_entry_t { int severity; const char *funcname; const char *suffix; const char *format; char *generated_msg; } mock_saved_log_entry_t; void mock_clean_saved_logs(void); const smartlist_t *mock_saved_logs(void); void setup_capture_of_logs(int new_level); void setup_full_capture_of_logs(int new_level); void teardown_capture_of_logs(void); int mock_saved_log_has_message(const char *msg); int mock_saved_log_has_message_containing(const char *msg); int mock_saved_log_has_message_not_containing(const char *msg); int mock_saved_log_has_severity(int severity); int mock_saved_log_has_entry(void); int mock_saved_log_n_entries(void); void mock_dump_saved_logs(void); #define assert_log_predicate(predicate, failure_msg) \ do { \ if (!(predicate)) { \ TT_FAIL(failure_msg); \ mock_dump_saved_logs(); \ TT_EXIT_TEST_FUNCTION; \ } \ } while (0) #define expect_log_msg(str) \ assert_log_predicate(mock_saved_log_has_message(str), \ ("expected log to contain \"%s\"", str)); #define expect_log_msg_containing(str) \ assert_log_predicate(mock_saved_log_has_message_containing(str), \ ("expected log to contain \"%s\"", str)); #define expect_log_msg_not_containing(str) \ assert_log_predicate(mock_saved_log_has_message_not_containing(str), \ ("expected log to not contain \"%s\"", str)); #define expect_log_msg_containing_either(str1, str2) \ assert_log_predicate(mock_saved_log_has_message_containing(str1) || \ mock_saved_log_has_message_containing(str2), \ ("expected log to contain \"%s\" or \"%s\"", str1, str2)); #define expect_log_msg_containing_either3(str1, str2, str3) \ assert_log_predicate(mock_saved_log_has_message_containing(str1) || \ mock_saved_log_has_message_containing(str2) || \ mock_saved_log_has_message_containing(str3), \ ("expected log to contain \"%s\" or \"%s\" or \"%s\"", \ str1, str2, str3)) #define expect_log_msg_containing_either4(str1, str2, str3, str4) \ assert_log_predicate(mock_saved_log_has_message_containing(str1) || \ mock_saved_log_has_message_containing(str2) || \ mock_saved_log_has_message_containing(str3) || \ mock_saved_log_has_message_containing(str4), \ ("expected log to contain \"%s\" or \"%s\" or \"%s\" or \"%s\"", \ str1, str2, str3, str4)) #define expect_single_log_msg(str) \ do { \ \ assert_log_predicate(mock_saved_log_has_message_containing(str) && \ mock_saved_log_n_entries() == 1, \ ("expected log to contain exactly 1 message \"%s\"", \ str)); \ } while (0); #define expect_single_log_msg_containing(str) \ do { \ assert_log_predicate(mock_saved_log_has_message_containing(str)&& \ mock_saved_log_n_entries() == 1 , \ ("expected log to contain 1 message, containing \"%s\"",\ str)); \ } while (0); #define expect_no_log_msg(str) \ assert_log_predicate(!mock_saved_log_has_message(str), \ ("expected log to not contain \"%s\"",str)); #define expect_no_log_msg_containing(str) \ assert_log_predicate(!mock_saved_log_has_message_containing(str), \ ("expected log to not contain \"%s\"", str)); #define expect_log_severity(severity) \ assert_log_predicate(mock_saved_log_has_severity(severity), \ ("expected log to contain severity " # severity)); #define expect_no_log_severity(severity) \ assert_log_predicate(!mock_saved_log_has_severity(severity), \ ("expected log to not contain severity " # severity)); #define expect_log_entry() \ assert_log_predicate(mock_saved_log_has_entry(), \ ("expected log to contain entries")); #define expect_no_log_entry() \ assert_log_predicate(!mock_saved_log_has_entry(), \ ("expected log to not contain entries")); #endif /* !defined(TOR_LOG_TEST_HELPERS_H) */
Java
/* * The Plaid API * * The Plaid REST API. Please see https://plaid.com/docs/api for more details. * * API version: 2020-09-14_1.78.0 */ // Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. package plaid import ( "encoding/json" ) // WalletTransactionExecuteResponse WalletTransactionExecuteResponse defines the response schema for `/wallet/transaction/execute` type WalletTransactionExecuteResponse struct { // A unique ID identifying the transaction TransactionId string `json:"transaction_id"` Status WalletTransactionStatus `json:"status"` // A unique identifier for the request, which can be used for troubleshooting. This identifier, like all Plaid identifiers, is case sensitive. RequestId string `json:"request_id"` AdditionalProperties map[string]interface{} } type _WalletTransactionExecuteResponse WalletTransactionExecuteResponse // NewWalletTransactionExecuteResponse instantiates a new WalletTransactionExecuteResponse object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewWalletTransactionExecuteResponse(transactionId string, status WalletTransactionStatus, requestId string) *WalletTransactionExecuteResponse { this := WalletTransactionExecuteResponse{} this.TransactionId = transactionId this.Status = status this.RequestId = requestId return &this } // NewWalletTransactionExecuteResponseWithDefaults instantiates a new WalletTransactionExecuteResponse object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewWalletTransactionExecuteResponseWithDefaults() *WalletTransactionExecuteResponse { this := WalletTransactionExecuteResponse{} return &this } // GetTransactionId returns the TransactionId field value func (o *WalletTransactionExecuteResponse) GetTransactionId() string { if o == nil { var ret string return ret } return o.TransactionId } // GetTransactionIdOk returns a tuple with the TransactionId field value // and a boolean to check if the value has been set. func (o *WalletTransactionExecuteResponse) GetTransactionIdOk() (*string, bool) { if o == nil { return nil, false } return &o.TransactionId, true } // SetTransactionId sets field value func (o *WalletTransactionExecuteResponse) SetTransactionId(v string) { o.TransactionId = v } // GetStatus returns the Status field value func (o *WalletTransactionExecuteResponse) GetStatus() WalletTransactionStatus { if o == nil { var ret WalletTransactionStatus return ret } return o.Status } // GetStatusOk returns a tuple with the Status field value // and a boolean to check if the value has been set. func (o *WalletTransactionExecuteResponse) GetStatusOk() (*WalletTransactionStatus, bool) { if o == nil { return nil, false } return &o.Status, true } // SetStatus sets field value func (o *WalletTransactionExecuteResponse) SetStatus(v WalletTransactionStatus) { o.Status = v } // GetRequestId returns the RequestId field value func (o *WalletTransactionExecuteResponse) GetRequestId() string { if o == nil { var ret string return ret } return o.RequestId } // GetRequestIdOk returns a tuple with the RequestId field value // and a boolean to check if the value has been set. func (o *WalletTransactionExecuteResponse) GetRequestIdOk() (*string, bool) { if o == nil { return nil, false } return &o.RequestId, true } // SetRequestId sets field value func (o *WalletTransactionExecuteResponse) SetRequestId(v string) { o.RequestId = v } func (o WalletTransactionExecuteResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if true { toSerialize["transaction_id"] = o.TransactionId } if true { toSerialize["status"] = o.Status } if true { toSerialize["request_id"] = o.RequestId } for key, value := range o.AdditionalProperties { toSerialize[key] = value } return json.Marshal(toSerialize) } func (o *WalletTransactionExecuteResponse) UnmarshalJSON(bytes []byte) (err error) { varWalletTransactionExecuteResponse := _WalletTransactionExecuteResponse{} if err = json.Unmarshal(bytes, &varWalletTransactionExecuteResponse); err == nil { *o = WalletTransactionExecuteResponse(varWalletTransactionExecuteResponse) } additionalProperties := make(map[string]interface{}) if err = json.Unmarshal(bytes, &additionalProperties); err == nil { delete(additionalProperties, "transaction_id") delete(additionalProperties, "status") delete(additionalProperties, "request_id") o.AdditionalProperties = additionalProperties } return err } type NullableWalletTransactionExecuteResponse struct { value *WalletTransactionExecuteResponse isSet bool } func (v NullableWalletTransactionExecuteResponse) Get() *WalletTransactionExecuteResponse { return v.value } func (v *NullableWalletTransactionExecuteResponse) Set(val *WalletTransactionExecuteResponse) { v.value = val v.isSet = true } func (v NullableWalletTransactionExecuteResponse) IsSet() bool { return v.isSet } func (v *NullableWalletTransactionExecuteResponse) Unset() { v.value = nil v.isSet = false } func NewNullableWalletTransactionExecuteResponse(val *WalletTransactionExecuteResponse) *NullableWalletTransactionExecuteResponse { return &NullableWalletTransactionExecuteResponse{value: val, isSet: true} } func (v NullableWalletTransactionExecuteResponse) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableWalletTransactionExecuteResponse) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
Java
chrome.app.runtime.onLaunched.addListener(function(){ chrome.app.window.create('index.html', { bounds: { width: Math.round(window.screen.availWidth - 100), height: Math.round(window.screen.availHeight - 100) } }); });
Java
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') require "yaml" shared_examples "a bullet" do let(:capacity) { 2 } subject do described_class.new(:machines => machines, :guns => capacity) end describe :fire do it "spawns correct number of threads" do bullets = ["first", "second"] subject.specs = bullets Parallel.expects(:map).with(bullets, :in_threads => capacity) subject.fire end it "executes loaded specs" do bullets = ["first", "second"] subject.specs = bullets Bullet::BulletClient.any_instance.stubs(:execute).returns("hello") subject.fire.should == ["hello"] * bullets.length end it "unloads after fire" do bullets = ["first", "second"] subject.specs = bullets Bullet::BulletClient.any_instance.stubs(:execute).returns(true) subject.fire subject.specs.should have(0).bullets end end end describe Bullet::BulletClient do subject { Bullet::BulletClient.new() } describe :unload do it "drops all collected specs and plan_list" do subject.plan_list = {"hello" => 1} subject.specs = ["test"] subject.unload subject.specs.should have(0).spec end end describe :load do it "collect plans" do subject.load("dummy_bullet.yml") subject.plan_list.should eq({"github" => { "user" => {"register" => 10}, "admin" => {"create_user" => 20} }}) end end describe :aim do it "choose target as the plan" do subject.aim("plan") subject.plan.should == "plan" end end describe :prepare do it "calculates path to specs" do subject.plan_list = {"normal" => {"user" => {"signin" => 1, "register" => 2}}} subject.plan = "normal" expected = ["user_signin", "user_register", "user_register"] subject.prepare (subject.specs.flatten - expected).should be_empty end it "distribute specs to machines" do subject.plan_list = {"normal" => {"user" => {"signin" => 1, "register" => 2}}} subject.plan = "normal" subject.machines = 2 subject.prepare subject.specs.should have(2).sets end end describe :ready? do it "verifies that specs exists" do subject.specs = [["hello"]] subject.ready?.should be_true end end describe :use do it "accept the path as look up path" do subject.use("hello") subject.spec_path.should == "hello" end end context "with threads" do it_behaves_like "a bullet" do let(:machines) { 2 } end end context "with processes" do it_behaves_like "a bullet" do let(:machines) { 2 } end end end
Java
#!/usr/bin/env python # # Copyright 2010 Facebook # # 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. """Python client library for the Facebook Platform. This client library is designed to support the Graph API and the official Facebook JavaScript SDK, which is the canonical way to implement Facebook authentication. Read more about the Graph API at http://developers.facebook.com/docs/api. You can download the Facebook JavaScript SDK at http://github.com/facebook/connect-js/. If your application is using Google AppEngine's webapp framework, your usage of this module might look like this: user = facebook.get_user_from_cookie(self.request.cookies, key, secret) if user: graph = facebook.GraphAPI(user["access_token"]) profile = graph.get_object("me") friends = graph.get_connections("me", "friends") """ import cgi import time import urllib import urllib2 import httplib import hashlib import hmac import base64 import logging import socket # Find a JSON parser try: import simplejson as json except ImportError: try: from django.utils import simplejson as json except ImportError: import json _parse_json = json.loads # Find a query string parser try: from urlparse import parse_qs except ImportError: from cgi import parse_qs class GraphAPI(object): """A client for the Facebook Graph API. See http://developers.facebook.com/docs/api for complete documentation for the API. The Graph API is made up of the objects in Facebook (e.g., people, pages, events, photos) and the connections between them (e.g., friends, photo tags, and event RSVPs). This client provides access to those primitive types in a generic way. For example, given an OAuth access token, this will fetch the profile of the active user and the list of the user's friends: graph = facebook.GraphAPI(access_token) user = graph.get_object("me") friends = graph.get_connections(user["id"], "friends") You can see a list of all of the objects and connections supported by the API at http://developers.facebook.com/docs/reference/api/. You can obtain an access token via OAuth or by using the Facebook JavaScript SDK. See http://developers.facebook.com/docs/authentication/ for details. If you are using the JavaScript SDK, you can use the get_user_from_cookie() method below to get the OAuth access token for the active user from the cookie saved by the SDK. """ def __init__(self, access_token=None, timeout=None): self.access_token = access_token self.timeout = timeout def get_object(self, id, **args): """Fetchs the given object from the graph.""" return self.request(id, args) def get_objects(self, ids, **args): """Fetchs all of the given object from the graph. We return a map from ID to object. If any of the IDs are invalid, we raise an exception. """ args["ids"] = ",".join(ids) return self.request("", args) def get_connections(self, id, connection_name, **args): """Fetchs the connections for given object.""" return self.request(id + "/" + connection_name, args) def put_object(self, parent_object, connection_name, **data): """Writes the given object to the graph, connected to the given parent. For example, graph.put_object("me", "feed", message="Hello, world") writes "Hello, world" to the active user's wall. Likewise, this will comment on a the first post of the active user's feed: feed = graph.get_connections("me", "feed") post = feed["data"][0] graph.put_object(post["id"], "comments", message="First!") See http://developers.facebook.com/docs/api#publishing for all of the supported writeable objects. Certain write operations require extended permissions. For example, publishing to a user's feed requires the "publish_actions" permission. See http://developers.facebook.com/docs/publishing/ for details about publishing permissions. """ assert self.access_token, "Write operations require an access token" return self.request(parent_object + "/" + connection_name, post_args=data) def put_wall_post(self, message, attachment={}, profile_id="me"): """Writes a wall post to the given profile's wall. We default to writing to the authenticated user's wall if no profile_id is specified. attachment adds a structured attachment to the status message being posted to the Wall. It should be a dictionary of the form: {"name": "Link name" "link": "http://www.example.com/", "caption": "{*actor*} posted a new review", "description": "This is a longer description of the attachment", "picture": "http://www.example.com/thumbnail.jpg"} """ return self.put_object(profile_id, "feed", message=message, **attachment) def put_comment(self, object_id, message): """Writes the given comment on the given post.""" return self.put_object(object_id, "comments", message=message) def put_like(self, object_id): """Likes the given post.""" return self.put_object(object_id, "likes") def delete_object(self, id): """Deletes the object with the given ID from the graph.""" self.request(id, post_args={"method": "delete"}) def delete_request(self, user_id, request_id): """Deletes the Request with the given ID for the given user.""" conn = httplib.HTTPSConnection('graph.facebook.com') url = '/%s_%s?%s' % ( request_id, user_id, urllib.urlencode({'access_token': self.access_token}), ) conn.request('DELETE', url) response = conn.getresponse() data = response.read() response = _parse_json(data) # Raise an error if we got one, but don't not if Facebook just # gave us a Bool value if (response and isinstance(response, dict) and response.get("error")): raise GraphAPIError(response) conn.close() def put_photo(self, image, message=None, album_id=None, **kwargs): """Uploads an image using multipart/form-data. image=File like object for the image message=Caption for your image album_id=None posts to /me/photos which uses or creates and uses an album for your application. """ object_id = album_id or "me" #it would have been nice to reuse self.request; #but multipart is messy in urllib post_args = { 'access_token': self.access_token, 'source': image, 'message': message, } post_args.update(kwargs) content_type, body = self._encode_multipart_form(post_args) req = urllib2.Request(("https://graph.facebook.com/%s/photos" % object_id), data=body) req.add_header('Content-Type', content_type) try: data = urllib2.urlopen(req).read() #For Python 3 use this: #except urllib2.HTTPError as e: except urllib2.HTTPError, e: data = e.read() # Facebook sends OAuth errors as 400, and urllib2 # throws an exception, we want a GraphAPIError try: response = _parse_json(data) # Raise an error if we got one, but don't not if Facebook just # gave us a Bool value if (response and isinstance(response, dict) and response.get("error")): raise GraphAPIError(response) except ValueError: response = data return response # based on: http://code.activestate.com/recipes/146306/ def _encode_multipart_form(self, fields): """Encode files as 'multipart/form-data'. Fields are a dict of form name-> value. For files, value should be a file object. Other file-like objects might work and a fake name will be chosen. Returns (content_type, body) ready for httplib.HTTP instance. """ BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' CRLF = '\r\n' L = [] for (key, value) in fields.items(): logging.debug("Encoding %s, (%s)%s" % (key, type(value), value)) if not value: continue L.append('--' + BOUNDARY) if hasattr(value, 'read') and callable(value.read): filename = getattr(value, 'name', '%s.jpg' % key) L.append(('Content-Disposition: form-data;' 'name="%s";' 'filename="%s"') % (key, filename)) L.append('Content-Type: image/jpeg') value = value.read() logging.debug(type(value)) else: L.append('Content-Disposition: form-data; name="%s"' % key) L.append('') if isinstance(value, unicode): logging.debug("Convert to ascii") value = value.encode('ascii') L.append(value) L.append('--' + BOUNDARY + '--') L.append('') body = CRLF.join(L) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body def request(self, path, args=None, post_args=None): """Fetches the given path in the Graph API. We translate args to a valid query string. If post_args is given, we send a POST request to the given path with the given arguments. """ args = args or {} if self.access_token: if post_args is not None: post_args["access_token"] = self.access_token else: args["access_token"] = self.access_token post_data = None if post_args is None else urllib.urlencode(post_args) try: file = urllib2.urlopen("https://graph.facebook.com/" + path + "?" + urllib.urlencode(args), post_data, timeout=self.timeout) except urllib2.HTTPError, e: response = _parse_json(e.read()) raise GraphAPIError(response) except TypeError: # Timeout support for Python <2.6 if self.timeout: socket.setdefaulttimeout(self.timeout) file = urllib2.urlopen("https://graph.facebook.com/" + path + "?" + urllib.urlencode(args), post_data) try: fileInfo = file.info() if fileInfo.maintype == 'text': response = _parse_json(file.read()) elif fileInfo.maintype == 'image': mimetype = fileInfo['content-type'] response = { "data": file.read(), "mime-type": mimetype, "url": file.url, } else: raise GraphAPIError('Maintype was not text or image') finally: file.close() if response and isinstance(response, dict) and response.get("error"): raise GraphAPIError(response["error"]["type"], response["error"]["message"]) return response def fql(self, query, args=None, post_args=None): """FQL query. Example query: "SELECT affiliations FROM user WHERE uid = me()" """ args = args or {} if self.access_token: if post_args is not None: post_args["access_token"] = self.access_token else: args["access_token"] = self.access_token post_data = None if post_args is None else urllib.urlencode(post_args) """Check if query is a dict and use the multiquery method else use single query """ if not isinstance(query, basestring): args["queries"] = query fql_method = 'fql.multiquery' else: args["query"] = query fql_method = 'fql.query' args["format"] = "json" try: file = urllib2.urlopen("https://api.facebook.com/method/" + fql_method + "?" + urllib.urlencode(args), post_data, timeout=self.timeout) except TypeError: # Timeout support for Python <2.6 if self.timeout: socket.setdefaulttimeout(self.timeout) file = urllib2.urlopen("https://api.facebook.com/method/" + fql_method + "?" + urllib.urlencode(args), post_data) try: content = file.read() response = _parse_json(content) #Return a list if success, return a dictionary if failed if type(response) is dict and "error_code" in response: raise GraphAPIError(response) except Exception, e: raise e finally: file.close() return response def extend_access_token(self, app_id, app_secret): """ Extends the expiration time of a valid OAuth access token. See <https://developers.facebook.com/roadmap/offline-access-removal/ #extend_token> """ args = { "client_id": app_id, "client_secret": app_secret, "grant_type": "fb_exchange_token", "fb_exchange_token": self.access_token, } response = urllib.urlopen("https://graph.facebook.com/oauth/" "access_token?" + urllib.urlencode(args)).read() query_str = parse_qs(response) if "access_token" in query_str: result = {"access_token": query_str["access_token"][0]} if "expires" in query_str: result["expires"] = query_str["expires"][0] return result else: response = json.loads(response) raise GraphAPIError(response) class GraphAPIError(Exception): def __init__(self, result): #Exception.__init__(self, message) #self.type = type self.result = result try: self.type = result["error_code"] except: self.type = "" # OAuth 2.0 Draft 10 try: self.message = result["error_description"] except: # OAuth 2.0 Draft 00 try: self.message = result["error"]["message"] except: # REST server style try: self.message = result["error_msg"] except: self.message = result Exception.__init__(self, self.message) def get_user_from_cookie(cookies, app_id, app_secret): """Parses the cookie set by the official Facebook JavaScript SDK. cookies should be a dictionary-like object mapping cookie names to cookie values. If the user is logged in via Facebook, we return a dictionary with the keys "uid" and "access_token". The former is the user's Facebook ID, and the latter can be used to make authenticated requests to the Graph API. If the user is not logged in, we return None. Download the official Facebook JavaScript SDK at http://github.com/facebook/connect-js/. Read more about Facebook authentication at http://developers.facebook.com/docs/authentication/. """ cookie = cookies.get("fbsr_" + app_id, "") if not cookie: return None parsed_request = parse_signed_request(cookie, app_secret) if not parsed_request: return None try: result = get_access_token_from_code(parsed_request["code"], "", app_id, app_secret) except GraphAPIError: return None result["uid"] = parsed_request["user_id"] return result def parse_signed_request(signed_request, app_secret): """ Return dictionary with signed request data. We return a dictionary containing the information in the signed_request. This includes a user_id if the user has authorised your application, as well as any information requested. If the signed_request is malformed or corrupted, False is returned. """ try: encoded_sig, payload = map(str, signed_request.split('.', 1)) sig = base64.urlsafe_b64decode(encoded_sig + "=" * ((4 - len(encoded_sig) % 4) % 4)) data = base64.urlsafe_b64decode(payload + "=" * ((4 - len(payload) % 4) % 4)) except IndexError: # Signed request was malformed. return False except TypeError: # Signed request had a corrupted payload. return False data = _parse_json(data) if data.get('algorithm', '').upper() != 'HMAC-SHA256': return False # HMAC can only handle ascii (byte) strings # http://bugs.python.org/issue5285 app_secret = app_secret.encode('ascii') payload = payload.encode('ascii') expected_sig = hmac.new(app_secret, msg=payload, digestmod=hashlib.sha256).digest() if sig != expected_sig: return False return data def auth_url(app_id, canvas_url, perms=None, **kwargs): url = "https://www.facebook.com/dialog/oauth?" kvps = {'client_id': app_id, 'redirect_uri': canvas_url} if perms: kvps['scope'] = ",".join(perms) kvps.update(kwargs) return url + urllib.urlencode(kvps) def get_access_token_from_code(code, redirect_uri, app_id, app_secret): """Get an access token from the "code" returned from an OAuth dialog. Returns a dict containing the user-specific access token and its expiration date (if applicable). """ args = { "code": code, "redirect_uri": redirect_uri, "client_id": app_id, "client_secret": app_secret, } # We would use GraphAPI.request() here, except for that the fact # that the response is a key-value pair, and not JSON. response = urllib.urlopen("https://graph.facebook.com/oauth/access_token" + "?" + urllib.urlencode(args)).read() query_str = parse_qs(response) if "access_token" in query_str: result = {"access_token": query_str["access_token"][0]} if "expires" in query_str: result["expires"] = query_str["expires"][0] return result else: response = json.loads(response) raise GraphAPIError(response) def get_app_access_token(app_id, app_secret): """Get the access_token for the app. This token can be used for insights and creating test users. app_id = retrieved from the developer page app_secret = retrieved from the developer page Returns the application access_token. """ # Get an app access token args = {'grant_type': 'client_credentials', 'client_id': app_id, 'client_secret': app_secret} file = urllib2.urlopen("https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args)) try: result = file.read().split("=")[1] finally: file.close() return result
Java