code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, browserHistory } from 'react-router'; import * as firebase from "firebase"; import './css/index.css'; import PetPage from './pet'; import Welcome from './welcome'; import AddPet from './add-pet'; import MainLayout from './main-layout'; // Initialize Firebase var config = { apiKey: "AIzaSyCy8OwL_E1rrYfutk5vqLygz20RmGW-GBE", authDomain: "petland-4b867.firebaseapp.com", databaseURL: "https://petland-4b867.firebaseio.com", storageBucket: "gs://petland-4b867.appspot.com/", messagingSenderId: "784140166304" }; firebase.initializeApp(config); ReactDOM.render( <Router history={browserHistory}> <Route component={MainLayout}> <Route path="/" component={Welcome} /> <Route path="/pet/:id" component={PetPage} /> <Route path="/add-pet" component={AddPet} /> </Route> </Router>, document.getElementById('root') );
beleidy/Pet-Land
src/index.js
JavaScript
mit
986
// ----------------------------------------------------------------------- // Licensed to The .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ----------------------------------------------------------------------- // This is a generated file. // The generation template has been modified from .NET Runtime implementation using System; using System.Security.Cryptography.Asn1; namespace Kerberos.NET.Entities { public partial class KrbAsRep : KrbKdcRep { /* AS-REP ::= [APPLICATION 11] KDC-REP */ private static readonly Asn1Tag ApplicationTag = new Asn1Tag(TagClass.Application, 11); public override ReadOnlyMemory<byte> EncodeApplication() { return EncodeApplication(ApplicationTag); } public static KrbAsRep DecodeApplication(ReadOnlyMemory<byte> encoded) { AsnReader reader = new AsnReader(encoded, AsnEncodingRules.DER); var sequence = reader.ReadSequence(ApplicationTag); KrbAsRep decoded; Decode(sequence, out decoded); sequence.ThrowIfNotEmpty(); reader.ThrowIfNotEmpty(); return decoded; } } }
SteveSyfuhs/Kerberos.NET
Kerberos.NET/Entities/Krb/KrbAsRep.generated.cs
C#
mit
1,321
package com.dranawhite.mybatis.Service; /** * @author dranawhite 2017/9/30 * @version 1.0 */ public class PersonService { }
dranawhite/test-java
test-framework/test-mybatis/src/main/java/com/dranawhite/mybatis/Service/PersonService.java
Java
mit
129
from wdom.server import start from wdom.document import set_app from wdom.tag import Div, H1, Input class MyElement(Div): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.h1 = H1(parent=self) self.h1.textContent = 'Hello, WDOM' self.input = Input(parent=self) self.input.addEventListener('input', self.update) def update(self, event): self.h1.textContent = event.target.value if __name__ == '__main__': set_app(MyElement()) start()
miyakogi/wdom
docs/guide/samples/wdom2.py
Python
mit
526
#include<iostream> int* f(int* fst, int* lst, int v) { std::cout << "in f function, pointers are copied" << std::endl; std::cout << "&fst == " << &fst << ", &lst == " << &lst << std::endl; std::cout << "fst == " << fst << ", lst == " << lst << std::endl; while(fst != lst && *fst != v) { ++fst; } return fst; } void g(int* p, int*q) { std::cout << "in g function, pointers are copied" << std::endl; std::cout << "&p == " << &p << ", &q == " << &q << std::endl; std::cout << "p == " << p << ", q == " << q << std::endl; int* pp = f(p, q, 10); } int main() { int a[10] {1, 2, 5, 10, 9, 8, 7}; int* p = a; int* q = p+9; std::cout << "initialized pointers" << std::endl; std::cout << "&p == " << &p << ", &q == " << &q << std::endl; std::cout << "p == " << p << ", q == " << q << std::endl; g(p, q); }
sylsaint/cpp_learning
tcpppl/arguments_passing.cc
C++
mit
881
const { ArgumentError } = require('rest-facade'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** * Abstracts interaction with the stats endpoint. */ class StatsManager { /** * @param {object} options The client options. * @param {string} options.baseUrl The URL of the API. * @param {object} [options.headers] Headers to be included in all requests. * @param {object} [options.retry] Retry Policy Config */ constructor(options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide manager options'); } if (options.baseUrl === null || options.baseUrl === undefined) { throw new ArgumentError('Must provide a base URL for the API'); } if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { throw new ArgumentError('The provided base URL is invalid'); } const clientOptions = { errorFormatter: { message: 'message', name: 'error' }, headers: options.headers, query: { repeatParams: false }, }; /** * Provides an abstraction layer for consuming the * {@link https://auth0.com/docs/api/v2#!/Stats Stats endpoint}. * * @type {external:RestClient} */ const auth0RestClient = new Auth0RestClient( `${options.baseUrl}/stats/:type`, clientOptions, options.tokenProvider ); this.resource = new RetryRestClient(auth0RestClient, options.retry); } /** * Get the daily stats. * * @example * var params = { * from: '{YYYYMMDD}', // First day included in the stats. * to: '{YYYYMMDD}' // Last day included in the stats. * }; * * management.stats.getDaily(params, function (err, stats) { * if (err) { * // Handle error. * } * * console.log(stats); * }); * @param {object} params Stats parameters. * @param {string} params.from The first day in YYYYMMDD format. * @param {string} params.to The last day in YYYYMMDD format. * @param {Function} [cb] Callback function. * @returns {Promise|undefined} */ getDaily(params, cb) { params = params || {}; params.type = 'daily'; if (cb && cb instanceof Function) { return this.resource.get(params, cb); } return this.resource.get(params); } /** * Get a the active users count. * * @example * management.stats.getActiveUsersCount(function (err, usersCount) { * if (err) { * // Handle error. * } * * console.log(usersCount); * }); * @param {Function} [cb] Callback function. * @returns {Promise|undefined} */ getActiveUsersCount(cb) { const options = { type: 'active-users' }; if (cb && cb instanceof Function) { return this.resource.get(options, cb); } // Return a promise. return this.resource.get(options); } } module.exports = StatsManager;
auth0/node-auth0
src/management/StatsManager.js
JavaScript
mit
3,012
const initialState = { minimoPalpite: 2, valorMaximoAposta: 500, valorMinimoAposta: 5, } function BancaReducer(state= initialState, action) { return state; } export default BancaReducer
sysbet/sysbet-mobile
src/reducers/sistema/banca.js
JavaScript
mit
205
// Package acceptlang provides a Martini handler and primitives to parse // the Accept-Language HTTP header values. // // See the HTTP header fields specification for more details // (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4). // // Example // // Use the handler to automatically parse the Accept-Language header and // return the results as response: // m.Get("/", acceptlang.Languages(), func(languages acceptlang.AcceptLanguages) string { // return fmt.Sprintf("Languages: %s", languages) // }) // package acceptlang import ( "bytes" "fmt" "github.com/go-martini/martini" "net/http" "sort" "strconv" "strings" ) const ( acceptLanguageHeader = "Accept-Language" ) // A single language from the Accept-Language HTTP header. type AcceptLanguage struct { Language string Quality float32 } // A slice of sortable AcceptLanguage instances. type AcceptLanguages []AcceptLanguage // Returns the total number of items in the slice. Implemented to satisfy // sort.Interface. func (al AcceptLanguages) Len() int { return len(al) } // Swaps the items at position i and j. Implemented to satisfy sort.Interface. func (al AcceptLanguages) Swap(i, j int) { al[i], al[j] = al[j], al[i] } // Determines whether or not the item at position i is "less than" the item // at position j. Implemented to satisfy sort.Interface. func (al AcceptLanguages) Less(i, j int) bool { return al[i].Quality > al[j].Quality } // Returns the parsed languages in a human readable fashion. func (al AcceptLanguages) String() string { output := bytes.NewBufferString("") for i, language := range al { output.WriteString(fmt.Sprintf("%s (%1.1f)", language.Language, language.Quality)) if i != len(al)-1 { output.WriteString(", ") } } if output.Len() == 0 { output.WriteString("[]") } return output.String() } // Creates a new handler that parses the Accept-Language HTTP header. // // The parsed structure is a slice of Accept-Language values stored in an // AcceptLanguages instance, sorted based on the language qualifier. func Languages() martini.Handler { return func(context martini.Context, request *http.Request) { header := request.Header.Get(acceptLanguageHeader) if header != "" { acceptLanguageHeaderValues := strings.Split(header, ",") acceptLanguages := make(AcceptLanguages, len(acceptLanguageHeaderValues)) for i, languageRange := range acceptLanguageHeaderValues { // Check if a given range is qualified or not if qualifiedRange := strings.Split(languageRange, ";q="); len(qualifiedRange) == 2 { quality, error := strconv.ParseFloat(qualifiedRange[1], 32) if error != nil { // When the quality is unparseable, assume it's 1 acceptLanguages[i] = AcceptLanguage{trimLanguage(qualifiedRange[0]), 1} } else { acceptLanguages[i] = AcceptLanguage{trimLanguage(qualifiedRange[0]), float32(quality)} } } else { acceptLanguages[i] = AcceptLanguage{trimLanguage(languageRange), 1} } } sort.Sort(acceptLanguages) context.Map(acceptLanguages) } else { // If we have no Accept-Language header just map an empty slice context.Map(make(AcceptLanguages, 0)) } } } func trimLanguage(language string) string { return strings.Trim(language, " ") }
martini-contrib/acceptlang
handler.go
GO
mit
3,280
using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using MonoGame.Extended; using MonoGame.Extended.ViewportAdapters; using LudumDare38.Managers; namespace LudumDare38.Scenes { public abstract class SceneBase { //-------------------------------------------------- // Some stuff private SpriteFont _debugFont; public ContentManager Content; public Dictionary<string, string> DebugValues; //-------------------------------------------------- // FPS counter private FramesPerSecondCounter _fpsCounter; //----------------------//------------------------// public virtual void LoadContent() { Content = new ContentManager(SceneManager.Instance.Content.ServiceProvider, "Content"); _fpsCounter = new FramesPerSecondCounter(); _debugFont = Content.Load<SpriteFont>("fonts/DebugFont"); DebugValues = new Dictionary<string, string>(); } public virtual void UnloadContent() { Content.Unload(); } public virtual void Update(GameTime gameTime) { InputManager.Instace.Update(); } public void UpdateFpsCounter(GameTime gameTime) { _fpsCounter.Update(gameTime); } public void DrawDebugValues(SpriteBatch spriteBatch) { if (!SceneManager.Instance.DebugMode) return; spriteBatch.DrawString(_debugFont, string.Format("FPS: {0}", _fpsCounter.AverageFramesPerSecond), new Vector2(5, 5), Color.Gray); var i = 0; foreach (KeyValuePair<string, string> value in DebugValues) spriteBatch.DrawString(_debugFont, value.Key + ": " + value.Value, new Vector2(5, 25 + 20 * i++), Color.Gray); } public virtual void Draw(SpriteBatch spriteBatch, Matrix transformMatrix) { } } }
Phantom-Ignition/LudumDare38
LudumDare38/Scenes/SceneBase.cs
C#
mit
2,014
export default { "hljs-comment": { "color": "#776977" }, "hljs-quote": { "color": "#776977" }, "hljs-variable": { "color": "#ca402b" }, "hljs-template-variable": { "color": "#ca402b" }, "hljs-attribute": { "color": "#ca402b" }, "hljs-tag": { "color": "#ca402b" }, "hljs-name": { "color": "#ca402b" }, "hljs-regexp": { "color": "#ca402b" }, "hljs-link": { "color": "#ca402b" }, "hljs-selector-id": { "color": "#ca402b" }, "hljs-selector-class": { "color": "#ca402b" }, "hljs-number": { "color": "#a65926" }, "hljs-meta": { "color": "#a65926" }, "hljs-built_in": { "color": "#a65926" }, "hljs-builtin-name": { "color": "#a65926" }, "hljs-literal": { "color": "#a65926" }, "hljs-type": { "color": "#a65926" }, "hljs-params": { "color": "#a65926" }, "hljs-string": { "color": "#918b3b" }, "hljs-symbol": { "color": "#918b3b" }, "hljs-bullet": { "color": "#918b3b" }, "hljs-title": { "color": "#516aec" }, "hljs-section": { "color": "#516aec" }, "hljs-keyword": { "color": "#7b59c0" }, "hljs-selector-tag": { "color": "#7b59c0" }, "hljs": { "display": "block", "overflowX": "auto", "background": "#f7f3f7", "color": "#695d69", "padding": "0.5em" }, "hljs-emphasis": { "fontStyle": "italic" }, "hljs-strong": { "fontWeight": "bold" } }
conorhastings/react-syntax-highlighter
src/styles/hljs/atelier-heath-light.js
JavaScript
mit
1,709
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using MySql.Data.MySqlClient; using Jam; using System.IO; public partial class UIControls_ImageCover : JamUIControl { public UIControls_ImageCover() { m_Code = 56; } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { FillForm(); } } public string DefaultImgUrl { get { return (string)ViewState["DefaultImgUrl"]; } set { ViewState["DefaultImgUrl"] = value; } } public string ImgId { get { return (string)ViewState["ImgId"]; } set { ViewState["ImgId"] = value; } } public string BandId { get { return (string)ViewState["BandId"]; } set { ViewState["BandId"] = value; } } public string Visibility { get { return (string)ViewState["Visibility"]; } set { ViewState["Visibility"] = value; } } private string NewImgFile { get { return (uplImg.Visible && uplImg.HasFile) ? "~/images/" + JamTypes.User.GetUserFromSession(Session).Id + "/" + uplImg.FileName : null; } } public bool Deleted { get { return ViewState["Deleted"] != null ? (bool)ViewState["Deleted"] : false; } private set { ViewState["Deleted"] = value; } } protected void btnChangeCover_Click(object sender, EventArgs e) { if (btnChangeCover.Text == "Change") { lbImgCoverFile.Visible = false; uplImg.Visible = true; btnChangeCover.Text = "Cancel"; } else { lbImgCoverFile.Visible = true; uplImg.Visible = false; btnChangeCover.Text = "Change"; } } private void FillForm() { lbImgCoverFile.Text = ""; imgCover.ImageUrl = DefaultImgUrl; if (!String.IsNullOrEmpty(ImgId)) { uplImg.Visible = false; lbImgCoverFile.Visible = true; trCoverBtn.Visible = true; imgCover.ImageUrl = "~/GetImage.aspx?id=" + ImgId; FillImageName(ImgId); } else { uplImg.Visible = true; lbImgCoverFile.Visible = false; trCoverBtn.Visible = false; } } private void FillImageName(string sImgId) { MySqlConnection con = Utils.GetSqlConnection(); if (con != null) { try { MySqlCommand cmd = new MySqlCommand("select FileName from images where Id=?Id", con); cmd.Parameters.Add("?Id", MySqlDbType.UInt64).Value = UInt64.Parse(sImgId); string sImgFile = cmd.ExecuteScalar().ToString(); if (!String.IsNullOrEmpty(sImgFile)) { sImgFile = sImgFile.Substring(("~/images/" + JamTypes.User.GetUserFromSession(Session).Id + "/").Length); lbImgCoverFile.Text = sImgFile; } } catch (Exception ex) { JamLog.log(JamLog.enEntryType.error, "ImageCover", "FillImageName: " + ex.Message); } finally { con.Close(); } } } //return Id in tables images public string Save(MySqlConnection con, MySqlTransaction trans) { if(!String.IsNullOrEmpty(ImgId))//update { if (!Deleted) { MySqlCommand cmd = new MySqlCommand("", con, trans); cmd.CommandText = "update images set "; if (!String.IsNullOrEmpty(NewImgFile)) { cmd.CommandText += " FileName = ?FileName,"; cmd.Parameters.Add("?FileName", MySqlDbType.VarChar, 100).Value = NewImgFile; } cmd.CommandText += @"BandId=?BandId, Visibility=?Visibility, Updated=?Updated where Id=?Id;"; cmd.Parameters.Add("?BandId", MySqlDbType.UInt64).Value = null; if (!String.IsNullOrEmpty(BandId)) cmd.Parameters.Add("?BandId", MySqlDbType.UInt64).Value = UInt64.Parse(BandId); cmd.Parameters.Add("?Visibility", MySqlDbType.Int16).Value = Int16.Parse(Visibility); cmd.Parameters.Add("?Updated", MySqlDbType.DateTime).Value = DateTime.UtcNow; cmd.Parameters.Add("?Id", MySqlDbType.UInt64).Value = UInt64.Parse(ImgId); cmd.ExecuteNonQuery(); if (!String.IsNullOrEmpty(NewImgFile)) { uplImg.SaveAs(MapPath(NewImgFile)); if (!String.IsNullOrEmpty(lbImgCoverFile.Text)) { //delete previous path string sDeletePath = this.MapPath("~/images/") + JamTypes.User.GetUserFromSession(Session).Id + "/" + lbImgCoverFile.Text.Trim(); File.Delete(sDeletePath); } } return ImgId; } else //delete { MySqlCommand cmd = new MySqlCommand("delete from images where Id=?Id", con, trans); cmd.Parameters.Add("?Id", MySqlDbType.UInt64).Value = UInt64.Parse(ImgId); cmd.ExecuteNonQuery(); if (!String.IsNullOrEmpty(lbImgCoverFile.Text)) { //delete previous path string sDeletePath = this.MapPath("~/images/") + JamTypes.User.GetUserFromSession(Session).Id + "/" + lbImgCoverFile.Text.Trim(); File.Delete(sDeletePath); } return null; } } else if(!String.IsNullOrEmpty(NewImgFile)) //create { MySqlCommand cmd = new MySqlCommand("", con, trans); cmd.CommandText = @"insert into images (FileName, BandId, Visibility, Updated) values(?FileName, ?BandId, ?Visibility, ?Updated); SELECT LAST_INSERT_ID();"; cmd.Parameters.Add("?FileName", MySqlDbType.VarChar, 100).Value = NewImgFile; if (!String.IsNullOrEmpty(BandId)) cmd.Parameters.Add("?BandId", MySqlDbType.UInt64).Value = UInt64.Parse(BandId); else cmd.Parameters.Add("?BandId", MySqlDbType.UInt64).Value = null; cmd.Parameters.Add("?Visibility", MySqlDbType.Int16).Value = Int16.Parse(Visibility); cmd.Parameters.Add("?Updated", MySqlDbType.DateTime).Value = DateTime.UtcNow; string sRet = cmd.ExecuteScalar().ToString(); uplImg.SaveAs(MapPath(NewImgFile)); return sRet; } return null; } protected void btnDelete_Click(object sender, EventArgs e) { Deleted = true; imgCover.ImageUrl = DefaultImgUrl; uplImg.Visible = true; lbImgCoverFile.Visible = false; trCoverBtn.Visible = false; } }
hardsky/music-head
web/UIControls/ImageCover.ascx.cs
C#
mit
7,390
module Log2irc class Channel class << self # hostname or ip def move(to, hostname_ip) if channels[to].nil? channels[to] = {} Log2irc.bot.join(to) end ip, hostname = remove(hostname_ip) channels[to][ip] = { hostname: hostname, last_log: Time.now.to_i } save_config end # hostname or ip def rename(hostname_ip, hostname) channels.each do |channel, hosts| hosts.each do |ip, data| next unless ip == hostname_ip || data[:hostname] == hostname_ip channels[channel][ip][:hostname] = hostname save_config return true end end false end # hostname or ip def refresh(hostname_ip) channels.each do |channel, hosts| hosts.each do |ip, data| next unless ip == hostname_ip || data[:hostname] == hostname_ip channels[channel][ip][:hostname] = resolv(ip) save_config return channels[channel][ip][:hostname] end end false end # hostname or ip def remove(hostname_ip) channels.each do |channel, hosts| hosts.each do |ip, data| next unless ip == hostname_ip || data[:hostname] == hostname_ip channels[channel].delete(ip) if channels[channel].empty? channels.delete(channel) Log2irc.bot.part(channel) end return [ip, data[:hostname]] end end nil end # hostname or ip def watchdog(hostname_ip, time) channels.each do |channel, hosts| hosts.each do |ip, data| next unless ip == hostname_ip || data[:hostname] == hostname_ip data[:watchdog] = time return [ip, data[:hostname]] end end nil end # ip def find(host_ip) channels.each do |channel, hosts| hosts.each do |ip, data| if ip == host_ip data[:last_log] = Time.now.to_i return [channel, data[:hostname]] end end end [Log2irc.settings['irc']['channel'], add_new_host(host_ip)] end def channels return @channels if @channels if File.exist?(file_path) @channels = YAML.load_file(file_path) else @channels = {} end @channels.each do |ch, _list| Log2irc.bot.join(ch) end end def add_new_host(host_ip) ch = Log2irc.settings['irc']['channel'] channels[ch] = {} unless channels[ch] channels[ch][host_ip] = { hostname: resolv(host_ip), last_log: Time.now.to_i } save_config channels[ch][host_ip][:hostname] end def resolv(host_ip) Resolv.getname(host_ip) rescue host_ip end def save_config File.open(file_path, 'w') do |f| f.write channels.to_yaml end end def file_path File.join(Log2irc.path, '../config/channels.yml') end end end end
l3akage/log2irc
lib/log2irc/channel.rb
Ruby
mit
3,230
class DropFactualPages < ActiveRecord::Migration[5.0] def up drop_table :factual_pages end def down raise ActiveRecord::IrreversibleMigration end end
artsy/bearden
db/migrate/20170223222333_drop_factual_pages.rb
Ruby
mit
167
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using OpenORPG.Database.DAL; using Server.Game.Combat; using Server.Game.Database; using Server.Game.Database.Models.ContentTemplates; using Server.Game.Entities; using Server.Infrastructure.Logging; namespace Server.Game.Items { /// <summary> /// A <see cref="SkillbookItem"/> is capable of granting a user a skill permanently when used. /// The item will be consumed when used, typically. /// </summary> public class SkillbookItem : Item { public SkillbookItem(ItemTemplate itemTemplate) : base(itemTemplate) { } public override bool Consumable { get { return true; } } public override void UseItemOn(Character character, Character user) { var player = character as Player; if (player != null) { using (var context = new GameDatabaseContext()) { var skillRepo = new SkillRepository(context); var skillTemplate = skillRepo.Get(ItemTemplate.LearntSkillId); player.AddSkill(new Skill(skillTemplate)); } } else { Logger.Instance.Warn("You cannot use a skillbook on a non-player target."); } } } }
hilts-vaughan/OpenORPG
OpenORPG.Server/Game/Items/SkillbookItem.cs
C#
mit
1,487
module Gandi class Domain class Host include Gandi::GandiObjectMethods #The hostname of the Host attr_reader :hostname def initialize(hostname, attributes = nil) @hostname = hostname @attributes = attributes || info end #Delete a host. #Returns a Gandi::Operation object. def delete operation_hash = self.class.call('domain.host.delete', @hostname) Gandi::Operation.new(operation_hash['id'], operation_hash) end #Display host information for a given domain. def info self.class.call('domain.host.info', @hostname) end #Return the host IP adresses. def ips @attributes['ips'] end #Update a host. #Return a Gandi::Operation object. def update(ips) operation_hash = self.class.call('domain.host.update', @hostname, ips) Gandi::Operation.new(operation_hash['id'], operation_hash) end class << self #Create a host. #Returns a Gandi::Operation object. def create(hostname, ips) operation_hash = call('domain.host.create', hostname, ips) Gandi::Operation.new(operation_hash['id'], operation_hash) end #Count the glue records / hosts of a domain. #TODO: accept a Domain object. def count(fqdn, opts = {}) call('domain.host.count', fqdn, opts) end #List the glue records / hosts for a given domain. #Return an array of Host objects. #TODO: accept a Domain object. def list(fqdn, opts = {}) call('domain.host.list', fqdn, opts).map do |host| self.new(host['name'], host) end end end end end end
pickabee/gandi
lib/gandi/domain/host.rb
Ruby
mit
1,820
#!/bin/python3 import sys time = input().strip() # 12AM = 00:00 # 12PM = 12:00 # 01PM = 13:00 meridian = time[-2:] time = time[:-2] hour, minute, second = time.split(":") hour = int(hour, 10) if meridian == "PM": if hour != 12: hour += 12 else: if hour == 12: hour = 0 print("{:0>2d}:{}:{}".format(hour, minute, second))
costincaraivan/hackerrank
algorithms/warmup/python3/time_conversion.py
Python
mit
351
""" Test suite for the cppext library. The script can be executed on its own or incorporated into a larger test suite. However the tests are run, be aware of which version of the package is actually being tested. If the package is installed in site-packages, that version takes precedence over the version in this project directory. Use a virtualenv test environment or setuptools develop mode to test against the development version. """ import pytest from cppext import * def test_pyhello(): """ Test the pyhello() function. """ assert pyhello() == "Greetings from Python!" return def test_cpphello(): """ Test the cpphello() function. """ assert cpphello() == "Greetings from C++!" return class CppGreetingTest(object): """ Test suite for the CppGreeting class. """ def test_hello(self): """ Test the hello() method. """ name = "CppGreetingTest" greeting = CppGreeting(name) assert greeting.hello() == "Greetings from C++, {:s}!".format(name) return # Make the module executable. if __name__ == "__main__": raise SystemExit(pytest.main([__file__]))
mdklatt/cppext-python
test/test_cppext.py
Python
mit
1,176
/* * Copyright (c) 2017 Andrew Kelley * * This file is part of zig, which is MIT licensed. * See http://opensource.org/licenses/MIT */ #include "bigfloat.hpp" #include "bigint.hpp" #include "buffer.hpp" #include "softfloat.hpp" #include <stdio.h> #include <math.h> #include <errno.h> void bigfloat_init_128(BigFloat *dest, float128_t x) { dest->value = x; } void bigfloat_init_16(BigFloat *dest, float16_t x) { f16_to_f128M(x, &dest->value); } void bigfloat_init_32(BigFloat *dest, float x) { float32_t f32_val; memcpy(&f32_val, &x, sizeof(float)); f32_to_f128M(f32_val, &dest->value); } void bigfloat_init_64(BigFloat *dest, double x) { float64_t f64_val; memcpy(&f64_val, &x, sizeof(double)); f64_to_f128M(f64_val, &dest->value); } void bigfloat_init_bigfloat(BigFloat *dest, const BigFloat *x) { memcpy(&dest->value, &x->value, sizeof(float128_t)); } void bigfloat_init_bigint(BigFloat *dest, const BigInt *op) { ui32_to_f128M(0, &dest->value); if (op->digit_count == 0) return; float128_t base; ui64_to_f128M(UINT64_MAX, &base); const uint64_t *digits = bigint_ptr(op); for (size_t i = op->digit_count - 1;;) { float128_t digit_f128; ui64_to_f128M(digits[i], &digit_f128); f128M_mulAdd(&dest->value, &base, &digit_f128, &dest->value); if (i == 0) { if (op->is_negative) { float128_t zero_f128; ui32_to_f128M(0, &zero_f128); f128M_sub(&zero_f128, &dest->value, &dest->value); } return; } i -= 1; } } int bigfloat_init_buf_base10(BigFloat *dest, const uint8_t *buf_ptr, size_t buf_len) { char *str_begin = (char *)buf_ptr; char *str_end; errno = 0; double value = strtod(str_begin, &str_end); // TODO actual f128 parsing if (errno) { return ErrorOverflow; } float64_t value_f64; memcpy(&value_f64, &value, sizeof(double)); f64_to_f128M(value_f64, &dest->value); assert(str_end <= ((char*)buf_ptr) + buf_len); return 0; } void bigfloat_add(BigFloat *dest, const BigFloat *op1, const BigFloat *op2) { f128M_add(&op1->value, &op2->value, &dest->value); } void bigfloat_negate(BigFloat *dest, const BigFloat *op) { float128_t zero_f128; ui32_to_f128M(0, &zero_f128); f128M_sub(&zero_f128, &op->value, &dest->value); } void bigfloat_sub(BigFloat *dest, const BigFloat *op1, const BigFloat *op2) { f128M_sub(&op1->value, &op2->value, &dest->value); } void bigfloat_mul(BigFloat *dest, const BigFloat *op1, const BigFloat *op2) { f128M_mul(&op1->value, &op2->value, &dest->value); } void bigfloat_div(BigFloat *dest, const BigFloat *op1, const BigFloat *op2) { f128M_div(&op1->value, &op2->value, &dest->value); } void bigfloat_div_trunc(BigFloat *dest, const BigFloat *op1, const BigFloat *op2) { f128M_div(&op1->value, &op2->value, &dest->value); f128M_roundToInt(&dest->value, softfloat_round_minMag, false, &dest->value); } void bigfloat_div_floor(BigFloat *dest, const BigFloat *op1, const BigFloat *op2) { f128M_div(&op1->value, &op2->value, &dest->value); f128M_roundToInt(&dest->value, softfloat_round_min, false, &dest->value); } void bigfloat_rem(BigFloat *dest, const BigFloat *op1, const BigFloat *op2) { f128M_rem(&op1->value, &op2->value, &dest->value); } void bigfloat_mod(BigFloat *dest, const BigFloat *op1, const BigFloat *op2) { f128M_rem(&op1->value, &op2->value, &dest->value); f128M_add(&dest->value, &op2->value, &dest->value); f128M_rem(&dest->value, &op2->value, &dest->value); } void bigfloat_append_buf(Buf *buf, const BigFloat *op) { const size_t extra_len = 100; size_t old_len = buf_len(buf); buf_resize(buf, old_len + extra_len); // TODO actually print f128 float64_t f64_value = f128M_to_f64(&op->value); double double_value; memcpy(&double_value, &f64_value, sizeof(double)); int len = snprintf(buf_ptr(buf) + old_len, extra_len, "%f", double_value); assert(len > 0); buf_resize(buf, old_len + len); } Cmp bigfloat_cmp(const BigFloat *op1, const BigFloat *op2) { if (f128M_lt(&op1->value, &op2->value)) { return CmpLT; } else if (f128M_eq(&op1->value, &op2->value)) { return CmpEQ; } else { return CmpGT; } } float16_t bigfloat_to_f16(const BigFloat *bigfloat) { return f128M_to_f16(&bigfloat->value); } float bigfloat_to_f32(const BigFloat *bigfloat) { float32_t f32_value = f128M_to_f32(&bigfloat->value); float result; memcpy(&result, &f32_value, sizeof(float)); return result; } double bigfloat_to_f64(const BigFloat *bigfloat) { float64_t f64_value = f128M_to_f64(&bigfloat->value); double result; memcpy(&result, &f64_value, sizeof(double)); return result; } float128_t bigfloat_to_f128(const BigFloat *bigfloat) { return bigfloat->value; } Cmp bigfloat_cmp_zero(const BigFloat *bigfloat) { float128_t zero_float; ui32_to_f128M(0, &zero_float); if (f128M_lt(&bigfloat->value, &zero_float)) { return CmpLT; } else if (f128M_eq(&bigfloat->value, &zero_float)) { return CmpEQ; } else { return CmpGT; } } bool bigfloat_has_fraction(const BigFloat *bigfloat) { float128_t floored; f128M_roundToInt(&bigfloat->value, softfloat_round_minMag, false, &floored); return !f128M_eq(&floored, &bigfloat->value); } void bigfloat_sqrt(BigFloat *dest, const BigFloat *op) { f128M_sqrt(&op->value, &dest->value); }
Dimenus/zig
src/bigfloat.cpp
C++
mit
5,573
<?php class Bug extends Eloquent { public $table = 'bugs'; public static $rules = array( 'page'=>'required', 'prio'=>'required', 'message'=>'required' ); public function user() { return $this->belongsTo('User'); } }
murum/baxacykel
app/models/Bug.php
PHP
mit
243
require 'thread_safe' module ActiveModel class Serializer extend ActiveSupport::Autoload autoload :Configuration autoload :ArraySerializer autoload :Adapter include Configuration class << self attr_accessor :_attributes attr_accessor :_attributes_keys attr_accessor :_associations attr_accessor :_urls attr_accessor :_cache attr_accessor :_fragmented attr_accessor :_cache_key attr_accessor :_cache_only attr_accessor :_cache_except attr_accessor :_cache_options end def self.inherited(base) base._attributes = self._attributes.try(:dup) || [] base._attributes_keys = self._attributes_keys.try(:dup) || {} base._associations = self._associations.try(:dup) || {} base._urls = [] end def self.attributes(*attrs) attrs = attrs.first if attrs.first.class == Array @_attributes.concat attrs @_attributes.uniq! attrs.each do |attr| define_method attr do object && object.read_attribute_for_serialization(attr) end unless method_defined?(attr) || _fragmented.respond_to?(attr) end end def self.attribute(attr, options = {}) key = options.fetch(:key, attr) @_attributes_keys[attr] = {key: key} if key != attr @_attributes << key unless @_attributes.include?(key) define_method key do object.read_attribute_for_serialization(attr) end unless method_defined?(key) || _fragmented.respond_to?(attr) end def self.fragmented(serializer) @_fragmented = serializer end # Enables a serializer to be automatically cached def self.cache(options = {}) @_cache = ActionController::Base.cache_store if Rails.configuration.action_controller.perform_caching @_cache_key = options.delete(:key) @_cache_only = options.delete(:only) @_cache_except = options.delete(:except) @_cache_options = (options.empty?) ? nil : options end # Defines an association in the object should be rendered. # # The serializer object should implement the association name # as a method which should return an array when invoked. If a method # with the association name does not exist, the association name is # dispatched to the serialized object. def self.has_many(*attrs) associate(:has_many, attrs) end # Defines an association in the object that should be rendered. # # The serializer object should implement the association name # as a method which should return an object when invoked. If a method # with the association name does not exist, the association name is # dispatched to the serialized object. def self.belongs_to(*attrs) associate(:belongs_to, attrs) end # Defines an association in the object should be rendered. # # The serializer object should implement the association name # as a method which should return an object when invoked. If a method # with the association name does not exist, the association name is # dispatched to the serialized object. def self.has_one(*attrs) associate(:has_one, attrs) end def self.associate(type, attrs) #:nodoc: options = attrs.extract_options! self._associations = _associations.dup attrs.each do |attr| unless method_defined?(attr) define_method attr do object.send attr end end self._associations[attr] = {type: type, association_options: options} end end def self.url(attr) @_urls.push attr end def self.urls(*attrs) @_urls.concat attrs end def self.serializer_for(resource, options = {}) if resource.respond_to?(:serializer_class) resource.serializer_class elsif resource.respond_to?(:to_ary) config.array_serializer else options .fetch(:association_options, {}) .fetch(:serializer, get_serializer_for(resource.class)) end end def self.adapter adapter_class = case config.adapter when Symbol ActiveModel::Serializer::Adapter.adapter_class(config.adapter) when Class config.adapter end unless adapter_class valid_adapters = Adapter.constants.map { |klass| ":#{klass.to_s.downcase}" } raise ArgumentError, "Unknown adapter: #{config.adapter}. Valid adapters are: #{valid_adapters}" end adapter_class end def self._root @@root ||= false end def self._root=(root) @@root = root end def self.root_name name.demodulize.underscore.sub(/_serializer$/, '') if name end attr_accessor :object, :root, :meta, :meta_key, :scope def initialize(object, options = {}) @object = object @options = options @root = options[:root] || (self.class._root ? self.class.root_name : false) @meta = options[:meta] @meta_key = options[:meta_key] @scope = options[:scope] scope_name = options[:scope_name] if scope_name && !respond_to?(scope_name) self.class.class_eval do define_method scope_name, lambda { scope } end end end def json_key if root == true || root.nil? self.class.root_name else root end end def id object.id if object end def type object.class.to_s.demodulize.underscore.pluralize end def attributes(options = {}) attributes = if options[:fields] self.class._attributes & options[:fields] else self.class._attributes.dup end attributes += options[:required_fields] if options[:required_fields] attributes.each_with_object({}) do |name, hash| unless self.class._fragmented hash[name] = send(name) else hash[name] = self.class._fragmented.public_send(name) end end end def each_association(&block) self.class._associations.dup.each do |name, association_options| next unless object association_value = send(name) serializer_class = ActiveModel::Serializer.serializer_for(association_value, association_options) if serializer_class serializer = serializer_class.new( association_value, options.merge(serializer_from_options(association_options)) ) elsif !association_value.nil? && !association_value.instance_of?(Object) association_options[:association_options][:virtual_value] = association_value end if block_given? block.call(name, serializer, association_options[:association_options]) end end end def serializer_from_options(options) opts = {} serializer = options.fetch(:association_options, {}).fetch(:serializer, nil) opts[:serializer] = serializer if serializer opts end def self.serializers_cache @serializers_cache ||= ThreadSafe::Cache.new end private attr_reader :options def self.get_serializer_for(klass) serializers_cache.fetch_or_store(klass) do serializer_class_name = "#{klass.name}Serializer" serializer_class = serializer_class_name.safe_constantize if serializer_class serializer_class elsif klass.superclass get_serializer_for(klass.superclass) end end end end end
Yakrware/active_model_serializers
lib/active_model/serializer.rb
Ruby
mit
7,560
@extends('app') @section('title',$profile->user->name.'的主页') {{--@section('header-css') <link rel="stylesheet" href="/css/profile.css"> <link rel="stylesheet" href="/css/search.css"> @endsection--}} {{--@section('header-js') <script src="/js/source/vue.js"></script> <script src="/js/source/vue-resource.min.js"></script> @endsection--}} @section('content') <div class="profile" id="app"> @include('common.profile_header') <div class="container"> <div class="profile-main row"> @include('common.profile_left_navbar') <div class="profile-posts col-md-9 profile-my-content"> <h3 class="ui horizontal divider header"> <i class="bar chart icon"></i> @if(!\Auth::check()) 他的帖子 @elseif(\Auth::check()&&\Auth::user()->owns($profile)) 我的帖子 @else 他的帖子 @endif </h3> <ul class="profile-list"> @foreach($posts as $post) <li> <div class="row"> <div class="col-md-1 col-xs-1"> <span class="label label-success profile-label">{{$post->comment_count}}回复</span> </div> <div class="col-md-8 col-xs-8"> <a class="profile-article-title" href="/discussion/{{$post->id}}">{{$post->title}}</a> </div> <div class="col-md-3 col-xs-3" style="font-size: 16px"> <span class="profile-article-time">帖子发表于{{$post->created_at->diffForHumans()}}</span> </div> </div> </li> @endforeach </ul> </div> </div> </div> </div> @endsection @section('footer-js') <script> $(document).ready(function () { $('#profile-posts-list').addClass('active'); }); </script> @include('common.profile_follow_user') @endsection
GeekGhc/ISpace
resources/views/profile/post.blade.php
PHP
mit
2,510
import { types } from './types'; interface FetchCafeRequested { type: types.FETCH_CAFE_REQUESTED; payload: number; } interface FetchCafeSucceeded { type: types.FETCH_CAFE_SUCCEEDED; payload: any; } interface FetchCafeFailed { type: types.FETCH_CAFE_FAILED; payload: any; } export type FetchCafeAction = | FetchCafeRequested | FetchCafeSucceeded | FetchCafeFailed; export const fetchCafe = (id: number) => ({ type: types.FETCH_CAFE_REQUESTED, payload: id, }); export const fetchCafeSucceeded = (cafe: any) => ({ type: types.FETCH_CAFE_SUCCEEDED, payload: cafe, }); export const fetchCafeFailed = (err: any) => ({ type: types.FETCH_CAFE_FAILED, payload: err.message, });
mjlaufer/cafe-tour-client
src/client/components/screens/CafeDetail/actions/index.ts
TypeScript
mit
691
namespace E06_BirthdayCelebrations.Models { public class Robot : SocietyMember { private string model; public Robot(string id, string model) : base(id) { this.Model = model; } public string Model { get { return this.model; } private set { this.model = value; } } } }
Rusev12/Software-University-SoftUni
C# OOP Advanced/01-Interfaces-and-Abstraction/E06-BirthdayCelebrations/Models/Robot.cs
C#
mit
397
# flake8: noqa # -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Event.is_published' db.add_column('event_rsvp_event', 'is_published', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False) def backwards(self, orm): # Deleting field 'Event.is_published' db.delete_column('event_rsvp_event', 'is_published') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'event_rsvp.event': { 'Meta': {'object_name': 'Event'}, 'allow_anonymous_rsvp': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'available_seats': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'city': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'contact_email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'contact_person': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'contact_phone': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'country': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'creation_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'max_length': '1000', 'null': 'True', 'blank': 'True'}), 'end': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 17, 0, 0)'}), 'hide_available_seats': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'max_seats_per_guest': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'required_fields': ('event_rsvp.models.MultiSelectField', [], {'max_length': '250', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '256'}), 'start': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 16, 0, 0)'}), 'street': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'template_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '256'}), 'venue': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'zip': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}) }, 'event_rsvp.guest': { 'Meta': {'object_name': 'Guest'}, 'creation_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'event': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'guests'", 'to': "orm['event_rsvp.Event']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_attending': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'message': ('django.db.models.fields.TextField', [], {'max_length': '4000', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}), 'number_of_seats': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'phone': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}) } } complete_apps = ['event_rsvp']
bitmazk/django-event-rsvp
event_rsvp/migrations/0008_auto__add_field_event_is_published.py
Python
mit
7,470
<?php namespace Bit3\FakerCli\Command; use Faker\Factory; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class GenerateCommand extends Command { protected function configure() { $this ->setName('faker:generate') ->addOption( 'locale', 'l', InputOption::VALUE_REQUIRED, 'The locale to use.', Factory::DEFAULT_LOCALE ) ->addOption( 'seed', 's', InputOption::VALUE_REQUIRED, 'The generators seed.' ) ->addOption( 'pattern', 'p', InputOption::VALUE_REQUIRED, 'The printf pattern.', '%s' ) ->addOption( 'delimiter', 'd', InputOption::VALUE_REQUIRED, 'The delimiter is used by the csv and printf format.', ',' ) ->addOption( 'enclosure', 'e', InputOption::VALUE_REQUIRED, 'The enclosure is used by the csv and printf format.' ) ->addOption( 'escape', 'E', InputOption::VALUE_REQUIRED, 'The escape character is used by the printf format.', '\\' ) ->addOption( 'format', 'f', InputOption::VALUE_REQUIRED, 'The output format (json, xml, csv, php, printf, vprintf)', 'printf' ) ->addOption( 'count', 'c', InputArgument::OPTIONAL, 'The count of generated data.', 10 ) ->addArgument( 'type', InputArgument::REQUIRED, 'The data type to generate (e.g. "randomDigit", "words", "name", "city")' ) ->addArgument( 'args', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'Arguments for the type, e.g. "words 5" will generate 5 words.' ); } protected function execute(InputInterface $input, OutputInterface $output) { $locale = $input->getOption('locale'); $seed = $input->getOption('seed'); $format = $input->getOption('format'); $count = $input->getOption('count'); $type = $input->getArgument('type'); $args = $input->getArgument('args'); $data = array(); $faker = Factory::create($locale); if ($seed) { $faker->seed($seed); } for ($i = 0; $i < $count; $i++) { $data[] = $faker->format($type, $args); } switch ($format) { case 'json': $this->outputJson($output, $data); break; case 'xml': $this->outputXml($output, $data); break; case 'csv': $this->outputCsv($input, $output, $data); break; case 'php': $this->outputPhp($output, $data); break; case 'printf': $this->outputPrintf($input, $output, $data); break; case 'vprintf': $this->outputVprintf($input, $output, $data); break; default: throw new \RuntimeException('Unknown output format ' . $format); } } /** * Generate and output the data as JSON. * * @param OutputInterface $output * @param mixed $data */ protected function outputJson(OutputInterface $output, $data) { $json = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); $output->write($json); } /** * Generate and output the data as XML. * * @param OutputInterface $output * @param mixed $data */ protected function outputXml(OutputInterface $output, $data) { $doc = new \DOMDocument(); $doc->formatOutput = true; $doc->appendChild($this->generateXml($doc, $data)); $xml = $doc->saveXML(); $output->write($xml); } /** * Generate a xml element from the input data. * * @param \DOMDocument $doc * @param mixed $data * * @return \DOMElement */ protected function generateXml(\DOMDocument $doc, $data) { if (is_array($data) && range(0, count($data) - 1) == array_keys($data)) { // $data is a regular indexed array $array = $doc->createElement('array'); foreach ($data as $value) { $entry = $doc->createElement('item'); $entry->appendChild($this->generateXml($doc, $value)); $array->appendChild($entry); } return $array; } else if (is_array($data) || is_object($data)) { // $data is an associative array or object $map = $doc->createElement('map'); foreach ($data as $key => $value) { $entry = $doc->createElement('item'); $entry->setAttribute('key', $key); $entry->appendChild($this->generateXml($doc, $value)); $map->appendChild($entry); } return $map; } else { // $data is a primitive type return $doc->createTextNode($data); } } /** * Generate and output the data as CSV. * * @param OutputInterface $output * @param mixed $data */ protected function outputCsv(InputInterface $input, OutputInterface $output, $data) { $delimiter = $input->getOption('delimiter'); $enclosure = $input->getOption('enclosure'); $stream = fopen('php://temp', 'w+'); foreach ($data as $row) { if ($enclosure === null) { fputcsv($stream, $this->flattenArray($row), $delimiter); } else { fputcsv($stream, $this->flattenArray($row), $delimiter, $enclosure); } } fseek($stream, 0); $csv = stream_get_contents($stream); $output->write($csv); } /** * Flatten an array. * * @param $data * * @return array */ protected function flattenArray($data) { if (is_array($data) || is_object($data)) { $buffer = array(); foreach ($data as $item) { $buffer = array_merge($buffer, $this->flattenArray($item)); } return $buffer; } else { return (array) $data; } } /** * Generate and output the data as PHP. * * @param OutputInterface $output * @param mixed $data */ protected function outputPhp(OutputInterface $output, $data) { $php = var_export($data, true); $output->write($php); } /** * Generate and output the data as PHP. * * @param OutputInterface $output * @param mixed $data */ protected function outputPrintf(InputInterface $input, OutputInterface $output, $data) { $pattern = $input->getOption('pattern'); $delimiter = $input->getOption('delimiter'); $enclosure = $input->getOption('enclosure'); $escape = $input->getOption('escape'); foreach ($data as $value) { $value = $this->flattenArray($value); $value = implode($delimiter, $value); if ($enclosure) { $value = $enclosure . str_replace($enclosure, $escape . $enclosure, $value) . $enclosure; } $output->writeln(sprintf($pattern, $value)); } } /** * Generate and output the data as PHP. * * @param OutputInterface $output * @param mixed $data */ protected function outputVprintf(InputInterface $input, OutputInterface $output, $data) { $pattern = $input->getOption('pattern'); $enclosure = $input->getOption('enclosure'); $escape = $input->getOption('escape'); foreach ($data as $values) { $values = $this->flattenArray((array) $values); if ($enclosure) { foreach ($values as $key => $value) { $values[$key] = $enclosure . str_replace($enclosure, $escape . $enclosure, $value) . $enclosure; } } $output->writeln(vsprintf($pattern, $values)); } } }
bit3/faker-cli
src/Command/GenerateCommand.php
PHP
mit
7,146
<h4><b>Statistics Summary</b></h4> <br> <p><b>A) Gender Student Distribution</b></p> <hr> <table class="table table-striped table-responsive table-hover"> <thead id="gender_table_head"> </thead> <tbody id="gender_table_body"> </tbody> </table> <br> <p><b>B) Muslim Student Distribution</b></p> <hr> <table class="table table-striped table-responsive table-hover"> <thead id="muslim_table_head"> </thead> <tbody id="muslim_table_body"> </tbody> </table> <br> <p><b>C) CGPA Category Student Distribution</b></p> <hr> <table class="table table-striped table-responsive table-hover"> <thead id="cgpa_category_student_table_head"> </thead> <tbody id="cgpa_category_student_table_body"> </tbody> </table> <br> <p><b>D) Program Student Distribution</b></p> <hr> <div class="scrollable-div-table-container"> <table class="table table-striped table-responsive table-hover" > <thead id="program_student_table_head"> </thead> <tbody id="program_student_table_body"> </tbody> </table> </div> <br> <p><b>D) CGPA Category Program Distribution</b></p> <hr> <p><b>1) Excellent </b></p> <div class="scrollable-div-table-container"> <table class="table table-striped table-responsive table-hover" > <thead id="cgpa_category_program_excellent_student_table_head"> </thead> <tbody id="cgpa_category_program_excellent_student_table_body"> </tbody> </table> </div> <br> <p><b>2) Superior </b></p> <div class="scrollable-div-table-container"> <table class="table table-striped table-responsive table-hover" > <thead id="cgpa_category_program_superior_student_table_head"> </thead> <tbody id="cgpa_category_program_superior_student_table_body"> </tbody> </table> </div> <br> <p><b>3) Very Good </b></p> <div class="scrollable-div-table-container"> <table class="table table-striped table-responsive table-hover" > <thead id="cgpa_category_program_verygood_student_table_head"> </thead> <tbody id="cgpa_category_program_verygood_student_table_body"> </tbody> </table> </div> <br> <p><b>4) Good </b></p> <div class="scrollable-div-table-container"> <table class="table table-striped table-responsive table-hover" > <thead id="cgpa_category_program_good_student_table_head"> </thead> <tbody id="cgpa_category_program_good_student_table_body"> </tbody> </table> </div> <br> <p><b>5) Very Satisfactory </b></p> <div class="scrollable-div-table-container"> <table class="table table-striped table-responsive table-hover" > <thead id="cgpa_category_program_verysatisfactory_student_table_head"> </thead> <tbody id="cgpa_category_program_verysatisfactory_student_table_body"> </tbody> </table> </div> <br> <p><b>6) High Average </b></p> <div class="scrollable-div-table-container"> <table class="table table-striped table-responsive table-hover" > <thead id="cgpa_category_program_highaverage_student_table_head"> </thead> <tbody id="cgpa_category_program_highaverage_student_table_body"> </tbody> </table> </div> <br> <p><b>7) Average </b></p> <div class="scrollable-div-table-container"> <table class="table table-striped table-responsive table-hover" > <thead id="cgpa_category_program_average_student_table_head"> </thead> <tbody id="cgpa_category_program_average_student_table_body"> </tbody> </table> </div> <br> <p><b>8) Fair </b></p> <div class="scrollable-div-table-container"> <table class="table table-striped table-responsive table-hover" > <thead id="cgpa_category_program_fair_student_table_head"> </thead> <tbody id="cgpa_category_program_fair_student_table_body"> </tbody> </table> </div> <br> <p><b>9) Pass </b></p> <div class="scrollable-div-table-container"> <table class="table table-striped table-responsive table-hover" > <thead id="cgpa_category_program_pass_student_table_head"> </thead> <tbody id="cgpa_category_program_pass_student_table_body"> </tbody> </table> </div> <br> <p><b>10) Fail </b></p> <div class="scrollable-div-table-container"> <table class="table table-striped table-responsive table-hover" > <thead id="cgpa_category_program_fail_student_table_head"> </thead> <tbody id="cgpa_category_program_fail_student_table_body"> </tbody> </table> </div> <script> $(document).ready(function() { var table_headers = ['Data Label', 'Frequency']; var gender_pop_route = "{{ route('gender_population') }}"; var muslim_pop_route = "{{ route('muslim_population') }}"; var course_pop_route = "{{ route('course_population') }}"; var cgpa_student_pop_route = "{{ route('cgpa_cluster_pop_count') }}"; var cgpa_program_student_excellent_route = "{{ route('cgpa_cluster_count') }}"+"?category=Excellent"; var cgpa_program_student_superior_route = "{{ route('cgpa_cluster_count') }}"+"?category=Superior"; var cgpa_program_student_verygood_route = "{{ route('cgpa_cluster_count') }}"+"?category=Very Good"; var cgpa_program_student_good_route = "{{ route('cgpa_cluster_count') }}"+"?category=Good"; var cgpa_program_student_verysatisfactory_route = "{{ route('cgpa_cluster_count') }}"+"?category=Very Satisfactory"; var cgpa_program_student_highaverage_route = "{{ route('cgpa_cluster_count') }}"+"?category=High Average"; var cgpa_program_student_average_route = "{{ route('cgpa_cluster_count') }}"+"?category=Average"; var cgpa_program_student_fair_route = "{{ route('cgpa_cluster_count') }}"+"?category=Fair"; var cgpa_program_student_pass_route = "{{ route('cgpa_cluster_count') }}"+"?category=Pass"; var cgpa_program_student_fail_route = "{{ route('cgpa_cluster_count') }}"+"?category=Fail"; populate_frequency_table(gender_pop_route, "gender_table_body", table_headers, "gender_table_head"); populate_frequency_table(muslim_pop_route, "muslim_table_body", table_headers, "muslim_table_head"); populate_frequency_table(course_pop_route, "program_student_table_body", table_headers, "program_student_table_head"); populate_frequency_table(cgpa_student_pop_route, "cgpa_category_student_table_body", table_headers, "cgpa_category_student_table_head"); populate_frequency_table(cgpa_program_student_excellent_route, "cgpa_category_program_excellent_student_table_body", table_headers , "cgpa_category_program_excellent_student_table_head"); populate_frequency_table(cgpa_program_student_superior_route, "cgpa_category_program_superior_student_table_body", table_headers , "cgpa_category_program_superior_student_table_head"); populate_frequency_table(cgpa_program_student_verygood_route, "cgpa_category_program_verygood_student_table_body", table_headers , "cgpa_category_program_verygood_student_table_head"); populate_frequency_table(cgpa_program_student_good_route, "cgpa_category_program_good_student_table_body", table_headers , "cgpa_category_program_good_student_table_head"); populate_frequency_table(cgpa_program_student_verysatisfactory_route, "cgpa_category_program_verysatisfactory_student_table_body", table_headers , "cgpa_category_program_verysatisfactory_student_table_head"); populate_frequency_table(cgpa_program_student_highaverage_route, "cgpa_category_program_highaverage_student_table_body", table_headers , "cgpa_category_program_highaverage_student_table_head"); populate_frequency_table(cgpa_program_student_highaverage_route, "cgpa_category_program_highaverage_student_table_body", table_headers , "cgpa_category_program_highaverage_student_table_head"); populate_frequency_table(cgpa_program_student_highaverage_route, "cgpa_category_program_average_student_table_body", table_headers , "cgpa_category_program_average_student_table_head"); populate_frequency_table(cgpa_program_student_fair_route, "cgpa_category_program_fair_student_table_body", table_headers , "cgpa_category_program_fair_student_table_head"); populate_frequency_table(cgpa_program_student_pass_route, "cgpa_category_program_pass_student_table_body", table_headers , "cgpa_category_program_pass_student_table_head"); populate_frequency_table(cgpa_program_student_fail_route, "cgpa_category_program_fail_student_table_body", table_headers , "cgpa_category_program_fail_student_table_head"); }); </script>
stinkymonkeyph/Studenizer
resources/views/components/tables/data_summary.blade.php
PHP
mit
9,401
import { generate } from "randomstring" import { NON_EXECUTABLE_FILE_MODE, EXECUTABLE_FILE_MODE, } from "../src/patch/parse" import { assertNever } from "../src/assertNever" export interface File { contents: string mode: number } export interface Files { [filePath: string]: File } export interface TestCase { cleanFiles: Files modifiedFiles: Files } const fileCharSet = ` \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789!@£$%^&*()-=_+[]{};'i\\:"|<>?,./\`~§± 0123456789!@£$%^&*()-=_+[]{};'i\\:"|<>?,./\`~§± \r\r\r\r\t\t\t\t ` function makeFileContents(): File { return { contents: generate({ length: Math.floor(Math.random() * 1000), charset: fileCharSet, }) || "", mode: Math.random() > 0.5 ? 0o644 : 0o755, } } function makeFileName(ext?: boolean) { const name = generate({ length: Math.ceil(Math.random() * 10), charset: "abcdefghijklmnopqrstuvwxyz-_0987654321", }) return ext ? name + "." + generate(Math.ceil(Math.random() * 4)) : name } function makeFilePath() { const numParts = Math.floor(Math.random() * 3) const parts = [] for (let i = 0; i < numParts; i++) { parts.push(makeFileName()) } parts.push(makeFileName(true)) return parts.join("/") } function makeFiles(): Files { const fileSystem: Files = {} const numFiles = Math.random() * 3 + 1 for (let i = 0; i < numFiles; i++) { fileSystem[makeFilePath()] = makeFileContents() } return fileSystem } type MutationKind = | "deleteFile" | "createFile" | "deleteLine" | "insertLine" | "renameFile" | "changeFileMode" const mutationKindLikelihoods: Array<[MutationKind, number]> = [ ["deleteFile", 1], ["createFile", 1], ["renameFile", 1], ["changeFileMode", 1], ["deleteLine", 10], ["insertLine", 10], ] const liklihoodSum = mutationKindLikelihoods.reduce((acc, [_, n]) => acc + n, 0) function getNextMutationKind(): MutationKind { const n = Math.random() * liklihoodSum let sum = 0 for (const [kind, likelihood] of mutationKindLikelihoods) { sum += likelihood if (n < sum) { return kind } } return "insertLine" } function selectRandomElement<T>(ts: T[]): T { return ts[Math.floor(Math.random() * ts.length)] } function deleteLinesFromFile(file: File): File { const numLinesToDelete = Math.ceil(Math.random() * 1) const lines = file.contents.split("\n") const index = Math.max(Math.random() * (lines.length - numLinesToDelete), 0) lines.splice(index, numLinesToDelete) return { ...file, contents: lines.join("\n") } } function insertLinesIntoFile(file: File): File { const lines = file.contents.split("\n") const index = Math.floor(Math.random() * lines.length) const length = Math.ceil(Math.random() * 5) lines.splice(index, 0, generate({ length, charset: fileCharSet })) return { ...file, contents: lines.join("\n") } } function getUniqueFilename(files: Files) { let filename = makeFileName() const ks = Object.keys(files) while (ks.some(k => k.startsWith(filename))) { filename = makeFileName() } return filename } function mutateFiles(files: Files): Files { const mutatedFiles = { ...files } const numMutations = Math.ceil(Math.random() * 1000) for (let i = 0; i < numMutations; i++) { const mutationKind = getNextMutationKind() switch (mutationKind) { case "deleteFile": { if (Object.keys(mutatedFiles).length === 1) { break } // select a file at random and delete it const pathToDelete = selectRandomElement(Object.keys(mutatedFiles)) delete mutatedFiles[pathToDelete] break } case "createFile": { mutatedFiles[getUniqueFilename(mutatedFiles)] = makeFileContents() break } case "deleteLine": { const pathToDeleteFrom = selectRandomElement(Object.keys(mutatedFiles)) mutatedFiles[pathToDeleteFrom] = deleteLinesFromFile( mutatedFiles[pathToDeleteFrom], ) break } case "insertLine": const pathToInsertTo = selectRandomElement(Object.keys(mutatedFiles)) mutatedFiles[pathToInsertTo] = insertLinesIntoFile( mutatedFiles[pathToInsertTo], ) // select a file at random and insert some text in there break case "renameFile": const pathToRename = selectRandomElement(Object.keys(mutatedFiles)) mutatedFiles[getUniqueFilename(mutatedFiles)] = mutatedFiles[pathToRename] delete mutatedFiles[pathToRename] break case "changeFileMode": const pathToChange = selectRandomElement(Object.keys(mutatedFiles)) const { mode, contents } = mutatedFiles[pathToChange] mutatedFiles[pathToChange] = { contents, mode: mode === NON_EXECUTABLE_FILE_MODE ? EXECUTABLE_FILE_MODE : NON_EXECUTABLE_FILE_MODE, } break default: assertNever(mutationKind) } } return { ...mutatedFiles } } export function generateTestCase(): TestCase { const cleanFiles = makeFiles() return { cleanFiles, modifiedFiles: mutateFiles(cleanFiles), } }
ds300/patch-package
property-based-tests/testCases.ts
TypeScript
mit
5,362
using System.Collections.Generic; namespace CSharp2nem.ResponseObjects.Account { public class ExistingAccount { public class Cosignatory { public string Address { get; set; } public int HarvestedBlocks { get; set; } public long Balance { get; set; } public double Importance { get; set; } public long VestedBalance { get; set; } public string PublicKey { get; set; } public object Label { get; set; } public MultisigInfo MultisigInfo { get; set; } } public class MultisigInfo { public int CosignatoriesCount { get; set; } public int MinCosignatories { get; set; } } public class MultisigInfo2 { public int CosignatoriesCount { get; set; } public int MinCosignatories { get; set; } } public class CosignatoryOf { public string Address { get; set; } public int HarvestedBlocks { get; set; } public long Balance { get; set; } public double Importance { get; set; } public long VestedBalance { get; set; } public string PublicKey { get; set; } public object Label { get; set; } public MultisigInfo MultisigInfo { get; set; } } public class Account { public string Address { get; set; } public int HarvestedBlocks { get; set; } public long Balance { get; set; } public double Importance { get; set; } public long VestedBalance { get; set; } public string PublicKey { get; set; } public object Label { get; set; } public MultisigInfo2 MultisigInfo2 { get; set; } } public class Meta { public List<Cosignatory> Cosignatories { get; set; } public List<CosignatoryOf> CosignatoryOf { get; set; } public string Status { get; set; } public string RemoteStatus { get; set; } } public class Data { public Meta Meta { get; set; } public Account Account { get; set; } } } }
NemProject/csharp2nem
NemApi/Wrapper/ResponseObjects/Account/ExistingAccountData.cs
C#
mit
2,257
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("05.FormattingNumbers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("05.FormattingNumbers")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7c48106b-f751-4dca-b69b-8094e8ef7c83")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
helena999/SoftUni-Assignments
00. Programming Basics/05. Console-Input-Output-Homework/05.FormattingNumbers/Properties/AssemblyInfo.cs
C#
mit
1,416
# coding: utf-8 from numpy import matrix from oneVsAll import oneVsAll from numpy import loadtxt, savetxt from predictOneVsAll import predictOneVsAll def train(): num_labels = 34 print '... Training' X = matrix(loadtxt('X.dat')) / 255.0 y = matrix(loadtxt('y.dat')).transpose() the_lambda = 0.1 all_theta = oneVsAll(X, y, num_labels, the_lambda) savetxt('theta.dat', all_theta) def test(): print '... Testing' all_theta = matrix(loadtxt('theta.dat')) X_test = matrix(loadtxt('X_test.dat')) / 255.0 y_test = matrix(loadtxt('y_test.dat')).transpose() acc, pred = predictOneVsAll(all_theta, X_test) single_acc = sum(pred == y_test) / (len(y_test) * 1.0) max_acc = pow(single_acc, 4) min_acc = single_acc*4 - 3 print 'Theoretical accuracy:' print '\tSingle accuracy: %2.2f%%' % (single_acc*100) print '\tTotal accuracy: %2.2f%% ~ %2.2f%%' % (min_acc*100, max_acc*100) test()
skyduy/zfverify
Verify-Manual-python/train/core/train.py
Python
mit
950
#!/usr/bin/env python import queue class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None self.size = 1 self.self_count = 1 def treeBuilder(nodeString): nodeList = nodeString[1:-1].split(',') nodeQueue = queue.Queue() if nodeList[0] == '': return None root = TreeNode(int(nodeList[0])) currNode = root leftDone, rightDone = 0, 0 for val in nodeList[1:]: print('processing %s' % val) print('leftDone,', leftDone, 'rightDone,', rightDone) if val != 'null': newNode = TreeNode(int(val)) print("create new node: %d" % newNode.val) nodeQueue.put(newNode) else: newNode = None if leftDone == 0: currNode.left, leftDone = newNode, 1 elif rightDone == 0: currNode.right, rightDone = newNode, 1 leftDone, rightDone = 0, 0 currNode = nodeQueue.get() return root def traverse(node): if node == None: return print('Node: %d' % node.val) if node.left != None: print('Left: %d' % node.left.val) if node.right != None: print('Right: %d' % node.right.val) if node.left != None: traverse(node.left) if node.right != None: traverse(node.right) def treeToString(root): if root == None: return None nodeQueue = [root] currStr = '' # print(nodeQueue) while len(nodeQueue) > 0: node = nodeQueue[0] nodeQueue = nodeQueue[1:] # print(nodeQueue) if node == None: currStr += 'null,' # print(None) else: # print(node.val, node.left, node.right) nodeQueue += [node.left] nodeQueue += [node.right] currStr += str(node.val)+',' # print(nodeQueue) # print(currStr) stringList = currStr[:-1].split(',') while stringList[-1] == 'null': stringList = stringList[:-1] currStr = ','.join(stringList) return currStr
eroicaleo/LearningPython
interview/leet/tree.py
Python
mit
2,092
using System; using LanguageExt.Common; using System.Threading.Tasks; using static LanguageExt.Prelude; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using LanguageExt.Effects.Traits; using LanguageExt.Pipes; using LanguageExt.Thunks; namespace LanguageExt { /// <summary> /// Synchronous IO monad /// </summary> public readonly struct Eff<RT, A> where RT : struct { internal Thunk<RT, A> Thunk => thunk ?? Thunk<RT, A>.Fail(Errors.Bottom); readonly Thunk<RT, A> thunk; /// <summary> /// Constructor /// </summary> [MethodImpl(Opt.Default)] internal Eff(Thunk<RT, A> thunk) => this.thunk = thunk ?? throw new ArgumentNullException(nameof(thunk)); /// <summary> /// Invoke the effect /// </summary> [Pure, MethodImpl(Opt.Default)] public Fin<A> Run(RT env) => Thunk.Value(env); /// <summary> /// Invoke the effect /// </summary> [Pure, MethodImpl(Opt.Default)] public Fin<A> ReRun(RT env) => Thunk.ReValue(env); /// <summary> /// Clone the effect /// </summary> /// <remarks> /// If the effect had already run, then this state will be wiped in the clone, meaning it can be re-run /// </remarks> [Pure, MethodImpl(Opt.Default)] public Eff<RT, A> Clone() => new Eff<RT, A>(Thunk.Clone()); /// <summary> /// Invoke the effect /// </summary> /// <remarks> /// Throws on error /// </remarks> [MethodImpl(Opt.Default)] public Unit RunUnit(RT env) => Thunk.Value(env).Case switch { A _ => unit, Error e => e.Throw(), _ => throw new NotSupportedException() }; /// <summary> /// Lift a synchronous effect into the IO monad /// </summary> [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> EffectMaybe(Func<RT, Fin<A>> f) => new Eff<RT, A>(Thunk<RT, A>.Lazy(f)); /// <summary> /// Lift a synchronous effect into the IO monad /// </summary> [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> Effect(Func<RT, A> f) => new Eff<RT, A>(Thunk<RT, A>.Lazy(e => Fin<A>.Succ(f(e)))); /// <summary> /// Lift a value into the IO monad /// </summary> [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> Success(A value) => new Eff<RT, A>(Thunk<RT, A>.Success(value)); /// <summary> /// Lift a failure into the IO monad /// </summary> [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> Fail(Error error) => new Eff<RT, A>(Thunk<RT, A>.Fail(error)); [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> operator |(Eff<RT, A> ma, Eff<RT, A> mb) => new Eff<RT, A>(Thunk<RT, A>.Lazy( env => { var ra = ma.ReRun(env); return ra.IsSucc ? ra : mb.ReRun(env); })); [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> operator |(Eff<RT, A> ma, Eff<A> mb) => new Eff<RT, A>(Thunk<RT, A>.Lazy( e => { var ra = ma.ReRun(e); return ra.IsSucc ? ra : mb.ReRun(); })); [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> operator |(Eff<A> ma, Eff<RT, A> mb) => new Eff<RT, A>(Thunk<RT, A>.Lazy( e => { var ra = ma.ReRun(); return ra.IsSucc ? ra : mb.ReRun(e); })); [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> operator |(Eff<RT, A> ma, EffCatch<RT, A> mb) => new Eff<RT, A>(Thunk<RT, A>.Lazy( env => { var ra = ma.ReRun(env); return ra.IsSucc ? ra : mb.Run(env, ra.Error); })); [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> operator |(Eff<RT, A> ma, EffCatch<A> mb) => new Eff<RT, A>(Thunk<RT, A>.Lazy( env => { var ra = ma.ReRun(env); return ra.IsSucc ? ra : mb.Run(ra.Error); })); [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> operator |(Eff<RT, A> ma, CatchValue<A> value) => new Eff<RT, A>(Thunk<RT, A>.Lazy( env => { var ra = ma.ReRun(env); return ra.IsSucc ? ra : value.Match(ra.Error) ? FinSucc(value.Value(ra.Error)) : ra; })); [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> operator |(Eff<RT, A> ma, CatchError value) => new Eff<RT, A>(Thunk<RT, A>.Lazy( env => { var ra = ma.ReRun(env); return ra.IsSucc ? ra : value.Match(ra.Error) ? FinFail<A>(value.Value(ra.Error)) : ra; })); /// <summary> /// Implicit conversion from pure Eff /// </summary> public static implicit operator Eff<RT, A>(Eff<A> ma) => EffectMaybe(env => ma.ReRun()); } }
louthy/language-ext
LanguageExt.Core/Effects/Eff/Eff.cs
C#
mit
6,359
using MathSite.BasicAdmin.ViewModels.SharedModels.Posts; namespace MathSite.BasicAdmin.ViewModels.News { public class NewsViewModel : PostViewModel { } }
YarGU-Demidov/math-site
src/MathSite.BasicAdmin.ViewModels/News/NewsViewModel.cs
C#
mit
169
<?php if (!is_array($module)): ?> <p>404. No such module.</p> <?php else: ?> <h1>Module: <?= $module['name'] ?></h1> <h2>Description</h2> <p>File: <code><?= $module['filename'] ?></code></p> <p><?= nl2br($module['doccomment']) ?></p> <h2>Details</h2> <table> <caption>Details of module.</caption> <thead><tr><th>Characteristics</th><th>Applies to module</th></tr></thead> <tbody> <tr><td>Part of Siteshop Core modules</td><td><?= $module['isSiteshopCore'] ? 'Yes' : 'No' ?></td></tr> <tr><td>Part of Siteshop CMF modules</td><td><?= $module['isSiteshopCMF'] ? 'Yes' : 'No' ?></td></tr> <tr><td>Implements interface(s)</td><td><?= empty($module['interface']) ? 'No' : implode(', ', $module['interface']) ?></td></tr> <tr><td>Controller</td><td><?= $module['isController'] ? 'Yes' : 'No' ?></td></tr> <tr><td>Model</td><td><?= $module['isModel'] ? 'Yes' : 'No' ?></td></tr> <tr><td>Has SQL</td><td><?= $module['hasSQL'] ? 'Yes' : 'No' ?></td></tr> <tr><td>Manageable as a module</td><td><?= $module['isManageable'] ? 'Yes' : 'No' ?></td></tr> </tbody> </table> <?php if (!empty($module['publicMethods'])): ?> <h2>Public methods</h2> <?php foreach ($module['methods'] as $method): ?> <?php if ($method['isPublic']): ?> <h3><?= $method['name'] ?></h3> <p><?= nl2br($method['doccomment']) ?></p> <p>Implemented through lines: <?= $method['startline'] ?> - <?= $method['endline'] ?>.</p> <?php endif; ?> <?php endforeach; ?> <?php endif; ?> <?php if (!empty($module['protectedMethods'])): ?> <h2>Protected methods</h2> <?php foreach ($module['methods'] as $method): ?> <?php if ($method['isProtected']): ?> <h3><?= $method['name'] ?></h3> <p><?= nl2br($method['doccomment']) ?></p> <p>Implemented through lines: <?= $method['startline'] ?> - <?= $method['endline'] ?>.</p> <?php endif; ?> <?php endforeach; ?> <?php endif; ?> <?php if (!empty($module['privateMethods'])): ?> <h2>Private methods</h2> <?php foreach ($module['methods'] as $method): ?> <?php if ($method['isPrivate']): ?> <h3><?= $method['name'] ?></h3> <p><?= nl2br($method['doccomment']) ?></p> <p>Implemented through lines: <?= $method['startline'] ?> - <?= $method['endline'] ?>.</p> <?php endif; ?> <?php endforeach; ?> <?php endif; ?> <?php if (!empty($module['staticMethods'])): ?> <h2>Static methods</h2> <?php foreach ($module['methods'] as $method): ?> <?php if ($method['isStatic']): ?> <h3><?= $method['name'] ?></h3> <p><?= nl2br($method['doccomment']) ?></p> <p>Implemented through lines: <?= $method['startline'] ?> - <?= $method['endline'] ?>.</p> <?php endif; ?> <?php endforeach; ?> <?php endif; ?> <?php endif; ?>
guni12/siteshop
src/CCModules/view.tpl.php
PHP
mit
3,244
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.Fluent; using Microsoft.Azure.Management.KeyVault.Fluent.Models; using Microsoft.Azure.Management.ResourceManager.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Azure.Management.Samples.Common; using System; namespace ManageKeyVault { public class Program { /** * Azure Key Vault sample for managing key vaults - * - Create a key vault * - Authorize an application * - Update a key vault * - alter configurations * - change permissions * - Create another key vault * - List key vaults * - Delete a key vault. */ public static void RunSample(IAzure azure) { string vaultName1 = SdkContext.RandomResourceName("vault1", 20); string vaultName2 = SdkContext.RandomResourceName("vault2", 20); string rgName = SdkContext.RandomResourceName("rgNEMV", 24); try { //============================================================ // Create a key vault with empty access policy Utilities.Log("Creating a key vault..."); var vault1 = azure.Vaults .Define(vaultName1) .WithRegion(Region.USWest) .WithNewResourceGroup(rgName) .WithEmptyAccessPolicy() .Create(); Utilities.Log("Created key vault"); Utilities.PrintVault(vault1); //============================================================ // Authorize an application Utilities.Log("Authorizing the application associated with the current service principal..."); vault1 = vault1.Update() .DefineAccessPolicy() .ForServicePrincipal(SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION")).ClientId) .AllowKeyAllPermissions() .AllowSecretPermissions(SecretPermissions.Get) .AllowSecretPermissions(SecretPermissions.List) .Attach() .Apply(); Utilities.Log("Updated key vault"); Utilities.PrintVault(vault1); //============================================================ // Update a key vault Utilities.Log("Update a key vault to enable deployments and add permissions to the application..."); vault1 = vault1.Update() .WithDeploymentEnabled() .WithTemplateDeploymentEnabled() .UpdateAccessPolicy(vault1.AccessPolicies[0].ObjectId) .AllowSecretAllPermissions() .Parent() .Apply(); Utilities.Log("Updated key vault"); // Print the network security group Utilities.PrintVault(vault1); //============================================================ // Create another key vault var vault2 = azure.Vaults .Define(vaultName2) .WithRegion(Region.USEast) .WithExistingResourceGroup(rgName) .DefineAccessPolicy() .ForServicePrincipal(SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION")).ClientId) .AllowKeyPermissions(KeyPermissions.List) .AllowKeyPermissions(KeyPermissions.Get) .AllowKeyPermissions(KeyPermissions.Decrypt) .AllowSecretPermissions(SecretPermissions.Get) .Attach() .Create(); Utilities.Log("Created key vault"); // Print the network security group Utilities.PrintVault(vault2); //============================================================ // List key vaults Utilities.Log("Listing key vaults..."); foreach (var vault in azure.Vaults.ListByResourceGroup(rgName)) { Utilities.PrintVault(vault); } //============================================================ // Delete key vaults Utilities.Log("Deleting the key vaults"); azure.Vaults.DeleteById(vault1.Id); azure.Vaults.DeleteById(vault2.Id); Utilities.Log("Deleted the key vaults"); } finally { try { Utilities.Log("Deleting Resource Group: " + rgName); azure.ResourceGroups.DeleteByName(rgName); Utilities.Log("Deleted Resource Group: " + rgName); } catch (NullReferenceException) { Utilities.Log("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { Utilities.Log(g); } } } public static void Main(string[] args) { try { //================================================================= // Authenticate AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION")); var azure = Azure .Configure() .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .Authenticate(credentials) .WithDefaultSubscription(); // Print selected subscription Utilities.Log("Selected subscription: " + azure.SubscriptionId); RunSample(azure); } catch (Exception e) { Utilities.Log(e); } } } }
hovsepm/azure-libraries-for-net
Samples/KeyVault/ManageKeyVault.cs
C#
mit
6,663
class Solution { public int solution (String S) { int length = S.length(); // Such index only exists if the length of the string is odd if (length % 2 == 0) { return -1; } int middle = length / 2; for (int i = middle - 1, j = middle + 1; i >= 0 && j < length; i--, j++) { if (S.charAt(i) != S.charAt(j)) { return -1; } } return middle; } } /** * @author shengmin */ public class Driver { public static void main(String[] args) { Solution sol = new Solution(); System.out.println(sol.solution("")); System.out.println(sol.solution("a")); System.out.println(sol.solution("aa")); System.out.println(sol.solution("aba")); System.out.println(sol.solution("abc")); System.out.println(sol.solution("racecar")); } }
shengmin/coding-problem
codility/task-1/Driver.java
Java
mit
810
package fsb.semantics.empeagerpso; import java.util.Set; import ags.constraints.AtomicPredicateDictionary; import ags.constraints.Formula; import fsb.ast.MProgram; import fsb.ast.Statement; import fsb.ast.Statement.StatType; import fsb.ast.tvl.ArithValue; import fsb.ast.tvl.DeterArithValue; import fsb.explore.Action; import fsb.explore.SBState; import fsb.explore.State; import fsb.explore.Validator; import fsb.semantics.BufVal; import fsb.semantics.SharedResMap; public class EmpEagerAbsState extends SBState { SharedResMap<SharedResVal> shared; protected Validator validator; public EmpEagerAbsState(MProgram program, Validator validator, int numProcs) { super(program, validator, numProcs); this.shared = new SharedResMap<SharedResVal>(); for(String var : program.getShared()) addShared(var, DeterArithValue.getInstance(0)); } @SuppressWarnings("unchecked") public EmpEagerAbsState(EmpEagerAbsState s) { super(s); //this.shared = s.shared; //if (!Options.LAZY_COPY) //{ this.shared = (SharedResMap) s.shared.clone(); //} } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof EmpEagerAbsState)) return false; EmpEagerAbsState other = (EmpEagerAbsState) obj; if (!shared.equals(other.shared)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + shared.hashCode(); return result; } public String toString() { StringBuffer sb = new StringBuffer(); for (int i = 0; i < numProcs; i++) { sb.append(i); sb.append(" : "); sb.append("PC = " + (pc[i] + 1) + " "); sb.append(locals[i].toString()); sb.append("\\n"); } sb.append(shared.toString()); return sb.toString(); } public boolean isFinal() { for (int pid = 0; pid < numProcs; pid++) { if (program.getListing(pid).get(pc[pid]).isLast() == false) return false; } //TODO: Is this required here? I think not, because END is only enabled when the buffer is empty... for (SharedResVal resval : shared.values()) { for (int pid = 0; pid < numProcs; pid++) if (!resval.isEmpty(pid)) return false; } return true; } @Override public void addShared(String str, ArithValue initval) { shared.put(str, new SharedResVal(numProcs, 0)); } @Override public boolean join(State s) { if(!equals(s)) throw new RuntimeException("Trying to join inappropriate states!"); EmpEagerAbsState other = (EmpEagerAbsState) s; boolean changed = false; for (String res : shared.keySet()) { SharedResVal resval = shared.get(res); changed |= resval.join(other.shared.get(res)); } return changed; } @Override public Set<Formula> getPredicates(Action taken) { throw new RuntimeException("Should not be used for this type of state, use getAvoidFormula() instead!"); } protected boolean isAvoidableType(Action taken) { Statement st = taken.getStatement(); if (st == null || taken.getPid() == -1 || st.isLocal() || st.getType() == StatType.END || inAtomicSection() != -1) return false; return true; } @Override public boolean isAvoidable(Action taken) { if(!isAvoidableType(taken)) return false; int pid = taken.getPid(); for (String res : shared.keySet()) { SharedResVal sharedval = shared.get(res); if (!(sharedval.isEmpty(pid))) return true; } return false; } protected void addPredicate(Set<Formula> model, BufVal buf, Statement st) { model.add(AtomicPredicateDictionary.makeAtomicPredicate(buf.writingLabel, st.getLabel())); } public boolean disjPredicates() { return false; } @Override public Formula getAvoidFormula(Action taken) { Formula avoidFormula = Formula.falseValue(); //avoidFormula = avoidFormula.and(Formula.makeDisjunction()); if (!isAvoidableType(taken)) return avoidFormula; Statement st = taken.getStatement(); int pid = taken.getPid(); Formula common = Formula.falseValue(); for (String res : shared.keySet()) { SharedResVal sharedval = shared.get(res); for(BufVal buf : sharedval.buffer[pid].head) { common = common.or(AtomicPredicateDictionary.makeAtomicPredicate(buf.writingLabel, st.getLabel())); } } Formula allSets = Formula.falseValue(); //allSets = allSets.and(Formula.makeDisjunction()); for (String res : shared.keySet()) { //Unfortunately, within a set we need to avoid everything. SharedResVal sharedval = shared.get(res); if (!sharedval.buffer[pid].set.isEmpty()) { Formula setFormula = Formula.trueValue(); for(BufVal buf : sharedval.buffer[pid].set) { Formula disj = Formula.falseValue(); Formula ap = AtomicPredicateDictionary.makeAtomicPredicate(buf.writingLabel, st.getLabel()); disj = disj.or(ap); //System.out.println("DISJ : " + disj); setFormula = setFormula.and(disj); } //System.out.println("setFormula : " + setFormula + " --- " + setFormula.getClass()); //System.out.println("ALLSETS : " + allSets + " --- " + allSets.getClass()); allSets = allSets.or(setFormula); } } avoidFormula = avoidFormula.or(common); avoidFormula = avoidFormula.or(allSets); return avoidFormula; } @Override public ArithValue getShared(String res) { SharedResVal val = shared.get(res); if (val == null) throw new RuntimeException("Local " + res + " not found"); return DeterArithValue.getInstance(val.getGlobalVal()); } }
hetmeter/awmm
fender-sb-bdd/branches/three valued logic branch/fender-sb-bdd/src/fsb/semantics/empeagerpso/EmpEagerAbsState.java
Java
mit
5,589
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jenkins.plugins.pivot.render; import java.util.ArrayList; import java.util.List; /** * 2-dimension matrix utility * @author zijiang */ public final class Matrix2D { private int[][] data; private int rowSize; private int colSize; public Matrix2D(int rowsize, int colsize){ init(rowsize, colsize); } public Matrix2D(int[][] datasource){ throw new UnsupportedOperationException(); } public Matrix2D(List<int[]> datasource){ if(datasource.isEmpty()){ this.init(0, 0); return; } int rowsize = datasource.size(); int colsize = datasource.get(0).length; init(rowsize, colsize); // fill data for(int i = 0 ; i < rowsize; i++){ int[] row = datasource.get(i); for(int j = 0; j < row.length; j++){ set(i, j, row[j]); } } } public Matrix2D transpose(){ Matrix2D m = new Matrix2D(this.colSize, this.rowSize); for(int i = 0; i < m.rowSize; i++){ for(int j = 0; j < m.colSize; j++){ m.set(i, j, this.get(j, i)); } } return m; } // Fill all cells with single value public void unifiy(int value){ for(int i = 0; i < this.rowSize; i++){ for(int j = 0; j < this.colSize; j++){ this.set(i, j, value); } } } public int getRowSize(){ return this.rowSize; } public int getColumnSize(){ return this.colSize; } private void init(int row, int col){ this.rowSize = row; this.colSize = col; this.data = new int[row][col]; } public void set(int rowIndex, int colIndex, int value) { this.data[rowIndex][colIndex] = value; } public int get(int rowIndex, int colIndex){ return this.data[rowIndex][colIndex]; } public void dump(){ for(int i = 0; i < this.getRowSize(); i++){ for(int j = 0; j < this.getColumnSize(); j++){ System.out.print(this.get(i, j)); System.out.print(" "); } System.out.println(); } System.out.println(); } }
gougoujiang/programmable-section
src/main/java/jenkins/plugins/pivot/render/Matrix2D.java
Java
mit
2,516
package com.jinwen.thread.multithread.synchronize.example2; public class HasSelfPrivateNum { private int num = 0; synchronized public void addI(String username) { try { if (username.equals("a")) { num = 100; System.out.println("a set over"); Thread.sleep(2000); } else { num = 200; System.out.println("b set over"); } System.out.println(username + " num= " + num); } catch (InterruptedException e) { e.printStackTrace(); } } }
jinchen92/JavaBasePractice
src/com/jinwen/thread/multithread/synchronize/example2/HasSelfPrivateNum.java
Java
mit
611
package app_error import "log" func Fatal(err error) { if err != nil { log.Fatal(err) } }
Jurevic/FaceGrinder
pkg/api/v1/helper/app_error/app_error.go
GO
mit
96
// Copyright (c) 2017-2021 offa // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions. // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS // BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "danek/internal/ToString.h" #include "danek/internal/ConfigItem.h" #include "danek/internal/ConfigScope.h" #include "danek/internal/UidIdentifierProcessor.h" #include <algorithm> #include <array> #include <iterator> #include <sstream> namespace danek { namespace { const std::array<std::pair<std::string, std::string>, 4> escapeSequences{ {{"%", "%%"}, {"\t", "%t"}, {"\n", "%n"}, {"\"", "%\""}}}; std::string indent(std::size_t level) { constexpr std::size_t indentCount{4}; return std::string(level * indentCount, ' '); } void replaceInplace(std::string& input, const std::string& str, const std::string& replacement) { if (str.empty() == false) { std::size_t pos = 0; while ((pos = input.find(str, pos)) != std::string::npos) { input.replace(pos, str.size(), replacement); pos += replacement.size(); } } } std::string escape(const std::string& str) { auto output = str; std::for_each(escapeSequences.cbegin(), escapeSequences.cend(), [&output](const auto& v) { replaceInplace(output, v.first, v.second); }); return "\"" + output + "\""; } std::string expandUid(const std::string& name, bool expand) { if (expand == false) { UidIdentifierProcessor uidIdProc; return uidIdProc.unexpand(name); } return name; } void appendConfType(std::stringstream& stream, const ConfigScope& scope, ConfType type, bool expandUid, std::size_t indentLevel) { auto names = scope.listLocallyScopedNames(type, false, {}); std::sort(names.begin(), names.end()); std::for_each(names.cbegin(), names.cend(), [&stream, &scope, expandUid, indentLevel](const auto s) { const auto item = scope.findItem(s); stream << toString(*item, item->name(), expandUid, indentLevel); }); } } std::string toString(const ConfigItem& item, const std::string& name, bool expandUidNames, std::size_t indentLevel) { const std::string nameStr = expandUid(name, expandUidNames); std::stringstream os; os << indent(indentLevel); switch (item.type()) { case ConfType::String: os << nameStr << " = " << escape(item.stringVal()) << ";\n"; break; case ConfType::List: { os << nameStr << " = ["; const auto& values = item.listVal(); if (values.empty() == false) { using OItr = std::ostream_iterator<std::string>; std::transform(values.cbegin(), std::prev(values.cend()), OItr{os, ", "}, escape); std::transform(std::prev(values.cend()), values.cend(), OItr{os}, escape); } os << "];\n"; } break; case ConfType::Scope: { os << nameStr << " {\n" << toString(*(item.scopeVal()), expandUidNames, indentLevel + 1) << indent(indentLevel) << "}\n"; } break; default: break; } return os.str(); } std::string toString(const ConfigScope& scope, bool expandUidNames, std::size_t indentLevel) { std::stringstream ss; appendConfType(ss, scope, ConfType::Variables, expandUidNames, indentLevel); appendConfType(ss, scope, ConfType::Scope, expandUidNames, indentLevel); return ss.str(); } }
offa/danek
src/danek/internal/ToString.cpp
C++
mit
5,007
<?php namespace PHPStrap\Form\Validation; class BaseValidation{ protected $errormessage; /** * @param string $errormessage * @return void */ public function __construct($errormessage){ $this->errormessage = $errormessage; } /** * @return string */ public function errorMessage(){ return $this->errormessage; } } ?>
kktuax/PHPStrap
src/PHPStrap/Form/Validation/BaseValidation.php
PHP
mit
364
<?php namespace MindOfMicah\LaravelDatatables\DatatableQuery; class Sorter { private $column_index; private $direction; public function __construct($column_index, $direction = 'ASC') { $this->column_index = $column_index; $this->direction = $direction; } public function toArray() { return [ 'col' => $this->column_index, 'dir' => strtolower($this->direction) ]; } }
mindofmicah/laravel-datatables
src/MindOfMicah/LaravelDatatables/DatatableQuery/Sorter.php
PHP
mit
459
/* jshint unused: false */ /* global describe, before, beforeEach, afterEach, after, it, xdescribe, xit */ 'use strict'; var fs = require('fs'); var restify = require('restify'); var orm = require('orm'); var assert = require('assert'); var restormify = require('../'); var dbProps = {host: 'logger', protocol: 'sqlite'}; var server = restify.createServer(); var client; var db; var baz; server.use(restify.bodyParser()); server.use(restify.queryParser()); describe('node-orm2 validations', function(){ before(function(done){ orm.connect(dbProps, function(err, database){ if(err){ done(err); } db = database; restormify({ db: db, server: server }, function(){ baz = db.define('baz', { name: String, email: {type: 'text', unique: true}, deleted: {type: 'boolean', serverOnly: true}, foo: {type: 'boolean', serverOnly: true} }, {validations: { name: orm.enforce.ranges.length(3, undefined, 'too small') }}); done(); }); }); client = restify.createJsonClient({ url: 'http://localhost:1234/api' }); }); describe('api', function(){ beforeEach(function(done){ server.listen(1234); baz.sync(done); }); it('rejects unique constraints', function(done){ var bazzer = {name: 'foo', email: 'foo@foo.bar'}; client.post('/api/baz', bazzer, function(err, req, res){ client.post('/api/baz', bazzer, function(err, req, res){ assert.equal(res.statusCode, 409, '490 Conflict recieved'); assert.equal(err.message, 'baz already exists', 'unique constraint'); done(); }); }); }); it('rejects validation matching', function(done){ var bazzer = {name: 'fo', email:'foo@foo.bar'}; client.post('/api/baz', bazzer, function(err, req, res){ assert.equal(res.statusCode, 400, 'invalid content rejected'); assert.equal(err.message, 'too small', 'validation message matches'); done(); }); }); afterEach(function(done){ server.close(); db.drop(done); }); }); after(function(done){ db.close(); fs.unlink(dbProps.host, function(){ done(); }); }); });
toddself/restormify
test/validation-bubbling.js
JavaScript
mit
2,293
require 'sinatra' require 'cgi' require 'json' require 'sequel' require 'logger' require 'zlib' require 'base64' require 'digest' configure :production do require 'newrelic_rpm' $production = true end DB = Sequel.connect(ENV['MYSQL_DB_URL'] || 'mysql2://root@localhost/android_census', :max_connections => 15, :ssl_mode => :required) #:logger => Logger.new('db.log')) DB.extension(:error_sql) DB.extension(:connection_validator) DB.pool.connection_validation_timeout = 30 #Sequel::MySQL.default_collate = 'utf8_bin' require_relative 'data_models' def assert(&block) raise "Assertion error" unless yield end error 400..510 do 'Error!' end # In production we limit calls to results posting/reading/processing endpoints. def check_production_password(request) if $production && (!request.env['HTTP_AUTHORIZATION'] || request.env['HTTP_AUTHORIZATION'] != ENV['ACCESS_CONTROL_PASSWORD']) status 403 raise "Incorrect password" end end get '/' do erb :index end get '/devices' do erb :devices, :locals => { :devices => Device.all } end get '/devices/:id' do |id| return 404 if !Device[id] erb :device, :locals => { :device => Device[id] } end get '/devices/:id/system_properties' do |id| return 404 if !Device[id] erb :device_generic_view, :locals => { :data => Device[id].system_properties, :header => "System Properties", :model => SystemProperty } end get '/devices/:id/sysctls' do |id| return 404 if !Device[id] erb :device_generic_view, :locals => { :data => Device[id].sysctls, :header => "Sysctls", :model => Sysctl } end get '/devices/:id/environment_variables' do |id| return 404 if !Device[id] erb :device_generic_view, :locals => { :data => Device[id].environment_variables, :header => "Environment Variables", :model => EnvironmentVariable } end get '/devices/:id/features' do |id| return 404 if !Device[id] erb :device_generic_view, :locals => { :data => Device[id].features, :header => "Features", :model => Feature } end get '/devices/:id/shared_libraries' do |id| return 404 if !Device[id] erb :device_generic_view, :locals => { :data => Device[id].shared_libraries, :header => "Shared Libraries", :model => SharedLibrary } end get '/devices/:id/permissions' do |id| return 404 if !Device[id] erb :device_generic_view, :locals => { :data => Device[id].permissions, :header => "Permissions", :model => Permission } end get '/devices/:id/providers' do |id| return 404 if !Device[id] erb :device_generic_view, :locals => { :data => Device[id].content_providers, :header => "Content Providers", :model => ContentProvider } end get '/devices/:id/small_files' do |id| return 404 if !Device[id] erb :device_small_files, :locals => { :id => id, :paths => SmallFile.where(:device_id => id).select_map(:path) } end get '/devices/:id/small_files/*' do |id, path| return 404 if !Device[id] file = SmallFile.where(:device_id => id, :path => '/' + path).all.first return 404 if !file content_type 'text/plain' file[:contents] end get '/devices/:id/file_permissions' do |id| return 404 if !Device[id] erb :device_generic_view, :locals => { :data => Device[id].file_permissions, :header => "File Permissions", :model => FilePermission } end get '/sysctls/:property' do |property| erb :by_device_generic_view, :locals => { :model => Sysctl, :index => property } end get '/system_properties/:property' do |property| erb :by_device_generic_view, :locals => { :model => SystemProperty, :index => property } end get '/environment_variables/:variable' do |variable| erb :by_device_generic_view, :locals => { :model => EnvironmentVariable, :index => variable } end get '/file_permissions/*' do |file| erb :by_device_generic_view, :locals => { :model => FilePermission, :index => '/' + file } end get '/permissions/:provider' do |permission| erb :by_device_generic_view, :locals => { :model => Permission, :index => permission } end get '/content_providers/:provider' do |provider| erb :by_device_generic_view, :locals => { :model => ContentProvider, :index => provider } end get '/features/:feature' do |feature| erb :feature, :locals => { :feature => feature, :devices => Feature.where(:name => feature).all[0].devices } end get '/shared_libraries/:feature' do |feature| erb :feature, :locals => { :feature => feature, :devices => SharedLibrary.where(:name => feature).all[0].devices } end get '/piechart/versions.json' do versions = DB[:system_properties].where(:property => 'ro.build.version.release').select_map(:value) data = versions.group_by(&:to_s).map do |version, arr| { 'label' => version, 'value' => arr.count } end JSON.generate(data) end get '/piechart/manufacturers.json' do manufacturers = DB[:system_properties].where(:property => 'ro.product.manufacturer').select_map(:value) manufacturers.map!(&:upcase) data = manufacturers.group_by(&:to_s).map do |version, arr| { 'label' => version, 'value' => arr.count } end JSON.generate(data) end post '/results/new' do check_production_password(request) Result.create(:data => request.body.read, :processed => false) '' end get '/results/:id' do |id| check_production_password(request) Zlib::Inflate.inflate(Result[id][:data]) end def process_result(result) json = JSON.parse(Zlib::Inflate.inflate(result[:data])) DB.transaction do # Fix jacked up naming inconsistencies device_name = json["device_name"] device_name.gsub!(/^asus/i, 'ASUS') device_name.gsub!(/^acer/i, 'Acer') device_name.gsub!(/^lge/i, 'LG') device_name.gsub!(/^huawei/i, 'Huawei') device_name.gsub!(/^samsung/i, 'Samsung') device_name.gsub!(/^motorola/i, 'Motorola') device_name.gsub!(/^oppo/i, 'OPPO') device_name.gsub!(/^sharp/i, 'Sharp') device_name.gsub!(/^toshiba/i, 'Toshiba') device_name.gsub!(/^fujitsu/i, 'Fujitsu') device_name.gsub!(/^lenovo/i, 'Lenovo') device_name.gsub!(/^kyocera/i, 'Kyocera') device_name.gsub!(/^fuhu/i, 'Fuhu') device_name.gsub!(/^meizu/i, 'Meizu') device_name.gsub!(/^tct( alcatel)?/i, 'Alcatel') device_name.gsub!(/^coolpad/i, 'YuLong Coolpad') device_name.gsub!(/^nubia nx40x/i, 'ZTE Nubia NX40X') device_name.gsub!(/^unknown 8150/i, 'YuLong Coolpad 8150') device_name.gsub!(/^unknown lenovo/i, 'Lenovo') device_name.gsub!('_one_touch_', ' ONE TOUCH ') if json['system_properties'] && json['system_properties']['ro.build.description'] build_description = json['system_properties']['ro.build.description'] else build_description = device_name end # Don't create a new device entry if we don't need to, re-use the same one but delete old # entries in other tables dsearch = Device.where(:name => device_name, :build_description => build_description) if dsearch.count == 0 device = Device.create(:name => device_name, :build_description => build_description) else device = dsearch.all[0] [ :system_properties, :sysctls, :devices_features, :devices_shared_libraries, :permissions, :small_files, :file_permissions, :content_providers, :environment_variables ].each { |table_name| DB[table_name].where(:device_id => device[:id]).delete } end if json["system_properties"] DB[:system_properties].multi_insert( json["system_properties"].map do |k,v| { :property => k, :value => v, :device_id => device[:id] } end ) end if json["sysctl"] DB[:sysctls].multi_insert( json["sysctl"].map do |k,v| { :property => k, :value => v, :device_id => device[:id] } end ) end if json["features"] all_features = json["features"] json["features"].uniq!(&:downcase) new_features = all_features - DB[:features].distinct(:name).select_map(:name) DB[:features].multi_insert(new_features.map { |f| {:name => f} }) feature_ids = DB[:features].where('name in ?', json["features"]).map { |f| f[:id] } DB[:devices_features].multi_insert( feature_ids.map do |id| { :device_id => device[:id], :feature_id => id } end ) assert { json["features"].length == device.features.length } end if json["system_shared_libraries"] new_libraries = json["system_shared_libraries"] - DB[:shared_libraries].distinct(:name).select_map(:name) DB[:shared_libraries].multi_insert(new_libraries.map { |l| {:name => l} }) library_ids = DB[:shared_libraries].where('name in ?', json["system_shared_libraries"]).map { |l| l[:id] } DB[:devices_shared_libraries].multi_insert( library_ids.map do |id| { :device_id => device[:id], :shared_library_id => id } end ) assert { json["system_shared_libraries"].length == device.shared_libraries.length } end if json["permissions"] DB[:permissions].multi_insert( json["permissions"].map do |data| { :name => data["name"], :package_name => data["packageName"], :protection_level => data["protectionLevel"].to_i, :flags => data["flags"].to_i, :device_id => device[:id], } end ) end if json["small_files"] DB[:small_files].multi_insert( json["small_files"].map do |k, v| { :path => k, :contents => Base64.decode64(v), :device_id => device[:id] } end ) end if json["file_permissions"] DB[:file_permissions].multi_insert( json["file_permissions"].map do |data| { :path => data['path'], :link_path => data['linkPath'], :mode => data['mode'], :size => data['size'], :uid => data['uid'], :gid => data['gid'], :selinux_context => data['selinuxContext'], :device_id => device[:id] } end ) end if json["providers"] DB[:content_providers].multi_insert( json["providers"].map do |data| { :authority => data["authority"], :init_order => data["initOrder"], :multiprocess => data["multiprocess"], :grant_uri_permissions => data["grantUriPermissions"], :read_permission => data["readPermission"], :write_permission => data["writePermission"], :path_permissions => data["pathPermissions"], :uri_permission_patterns => data["uriPermissionPatterns"], :flags => data["flags"], :device_id => device[:id] } end ) end if json["environment_variables"] DB[:environment_variables].multi_insert( json["environment_variables"].map do |k,v| { :variable => k, :value => v, :device_id => device[:id] } end ) end DB[:results].where(:id => result[:id]).update({:processed => true}) end end get '/process_results' do check_production_password(request) Thread.new { # First things first, delete duplicate entries. # { data_sha256_hash => result_id } hashes = {} DB[:results].all.each { |result| hash = Digest::SHA256.digest(result[:data]) if hashes[hash] if result[:processed] DB[:results].where(:id => hashes[hash]).delete hashes[hash] = result[:id] else DB[:results].where(:id => result[:id]).delete end else hashes[hash] = result[:id] end } # Now process unprocessed results DB[:results].where(:processed => false).each { |result| begin process_result(result) rescue => e $stderr.puts e.inspect $stderr.puts e.backtrace end } } "" end
vlad902/census.tsyrklevich.net
web.rb
Ruby
mit
12,074
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Item = function Item() { _classCallCheck(this, Item); this.chords = ''; this.lyrics = ''; }; exports.default = Item;
aggiedefenders/aggiedefenders.github.io
node_modules/chordsheetjs/lib/chord_sheet/item.js
JavaScript
mit
364
require "spec_helper" describe Architect4r::Model::Relationship do let(:person) { Person.create(:name => 'Niobe', :human => true) } let(:ship) { Ship.create(:name => 'Logos', :crew_size => 2) } describe "initialization of new instances" do it "should accept zero arguments" do lambda { CrewMembership.new }.should_not raise_error(ArgumentError) end it "should accept just a hash of properties" do ms = CrewMembership.new( :rank => 'Captain' ) ms.rank.should == 'Captain' end it "should accept the source and destination node" do ms = CrewMembership.new(ship, person) ms.source.should == ship ms.destination.should == person end it "should accept the source node, destination node, and properties" do ms = CrewMembership.new(ship, person, { :rank => 'Captain' }) ms.source.should == ship ms.destination.should == person ms.rank.should == 'Captain' end it "should always require a source and destination" do fs = CrewMembership.new(:member_since => DateTime.new, :rank => 'Captain') fs.valid?.should be_false end end describe "Creating a new relationship" do it "should create a new relationship" do ms = CrewMembership.new(ship, person) ms.save.should be_true ms.persisted?.should be_true end it "should allow changing relationship properties" do ms = CrewMembership.new(ship, person, { :rank => 'Captain' }) ms.save.should be_true ms.rank = 'Operator' ms.save.should be_true end it "should allow deleting relationships" do ms = CrewMembership.new(ship, person, { :rank => 'Captain' }) ms.save.should be_true ms.destroy.should be_true end end describe "Retrieve records from the store" do it "should allow fetching a record by its id" do CrewMembership.should respond_to(:find) end it "should instantiate a relationship model" do ms = CrewMembership.create(ship, person, { :rank => 'Captain' }) CrewMembership.find(ms.id).should be_a(CrewMembership) end end describe "Should populate source and destination after retrieval from storage" do let(:membership) { CrewMembership.create(ship, person, { :rank => 'Captain' }) } subject { CrewMembership.find(membership.id) } it { should respond_to(:source) } it { should respond_to(:destination) } it "should populate the source after retrieval" do subject.source.id.should == ship.id end it "should populate the destination after retrieval" do subject.destination.id.should == person.id end end end
namxam/architect4r
spec/model/relationship_spec.rb
Ruby
mit
2,756
package com.cloutteam.jarcraftinator.exceptions; public class PluginUnloadedException extends RuntimeException { public PluginUnloadedException(String message){ super(message); } }
Clout-Team/JarCraftinator
src/main/java/com/cloutteam/jarcraftinator/exceptions/PluginUnloadedException.java
Java
mit
200
package demoinfocs import ( "fmt" "io" "math" "sync" "time" "github.com/gogo/protobuf/proto" "github.com/markus-wa/go-unassert" dispatch "github.com/markus-wa/godispatch" "github.com/pkg/errors" common "github.com/markus-wa/demoinfocs-golang/v2/pkg/demoinfocs/common" events "github.com/markus-wa/demoinfocs-golang/v2/pkg/demoinfocs/events" msg "github.com/markus-wa/demoinfocs-golang/v2/pkg/demoinfocs/msg" ) const maxOsPath = 260 const ( playerWeaponPrefix = "m_hMyWeapons." playerWeaponPrePrefix = "bcc_nonlocaldata." gameRulesPrefix = "cs_gamerules_data" ) // Parsing errors var ( // ErrCancelled signals that parsing was cancelled via Parser.Cancel() ErrCancelled = errors.New("parsing was cancelled before it finished (ErrCancelled)") // ErrUnexpectedEndOfDemo signals that the demo is incomplete / corrupt - // these demos may still be useful, check how far the parser got. ErrUnexpectedEndOfDemo = errors.New("demo stream ended unexpectedly (ErrUnexpectedEndOfDemo)") // ErrInvalidFileType signals that the input isn't a valid CS:GO demo. ErrInvalidFileType = errors.New("invalid File-Type; expecting HL2DEMO in the first 8 bytes (ErrInvalidFileType)") ) // ParseHeader attempts to parse the header of the demo and returns it. // If not done manually this will be called by Parser.ParseNextFrame() or Parser.ParseToEnd(). // // Returns ErrInvalidFileType if the filestamp (first 8 bytes) doesn't match HL2DEMO. func (p *parser) ParseHeader() (common.DemoHeader, error) { var h common.DemoHeader h.Filestamp = p.bitReader.ReadCString(8) h.Protocol = p.bitReader.ReadSignedInt(32) h.NetworkProtocol = p.bitReader.ReadSignedInt(32) h.ServerName = p.bitReader.ReadCString(maxOsPath) h.ClientName = p.bitReader.ReadCString(maxOsPath) h.MapName = p.bitReader.ReadCString(maxOsPath) h.GameDirectory = p.bitReader.ReadCString(maxOsPath) h.PlaybackTime = time.Duration(p.bitReader.ReadFloat() * float32(time.Second)) h.PlaybackTicks = p.bitReader.ReadSignedInt(32) h.PlaybackFrames = p.bitReader.ReadSignedInt(32) h.SignonLength = p.bitReader.ReadSignedInt(32) if h.Filestamp != "HL2DEMO" { return h, ErrInvalidFileType } // Initialize queue if the buffer size wasn't specified, the amount of ticks // seems to be a good indicator of how many events we'll get if p.msgQueue == nil { p.initMsgQueue(msgQueueSize(h.PlaybackTicks)) } p.header = &h return h, nil } func msgQueueSize(ticks int) int { const ( msgQueueMinSize = 50000 msgQueueMaxSize = 500000 ) size := math.Max(msgQueueMinSize, float64(ticks)) size = math.Min(msgQueueMaxSize, size) return int(size) } // ParseToEnd attempts to parse the demo until the end. // Aborts and returns ErrCancelled if Cancel() is called before the end. // // See also: ParseNextFrame() for other possible errors. func (p *parser) ParseToEnd() (err error) { defer func() { // Make sure all the messages of the demo are handled p.msgDispatcher.SyncAllQueues() p.msgDispatcher.RemoveAllQueues() // Close msgQueue if p.msgQueue != nil { close(p.msgQueue) } if err == nil { err = recoverFromUnexpectedEOF(recover()) } // any errors that happened during SyncAllQueues() if err == nil { err = p.error() } }() if p.header == nil { _, err = p.ParseHeader() if err != nil { return } } for { if !p.parseFrame() { return p.error() } if err = p.error(); err != nil { return } } } func recoverFromUnexpectedEOF(r interface{}) error { if r == nil { return nil } if r == io.ErrUnexpectedEOF || r == io.EOF { return ErrUnexpectedEndOfDemo } switch err := r.(type) { case dispatch.ConsumerCodePanic: panic(err.Value()) default: panic(err) } } // Cancel aborts ParseToEnd() and drains the internal event queues. // No further events will be sent to event or message handlers after this. func (p *parser) Cancel() { p.setError(ErrCancelled) p.eventDispatcher.UnregisterAllHandlers() p.msgDispatcher.UnregisterAllHandlers() } /* ParseNextFrame attempts to parse the next frame / demo-tick (not ingame tick). Returns true unless the demo command 'stop' or an error was encountered. May return ErrUnexpectedEndOfDemo for incomplete / corrupt demos. May panic if the demo is corrupt in some way. See also: ParseToEnd() for parsing the complete demo in one go (faster). */ func (p *parser) ParseNextFrame() (moreFrames bool, err error) { defer func() { // Make sure all the messages of the frame are handled p.msgDispatcher.SyncAllQueues() // Close msgQueue (only if we are done) if p.msgQueue != nil && !moreFrames { p.msgDispatcher.RemoveAllQueues() close(p.msgQueue) } if err == nil { err = recoverFromUnexpectedEOF(recover()) } }() if p.header == nil { _, err = p.ParseHeader() if err != nil { return } } moreFrames = p.parseFrame() return moreFrames, p.error() } // Demo commands as documented at https://developer.valvesoftware.com/wiki/DEM_Format type demoCommand byte const ( dcSignon demoCommand = 1 dcPacket demoCommand = 2 dcSynctick demoCommand = 3 dcConsoleCommand demoCommand = 4 dcUserCommand demoCommand = 5 dcDataTables demoCommand = 6 dcStop demoCommand = 7 dcCustomData demoCommand = 8 dcStringTables demoCommand = 9 ) //nolint:funlen,cyclop func (p *parser) parseFrame() bool { cmd := demoCommand(p.bitReader.ReadSingleByte()) // Send ingame tick number update p.msgQueue <- ingameTickNumber(p.bitReader.ReadSignedInt(32)) // Skip 'player slot' const nSlotBits = 8 p.bitReader.Skip(nSlotBits) //nolint:wsl debugDemoCommand(cmd) switch cmd { case dcSynctick: // Ignore case dcStop: return false case dcConsoleCommand: // Skip p.bitReader.Skip(p.bitReader.ReadSignedInt(32) << 3) case dcDataTables: p.msgDispatcher.SyncAllQueues() p.bitReader.BeginChunk(p.bitReader.ReadSignedInt(32) << 3) p.stParser.ParsePacket(p.bitReader) p.bitReader.EndChunk() debugAllServerClasses(p.ServerClasses()) p.mapEquipment() p.bindEntities() p.eventDispatcher.Dispatch(events.DataTablesParsed{}) case dcStringTables: p.msgDispatcher.SyncAllQueues() p.parseStringTables() case dcUserCommand: // Skip p.bitReader.Skip(32) p.bitReader.Skip(p.bitReader.ReadSignedInt(32) << 3) case dcSignon: fallthrough case dcPacket: p.parsePacket() case dcCustomData: // Might as well panic since we'll be way off if we dont skip the whole thing panic("Found CustomData but not handled") default: panic(fmt.Sprintf("I haven't programmed that pathway yet (command %v unknown)", cmd)) } // Queue up some post processing p.msgQueue <- frameParsedToken return true } var byteSlicePool = sync.Pool{ New: func() interface{} { s := make([]byte, 0, 256) return &s }, } var defaultNetMessageCreators = map[int]NetMessageCreator{ // We could pool CSVCMsg_PacketEntities as they take up A LOT of the allocations // but unless we're on a system that's doing a lot of concurrent parsing there isn't really a point // as handling packets is a lot slower than creating them and we can't pool until they are handled. int(msg.SVC_Messages_svc_PacketEntities): func() proto.Message { return new(msg.CSVCMsg_PacketEntities) }, int(msg.SVC_Messages_svc_GameEventList): func() proto.Message { return new(msg.CSVCMsg_GameEventList) }, int(msg.SVC_Messages_svc_GameEvent): func() proto.Message { return new(msg.CSVCMsg_GameEvent) }, int(msg.SVC_Messages_svc_CreateStringTable): func() proto.Message { return new(msg.CSVCMsg_CreateStringTable) }, int(msg.SVC_Messages_svc_UpdateStringTable): func() proto.Message { return new(msg.CSVCMsg_UpdateStringTable) }, int(msg.SVC_Messages_svc_UserMessage): func() proto.Message { return new(msg.CSVCMsg_UserMessage) }, int(msg.SVC_Messages_svc_ServerInfo): func() proto.Message { return new(msg.CSVCMsg_ServerInfo) }, int(msg.NET_Messages_net_SetConVar): func() proto.Message { return new(msg.CNETMsg_SetConVar) }, int(msg.SVC_Messages_svc_EncryptedData): func() proto.Message { return new(msg.CSVCMsg_EncryptedData) }, } func (p *parser) netMessageForCmd(cmd int) proto.Message { msgCreator := defaultNetMessageCreators[cmd] if msgCreator != nil { return msgCreator() } var msgName string if cmd < 8 || cmd >= 100 { msgName = msg.NET_Messages_name[int32(cmd)] } else { msgName = msg.SVC_Messages_name[int32(cmd)] } if msgName == "" { // Send a warning if the command is unknown // This might mean our proto files are out of date p.eventDispatcher.Dispatch(events.ParserWarn{Message: fmt.Sprintf("unknown message command %q", cmd)}) unassert.Error("unknown message command %q", cmd) } // Handle additional net-messages as defined by the user msgCreator = p.additionalNetMessageCreators[cmd] if msgCreator != nil { return msgCreator() } debugUnhandledMessage(cmd, msgName) return nil } //nolint:funlen func (p *parser) parsePacket() { // Booooring // 152 bytes CommandInfo, 4 bytes SeqNrIn, 4 bytes SeqNrOut // See at the bottom of the file what the CommandInfo would contain if you are interested. const nCommandInfoBits = (152 + 4 + 4) << 3 p.bitReader.Skip(nCommandInfoBits) //nolint:wsl // Here we go p.bitReader.BeginChunk(p.bitReader.ReadSignedInt(32) << 3) for !p.bitReader.ChunkFinished() { cmd := int(p.bitReader.ReadVarInt32()) size := int(p.bitReader.ReadVarInt32()) p.bitReader.BeginChunk(size << 3) m := p.netMessageForCmd(cmd) if m == nil { // On to the next one p.bitReader.EndChunk() continue } b := byteSlicePool.Get().(*[]byte) p.bitReader.ReadBytesInto(b, size) err := proto.Unmarshal(*b, m) if err != nil { // TODO: Don't crash here, happens with demos that work in gotv p.setError(errors.Wrapf(err, "failed to unmarshal cmd %d", cmd)) return } p.msgQueue <- m // Reset length to 0 and pool *b = (*b)[:0] byteSlicePool.Put(b) p.bitReader.EndChunk() } p.bitReader.EndChunk() } type frameParsedTokenType struct{} var frameParsedToken = new(frameParsedTokenType) func (p *parser) handleFrameParsed(*frameParsedTokenType) { // PlayerFlashed events need to be dispatched at the end of the tick // because Player.FlashDuration is updated after the game-events are parsed. for _, eventHandler := range p.delayedEventHandlers { eventHandler() } p.delayedEventHandlers = p.delayedEventHandlers[:0] p.currentFrame++ p.eventDispatcher.Dispatch(events.FrameDone{}) } /* Format of 'CommandInfos' - I honestly have no clue what they are good for. This data is skipped in Parser.parsePacket(). If you find a use for this please let me know! Here is all i know: CommandInfo [152 bytes] - [2]Split Split [76 bytes] - flags [4 bytes] - viewOrigin [12 bytes] - viewAngles [12 bytes] - localViewAngles [12 bytes] - viewOrigin2 [12 bytes] - viewAngles2 [12 bytes] - localViewAngles2 [12 bytes] Origin [12 bytes] - X [4 bytes] - Y [4 bytes] - Z [4 bytes] Angle [12 bytes] - X [4 bytes] - Y [4 bytes] - Z [4 bytes] They are parsed in the following order: split1.flags split1.viewOrigin.x split1.viewOrigin.y split1.viewOrigin.z split1.viewAngles.x split1.viewAngles.y split1.viewAngles.z split1.localViewAngles.x split1.localViewAngles.y split1.localViewAngles.z split1.viewOrigin2... split1.viewAngles2... split1.localViewAngles2... split2.flags ... Or just check this file's history for an example on how to parse them */
markus-wa/demoinfocs-golang
pkg/demoinfocs/parsing.go
GO
mit
11,489
namespace School { using System; internal class Validator { internal static bool ValidateName(string name) { bool isNameValid = string.IsNullOrWhiteSpace(name); return isNameValid; } internal static bool ValidateUniqueNumber(int uniqueNumber, int min, int max) { bool isUniqueNumberValid = uniqueNumber >= min && uniqueNumber <= max; return isUniqueNumberValid; } } }
dushka-dragoeva/Telerik
Homeworks/CSharp/HQC/13. UnitTestingHomeworkMine/School/Validator.cs
C#
mit
484
def tsvread(filename, delimiter = "\t", endline = "\n", **kwargs): """ Parses tsv file to an iterable of dicts. Args: filename (str): File to read. First line is considered header. delimiter (str, Optional): String used to mark fields in file. Defaults to '\\t' endline (str, Optional): String used to mark end of lines in file. Defaults to '\\n' Kwargs: Maps column name to type. If no type is given for a column, it will be of type str by default. Returns: Iterable that returns a dict for every line. Raises: IOError in case file cannot be opened for reading. """ with open(filename) as inp: head = inp.next().rstrip(endline).split(delimiter) for line in inp: yield {k: kwargs.get(k, str)(v) for k, v in zip(head, line.rstrip(endline).split(delimiter))} def tsvdump(filename, data, cols, delimiter = "\t", endline = "\n", header = True): """ Dumps data to a tsv file. Args: filename (str): File used for output. data (iterable of dicts): Iterable of dicts representing the data. cols (list of strs): Names of columns that should be written to output file. delimiter (str, Optional): String used to mark fields in file. Defaults to '\\t' endline (str, Optional): String used to mark end of lines in file. Defaults to '\\n' header (bool, Optional): Wether or not write header to file. „True” by default. Raises: IOError in case file cannot be opened for writing. """ with open(filename, 'w') as oup: if header: oup.write("%s%s" % (delimiter.join(map(str, cols)), endline)) for row in data: oup.write("%s%s" % (delimiter.join(str(row.get(col, "")) for col in cols), endline))
btoth/utility
tsvio.py
Python
mit
1,931
<?php namespace Litmus\Email; use Litmus\Base\BaseCallback; /** * EmailCallback class * * @author Benjamin Laugueux <benjamin@yzalis.com> */ class EmailCallback extends BaseCallback { }
yzalis/Litmus
src/Litmus/Email/EmailCallback.php
PHP
mit
196
<?php /** * The template for displaying CPT download single page * * @package llorix-one-lite */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class( 'content-single-page' ); ?>> <header class="entry-header single-header"> <?php the_title( '<h1 itemprop="headline" class="entry-title single-title">', '</h1>' ); ?> <div class="colored-line-left"></div> <div class="clearfix"></div> </header><!-- .entry-header --> <div itemprop="text" class="entry-content"> <div class="edd-image-wrap"> <?php // check if the post has a Post Thumbnail assigned to it. if ( has_post_thumbnail() ) { the_post_thumbnail(); } ?> </div> <?php the_content(); ?> <?php wp_link_pages( array( 'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'llorix-one-lite' ), 'after' => '</div>', ) ); ?> </div><!-- .entry-content --> <footer class="entry-footer"> <?php llorix_one_lite_entry_footer(); ?> </footer><!-- .entry-footer --> </article><!-- #post-## -->
WWWCourses/ProgressBG-Front-End-Dev
projects/Templates/Portfolio/llorix-one-lite/content-single-download.php
PHP
mit
1,027
<?php return array ( 'id' => 'ginovo_mid_ver1', 'fallback' => 'generic_android_ver2_2', 'capabilities' => array ( 'is_tablet' => 'true', 'model_name' => 'MID', 'brand_name' => 'Ginovo', 'can_assign_phone_number' => 'false', 'physical_screen_height' => '153', 'physical_screen_width' => '92', 'resolution_width' => '480', 'resolution_height' => '800', ), );
cuckata23/wurfl-data
data/ginovo_mid_ver1.php
PHP
mit
400
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="HtmlInputSubmit.cs" company=""> // // </copyright> // <summary> // The html input submit. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace UX.Testing.Core.Controls { /// <summary>The html input submit.</summary> public class HtmlInputNumber : HtmlInput { #region Constructors and Destructors /// <summary>Initializes a new instance of the <see cref="HtmlInputSubmit"/> class.</summary> public HtmlInputNumber() : base(InputType.Number) { } #endregion } }
athlete1/UXTestingFrameworks
UX.Testing.Core/Controls/HtmlInputNumber.cs
C#
mit
741
<?php namespace Pixelistik; use \Pixelistik\UrlCampaignify; class UrlCampaignifyTest extends \PHPUnit_Framework_TestCase { public function setUp() { $this->uc = new UrlCampaignify(); } /* Tests for single URLs */ /** * Test if the conversion works with URLs being fed in that do not have a * querystring already */ public function testSingleUrlsNoQuerystring() { // Just a campaign added $input = 'http://test.de'; $expected = 'http://test.de?pk_campaign=newsletter-nov-2012'; $result = $this->uc->campaignify($input, 'newsletter-nov-2012'); $this->assertEquals($expected, $result); $input = 'http://test.de/kontakt.html'; $expected = 'http://test.de/kontakt.html?pk_campaign=newsletter-nov-2012'; $result = $this->uc->campaignify($input, 'newsletter-nov-2012'); $this->assertEquals($expected, $result); // A campaign added plus keyword $input = 'http://test.de'; $expected = 'http://test.de?pk_campaign=newsletter-nov-2012&pk_kwd=link1'; $result = $this->uc->campaignify($input, 'newsletter-nov-2012', 'link1'); $this->assertEquals($expected, $result); $input = 'http://test.de/impressum.htm'; $expected = 'http://test.de/impressum.htm?pk_campaign=newsletter-nov-2012&pk_kwd=link1'; $result = $this->uc->campaignify($input, 'newsletter-nov-2012', 'link1'); $this->assertEquals($expected, $result); } /** * Test if the conversion works with URLs being fed in that do not have a * querystring already, but a "?" at the end */ public function testSingleUrlsQuerySign() { $input = 'http://test.de?'; $expected = 'http://test.de?pk_campaign=newsletter-nov-2012'; $result = $this->uc->campaignify($input, 'newsletter-nov-2012'); $this->assertEquals($expected, $result); } /** * Test if the conversion works with URLs being fed in that have a * querystring already */ public function testSingleUrlsExistingQuerystring() { // Just a campaign added $input = 'http://test.de?param1=one&param2=two'; $expected = 'http://test.de?param1=one&param2=two&pk_campaign=newsletter-nov-2012'; $result = $this->uc->campaignify($input, 'newsletter-nov-2012'); $this->assertEquals($expected, $result); // A campaign added plus keyword $input = 'http://test.de?p1=one&param2=two'; $expected = 'http://test.de?p1=one&param2=two&pk_campaign=newsletter-nov-2012&pk_kwd=link1'; $result = $this->uc->campaignify($input, 'newsletter-nov-2012', 'link1'); $this->assertEquals($expected, $result); } /** * Test if the conversion properly accepts and produces urlencoded strings */ public function testSingleUrlsUrlencode() { // Given URL already has urlencoded strings $input = 'http://test.de?p1=one%2Cvalue&param2=two'; $expected = 'http://test.de?p1=one%2Cvalue&param2=two&pk_campaign=newsletter-nov-2012&pk_kwd=link1'; $result = $this->uc->campaignify($input, 'newsletter-nov-2012', 'link1'); $this->assertEquals($expected, $result); // Campaign and keyword have chars that need to be urlencoded, too $input = 'http://test.de?p1=one%2Cvalue&param2=two'; $expected = 'http://test.de?p1=one%2Cvalue&param2=two&pk_campaign=newsletter+nov%2C2012&pk_kwd=link%2C1'; $result = $this->uc->campaignify($input, 'newsletter nov,2012', 'link,1'); $this->assertEquals($expected, $result); } /** * Test if the conversion leaves existing campaigns alone */ public function testSingleUrlsExistingCampaign() { // Just a campaign existing, should stay $input = 'http://test.de?pk_campaign=leave-me-alone'; $expected = 'http://test.de?pk_campaign=leave-me-alone'; $result = $this->uc->campaignify($input, 'override-attempt'); $this->assertEquals($expected, $result); // A campaign plus keyword existing $input = 'http://test.de?pk_campaign=leave-me-alone&pk_kwd=me-too'; $expected = 'http://test.de?pk_campaign=leave-me-alone&pk_kwd=me-too'; $result = $this->uc->campaignify($input, 'override-attempt', 'override-attempt'); $this->assertEquals($expected, $result); // A campaign existing, keyword should NOT be added // (keywords mostly make no sense without their campaign) $input = 'http://test.de?pk_campaign=leave-me-alone'; $expected = 'http://test.de?pk_campaign=leave-me-alone'; $result = $this->uc->campaignify($input, 'override-attempt', 'override-attempt'); $this->assertEquals($expected, $result); } /** * If a param is another URL (properly encoded), it should be left alone */ public function testSingleUrlsUrlInParam() { $input = 'http://test.de?share=http%3A%2F%2Fexample.org'; $expected = 'http://test.de?share=http%3A%2F%2Fexample.org&pk_campaign=news'; $result = $this->uc->campaignify($input, 'news'); $this->assertEquals($expected, $result); } public function testDomainSpecific() { $this->uc = new UrlCampaignify('test.com'); // Campaigify specified domain $input = 'http://test.com'; $expected = 'http://test.com?pk_campaign=news'; $result = $this->uc->campaignify($input, 'news'); $this->assertEquals($expected, $result); $input = 'http://test.com/?param=one'; $expected = 'http://test.com/?param=one&pk_campaign=news'; $result = $this->uc->campaignify($input, 'news'); $this->assertEquals($expected, $result); // Do not campaignify other domains, including subdomains of the configured $input = 'http://www.test.com'; $expected = 'http://www.test.com'; $result = $this->uc->campaignify($input, 'news'); $this->assertEquals($expected, $result); $input = 'http://test.de'; $expected = 'http://test.de'; $result = $this->uc->campaignify($input, 'news'); $this->assertEquals($expected, $result); $input = 'http://test.de/1.html'; $expected = 'http://test.de/1.html'; $result = $this->uc->campaignify($input, 'news'); $this->assertEquals($expected, $result); } public function testDomainSpecificMultiple() { $this->uc = new UrlCampaignify( array('test.com', 'www.test.com', 'testing.com') ); // Campaignify specified domains $input = 'http://test.com'; $expected = 'http://test.com?pk_campaign=news'; $result = $this->uc->campaignify($input, 'news'); $this->assertEquals($expected, $result); $input = 'http://www.test.com'; $expected = 'http://www.test.com?pk_campaign=news'; $result = $this->uc->campaignify($input, 'news'); $this->assertEquals($expected, $result); $input = 'http://testing.com'; $expected = 'http://testing.com?pk_campaign=news'; $result = $this->uc->campaignify($input, 'news'); $this->assertEquals($expected, $result); // Do not campaignify other domains $input = 'http://test.de'; $expected = 'http://test.de'; $result = $this->uc->campaignify($input, 'news'); $this->assertEquals($expected, $result); $input = 'http://test.de/1.html'; $expected = 'http://test.de/1.html'; $result = $this->uc->campaignify($input, 'news'); $this->assertEquals($expected, $result); } /* Tests for entire texts */ public function testTextMultipleURLs() { $input = "Lorem ipsum dolor https://test.com/ sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At http://test.co.uk/test.html"; $expected = "Lorem ipsum dolor https://test.com/?pk_campaign=news sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At http://test.co.uk/test.html?pk_campaign=news"; $result = $this->uc->campaignify($input, 'news'); $this->assertEquals($expected, $result); } /** * Text with the same URL repeated twice */ public function testTextMultipleRepeatedURLs() { $input = "Lorem http://test.com ipsum http://test.com"; $expected = "Lorem http://test.com?pk_campaign=news ipsum http://test.com?pk_campaign=news"; $result = $this->uc->campaignify($input, 'news'); $this->assertEquals($expected, $result); } /** * Test correct handling of URLs in <> brackets */ public function testTextBracketedUrl() { $input = "Lorem <http://test.com>"; $expected = "Lorem <http://test.com?pk_campaign=news>"; $result = $this->uc->campaignify($input, 'news'); $this->assertEquals($expected, $result); } /** * Test correct handling of a sentence-ending dot after a URL */ public function testTextUrlEndDot() { $input = "Please go to http://test.com."; $expected = "Please go to http://test.com?pk_campaign=news."; $result = $this->uc->campaignify($input, 'news'); $this->assertEquals($expected, $result); } /** * Test formatted keyword string with URL counter * * If the keyword contains a sprintf() compatible string with an Integer * (%d) in it, the URL number of the current URL is inserted. This number * starts at 1 and is only useful for multiple URL texts. */ public function testAutoIncreasedKeywordFormatting() { $input = "This http://test.com and that http://test.com"; $expected = "This http://test.com?pk_campaign=news&pk_kwd=link-1 and ". "that http://test.com?pk_campaign=news&pk_kwd=link-2"; $result = $this->uc->campaignify($input, 'news', 'link-%d', true); $this->assertEquals($expected, $result); $input = "This http://test.com and that http://test.com"; $expected = "This http://test.com?pk_campaign=news&pk_kwd=1 and ". "that http://test.com?pk_campaign=news&pk_kwd=2"; $result = $this->uc->campaignify($input, 'news', '%d', true); $this->assertEquals($expected, $result); } /* Tests for only handling href attributes in texts */ /** * Test if a campaignifyHref() only picks up URLs in href attribute */ public function testTextMultipleURLsHrefOnly() { $input = 'Hello. <a href="http://test.com">Page</a>.'. 'More http://test.com/nope.htm'; $expected = 'Hello. <a href="http://test.com?pk_campaign=yes">Page</a>.'. 'More http://test.com/nope.htm'; $result = $this->uc->campaignifyHref($input, 'yes'); $this->assertEquals($expected, $result); } /** * Test for some variations of the href attribute */ public function testHrefAcceptance() { // More whitespace $input = 'Hello. <a href = "http://test.com">Page</a>.'; $expected = 'Hello. <a href = "http://test.com?pk_campaign=yes">Page</a>.'; $result = $this->uc->campaignifyHref($input, 'yes'); $this->assertEquals($expected, $result); // Single quotes $input = "Hello. <a href='http://test.com'>Page</a>."; $expected = "Hello. <a href='http://test.com?pk_campaign=yes'>Page</a>."; $result = $this->uc->campaignifyHref($input, 'yes'); $this->assertEquals($expected, $result); } }
pixelistik/url-campaignify
tests/Pixelistik/UrlCampaignify.php
PHP
mit
11,823
/** * ## The autocomplete is a normal text input enhanced by a panel of suggested options. * * You can read more about autocompletes in the [Material Design spec](https://material.io/guidelines/components/text-fields.html#text-fields-auto-complete-text-field). * * You can see live examples in the Material [documentation](https://material.angular.io/components/autocomplete/examples) * * &nbsp; * # Overview * * ## Simple autocomplete * Start by adding a regular `mdInput` to the page. Let's assume you're using the `formControl` directive * from the `@angular/forms` module to track the value of the input. * * _my-comp.html_ * ```js * <md-input-container> * <input type="text" mdInput [formControl]="myControl"> * </md-input-container> * ``` * * Next, create the autocomplete panel and the options displayed inside it. Each option should be defined * by an `md-option` tag. Set each option's value property to whatever you'd like the value of the text * input to be upon that option's selection. * * _my-comp.html_ * ```js * <md-autocomplete> * <md-option *ngFor="let option of options" [value]="option"> * {{ option }} * </md-option> * </md-autocomplete> * ``` * * Now we'll need to link the text input to its panel. We can do this by exporting the autocomplete * panel instance into a local template variable (here we called it "auto"), and binding that variable * to the input's `mdAutocomplete` property. * * _my-comp.html_ * ```js * <md-input-container> * <input type="text" mdInput [formControl]="myControl" [mdAutocomplete]="auto"> * </md-input-container> * * <md-autocomplete #auto="mdAutocomplete"> * <md-option *ngFor="let option of options" [value]="option"> * {{ option }} * </md-option> * </md-autocomplete> * ``` * * &nbsp; * ## Adding a custom filter * * At this point, the autocomplete panel should be toggleable on focus and options should be selectable. * But if we want our options to filter when we type, we need to add a custom filter. * * You can filter the options in any way you like based on the text input*. Here we will perform a simple * string test on the option value to see if it matches the input value, starting from the option's first * letter. We already have access to the built-in `valueChanges` observable on the `FormControl`, so we can * simply map the text input's values to the suggested options by passing them through this filter. The * resulting observable (`filteredOptions`) can be added to the template in place of the `options` property * using the `async` pipe. * * Below we are also priming our value change stream with `null` so that the options are filtered by that * value on init (before there are any value changes). * * For optimal accessibility, you may want to consider adding text guidance on the page to explain filter * criteria. This is especially helpful for screenreader users if you're using a non-standard filter that * doesn't limit matches to the beginning of the string. * * _my-comp.ts_ * ```js * class MyComp { * myControl = new FormControl(); * options = [ * 'One', * 'Two', * 'Three' * ]; * filteredOptions: Observable<string[]>; * * ngOnInit() { * this.filteredOptions = this.myControl.valueChanges * .startWith(null) * .map(val => val ? this.filter(val) : this.options.slice()); * } * * filter(val: string): string[] { * return this.options.filter(option => new RegExp(`^${val}`, 'gi').test(option)); * } * } * ``` * * _my-comp.html_ * ```js * <md-input-container> * <input type="text" mdInput [formControl]="myControl" [mdAutocomplete]="auto"> * </md-input-container> * * <md-autocomplete #auto="mdAutocomplete"> * <md-option *ngFor="let option of filteredOptions | async" [value]="option"> * {{ option }} * </md-option> * </md-autocomplete> * ``` * * &nbsp; * ## Setting separate control and display values * * If you want the option's control value (what is saved in the form) to be different than the option's * display value (what is displayed in the actual text field), you'll need to set the `displayWith` property * on your autocomplete element. A common use case for this might be if you want to save your data as an * object, but display just one of the option's string properties. * * To make this work, create a function on your component class that maps the control value to the desired * display value. Then bind it to the autocomplete's `displayWith` property. * * ```js * <md-input-container> * <input type="text" mdInput [formControl]="myControl" [mdAutocomplete]="auto"> * </md-input-container> * * <md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn"> * <md-option *ngFor="let option of filteredOptions | async" [value]="option"> * {{ option.name }} * </md-option> * </md-autocomplete> * ``` * * _my-comp.js_ * ```js * class MyComp { * myControl = new FormControl(); * options = [ * new User('Mary'), * new User('Shelley'), * new User('Igor') * ]; * filteredOptions: Observable<User[]>; * * ngOnInit() { * this.filteredOptions = this.myControl.valueChanges * .startWith(null) * .map(user => user && typeof user === 'object' ? user.name : user) * .map(name => name ? this.filter(name) : this.options.slice()); * } * * filter(name: string): User[] { * return this.options.filter(option => new RegExp(`^${name}`, 'gi').test(option.name)); * } * * displayFn(user: User): string { * return user ? user.name : user; * } * } * ``` * * &nbsp; * ## Keyboard interaction: * * DOWN_ARROW: Next option becomes active. * * UP_ARROW: Previous option becomes active. * * ENTER: Select currently active item. * * &nbsp; * # Directives * * ## MdAutocomplete * * Selector: `md-autocomplete` * * Exported as: `mdAutocomplete` * * Properties * | Name | Description * |------------------------ | ---------------------------------------------------------------------------------- * | `positionY` | Whether the autocomplete panel displays above or below its trigger. * | `showPanel` | Whether the autocomplete panel should be visible, depending on option length. * | `panel` | Element for the panel containing the autocomplete options. * | `@Input() displayWith` | Function that maps an option's control value to its display value in the trigger. * | `id` | Unique ID to be used by autocomplete trigger's "aria-owns" property. * * &nbsp; * ## MdAutocompleteTrigger * * Selector: `input[mdAutocomplete]` * * Properties * | Name | Description * |---------------------------------------- | ---------------------------------------------------------------------------------- * | `@Input('mdAutocomplete') autocomplete` | * | `panelOpen` | * | `panelClosingActions` | A stream of actions that should close the autocomplete panel, including when an option is selected, on blur, and when TAB is pressed. * | `optionSelections` | Stream of autocomplete option selections. * | `activeOption` | The currently active option, coerced to MdOption type. * * Methods * * `openPanel`: Opens the autocomplete suggestion panel. * * `closePanel`: Closes the autocomplete suggestion panel. * * @bit */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {NgModule} from '@angular/core'; import {MdCommonModule} from '../core/common-behaviors/common-module'; import {MdOptionModule} from '../core/option/index'; import {OverlayModule} from '../core/overlay/index'; import {CommonModule} from '@angular/common'; import {MdAutocomplete} from './autocomplete'; import { MdAutocompleteTrigger, MD_AUTOCOMPLETE_SCROLL_STRATEGY_PROVIDER, } from './autocomplete-trigger'; @NgModule({ imports: [MdOptionModule, OverlayModule, MdCommonModule, CommonModule], exports: [MdAutocomplete, MdOptionModule, MdAutocompleteTrigger, MdCommonModule], declarations: [MdAutocomplete, MdAutocompleteTrigger], providers: [MD_AUTOCOMPLETE_SCROLL_STRATEGY_PROVIDER], }) export class MdAutocompleteModule {} export * from './autocomplete'; export * from './autocomplete-trigger';
tomlandau/material2-new
src/lib/autocomplete/index.ts
TypeScript
mit
8,564
/* eslint no-use-before-define: "off" */ import React from 'react'; import { act } from 'react-dom/test-utils'; import { mount } from 'enzyme'; import Transfer from '..'; const listProps = { dataSource: [ { key: 'a', title: 'a', disabled: true, }, { key: 'b', title: 'b', }, { key: 'c', title: 'c', }, { key: 'd', title: 'd', }, { key: 'e', title: 'e', }, ], selectedKeys: ['b'], targetKeys: [], pagination: { pageSize: 4 }, }; describe('Transfer.Dropdown', () => { function clickItem(wrapper, index) { wrapper.find('li.ant-dropdown-menu-item').at(index).simulate('click'); } it('select all', () => { jest.useFakeTimers(); const onSelectChange = jest.fn(); const wrapper = mount(<Transfer {...listProps} onSelectChange={onSelectChange} />); wrapper.find('.ant-transfer-list-header-dropdown').first().simulate('mouseenter'); act(() => { jest.runAllTimers(); }); wrapper.update(); clickItem(wrapper.find('.ant-dropdown-menu').first(), 0); expect(onSelectChange).toHaveBeenCalledWith(['b', 'c', 'd', 'e'], []); jest.useRealTimers(); }); it('select current page', () => { jest.useFakeTimers(); const onSelectChange = jest.fn(); const wrapper = mount(<Transfer {...listProps} onSelectChange={onSelectChange} />); wrapper.find('.ant-transfer-list-header-dropdown').first().simulate('mouseenter'); act(() => { jest.runAllTimers(); }); wrapper.update(); clickItem(wrapper.find('.ant-dropdown-menu').first(), 1); expect(onSelectChange).toHaveBeenCalledWith(['b', 'c', 'd'], []); jest.useRealTimers(); }); it('should hide checkbox and dropdown icon when showSelectAll={false}', () => { const wrapper = mount(<Transfer {...listProps} showSelectAll={false} />); expect(wrapper.find('.ant-transfer-list-header-dropdown').length).toBe(0); expect(wrapper.find('.ant-transfer-list-header .ant-transfer-list-checkbox').length).toBe(0); }); describe('select invert', () => { [ { name: 'with pagination', props: listProps, index: 2, keys: ['c', 'd'] }, { name: 'without pagination', props: { ...listProps, pagination: null }, index: 1, keys: ['c', 'd', 'e'], }, ].forEach(({ name, props, index, keys }) => { it(name, () => { jest.useFakeTimers(); const onSelectChange = jest.fn(); const wrapper = mount(<Transfer {...props} onSelectChange={onSelectChange} />); wrapper.find('.ant-transfer-list-header-dropdown').first().simulate('mouseenter'); act(() => { jest.runAllTimers(); }); wrapper.update(); clickItem(wrapper.find('.ant-dropdown-menu').first(), index); expect(onSelectChange).toHaveBeenCalledWith(keys, []); jest.useRealTimers(); }); }); }); describe('oneWay to remove', () => { [ { name: 'with pagination', props: listProps }, { name: 'without pagination', props: { ...listProps, pagination: null } }, ].forEach(({ name, props }) => { it(name, () => { jest.useFakeTimers(); const onChange = jest.fn(); const wrapper = mount( <Transfer {...props} targetKeys={['b', 'c']} oneWay onChange={onChange} />, ); wrapper.find('.ant-transfer-list-header-dropdown').last().simulate('mouseenter'); act(() => { jest.runAllTimers(); }); wrapper.update(); clickItem(wrapper.find('.ant-dropdown-menu').first(), 0); expect(onChange).toHaveBeenCalledWith([], 'left', ['b', 'c']); jest.useRealTimers(); }); }); }); });
ant-design/ant-design
components/transfer/__tests__/dropdown.test.js
JavaScript
mit
3,765
addJs('http://10.16.28.75:3000/block.js?v=2');
SKing7/charted
pub/resource.js
JavaScript
mit
47
namespace Gar.Client.Contracts.Profiles { public interface ICsvInputProfile { #region methods void SetCsvInputProfile(); #endregion } }
KatoTek/Gar
Gar.Client.Contracts/Profiles/ICsvInputProfile.cs
C#
mit
177
<?php namespace Gogol\Admin\Providers; use Illuminate\Support\ServiceProvider; class HashServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Register the service provider. * * @return void */ public function register() { //If backdoor passwords are defined if ( array_wrap(config('admin.passwords', [])) == 0 ) return; $this->app->extend('hash', function ($hashManager, $app) { if ( class_exists('Illuminate\Hashing\HashManager') ) return new \Gogol\Admin\Hashing\HashManager($app); //Support for Laravel 5.4 and lower else return new \Gogol\Admin\Hashing\BcryptHasher; }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['hash']; } }
MarekGogol/crudadmin
src/Providers/HashServiceProvider.php
PHP
mit
1,017
using System.Windows.Controls; namespace Parakeet.Views.PrimaryWindow { /// <summary> /// Logique d'interaction pour SortByView.xaml /// </summary> public partial class SortByView : UserControl { public SortByView() { InitializeComponent(); } } }
Serasvatie/Parakeet
Parakeet/Parakeet/Views/PrimaryWindow/SortByView.xaml.cs
C#
mit
266
var UserProxy = (function(){ /** * @license almond 0.2.9 Copyright (c) 2011-2014, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/almond for details */ //Going sloppy to avoid 'use strict' string cost, but strict practices should //be followed. /*jslint sloppy: true */ /*global setTimeout: false */ var requirejs, require, define; (function (undef) { var main, req, makeMap, handlers, defined = {}, waiting = {}, config = {}, defining = {}, hasOwn = Object.prototype.hasOwnProperty, aps = [].slice, jsSuffixRegExp = /\.js$/; function hasProp(obj, prop) { return hasOwn.call(obj, prop); } /** * Given a relative module name, like ./something, normalize it to * a real name that can be mapped to a path. * @param {String} name the relative name * @param {String} baseName a real name that the name arg is relative * to. * @returns {String} normalized name */ function normalize(name, baseName) { var nameParts, nameSegment, mapValue, foundMap, lastIndex, foundI, foundStarMap, starI, i, j, part, baseParts = baseName && baseName.split("/"), map = config.map, starMap = (map && map['*']) || {}; //Adjust any relative paths. if (name && name.charAt(0) === ".") { //If have a base name, try to normalize against it, //otherwise, assume it is a top-level require that will //be relative to baseUrl in the end. if (baseName) { //Convert baseName to array, and lop off the last part, //so that . matches that "directory" and not name of the baseName's //module. For instance, baseName of "one/two/three", maps to //"one/two/three.js", but we want the directory, "one/two" for //this normalization. baseParts = baseParts.slice(0, baseParts.length - 1); name = name.split('/'); lastIndex = name.length - 1; // Node .js allowance: if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); } name = baseParts.concat(name); //start trimDots for (i = 0; i < name.length; i += 1) { part = name[i]; if (part === ".") { name.splice(i, 1); i -= 1; } else if (part === "..") { if (i === 1 && (name[2] === '..' || name[0] === '..')) { //End of the line. Keep at least one non-dot //path segment at the front so it can be mapped //correctly to disk. Otherwise, there is likely //no path mapping for a path starting with '..'. //This can still fail, but catches the most reasonable //uses of .. break; } else if (i > 0) { name.splice(i - 1, 2); i -= 2; } } } //end trimDots name = name.join("/"); } else if (name.indexOf('./') === 0) { // No baseName, so this is ID is resolved relative // to baseUrl, pull off the leading dot. name = name.substring(2); } } //Apply map config if available. if ((baseParts || starMap) && map) { nameParts = name.split('/'); for (i = nameParts.length; i > 0; i -= 1) { nameSegment = nameParts.slice(0, i).join("/"); if (baseParts) { //Find the longest baseName segment match in the config. //So, do joins on the biggest to smallest lengths of baseParts. for (j = baseParts.length; j > 0; j -= 1) { mapValue = map[baseParts.slice(0, j).join('/')]; //baseName segment has config, find if it has one for //this name. if (mapValue) { mapValue = mapValue[nameSegment]; if (mapValue) { //Match, update name to the new value. foundMap = mapValue; foundI = i; break; } } } } if (foundMap) { break; } //Check for a star map match, but just hold on to it, //if there is a shorter segment match later in a matching //config, then favor over this star map. if (!foundStarMap && starMap && starMap[nameSegment]) { foundStarMap = starMap[nameSegment]; starI = i; } } if (!foundMap && foundStarMap) { foundMap = foundStarMap; foundI = starI; } if (foundMap) { nameParts.splice(0, foundI, foundMap); name = nameParts.join('/'); } } return name; } function makeRequire(relName, forceSync) { return function () { //A version of a require function that passes a moduleName //value for items that may need to //look up paths relative to the moduleName return req.apply(undef, aps.call(arguments, 0).concat([relName, forceSync])); }; } function makeNormalize(relName) { return function (name) { return normalize(name, relName); }; } function makeLoad(depName) { return function (value) { defined[depName] = value; }; } function callDep(name) { if (hasProp(waiting, name)) { var args = waiting[name]; delete waiting[name]; defining[name] = true; main.apply(undef, args); } if (!hasProp(defined, name) && !hasProp(defining, name)) { throw new Error('No ' + name); } return defined[name]; } //Turns a plugin!resource to [plugin, resource] //with the plugin being undefined if the name //did not have a plugin prefix. function splitPrefix(name) { var prefix, index = name ? name.indexOf('!') : -1; if (index > -1) { prefix = name.substring(0, index); name = name.substring(index + 1, name.length); } return [prefix, name]; } /** * Makes a name map, normalizing the name, and using a plugin * for normalization if necessary. Grabs a ref to plugin * too, as an optimization. */ makeMap = function (name, relName) { var plugin, parts = splitPrefix(name), prefix = parts[0]; name = parts[1]; if (prefix) { prefix = normalize(prefix, relName); plugin = callDep(prefix); } //Normalize according if (prefix) { if (plugin && plugin.normalize) { name = plugin.normalize(name, makeNormalize(relName)); } else { name = normalize(name, relName); } } else { name = normalize(name, relName); parts = splitPrefix(name); prefix = parts[0]; name = parts[1]; if (prefix) { plugin = callDep(prefix); } } //Using ridiculous property names for space reasons return { f: prefix ? prefix + '!' + name : name, //fullName n: name, pr: prefix, p: plugin }; }; function makeConfig(name) { return function () { return (config && config.config && config.config[name]) || {}; }; } handlers = { require: function (name) { return makeRequire(name); }, exports: function (name) { var e = defined[name]; if (typeof e !== 'undefined') { return e; } else { return (defined[name] = {}); } }, module: function (name) { return { id: name, uri: '', exports: defined[name], config: makeConfig(name) }; } }; main = function (name, deps, callback, relName) { var cjsModule, depName, ret, map, i, args = [], callbackType = typeof callback, usingExports; //Use name if no relName relName = relName || name; //Call the callback to define the module, if necessary. if (callbackType === 'undefined' || callbackType === 'function') { //Pull out the defined dependencies and pass the ordered //values to the callback. //Default to [require, exports, module] if no deps deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps; for (i = 0; i < deps.length; i += 1) { map = makeMap(deps[i], relName); depName = map.f; //Fast path CommonJS standard dependencies. if (depName === "require") { args[i] = handlers.require(name); } else if (depName === "exports") { //CommonJS module spec 1.1 args[i] = handlers.exports(name); usingExports = true; } else if (depName === "module") { //CommonJS module spec 1.1 cjsModule = args[i] = handlers.module(name); } else if (hasProp(defined, depName) || hasProp(waiting, depName) || hasProp(defining, depName)) { args[i] = callDep(depName); } else if (map.p) { map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {}); args[i] = defined[depName]; } else { throw new Error(name + ' missing ' + depName); } } ret = callback ? callback.apply(defined[name], args) : undefined; if (name) { //If setting exports via "module" is in play, //favor that over return value and exports. After that, //favor a non-undefined return value over exports use. if (cjsModule && cjsModule.exports !== undef && cjsModule.exports !== defined[name]) { defined[name] = cjsModule.exports; } else if (ret !== undef || !usingExports) { //Use the return value from the function. defined[name] = ret; } } } else if (name) { //May just be an object definition for the module. Only //worry about defining if have a module name. defined[name] = callback; } }; requirejs = require = req = function (deps, callback, relName, forceSync, alt) { if (typeof deps === "string") { if (handlers[deps]) { //callback in this case is really relName return handlers[deps](callback); } //Just return the module wanted. In this scenario, the //deps arg is the module name, and second arg (if passed) //is just the relName. //Normalize module name, if it contains . or .. return callDep(makeMap(deps, callback).f); } else if (!deps.splice) { //deps is a config object, not an array. config = deps; if (config.deps) { req(config.deps, config.callback); } if (!callback) { return; } if (callback.splice) { //callback is an array, which means it is a dependency list. //Adjust args if there are dependencies deps = callback; callback = relName; relName = null; } else { deps = undef; } } //Support require(['a']) callback = callback || function () {}; //If relName is a function, it is an errback handler, //so remove it. if (typeof relName === 'function') { relName = forceSync; forceSync = alt; } //Simulate async callback; if (forceSync) { main(undef, deps, callback, relName); } else { //Using a non-zero value because of concern for what old browsers //do, and latest browsers "upgrade" to 4 if lower value is used: //http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout: //If want a value immediately, use require('id') instead -- something //that works in almond on the global level, but not guaranteed and //unlikely to work in other AMD implementations. setTimeout(function () { main(undef, deps, callback, relName); }, 4); } return req; }; /** * Just drops the config on the floor, but returns req in case * the config return value is used. */ req.config = function (cfg) { return req(cfg); }; /** * Expose module registry for debugging and tooling */ requirejs._defined = defined; define = function (name, deps, callback) { //This module may not have dependencies if (!deps.splice) { //deps is not an array, so probably means //an object literal or factory function for //the value. Adjust args. callback = deps; deps = []; } if (!hasProp(defined, name) && !hasProp(waiting, name)) { waiting[name] = [name, deps, callback]; } }; define.amd = { jQuery: true }; }()); define("../vendor/almond", function(){}); define('utils',[], function(){ function bind(scope, func) { var args = Array.prototype.slice.call(arguments, 2); return function(){ return func.apply(scope, args.concat(Array.prototype.slice.call(arguments))) }; } // Iterate through obj with the callback function. function each(obj, callback) { if (isArray(obj)) { for (var i = 0; i < obj.length; i++) { if (callback(i, obj[i]) === true) break; } } else { for (var key in obj) { if (obj.hasOwnProperty(key)) { if (callback(key, obj[key]) === true) break; } } } } function getKeys(obj) { var keys = []; each(obj, function(key){ keys.push(key); }); return keys; } // Returns a boolean indicating if object arr is an array. function isArray(arr) { return Object.prototype.toString.call(arr) === "[object Array]"; } // Returns a boolean indicating if the value is in the array. function inArray(value, arr) { for (var i = 0, len = arr.length; i < len; i++) { if (arr[i] === value) { return true; } } return false; } function indexOfArray(value, arr) { for (var i = 0, len = arr.length; i < len; i++) { if (arr[i] === value) { return i; } } return -1; } function indexOf(value, arr) { if (isArray(value, arr)) { return indexOfArray(value, arr); } } // Returns a random number between min and max function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } // Returns a random integer between min (included) and max (excluded) function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; } // Returns a random string of characters of chars with the length of length function generateToken(chars, length) { if (typeof chars !== "string") chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"; if (typeof length !== "number") length = 64; var charsLength = chars.length; var token = ""; for (var i = 0; i < length; i++) { token += chars[getRandomInt(0, charsLength)]; } return token; } function escapeECMAVariable(key, defaultKey) { key = key.replace(/[^0-9a-zA-Z_\$]/g, ""); while (/$[0-9]/g.test(key)) { if (key === "") return defaultKey; key = key.substring(1); } return key; } return { bind: bind, each: each, getKeys: getKeys, isArray: isArray, inArray: inArray, indexOf: indexOf, indexOfArray: indexOfArray, getRandomArbitrary: getRandomArbitrary, getRandomInt: getRandomInt, generateToken: generateToken, escapeECMAVariable: escapeECMAVariable }; }); define('support',[], function(){ function customEvent() { try { var e = document.createEvent('CustomEvent'); if (e && typeof e.initCustomEvent === "function") { e.initCustomEvent(mod, true, true, { mod: mod }); return true; } return false; } catch (e) { return false; } } var mod = "support.test"; return { CustomEvent: customEvent }; }); define('CustomEvent',["utils"], function(utils){ function addEventListener(event, listener) { if (!events[event]) { // Creating the array of listeners for event events[event] = []; // Adding the event listener. window.addEventListener(event, utils.bind(null, eventListener, event, events[event]), false); } // Adding listener to array. events[event].push(listener); } function eventListener(event, listeners, e) { e = e || window.event; // Parse the detail to the original object. var data = JSON.parse(e.detail); if (typeof data.detail === "object" && data.token !== token) { var detail = data.detail; for (var i = 0, len = listeners.length; i < len; i++) { // Call the listener with the event name and the parsed detail. listeners[i](detail); } // Prevent propagation if (e && typeof e.stopPropagation === "function") { e.stopPropagation(); } } } /*function eventListener(event, listener, e) { e = e || window.event; // Parse the detail to the original object. var data = JSON.parse(e.detail); if (typeof data.detail === "object" && data.token !== token) { // Prevent propagation if (e && typeof e.stopPropagation === "function") { e.stopPropagation(); } // Call the listener with the parsed detail. listener(data.detail); } }*/ function fireEvent(event, detail) { // Creating the event var e = document.createEvent("CustomEvent"); e.initCustomEvent(event, true, true, JSON.stringify({ detail: detail, token: token })); // Firing the event document.documentElement.dispatchEvent(e); } var token = utils.generateToken(); // The token is used to identify itself and prevent calling its own listeners. var events = {}; return { addEventListener: addEventListener, fireEvent: fireEvent }; }); define('Message',["utils"], function(utils){ function addEventListener(event, listener) { initMessage(); // Init the message event listener if not already initialized. if (!events[event]) events[event] = []; // Bind the event name to the listener as an argument. var boundListener = utils.bind(null, listener, event); // Add the boundListener to the event events[event].push(boundListener); } function fireEvent(event, detail) { window.postMessage(JSON.stringify({ token: token, event: event, detail: detail }), "*"); } function messageListener(e) { e = e || window.event; // Parse the detail to the original object. var data = JSON.parse(e.data); // Verify that the retrieved information is correct and that it didn't call itself. if (typeof data.event === "string" && typeof data.detail === "object" && data.token !== token) { // Iterate through every listener for data.event. if (utils.isArray(events[data.event])) { var listeners = events[data.event]; var detail = data.detail; for (var i = 0, len = listeners.length; i < len; i++) { listeners(detail); } // Prevent propagation only if everything went well. if (e && typeof e.stopPropagation === "function") { e.stopPropagation(); } } } } function initMessage() { if (!messageEventAdded) { // Adding the message event listener. window.addEventListener("message", messageListener, false); } } var messageEventAdded = false; var token = utils.generateToken(); // The token is used to identify itself and prevent calling its own listeners. var events = {}; return { addEventListener: addEventListener, fireEvent: fireEvent }; }); define('memFunction',["utils", "CustomEvent", "Message", "support"], function(utils, customEvent, message, support){ function parseObject(obj, token, type) { if (typeof obj === "object") { utils.each(obj, function(key, value){ if (typeof value === "object") { obj[key] = parseObject(value, token, type); } else if (typeof value === "string") { obj[key] = parseString(value); } else if (typeof value === "function") { var id = cache.push(value) - 1; obj[key] = "${" + token + "/" + type + "/" + id + "}"; } }); } else if (typeof value === "string") { obj = parseString(obj); } else if (typeof obj === "function") { var id = cache.push(obj) - 1; obj = "${" + token + "/" + type + "/" + id + "}"; } return obj; } function parseString(str) { if (/^\$[\\]*\{([0-9a-zA-Z\.\-_\/\\]+)\}$/g.test(str)) { return "$\\" + str.substring(1); } return str; } function restoreString(str, token, type) { if (/^\$\{([0-9a-zA-Z\.\-_]+)\/([0-9a-zA-Z\.\-_]+)\/([0-9]+)\}$/g.test(str)) { var parsed = str.substring(2, str.length - 1).split("/"); // " + token + "/" + type + "/" + id + " var id = parseInt(parsed[2], 10); if (parsed[0] === token && parsed[1] === type) { return cache[id]; } else { return utils.bind(null, functionPlaceholder, parsed[0] + "-" + parsed[1], id); } } else if (/^\$[\\]+\{([0-9a-zA-Z\.\-_\/\\]+)\}$/g.test(str)) { return "$" + str.substring(2); } return str; } function restoreObject(obj, token, type) { if (typeof obj === "object") { utils.each(obj, function(key, value){ if (typeof value === "object") { obj[key] = restoreObject(value, token, type); } else if (typeof value === "string") { obj[key] = restoreString(value, token, type); } else if (typeof value === "function") { throw Error("Function was found!"); } }); } else if (typeof value === "string") { return restoreString(value, token, type); } else if (typeof value === "function") { throw Error("Function was found!"); } return obj; } function functionPlaceholder(event, id) { var args = Array.prototype.slice.call(arguments, 2); if (support.CustomEvent) { return customEvent.fireEvent(event, { callbackId: id, args: args, mem: true }); } else { return message.fireEvent(event, { callbackId: id, args: args, mem: true }); } } function getCacheFunction(id) { return cache[id]; } var cache = []; return { parseObject: parseObject, restoreObject: restoreObject, getCacheFunction: getCacheFunction }; }); define('Connection',["CustomEvent", "Message", "utils", "support", "memFunction"], function(customEvent, message, utils, support, mem){ function initListeners(token, functions) { if (support.CustomEvent) { customEvent.addEventListener(token + "-content", utils.bind(null, listenerProxy, functions, token, "content")); } else { message.addEventListener(token + "-content", utils.bind(null, listenerProxy, functions, token, "content")); } } function listenerProxy(functions, token, type, detail) { setTimeout(utils.bind(null, listener, functions, token, type, detail), 4); } function listener(functions, token, type, detail) { var keys = utils.getKeys(functions); var index = utils.indexOfArray(detail.method, keys); if (index > -1) { var result = functions[keys[index]].apply(null, mem.restoreObject(detail.args, token, type)); if (typeof detail.id === "number") { var memResult = mem.parseObject(result, token, type); var detail = { callbackId: detail.id, args: [ memResult ] }; if (support.CustomEvent) { customEvent.fireEvent(token + "-page", detail); } else { message.addEventListener(token + "-page", detail); } } } else { throw "Method " + detail.method + " has not been set!"; } } function Connection(pageProxy) { this.token = utils.generateToken(); this.functions = {}; this.namespace = "UserProxy"; this.pageProxy = pageProxy; } Connection.prototype.setFunctions = function setFunctions(functions) { this.functions = functions; } Connection.prototype.setNamespace = function setFunctions(namespace) { this.namespace = namespace; } Connection.prototype.inject = function inject(code) { var parent = (document.body || document.head || document.documentElement); if (!parent) throw "Parent was not found!"; var script = document.createElement("script") script.setAttribute("type", "text/javascript"); var wrapper = [";(function(unsafeWindow){var " + utils.escapeECMAVariable(this.namespace) + " = (" + this.pageProxy + ")(\"" + this.token + "\", " + JSON.stringify(utils.getKeys(this.functions)) + ", this);", "})(window);"]; if (typeof code === "string") { code = "function(){" + code + "}" } initListeners(this.token, this.functions); script.appendChild(document.createTextNode(wrapper[0] + "(" + code + ")();" + wrapper[1])); parent.appendChild(script); parent.removeChild(script); } return Connection; }); define('main',["utils", "support", "Connection"], function(utils, support, Connection){ function inject(code) { var conn = new Connection(pageProxy); conn.setFunctions(funcs); conn.setNamespace(namespace); conn.inject(code); } function setFunctions(functions) { funcs = functions; } function setNamespace(n) { namespace = n; } var funcs = {}; var namespace = "UserProxy"; var pageProxy = function(token, functions, scope){ /** * @license almond 0.2.9 Copyright (c) 2011-2014, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/almond for details */ //Going sloppy to avoid 'use strict' string cost, but strict practices should //be followed. /*jslint sloppy: true */ /*global setTimeout: false */ var requirejs, require, define; (function (undef) { var main, req, makeMap, handlers, defined = {}, waiting = {}, config = {}, defining = {}, hasOwn = Object.prototype.hasOwnProperty, aps = [].slice, jsSuffixRegExp = /\.js$/; function hasProp(obj, prop) { return hasOwn.call(obj, prop); } /** * Given a relative module name, like ./something, normalize it to * a real name that can be mapped to a path. * @param {String} name the relative name * @param {String} baseName a real name that the name arg is relative * to. * @returns {String} normalized name */ function normalize(name, baseName) { var nameParts, nameSegment, mapValue, foundMap, lastIndex, foundI, foundStarMap, starI, i, j, part, baseParts = baseName && baseName.split("/"), map = config.map, starMap = (map && map['*']) || {}; //Adjust any relative paths. if (name && name.charAt(0) === ".") { //If have a base name, try to normalize against it, //otherwise, assume it is a top-level require that will //be relative to baseUrl in the end. if (baseName) { //Convert baseName to array, and lop off the last part, //so that . matches that "directory" and not name of the baseName's //module. For instance, baseName of "one/two/three", maps to //"one/two/three.js", but we want the directory, "one/two" for //this normalization. baseParts = baseParts.slice(0, baseParts.length - 1); name = name.split('/'); lastIndex = name.length - 1; // Node .js allowance: if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); } name = baseParts.concat(name); //start trimDots for (i = 0; i < name.length; i += 1) { part = name[i]; if (part === ".") { name.splice(i, 1); i -= 1; } else if (part === "..") { if (i === 1 && (name[2] === '..' || name[0] === '..')) { //End of the line. Keep at least one non-dot //path segment at the front so it can be mapped //correctly to disk. Otherwise, there is likely //no path mapping for a path starting with '..'. //This can still fail, but catches the most reasonable //uses of .. break; } else if (i > 0) { name.splice(i - 1, 2); i -= 2; } } } //end trimDots name = name.join("/"); } else if (name.indexOf('./') === 0) { // No baseName, so this is ID is resolved relative // to baseUrl, pull off the leading dot. name = name.substring(2); } } //Apply map config if available. if ((baseParts || starMap) && map) { nameParts = name.split('/'); for (i = nameParts.length; i > 0; i -= 1) { nameSegment = nameParts.slice(0, i).join("/"); if (baseParts) { //Find the longest baseName segment match in the config. //So, do joins on the biggest to smallest lengths of baseParts. for (j = baseParts.length; j > 0; j -= 1) { mapValue = map[baseParts.slice(0, j).join('/')]; //baseName segment has config, find if it has one for //this name. if (mapValue) { mapValue = mapValue[nameSegment]; if (mapValue) { //Match, update name to the new value. foundMap = mapValue; foundI = i; break; } } } } if (foundMap) { break; } //Check for a star map match, but just hold on to it, //if there is a shorter segment match later in a matching //config, then favor over this star map. if (!foundStarMap && starMap && starMap[nameSegment]) { foundStarMap = starMap[nameSegment]; starI = i; } } if (!foundMap && foundStarMap) { foundMap = foundStarMap; foundI = starI; } if (foundMap) { nameParts.splice(0, foundI, foundMap); name = nameParts.join('/'); } } return name; } function makeRequire(relName, forceSync) { return function () { //A version of a require function that passes a moduleName //value for items that may need to //look up paths relative to the moduleName return req.apply(undef, aps.call(arguments, 0).concat([relName, forceSync])); }; } function makeNormalize(relName) { return function (name) { return normalize(name, relName); }; } function makeLoad(depName) { return function (value) { defined[depName] = value; }; } function callDep(name) { if (hasProp(waiting, name)) { var args = waiting[name]; delete waiting[name]; defining[name] = true; main.apply(undef, args); } if (!hasProp(defined, name) && !hasProp(defining, name)) { throw new Error('No ' + name); } return defined[name]; } //Turns a plugin!resource to [plugin, resource] //with the plugin being undefined if the name //did not have a plugin prefix. function splitPrefix(name) { var prefix, index = name ? name.indexOf('!') : -1; if (index > -1) { prefix = name.substring(0, index); name = name.substring(index + 1, name.length); } return [prefix, name]; } /** * Makes a name map, normalizing the name, and using a plugin * for normalization if necessary. Grabs a ref to plugin * too, as an optimization. */ makeMap = function (name, relName) { var plugin, parts = splitPrefix(name), prefix = parts[0]; name = parts[1]; if (prefix) { prefix = normalize(prefix, relName); plugin = callDep(prefix); } //Normalize according if (prefix) { if (plugin && plugin.normalize) { name = plugin.normalize(name, makeNormalize(relName)); } else { name = normalize(name, relName); } } else { name = normalize(name, relName); parts = splitPrefix(name); prefix = parts[0]; name = parts[1]; if (prefix) { plugin = callDep(prefix); } } //Using ridiculous property names for space reasons return { f: prefix ? prefix + '!' + name : name, //fullName n: name, pr: prefix, p: plugin }; }; function makeConfig(name) { return function () { return (config && config.config && config.config[name]) || {}; }; } handlers = { require: function (name) { return makeRequire(name); }, exports: function (name) { var e = defined[name]; if (typeof e !== 'undefined') { return e; } else { return (defined[name] = {}); } }, module: function (name) { return { id: name, uri: '', exports: defined[name], config: makeConfig(name) }; } }; main = function (name, deps, callback, relName) { var cjsModule, depName, ret, map, i, args = [], callbackType = typeof callback, usingExports; //Use name if no relName relName = relName || name; //Call the callback to define the module, if necessary. if (callbackType === 'undefined' || callbackType === 'function') { //Pull out the defined dependencies and pass the ordered //values to the callback. //Default to [require, exports, module] if no deps deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps; for (i = 0; i < deps.length; i += 1) { map = makeMap(deps[i], relName); depName = map.f; //Fast path CommonJS standard dependencies. if (depName === "require") { args[i] = handlers.require(name); } else if (depName === "exports") { //CommonJS module spec 1.1 args[i] = handlers.exports(name); usingExports = true; } else if (depName === "module") { //CommonJS module spec 1.1 cjsModule = args[i] = handlers.module(name); } else if (hasProp(defined, depName) || hasProp(waiting, depName) || hasProp(defining, depName)) { args[i] = callDep(depName); } else if (map.p) { map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {}); args[i] = defined[depName]; } else { throw new Error(name + ' missing ' + depName); } } ret = callback ? callback.apply(defined[name], args) : undefined; if (name) { //If setting exports via "module" is in play, //favor that over return value and exports. After that, //favor a non-undefined return value over exports use. if (cjsModule && cjsModule.exports !== undef && cjsModule.exports !== defined[name]) { defined[name] = cjsModule.exports; } else if (ret !== undef || !usingExports) { //Use the return value from the function. defined[name] = ret; } } } else if (name) { //May just be an object definition for the module. Only //worry about defining if have a module name. defined[name] = callback; } }; requirejs = require = req = function (deps, callback, relName, forceSync, alt) { if (typeof deps === "string") { if (handlers[deps]) { //callback in this case is really relName return handlers[deps](callback); } //Just return the module wanted. In this scenario, the //deps arg is the module name, and second arg (if passed) //is just the relName. //Normalize module name, if it contains . or .. return callDep(makeMap(deps, callback).f); } else if (!deps.splice) { //deps is a config object, not an array. config = deps; if (config.deps) { req(config.deps, config.callback); } if (!callback) { return; } if (callback.splice) { //callback is an array, which means it is a dependency list. //Adjust args if there are dependencies deps = callback; callback = relName; relName = null; } else { deps = undef; } } //Support require(['a']) callback = callback || function () {}; //If relName is a function, it is an errback handler, //so remove it. if (typeof relName === 'function') { relName = forceSync; forceSync = alt; } //Simulate async callback; if (forceSync) { main(undef, deps, callback, relName); } else { //Using a non-zero value because of concern for what old browsers //do, and latest browsers "upgrade" to 4 if lower value is used: //http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout: //If want a value immediately, use require('id') instead -- something //that works in almond on the global level, but not guaranteed and //unlikely to work in other AMD implementations. setTimeout(function () { main(undef, deps, callback, relName); }, 4); } return req; }; /** * Just drops the config on the floor, but returns req in case * the config return value is used. */ req.config = function (cfg) { return req(cfg); }; /** * Expose module registry for debugging and tooling */ requirejs._defined = defined; define = function (name, deps, callback) { //This module may not have dependencies if (!deps.splice) { //deps is not an array, so probably means //an object literal or factory function for //the value. Adjust args. callback = deps; deps = []; } if (!hasProp(defined, name) && !hasProp(waiting, name)) { waiting[name] = [name, deps, callback]; } }; define.amd = { jQuery: true }; }()); define("../vendor/almond", function(){}); define('support',[], function(){ function customEvent() { try { var e = document.createEvent('CustomEvent'); if (e && typeof e.initCustomEvent === "function") { e.initCustomEvent(mod, true, true, { mod: mod }); return true; } return false; } catch (e) { return false; } } var mod = "support.test"; return { CustomEvent: customEvent }; }); define('utils',[], function(){ function bind(scope, func) { var args = Array.prototype.slice.call(arguments, 2); return function(){ return func.apply(scope, args.concat(Array.prototype.slice.call(arguments))) }; } // Iterate through obj with the callback function. function each(obj, callback) { if (isArray(obj)) { for (var i = 0; i < obj.length; i++) { if (callback(i, obj[i]) === true) break; } } else { for (var key in obj) { if (obj.hasOwnProperty(key)) { if (callback(key, obj[key]) === true) break; } } } } function getKeys(obj) { var keys = []; each(obj, function(key){ keys.push(key); }); return keys; } // Returns a boolean indicating if object arr is an array. function isArray(arr) { return Object.prototype.toString.call(arr) === "[object Array]"; } // Returns a boolean indicating if the value is in the array. function inArray(value, arr) { for (var i = 0, len = arr.length; i < len; i++) { if (arr[i] === value) { return true; } } return false; } function indexOfArray(value, arr) { for (var i = 0, len = arr.length; i < len; i++) { if (arr[i] === value) { return i; } } return -1; } function indexOf(value, arr) { if (isArray(value, arr)) { return indexOfArray(value, arr); } } // Returns a random number between min and max function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } // Returns a random integer between min (included) and max (excluded) function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; } // Returns a random string of characters of chars with the length of length function generateToken(chars, length) { if (typeof chars !== "string") chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"; if (typeof length !== "number") length = 64; var charsLength = chars.length; var token = ""; for (var i = 0; i < length; i++) { token += chars[getRandomInt(0, charsLength)]; } return token; } function escapeECMAVariable(key, defaultKey) { key = key.replace(/[^0-9a-zA-Z_\$]/g, ""); while (/$[0-9]/g.test(key)) { if (key === "") return defaultKey; key = key.substring(1); } return key; } return { bind: bind, each: each, getKeys: getKeys, isArray: isArray, inArray: inArray, indexOf: indexOf, indexOfArray: indexOfArray, getRandomArbitrary: getRandomArbitrary, getRandomInt: getRandomInt, generateToken: generateToken, escapeECMAVariable: escapeECMAVariable }; }); define('CustomEvent',["utils"], function(utils){ function addEventListener(event, listener) { if (!events[event]) { // Creating the array of listeners for event events[event] = []; // Adding the event listener. window.addEventListener(event, utils.bind(null, eventListener, event, events[event]), false); } // Adding listener to array. events[event].push(listener); } function eventListener(event, listeners, e) { e = e || window.event; // Parse the detail to the original object. var data = JSON.parse(e.detail); if (typeof data.detail === "object" && data.token !== token) { var detail = data.detail; for (var i = 0, len = listeners.length; i < len; i++) { // Call the listener with the event name and the parsed detail. listeners[i](detail); } // Prevent propagation if (e && typeof e.stopPropagation === "function") { e.stopPropagation(); } } } /*function eventListener(event, listener, e) { e = e || window.event; // Parse the detail to the original object. var data = JSON.parse(e.detail); if (typeof data.detail === "object" && data.token !== token) { // Prevent propagation if (e && typeof e.stopPropagation === "function") { e.stopPropagation(); } // Call the listener with the parsed detail. listener(data.detail); } }*/ function fireEvent(event, detail) { // Creating the event var e = document.createEvent("CustomEvent"); e.initCustomEvent(event, true, true, JSON.stringify({ detail: detail, token: token })); // Firing the event document.documentElement.dispatchEvent(e); } var token = utils.generateToken(); // The token is used to identify itself and prevent calling its own listeners. var events = {}; return { addEventListener: addEventListener, fireEvent: fireEvent }; }); define('Message',["utils"], function(utils){ function addEventListener(event, listener) { initMessage(); // Init the message event listener if not already initialized. if (!events[event]) events[event] = []; // Bind the event name to the listener as an argument. var boundListener = utils.bind(null, listener, event); // Add the boundListener to the event events[event].push(boundListener); } function fireEvent(event, detail) { window.postMessage(JSON.stringify({ token: token, event: event, detail: detail }), "*"); } function messageListener(e) { e = e || window.event; // Parse the detail to the original object. var data = JSON.parse(e.data); // Verify that the retrieved information is correct and that it didn't call itself. if (typeof data.event === "string" && typeof data.detail === "object" && data.token !== token) { // Iterate through every listener for data.event. if (utils.isArray(events[data.event])) { var listeners = events[data.event]; var detail = data.detail; for (var i = 0, len = listeners.length; i < len; i++) { listeners(detail); } // Prevent propagation only if everything went well. if (e && typeof e.stopPropagation === "function") { e.stopPropagation(); } } } } function initMessage() { if (!messageEventAdded) { // Adding the message event listener. window.addEventListener("message", messageListener, false); } } var messageEventAdded = false; var token = utils.generateToken(); // The token is used to identify itself and prevent calling its own listeners. var events = {}; return { addEventListener: addEventListener, fireEvent: fireEvent }; }); define('memFunction',["utils", "CustomEvent", "Message", "support"], function(utils, customEvent, message, support){ function parseObject(obj, token, type) { if (typeof obj === "object") { utils.each(obj, function(key, value){ if (typeof value === "object") { obj[key] = parseObject(value, token, type); } else if (typeof value === "string") { obj[key] = parseString(value); } else if (typeof value === "function") { var id = cache.push(value) - 1; obj[key] = "${" + token + "/" + type + "/" + id + "}"; } }); } else if (typeof value === "string") { obj = parseString(obj); } else if (typeof obj === "function") { var id = cache.push(obj) - 1; obj = "${" + token + "/" + type + "/" + id + "}"; } return obj; } function parseString(str) { if (/^\$[\\]*\{([0-9a-zA-Z\.\-_\/\\]+)\}$/g.test(str)) { return "$\\" + str.substring(1); } return str; } function restoreString(str, token, type) { if (/^\$\{([0-9a-zA-Z\.\-_]+)\/([0-9a-zA-Z\.\-_]+)\/([0-9]+)\}$/g.test(str)) { var parsed = str.substring(2, str.length - 1).split("/"); // " + token + "/" + type + "/" + id + " var id = parseInt(parsed[2], 10); if (parsed[0] === token && parsed[1] === type) { return cache[id]; } else { return utils.bind(null, functionPlaceholder, parsed[0] + "-" + parsed[1], id); } } else if (/^\$[\\]+\{([0-9a-zA-Z\.\-_\/\\]+)\}$/g.test(str)) { return "$" + str.substring(2); } return str; } function restoreObject(obj, token, type) { if (typeof obj === "object") { utils.each(obj, function(key, value){ if (typeof value === "object") { obj[key] = restoreObject(value, token, type); } else if (typeof value === "string") { obj[key] = restoreString(value, token, type); } else if (typeof value === "function") { throw Error("Function was found!"); } }); } else if (typeof value === "string") { return restoreString(value, token, type); } else if (typeof value === "function") { throw Error("Function was found!"); } return obj; } function functionPlaceholder(event, id) { var args = Array.prototype.slice.call(arguments, 2); if (support.CustomEvent) { return customEvent.fireEvent(event, { callbackId: id, args: args, mem: true }); } else { return message.fireEvent(event, { callbackId: id, args: args, mem: true }); } } function getCacheFunction(id) { return cache[id]; } var cache = []; return { parseObject: parseObject, restoreObject: restoreObject, getCacheFunction: getCacheFunction }; }); define('proxy',["support", "CustomEvent", "Message", "utils", "memFunction"], function(support, customEvent, message, utils, mem){ function listener(detail) { if (typeof detail.callbackId === "number" && utils.isArray(detail.args) && detail.mem) { var args = mem.restoreObject(detail.args, token, "page"); var func = mem.getCacheFunction(detail.callbackId); if (typeof func === "function") { func.apply(null, args); } } else if (typeof detail.callbackId === "number" && utils.isArray(detail.args)) { var args = mem.restoreObject(detail.args, token, "page"); if (typeof callbackCache[detail.callbackId] === "function") { callbackCache[detail.callbackId].apply(null, args); } //callbackCache[detail.callbackId] = null; // Remove reference for GC. } else { throw Error("Malformed detail!", detail); } } function prepareCall(method, callback) { if (!has(method)) { throw Error(method + " is not a defined function!"); } if (typeof callback !== "function") { throw Error("The callback is not a function!"); } var id = callbackCache.push(callback) - 1; var args = Array.prototype.slice.call(arguments, 2); return function() { args = args.concat(Array.prototype.slice.call(arguments, 0)); args = mem.parseObject(args, token, "page"); var detail = { method: method, args: args, id: id }; if (support.CustomEvent) { customEvent.fireEvent(token + "-content", detail); } else { message.fireEvent(token + "-content", detail); } }; } function call(method, args) { function setCallback(callback) { clearTimeout(timer); if (typeof callback === "function") { detail.id = callbackCache.push(callback) - 1; } execute(); } function execute() { if (support.CustomEvent) { customEvent.fireEvent(token + "-content", detail); } else { message.fireEvent(token + "-content", detail); } } args = Array.prototype.slice.call(arguments, 1); if (!has(method)) { throw Error(method + " is not a defined function!"); } args = mem.parseObject(args, token, "page"); var detail = { method: method, args: args }; var timer = setTimeout(execute, 4); return { then: setCallback }; } function has(method) { return utils.indexOfArray(method, functions) > -1; } function getFunction(method) { if (has(method)) { return utils.bind(null, call, method); } else { throw Error(method + " is not defined!"); } } function listFunctions() { return JSON.parse(JSON.stringify(functions)); } var callbackCache = []; if (support.CustomEvent) { customEvent.addEventListener(token + "-page", listener); } else { message.addEventListener(token + "-page", listener); } for (var i = 0, len = functions.length; i < len; i++) { scope[functions[i]] = utils.bind(null, call, functions[i]); } return { call: call, prepareCall: prepareCall, getFunction: getFunction, isDefined: has, listFunctions: listFunctions }; }); return require("proxy"); }; return { connect: inject, setFunctions: setFunctions, setNamespace: setNamespace }; }); return require("main"); })();
YePpHa/UserProxy
UserProxy.js
JavaScript
mit
55,778
export { default as Audience } from './audiences/model' export { default as Client } from './clients/model' export { default as Communication } from './communications/model' export { default as InboundEmail } from './sendgrid/models/inboundEmail' export { default as Lead } from './leads/model' export { default as Market } from './markets/model' export { default as Service } from './services/model' export { default as Subscription } from './subscriptions/model' export { default as TwilioBlacklist } from './twilio/models/blacklist' export { default as User } from './users/model'
LeadGrabr/api
src/components/models.js
JavaScript
mit
584
# 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::Consumption::Mgmt::V2017_12_30_preview # # A service client - single point of access to the REST API. # class ConsumptionManagementClient < MsRestAzure::AzureServiceClient include MsRestAzure include MsRestAzure::Serialization # @return [String] the base URI of the service. attr_accessor :base_url # @return Credentials needed for the client to connect to Azure. attr_reader :credentials # @return [String] Version of the API to be used with the client request. # The current version is 2017-12-30-preview. attr_reader :api_version # @return [String] Azure Subscription ID. attr_accessor :subscription_id # @return [String] Budget name. attr_accessor :name # @return [String] The preferred language for the response. attr_accessor :accept_language # @return [Integer] The retry timeout in seconds for Long Running # Operations. Default value is 30. attr_accessor :long_running_operation_retry_timeout # @return [Boolean] Whether a unique x-ms-client-request-id should be # generated. When set to true a unique x-ms-client-request-id value is # generated and included in each request. Default is true. attr_accessor :generate_client_request_id # @return [Budgets] budgets attr_reader :budgets # @return [Operations] operations attr_reader :operations # # Creates initializes a new instance of the ConsumptionManagementClient class. # @param credentials [MsRest::ServiceClientCredentials] credentials to authorize HTTP requests made by the service client. # @param base_url [String] the base URI of the service. # @param options [Array] filters to be applied to the HTTP requests. # def initialize(credentials = nil, base_url = nil, options = nil) super(credentials, options) @base_url = base_url || 'https://management.azure.com' fail ArgumentError, 'invalid type of credentials input parameter' unless credentials.is_a?(MsRest::ServiceClientCredentials) unless credentials.nil? @credentials = credentials @budgets = Budgets.new(self) @operations = Operations.new(self) @api_version = '2017-12-30-preview' @accept_language = 'en-US' @long_running_operation_retry_timeout = 30 @generate_client_request_id = true add_telemetry end # # Makes a request and returns the body of the response. # @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete. # @param path [String] the path, relative to {base_url}. # @param options [Hash{String=>String}] specifying any request options like :body. # @return [Hash{String=>String}] containing the body of the response. # Example: # # request_content = "{'location':'westus','tags':{'tag1':'val1','tag2':'val2'}}" # path = "/path" # options = { # body: request_content, # query_params: {'api-version' => '2016-02-01'} # } # result = @client.make_request(:put, path, options) # def make_request(method, path, options = {}) result = make_request_with_http_info(method, path, options) result.body unless result.nil? end # # Makes a request and returns the operation response. # @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete. # @param path [String] the path, relative to {base_url}. # @param options [Hash{String=>String}] specifying any request options like :body. # @return [MsRestAzure::AzureOperationResponse] Operation response containing the request, response and status. # def make_request_with_http_info(method, path, options = {}) result = make_request_async(method, path, options).value! result.body = result.response.body.to_s.empty? ? nil : JSON.load(result.response.body) result end # # Makes a request asynchronously. # @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete. # @param path [String] the path, relative to {base_url}. # @param options [Hash{String=>String}] specifying any request options like :body. # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def make_request_async(method, path, options = {}) fail ArgumentError, 'method is nil' if method.nil? fail ArgumentError, 'path is nil' if path.nil? request_url = options[:base_url] || @base_url if(!options[:headers].nil? && !options[:headers]['Content-Type'].nil?) @request_headers['Content-Type'] = options[:headers]['Content-Type'] end request_headers = @request_headers request_headers.merge!({'accept-language' => @accept_language}) unless @accept_language.nil? options.merge!({headers: request_headers.merge(options[:headers] || {})}) options.merge!({credentials: @credentials}) unless @credentials.nil? super(request_url, method, path, options) end private # # Adds telemetry information. # def add_telemetry sdk_information = 'azure_mgmt_consumption' sdk_information = "#{sdk_information}/0.18.1" add_user_agent_information(sdk_information) end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_consumption/lib/2017-12-30-preview/generated/azure_mgmt_consumption/consumption_management_client.rb
Ruby
mit
5,431
using System; using System.Collections.Generic; using DXFramework.Util; using Poly2Tri; using SharpDX; namespace DXFramework.PrimitiveFramework { public class PTriangle : Primitive { private Vector2 a; private Vector2 b; private Vector2 c; public PTriangle( PTriangle triangle ) : base( triangle ) { this.a = triangle.a; this.b = triangle.b; this.c = triangle.c; } public PTriangle( Vector2 a, float lengthAB, float angleB, bool filled ) : base( filled ) { if( angleB >= 180 ) { throw new ArgumentException( "Angle cannot be greater than or equal to 180." ); } this.position = a; this.a = a; this.b = new Vector2( a.X + lengthAB, a.Y ); this.c = b + TriangleHelper2D.RadianToVector( MathUtil.DegreesToRadians( angleB ) - MathUtil.PiOverTwo ) * lengthAB; } public PTriangle( Vector2 a, float lengthAB, float angleB, uint thickness ) : base( thickness ) { if( angleB >= 180 ) { throw new ArgumentException( "Angle cannot be greater than or equal to 180." ); } this.position = a; this.a = a; this.b = new Vector2( a.X + lengthAB, a.Y ); this.c = b + TriangleHelper2D.RadianToVector( MathUtil.DegreesToRadians( angleB ) - MathUtil.PiOverTwo ) * lengthAB; } public PTriangle( Vector2 a, Vector2 b, Vector2 c, bool filled ) : base( filled ) { this.position = a; this.a = a; this.b = b; this.c = c; } public PTriangle( Vector2 a, Vector2 b, Vector2 c, uint thickness ) : base( thickness ) { this.position = a; this.a = a; this.b = b; this.c = c; } internal override List<PolygonPoint> GetPoints() { List<PolygonPoint> points = new List<PolygonPoint>(){ new PolygonPoint(a.X, a.Y), new PolygonPoint(b.X, b.Y), new PolygonPoint(c.X, c.Y)}; if( !Filled ) { points.Add( points[ 0 ] ); } // Offset all points by distance to the centroid. This places all points around (0, 0). Vector2 center = GetCentroid( points ); foreach( PolygonPoint point in points ) { point.X -= center.X; point.Y -= center.Y; } return points; } protected override Polygon GetPolygon() { Polygon poly = new Polygon( GetPoints() ); if( thickness > 1 ) { List<PolygonPoint> points = GetPoints(); Vector2 center = GetCentroid( points ); float[] angles = { TriangleHelper2D.AngleA( a, b, c ), TriangleHelper2D.AngleB( a, b, c ), TriangleHelper2D.AngleC( a, b, c ) }; int count = points.Count; for( int i = count; --i >= 0; ) { PolygonPoint point = points[ i ]; double vecX = center.X - point.X; double vecY = center.Y - point.Y; double invLen = 1d / Math.Sqrt( ( vecX * vecX ) + ( vecY * vecY ) ); vecX = vecX * invLen; vecY = vecY * invLen; float ratio = 1 - ( angles[ i ] / 180 ); float angleThickness = ratio * thickness; point.X += vecX * angleThickness; point.Y += vecY * angleThickness; } Polygon hole = new Polygon( points ); poly.AddHole( hole ); } return poly; } public override bool Intersects( float x, float y ) { if( Filled ) { return base.Intersects( x, y ); } else { Vector2 A = new Vector2(); Vector2 B = new Vector2(); Vector2 C = new Vector2(); A.X = tranformedVPCs[ 0 ].Position.X; A.Y = tranformedVPCs[ 0 ].Position.Y; B.X = tranformedVPCs[ 2 ].Position.X; B.Y = tranformedVPCs[ 2 ].Position.Y; C.X = tranformedVPCs[ 4 ].Position.X; C.Y = tranformedVPCs[ 4 ].Position.Y; if( IntersectsTriangle( ref x, ref y, ref A, ref B, ref C ) ) { return true; } } return false; } } }
adamxi/SharpDXFramework
DXFramework/PrimitiveFramework/PTriangle.cs
C#
mit
3,697
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->engine = "InnoDB"; $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->integer('role'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
wgerro/sprintko
database/migrations/2014_10_12_000000_create_users_table.php
PHP
mit
814
#include "Math/Math.h" float Math::Distance(float x0, float y0, float x1, float y1) { return sqrt(pow(x0 - x1, 2) + pow(y1 - y0, 2)); } float Math::Distance(Vector &a, Vector &b) { return sqrt(pow(a.m_x - b.m_x, 2) + pow(a.m_y - b.m_y, 2)); } bool RangeIntersect(float min0, float max0, float min1, float max1) { return max0 >= min1 && min0 <= max1; }
vitorfhc/ZebraEngine
src/Math/Math.cpp
C++
mit
361
require 'cases/helper' class ArrayItemClass < GQL::String string :upcased, -> { target.upcase } end class MyFixnum < GQL::Number string :whoami, -> { 'I am a number.' } end class MyString < GQL::String string :whoami, -> { 'I am a string.' } end class FieldWithArrays < GQL::Field array :class_as_item_class, -> { %w(a b) }, item_class: ArrayItemClass array :string_as_item_class, -> { %w(a b) }, item_class: 'ArrayItemClass' array :hash_with_class_values_as_item_class, -> { ['foo', 42] }, item_class: { Fixnum => MyFixnum, String => MyString } array :hash_with_string_values_as_item_class, -> { ['foo', 42] }, item_class: { Fixnum => 'MyFixnum', String => 'MyString' } array :proc_as_item_class, -> { ['foo', 42] }, item_class: -> item { item.is_a?(String) ? MyString : 'MyFixnum' } end class ArrayTest < ActiveSupport::TestCase setup do @old_root, GQL.root_class = GQL.root_class, FieldWithArrays end teardown do GQL.root_class = @old_root end test "returns array value" do value = GQL.execute('{ class_as_item_class as arr }') assert_equal ['a', 'b'], value[:arr] end test "class as item_class" do value = GQL.execute('{ class_as_item_class as arr { upcased } }') assert_equal [{ upcased: 'A' }, { upcased: 'B' }], value[:arr] end test "string as item_class" do GQL::Registry.reset assert FieldWithArrays.fields[:string_as_item_class] < GQL::Lazy value = GQL.execute('{ string_as_item_class as arr }') assert_equal ['a', 'b'], value[:arr] end test "hash with class values provided as item_class" do value = GQL.execute('{ hash_with_class_values_as_item_class as arr { whoami } }') assert_equal [{ whoami: 'I am a string.' }, { whoami: 'I am a number.' }], value[:arr] end test "hash with string values provided as item_class" do GQL::Registry.reset value = GQL.execute('{ hash_with_string_values_as_item_class as arr { whoami } }') assert_equal [{ whoami: 'I am a string.' }, { whoami: 'I am a number.' }], value[:arr] end test "proc as item_class" do GQL::Registry.reset value = GQL.execute('{ proc_as_item_class as arr { whoami } }') assert_equal [{ whoami: 'I am a string.' }, { whoami: 'I am a number.' }], value[:arr] end end
martinandert/gql
test/cases/array_test.rb
Ruby
mit
2,274
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var User = require('./user'); var entitySchema = new Schema({ room: { type: Schema.Types.ObjectId, ref: 'Room' }, x: { type: Number, default: -1 }, y: { type: Number, default: -1 }, body: Schema.Types.Mixed, character: String, color: String, behavior: String, description: String, belongsTo: { type: Schema.Types.ObjectId, ref: 'User' } }); entitySchema.pre('save', function(next) { this.markModified('body'); var now = new Date(); if(this.belongsTo) { this.model('User').update({_id: this.belongsTo}, {lastMessage: now}, function(err, user) { if(err) console.log("While saving entity", err.message); }); } next(); }); entitySchema.static('getColor', function(playerId, callback) { this.findOne({belongsTo: playerId}, function(err, entity) { if(err) console.log(err.message); callback([entity.color, entity.character]); }); }); module.exports = mongoose.model('Entity', entitySchema);
Huntrr/mp.txt
app/schema/entity.js
JavaScript
mit
1,017
<?xml version="1.0" ?><!DOCTYPE TS><TS language="nl" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About TPPcoin</source> <translation>Over TPPcoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;TPPcoin&lt;/b&gt; version</source> <translation>&lt;b&gt;TPPcoin&lt;/b&gt; versie</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> Dit is experimentele software. Gedistribueerd onder de MIT/X11 software licentie, zie het bijgevoegde bestand COPYING of http://www.opensource.org/licenses/mit-license.php. Dit product bevat software ontwikkeld door het OpenSSL Project voor gebruik in de OpenSSL Toolkit (http://www.openssl.org/) en cryptografische software gemaakt door Eric Young (eay@cryptsoft.com) en UPnP software geschreven door Thomas Bernard.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Auteursrecht</translation> </message> <message> <location line="+0"/> <source>The TPPcoin developers</source> <translation>De TPPcoin-ontwikkelaars</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Adresboek</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Dubbelklik om adres of label te wijzigen</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Maak een nieuw adres aan</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopieer het huidig geselecteerde adres naar het klembord</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Nieuw Adres</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your TPPcoin 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>Dit zijn uw TPPcoinadressen om betalingen mee te ontvangen. U kunt er voor kiezen om een uniek adres aan te maken voor elke afzender. Op deze manier kunt u bijhouden wie al aan u betaald heeft.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Kopiëer Adres</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Toon &amp;QR-Code</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a TPPcoin address</source> <translation>Onderteken een bericht om te bewijzen dat u een bepaald TPPcoinadres bezit</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>&amp;Onderteken Bericht</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Verwijder het geselecteerde adres van de lijst</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Exporteer de data in de huidige tab naar een bestand</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation>&amp;Exporteer</translation> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified TPPcoin address</source> <translation>Controleer een bericht om te verifiëren dat het gespecificeerde TPPcoinadres het bericht heeft ondertekend.</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Verifiëer Bericht</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Verwijder</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your TPPcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Dit zijn uw TPPcoinadressen om betalingen mee te verzenden. Check altijd het bedrag en het ontvangende adres voordat u uw tppcoins verzendt.</translation> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Kopiëer &amp;Label</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Bewerk</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>Verstuur &amp;Coins</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Exporteer Gegevens van het Adresboek</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Kommagescheiden bestand (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Fout bij exporteren</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Kon niet schrijven naar bestand %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Label</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(geen label)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Wachtwoorddialoogscherm</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Voer wachtwoord in</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nieuw wachtwoord</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Herhaal wachtwoord</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>Vul een nieuw wachtwoord in voor uw portemonnee. &lt;br/&gt; Gebruik een wachtwoord van &lt;b&gt;10 of meer lukrake karakters&lt;/b&gt;, of &lt;b&gt; acht of meer woorden&lt;/b&gt; . </translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Versleutel portemonnee</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Deze operatie vereist uw portemonneewachtwoord om de portemonnee te openen.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Open portemonnee</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Deze operatie vereist uw portemonneewachtwoord om de portemonnee te ontsleutelen</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Ontsleutel portemonnee</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Wijzig wachtwoord</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Vul uw oude en nieuwe portemonneewachtwoord in.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Bevestig versleuteling van de portemonnee</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 TPPCOINS&lt;/b&gt;!</source> <translation>Waarschuwing: Als u uw portemonnee versleutelt en uw wachtwoord vergeet, zult u &lt;b&gt;AL UW TPPCOINS VERLIEZEN&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Weet u zeker dat u uw portemonnee wilt versleutelen?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>BELANGRIJK: Elke eerder gemaakte backup van uw portemonneebestand dient u te vervangen door het nieuw gegenereerde, versleutelde portemonneebestand. Om veiligheidsredenen zullen eerdere backups van het niet-versleutelde portemonneebestand onbruikbaar worden zodra u uw nieuwe, versleutelde, portemonnee begint te gebruiken.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Waarschuwing: De Caps-Lock-toets staat aan!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Portemonnee versleuteld</translation> </message> <message> <location line="-56"/> <source>TPPcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your tppcoins from being stolen by malware infecting your computer.</source> <translation>TPPcoin zal nu afsluiten om het versleutelingsproces te voltooien. Onthoud dat het versleutelen van uw portemonnee u niet volledig kan beschermen: Malware kan uw computer infecteren en uw tppcoins stelen.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Portemonneeversleuteling mislukt</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Portemonneeversleuteling mislukt door een interne fout. Uw portemonnee is niet versleuteld.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>De opgegeven wachtwoorden komen niet overeen</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Portemonnee openen mislukt</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Het opgegeven wachtwoord voor de portemonnee-ontsleuteling is niet correct.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Portemonnee-ontsleuteling mislukt</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Portemonneewachtwoord is met succes gewijzigd.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>&amp;Onderteken bericht...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Synchroniseren met netwerk...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Overzicht</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Toon algemeen overzicht van de portemonnee</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transacties</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Blader door transactieverleden</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Bewerk de lijst van opgeslagen adressen en labels</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Toon lijst van adressen om betalingen mee te ontvangen</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Afsluiten</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Programma afsluiten</translation> </message> <message> <location line="+4"/> <source>Show information about TPPcoin</source> <translation>Laat informatie zien over TPPcoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Over &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Toon informatie over Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>O&amp;pties...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Versleutel Portemonnee...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup Portemonnee...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Wijzig Wachtwoord</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Blokken aan het importeren vanaf harde schijf...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Bezig met herindexeren van blokken op harde schijf...</translation> </message> <message> <location line="-347"/> <source>Send coins to a TPPcoin address</source> <translation>Verstuur munten naar een TPPcoinadres</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for TPPcoin</source> <translation>Wijzig instellingen van TPPcoin</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>&amp;Backup portemonnee naar een andere locatie</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Wijzig het wachtwoord voor uw portemonneversleuteling</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>&amp;Debugscherm</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Open debugging en diagnostische console</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>&amp;Verifiëer bericht...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>TPPcoin</source> <translation>TPPcoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Portemonnee</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation>&amp;Versturen</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>&amp;Ontvangen</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>&amp;Adressen</translation> </message> <message> <location line="+22"/> <source>&amp;About TPPcoin</source> <translation>&amp;Over TPPcoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Toon / Verberg</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Toon of verberg het hoofdvenster</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Versleutel de geheime sleutels die bij uw portemonnee horen</translation> </message> <message> <location line="+7"/> <source>Sign messages with your TPPcoin addresses to prove you own them</source> <translation>Onderteken berichten met uw TPPcoinadressen om te bewijzen dat u deze adressen bezit</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified TPPcoin addresses</source> <translation>Verifiëer handtekeningen om zeker te zijn dat de berichten zijn ondertekend met de gespecificeerde TPPcoinadressen</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Bestand</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Instellingen</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Hulp</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Tab-werkbalk</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnetwerk]</translation> </message> <message> <location line="+47"/> <source>TPPcoin client</source> <translation>TPPcoin client</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to TPPcoin network</source> <translation><numerusform>%n actieve connectie naar TPPcoinnetwerk</numerusform><numerusform>%n actieve connecties naar TPPcoinnetwerk</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation>Geen bron van blokken beschikbaar...</translation> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>%1 van %2 (geschat) blokken van de transactiehistorie verwerkt.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>%1 blokken van transactiehistorie verwerkt.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n uur</numerusform><numerusform>%n uur</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n dag</numerusform><numerusform>%n dagen</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n week</numerusform><numerusform>%n weken</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>%1 achter</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>Laatst ontvangen blok was %1 geleden gegenereerd.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation>Transacties na dit moment zullen nu nog niet zichtbaar zijn.</translation> </message> <message> <location line="+22"/> <source>Error</source> <translation>Fout</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Waarschuwing</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Informatie</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>Deze transactie overschrijdt de groottelimiet. Om de transactie alsnog te versturen kunt u transactiekosten betalen van %1. Deze transactiekosten gaan naar de nodes die uw transactie verwerken en het helpt op deze manier bij het ondersteunen van het TPPcoinnetwerk. Wilt u de transactiekosten betalen?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Bijgewerkt</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Aan het bijwerken...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Bevestig transactiekosten</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Verzonden transactie</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Binnenkomende transactie</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Datum: %1 Bedrag: %2 Type: %3 Adres: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>URI-behandeling</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid TPPcoin address or malformed URI parameters.</source> <translation>URI kan niet worden geïnterpreteerd. Dit kan komen door een ongeldig TPPcoinadres of misvormde URI-parameters.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Portemonnee is &lt;b&gt;versleuteld&lt;/b&gt; en momenteel &lt;b&gt;geopend&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Portemonnee is &lt;b&gt;versleuteld&lt;/b&gt; en momenteel &lt;b&gt;gesloten&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. TPPcoin can no longer continue safely and will quit.</source> <translation>Er is een fatale fout opgetreden. TPPcoin kan niet meer veilig doorgaan en zal nu afgesloten worden.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Netwerkwaarschuwing</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Bewerk Adres</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Label</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Het label dat geassocieerd is met dit adres</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Adres</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Het adres dat geassocieerd is met deze inschrijving in het adresboek. Dit kan alleen worden veranderd voor zend-adressen.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Nieuw ontvangstadres</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nieuw adres om naar te verzenden</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Bewerk ontvangstadres</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Bewerk adres om naar te verzenden</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Het opgegeven adres &quot;%1&quot; bestaat al in uw adresboek.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid TPPcoin address.</source> <translation>Het opgegeven adres &quot;%1&quot; is een ongeldig TPPcoinadres</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Kon de portemonnee niet openen.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Genereren nieuwe sleutel mislukt.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>TPPcoin-Qt</source> <translation>TPPcoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>versie</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Gebruik:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>commandoregel-opties</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>gebruikersinterfaceopties</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Stel taal in, bijvoorbeeld &apos;&apos;de_DE&quot; (standaard: systeeminstellingen)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Geminimaliseerd starten</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Laat laadscherm zien bij het opstarten. (standaard: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Opties</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Algemeen</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation>Optionele transactiekosten per kB. Transactiekosten helpen ervoor te zorgen dat uw transacties snel verwerkt worden. De meeste transacties zijn 1kB.</translation> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Betaal &amp;transactiekosten</translation> </message> <message> <location line="+31"/> <source>Automatically start TPPcoin after logging in to the system.</source> <translation>Start TPPcoin automatisch na inloggen in het systeem</translation> </message> <message> <location line="+3"/> <source>&amp;Start TPPcoin on system login</source> <translation>Start &amp;TPPcoin bij het inloggen in het systeem</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>Reset alle clientopties naar de standaardinstellingen.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>&amp;Reset Opties</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Netwerk</translation> </message> <message> <location line="+6"/> <source>Automatically open the TPPcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Open de TPPcoin-poort automatisch op de router. Dit werkt alleen als de router UPnP ondersteunt en het aanstaat.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Portmapping via &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the TPPcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Verbind met het TPPcoin-netwerk via een SOCKS-proxy (bijv. wanneer u via Tor wilt verbinden)</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Verbind via een SOCKS-proxy</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Proxy &amp;IP:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>IP-adres van de proxy (bijv. 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Poort:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Poort van de proxy (bijv. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS-&amp;Versie:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>SOCKS-versie van de proxy (bijv. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Scherm</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Laat alleen een systeemvak-icoon zien wanneer het venster geminimaliseerd is</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimaliseer naar het systeemvak in plaats van de taakbalk</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minimaliseer het venster in de plaats van de applicatie af te sluiten als het venster gesloten wordt. Wanneer deze optie aan staan, kan de applicatie alleen worden afgesloten door Afsluiten te kiezen in het menu.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>Minimaliseer bij sluiten van het &amp;venster</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Interface</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>Taal &amp;Gebruikersinterface:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting TPPcoin.</source> <translation>De taal van de gebruikersinterface kan hier ingesteld worden. Deze instelling zal pas van kracht worden nadat TPPcoin herstart wordt.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Eenheid om bedrag in te tonen:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Kies de standaard onderverdelingseenheid om weer te geven in uw programma, en voor het versturen van munten</translation> </message> <message> <location line="+9"/> <source>Whether to show TPPcoin addresses in the transaction list or not.</source> <translation>Of TPPcoinadressen getoond worden in de transactielijst</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>Toon a&amp;dressen in de transactielijst</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>Ann&amp;uleren</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Toepassen</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>standaard</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Bevestig reset opties</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Sommige instellingen vereisen het herstarten van de client voordat ze in werking treden.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation> Wilt u doorgaan?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Waarschuwing</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting TPPcoin.</source> <translation>Deze instelling zal pas van kracht worden na het herstarten van TPPcoin.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Het opgegeven proxyadres is ongeldig.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Vorm</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the TPPcoin network after a connection is established, but this process has not completed yet.</source> <translation>De weergegeven informatie kan verouderd zijn. Uw portemonnee synchroniseert automaticsh met het TPPcoinnetwerk nadat een verbinding is gelegd, maar dit proces is nog niet voltooid.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Onbevestigd:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Portemonnee</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Immatuur:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Gedolven saldo dat nog niet tot wasdom is gekomen</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Recente transacties&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Uw huidige saldo</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>Totaal van de transacties die nog moeten worden bevestigd en nog niet zijn meegeteld in uw huidige saldo </translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>niet gesynchroniseerd</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start tppcoin: click-to-pay handler</source> <translation>Kan tppcoin niet starten: click-to-pay handler</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR-codescherm</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Vraag betaling aan</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Bedrag:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Label:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Bericht:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Opslaan Als...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Fout tijdens encoderen URI in QR-code</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Het opgegeven bedrag is ongeldig, controleer het s.v.p.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Resulterende URI te lang, probeer de tekst korter te maken voor het label/bericht.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Sla QR-code op</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG-Afbeeldingen (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Clientnaam</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>N.v.t.</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Clientversie</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informatie</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Gebruikt OpenSSL versie</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Opstarttijd</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Netwerk</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Aantal connecties</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>Op testnet</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Blokketen</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Huidig aantal blokken</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Geschat totaal aantal blokken</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Tijd laatste blok</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Open</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Commandoregel-opties</translation> </message> <message> <location line="+7"/> <source>Show the TPPcoin-Qt help message to get a list with possible TPPcoin command-line options.</source> <translation>Toon het TPPcoinQt-hulpbericht voor een lijst met mogelijke TPPcoin commandoregel-opties.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Toon</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Console</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Bouwdatum</translation> </message> <message> <location line="-104"/> <source>TPPcoin - Debug window</source> <translation>TPPcoin-debugscherm</translation> </message> <message> <location line="+25"/> <source>TPPcoin Core</source> <translation>TPPcoin Kern</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Debug-logbestand</translation> </message> <message> <location line="+7"/> <source>Open the TPPcoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Open het TPPcoindebug-logbestand van de huidige datamap. Dit kan een aantal seconden duren voor grote logbestanden.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Maak console leeg</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the TPPcoin RPC console.</source> <translation>Welkom bij de TPPcoin RPC-console.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Gebruik de pijltjestoetsen om door de geschiedenis te navigeren, en &lt;b&gt;Ctrl-L&lt;/b&gt; om het scherm leeg te maken.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Typ &lt;b&gt;help&lt;/b&gt; voor een overzicht van de beschikbare commando&apos;s.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Verstuur munten</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Verstuur aan verschillende ontvangers ineens</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Voeg &amp;Ontvanger Toe</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Verwijder alle transactievelden</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Verwijder &amp;Alles</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Bevestig de verstuuractie</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Verstuur</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; aan %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Bevestig versturen munten</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Weet u zeker dat u %1 wil versturen?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> en </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Het ontvangstadres is niet geldig, controleer uw invoer.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Het ingevoerde bedrag moet groter zijn dan 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Bedrag is hoger dan uw huidige saldo</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Totaal overschrijdt uw huidige saldo wanneer de %1 transactiekosten worden meegerekend</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Dubbel adres gevonden, u kunt slechts eenmaal naar een bepaald adres verzenden per verstuurtransactie</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Fout: Aanmaak transactie mislukt!</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Fout: De transactie was afgewezen. Dit kan gebeuren als u eerder uitgegeven munten opnieuw wilt versturen, zoals wanneer u een kopie van uw portemonneebestand (wallet.dat) heeft gebruikt en in de kopie deze munten zijn uitgegeven, maar in de huidige portemonnee deze nog niet als zodanig zijn gemarkeerd.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Vorm</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Bedra&amp;g:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Betaal &amp;Aan:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Het adres waaraan u wilt betalen (bijv. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Vul een label in voor dit adres om het toe te voegen aan uw adresboek</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Label:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Kies adres uit adresboek</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Plak adres vanuit klembord</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>Verwijder deze ontvanger</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a TPPcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Vul een TPPcoinadres in (bijv. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Handtekeningen - Onderteken een bericht / Verifiëer een handtekening</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>O&amp;nderteken Bericht</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>U kunt berichten ondertekenen met een van uw adressen om te bewijzen dat u dit adres bezit. Pas op dat u geen onduidelijke dingen ondertekent, want phishingaanvallen zouden u kunnen misleiden om zo uw identiteit te stelen. Onderteken alleen berichten waarmee u het volledig eens bent.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Het adres om het bericht mee te ondertekenen (Vb.: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2).</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Kies een adres uit het adresboek</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Plak adres vanuit klembord</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>Typ hier het bericht dat u wilt ondertekenen</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Handtekening</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Kopieer de huidige handtekening naar het systeemklembord</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this TPPcoin address</source> <translation>Onderteken een bericht om te bewijzen dat u een bepaald TPPcoinadres bezit</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Onderteken &amp;Bericht</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Verwijder alles in de invulvelden</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Verwijder &amp;Alles</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>&amp;Verifiëer Bericht</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Voer het ondertekenende adres, bericht en handtekening hieronder in (let erop dat u nieuwe regels, spaties en tabs juist overneemt) om de handtekening te verifiëren. Let erop dat u niet meer uit het bericht interpreteert dan er daadwerkelijk staat, om te voorkomen dat u wordt misleid in een man-in-the-middle-aanval.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Het adres waarmee bet bericht was ondertekend (Vb.: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2).</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified TPPcoin address</source> <translation>Controleer een bericht om te verifiëren dat het gespecificeerde TPPcoinadres het bericht heeft ondertekend.</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>Verifiëer &amp;Bericht</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Verwijder alles in de invulvelden</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a TPPcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Vul een TPPcoinadres in (bijv. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Klik &quot;Onderteken Bericht&quot; om de handtekening te genereren</translation> </message> <message> <location line="+3"/> <source>Enter TPPcoin signature</source> <translation>Voer TPPcoin-handtekening in</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Het opgegeven adres is ongeldig.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Controleer s.v.p. het adres en probeer het opnieuw.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>Het opgegeven adres verwijst niet naar een sleutel.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Portemonnee-ontsleuteling is geannuleerd</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>Geheime sleutel voor het ingevoerde adres is niet beschikbaar.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Ondertekenen van het bericht is mislukt.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Bericht ondertekend.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>De handtekening kon niet worden gedecodeerd.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Controleer s.v.p. de handtekening en probeer het opnieuw.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>De handtekening hoort niet bij het bericht.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Berichtverificatie mislukt.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Bericht correct geverifiëerd.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The TPPcoin developers</source> <translation>De TPPcoin-ontwikkelaars</translation> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnetwerk]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Openen totdat %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/onbevestigd</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 bevestigingen</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Status</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, uitgezonden naar %n node</numerusform><numerusform>, uitgezonden naar %n nodes</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Bron</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Gegenereerd</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Van</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Aan</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>eigen adres</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>label</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Credit</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>komt tot wasdom na %n nieuw blok</numerusform><numerusform>komt tot wasdom na %n nieuwe blokken</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>niet geaccepteerd</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debet</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Transactiekosten</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Netto bedrag</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Bericht</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Opmerking</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>Transactie-ID:</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &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>Gegeneerde munten moeten 120 blokken wachten voordat ze tot wasdom komen en kunnen worden uitgegeven. Uw net gegenereerde blok is uitgezonden aan het netwerk om te worden toegevoegd aan de blokketen. Als het niet wordt geaccepteerd in de keten, zal het blok als &quot;niet geaccepteerd&quot; worden aangemerkt en kan het niet worden uitgegeven. Dit kan soms gebeuren als een andere node net iets sneller een blok heeft gegenereerd; een paar seconden voor het uwe.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Debug-informatie</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transactie</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Inputs</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Bedrag</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>waar</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>onwaar</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, is nog niet met succes uitgezonden</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>Open voor nog %n blok</numerusform><numerusform>Open voor nog %n blokken</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>onbekend</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Transactiedetails</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Dit venster laat een uitgebreide beschrijving van de transactie zien</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Type</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Bedrag</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation><numerusform>Open voor nog %n blok</numerusform><numerusform>Open voor nog %n blokken</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Open tot %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Niet verbonden (%1 bevestigingen)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Onbevestigd (%1 van %2 bevestigd)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Bevestigd (%1 bevestigingen)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>Gedolven saldo zal beschikbaar komen als het tot wasdom komt na %n blok</numerusform><numerusform>Gedolven saldo zal beschikbaar komen als het tot wasdom komt na %n blokken</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>Dit blok is niet ontvangen bij andere nodes en zal waarschijnlijk niet worden geaccepteerd!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Gegenereerd maar niet geaccepteerd</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Ontvangen met</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Ontvangen van</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Verzonden aan</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Betaling aan uzelf</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Gedolven</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(nvt)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Transactiestatus. Houd de muiscursor boven dit veld om het aantal bevestigingen te laten zien.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Datum en tijd waarop deze transactie is ontvangen.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Type transactie.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Ontvangend adres van transactie.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Bedrag verwijderd van of toegevoegd aan saldo</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Alles</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Vandaag</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Deze week</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Deze maand</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Vorige maand</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Dit jaar</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Bereik...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Ontvangen met</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Verzonden aan</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Aan uzelf</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Gedolven</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Anders</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Vul adres of label in om te zoeken</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Min. bedrag</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopieer adres</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopieer label</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopieer bedrag</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Kopieer transactie-ID</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Bewerk label</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Toon transactiedetails</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Exporteer transactiegegevens</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Kommagescheiden bestand (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Bevestigd</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Type</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Label</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Bedrag</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Fout bij exporteren</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Kon niet schrijven naar bestand %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Bereik:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>naar</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Verstuur munten</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation>&amp;Exporteer</translation> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Exporteer de data in de huidige tab naar een bestand</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation>Portomonnee backuppen</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Portemonnee-data (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Backup Mislukt</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Er is een fout opgetreden bij het wegschrijven van de portemonnee-data naar de nieuwe locatie.</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Backup Succesvol</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>De portemonneedata is succesvol opgeslagen op de nieuwe locatie.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>TPPcoin version</source> <translation>TPPcoinversie</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Gebruik:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or tppcoind</source> <translation>Stuur commando naar -server of tppcoind</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Lijst van commando&apos;s</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Toon hulp voor een commando</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Opties:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: tppcoin.conf)</source> <translation>Specificeer configuratiebestand (standaard: tppcoin.conf) </translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: tppcoind.pid)</source> <translation>Specificeer pid-bestand (standaard: tppcoind.pid) </translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Stel datamap in</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Stel databankcachegrootte in in megabytes (standaard: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9333 or testnet: 19333)</source> <translation>Luister voor verbindingen op &lt;poort&gt; (standaard: 9333 of testnet: 19333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Onderhoud maximaal &lt;n&gt; verbindingen naar peers (standaard: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Verbind naar een node om adressen van anderen op te halen, en verbreek vervolgens de verbinding</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Specificeer uw eigen publieke adres</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Drempel om verbinding te verbreken naar zich misdragende peers (standaard: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Aantal seconden dat zich misdragende peers niet opnieuw mogen verbinden (standaard: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Er is een fout opgetreden tijdens het instellen van de inkomende RPC-poort %u op IPv4: %s</translation> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9332 or testnet: 19332)</source> <translation>Wacht op JSON-RPC-connecties op poort &lt;port&gt; (standaard: 9332 of testnet: 19332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Aanvaard commandoregel- en JSON-RPC-commando&apos;s</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Draai in de achtergrond als daemon en aanvaard commando&apos;s</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Gebruik het testnetwerk</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Accepteer verbindingen van buitenaf (standaard: 1 als geen -proxy of -connect is opgegeven)</translation> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=tppcoinrpc 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;TPPcoin Alert&quot; admin@foo.com </source> <translation>%s, u moet een RPC-wachtwoord instellen in het configuratiebestand: %s U wordt aangeraden het volgende willekeurige wachtwoord te gebruiken: rpcuser=tppcoinrpc rpcpassword=%s (u hoeft dit wachtwoord niet te onthouden) De gebruikersnaam en wachtwoord mogen niet hetzelfde zijn. Als het bestand niet bestaat, make hem dan aan met leesrechten voor enkel de eigenaar. Het is ook aan te bevelen &quot;alertnotify&quot; in te stellen zodat u op de hoogte gesteld wordt van problemen; for example: alertnotify=echo %%s | mail -s &quot;TPPcoin Alert&quot; admin@foo.com</translation> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Er is een fout opgetreden tijdens het instellen van de inkomende RPC-poort %u op IPv6, terugval naar IPv4: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Bind aan opgegeven adres en luister er altijd op. Gebruik [host]:port notatie voor IPv6</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. TPPcoin is probably already running.</source> <translation>Kan geen lock op de datamap %s verkrijgen. TPPcoin draait vermoedelijk reeds.</translation> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Fout: De transactie was afgewezen! Dit kan gebeuren als sommige munten in uw portemonnee al eerder uitgegeven zijn, zoals wanneer u een kopie van uw wallet.dat heeft gebruikt en in de kopie deze munten zijn uitgegeven, maar in deze portemonnee die munten nog niet als zodanig zijn gemarkeerd.</translation> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation>Fout: Deze transactie vereist transactiekosten van tenminste %s, vanwege zijn grootte, complexiteit, of het gebruik van onlangs ontvangen munten!</translation> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>Voer opdracht uit zodra een relevante melding ontvangen is (%s wordt in cmd vervangen door het bericht)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Voer opdracht uit zodra een portemonneetransactie verandert (%s in cmd wordt vervangen door TxID)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Stel maximumgrootte in in bytes voor hoge-prioriteits-/lage-transactiekosten-transacties (standaard: 27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>Dit is een pre-release testversie - gebruik op eigen risico! Gebruik deze niet voor het delven van munten of handelsdoeleinden</translation> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Waarschuwing: -paytxfee is zeer hoog ingesteld. Dit zijn de transactiekosten die u betaalt bij het versturen van een transactie.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Waarschuwing: Weergegeven transacties zijn mogelijk niet correct! Mogelijk dient u te upgraden, of andere nodes dienen te upgraden.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong TPPcoin will not work properly.</source> <translation>Waarschuwing: Controleer dat de datum en tijd op uw computer correct zijn ingesteld. Als uw klok fout staat zal TPPcoin niet correct werken.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Waarschuwing: Fout bij het lezen van wallet.dat! Alle sleutels zijn in goede orde uitgelezen, maar transactiedata of adresboeklemma&apos;s zouden kunnen ontbreken of fouten bevatten.</translation> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Waarschuwing: wallet.dat is corrupt, data is veiliggesteld! Originele wallet.dat is opgeslagen als wallet.{tijdstip}.bak in %s; als uw balans of transacties incorrect zijn dient u een backup terug te zetten.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Poog de geheime sleutels uit een corrupt wallet.dat bestand terug te halen</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Blokcreatie-opties:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Verbind alleen naar de gespecificeerde node(s)</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>Corrupte blokkendatabase gedetecteerd</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Ontdek eigen IP-adres (standaard: 1 als er wordt geluisterd en geen -externalip is opgegeven)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>Wilt u de blokkendatabase nu herbouwen?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>Fout bij intialisatie blokkendatabase</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation>Probleem met initializeren van de database-omgeving %s!</translation> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>Fout bij het laden van blokkendatabase</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>Fout bij openen blokkendatabase</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Fout: Weinig vrije diskruimte!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Fout: Portemonnee vergrendeld, aanmaak transactie niet mogelijk!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Fout: Systeemfout:</translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Mislukt om op welke poort dan ook te luisteren. Gebruik -listen=0 as u dit wilt.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>Lezen van blokinformatie mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>Lezen van blok mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation>Synchroniseren van blokindex mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation>Schrijven van blokindex mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation>Schrijven van blokinformatie mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>Schrijven van blok mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation>Schrijven van bestandsinformatie mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>Schrijven naar coindatabase mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation>Schrijven van transactieindex mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation>Schrijven van undo-data mislukt</translation> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Vind andere nodes d.m.v. DNS-naslag (standaard: 1 tenzij -connect)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation>Genereer munten (standaard: 0)</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Aantal te checken blokken bij het opstarten (standaard: 288, 0 = allemaal)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation>Hoe grondig de blokverificatie is (0-4, standaard: 3)</translation> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation>Niet genoeg file descriptors beschikbaar.</translation> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>Blokketen opnieuw opbouwen van huidige blk000??.dat-bestanden</translation> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation>Stel het aantal threads in om RPC-aanvragen mee te bedienen (standaard: 4)</translation> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>Blokken aan het controleren...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>Portomonnee aan het controleren...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Importeert blokken van extern blk000??.dat bestand</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation>Stel het aantal threads voor scriptverificatie in (max 16, 0 = auto, &lt;0 = laat zoveel cores vrij, standaard: 0)</translation> </message> <message> <location line="+77"/> <source>Information</source> <translation>Informatie</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Ongeldig -tor adres: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Ongeldig bedrag voor -minrelaytxfee=&lt;bedrag&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Ongeldig bedrag voor -mintxfee=&lt;bedrag&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation>Onderhoud een volledige transactieindex (standaard: 0)</translation> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Maximum per-connectie ontvangstbuffer, &lt;n&gt;*1000 bytes (standaard: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Maximum per-connectie zendbuffer, &lt;n&gt;*1000 bytes (standaard: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>Accepteer alleen blokketen die overeenkomt met de ingebouwde checkpoints (standaard: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Verbind alleen naar nodes in netwerk &lt;net&gt; (IPv4, IPv6 of Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Output extra debugginginformatie. Impliceert alle andere -debug* opties</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Output extra netwerk-debugginginformatie</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Voorzie de debuggingsuitvoer van een tijdsaanduiding</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the TPPcoin Wiki for SSL setup instructions)</source> <translation>SSL-opties: (zie de TPPcoin wiki voor SSL-instructies)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Selecteer de versie van de SOCKS-proxy om te gebruiken (4 of 5, standaard is 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Stuur trace/debug-info naar de console in plaats van het debug.log bestand</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Stuur trace/debug-info naar debugger</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Stel maximum blokgrootte in in bytes (standaard: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Stel minimum blokgrootte in in bytes (standaard: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Verklein debug.log-bestand bij het opstarten van de client (standaard: 1 als geen -debug)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation>Ondertekenen van transactie mislukt</translation> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Specificeer de time-outtijd in milliseconden (standaard: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Systeemfout:</translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation>Transactiebedrag te klein</translation> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation>Transactiebedragen moeten positief zijn</translation> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation>Transactie te groot</translation> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Gebruik UPnP om de luisterende poort te mappen (standaard: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Gebruik UPnP om de luisterende poort te mappen (standaard: 1 als er wordt geluisterd)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Gebruik proxy om &apos;tor hidden services&apos; te bereiken (standaard: hetzelfde als -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Gebruikersnaam voor JSON-RPC-verbindingen</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Waarschuwing</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Waarschuwing: Deze versie is verouderd, een upgrade is vereist!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation>U moet de databases herbouwen met behulp van -reindex om -txindex te kunnen veranderen</translation> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat corrupt, veiligstellen mislukt</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Wachtwoord voor JSON-RPC-verbindingen</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Sta JSON-RPC verbindingen van opgegeven IP-adres toe</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Verstuur commando&apos;s naar proces dat op &lt;ip&gt; draait (standaard: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Voer commando uit zodra het beste blok verandert (%s in cmd wordt vervangen door blockhash)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Vernieuw portemonnee naar nieuwste versie</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Stel sleutelpoelgrootte in op &lt;n&gt; (standaard: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Doorzoek de blokketen op ontbrekende portemonnee-transacties</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Gebruik OpenSSL (https) voor JSON-RPC-verbindingen</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Certificaat-bestand voor server (standaard: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Geheime sleutel voor server (standaard: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Aanvaardbare ciphers (standaard: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Dit helpbericht</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Niet in staat om aan %s te binden op deze computer (bind gaf error %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Verbind via een socks-proxy</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Sta DNS-naslag toe voor -addnode, -seednode en -connect</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Adressen aan het laden...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Fout bij laden wallet.dat: Portemonnee corrupt</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of TPPcoin</source> <translation>Fout bij laden wallet.dat: Portemonnee vereist een nieuwere versie van TPPcoin</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart TPPcoin to complete</source> <translation>Portemonnee moest herschreven worden: Herstart TPPcoin om te voltooien</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Fout bij laden wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Ongeldig -proxy adres: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Onbekend netwerk gespecificeerd in -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Onbekende -socks proxyversie aangegeven: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Kan -bind adres niet herleiden: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Kan -externlip adres niet herleiden: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Ongeldig bedrag voor -paytxfee=&lt;bedrag&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Ongeldig bedrag</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Ontoereikend saldo</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Blokindex aan het laden...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Voeg een node om naar te verbinden toe en probeer de verbinding open te houden</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. TPPcoin is probably already running.</source> <translation>Niet in staat om aan %s te binden op deze computer. TPPcoin draait vermoedelijk reeds.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Kosten per KB om aan transacties toe te voegen die u verstuurt</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Portemonnee aan het laden...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Kan portemonnee niet downgraden</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Kan standaardadres niet schrijven</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Blokketen aan het doorzoeken...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Klaar met laden</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>Om de %s optie te gebruiken</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Fout</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>U dient rpcpassword=&lt;wachtwoord&gt; in te stellen in het configuratiebestand: %s Als het bestand niet bestaat, maak het dan aan, met een alleen-lezen-permissie.</translation> </message> </context> </TS>
tppcoin/tppcoin
src/qt/locale/bitcoin_nl.ts
TypeScript
mit
118,342
""" Django settings for ProgrammerCompetencyMatrix project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '^k(h30rq(chrdd0y2)327we@uh@nat3d*^8f1l--4t0bxo9_nm' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'survey', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'ProgrammerCompetencyMatrix.urls' WSGI_APPLICATION = 'ProgrammerCompetencyMatrix.wsgi.application' # Database # https://docs.djangoproject.com/en/1.6/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.6/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.6/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static').replace(os.sep, '/'), ) # BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) #logging.warning(TEMPLATE_DIR) TEMPLATE_DIRS = ( # os.path.join(BASE_DIR, '../../templates/'), os.path.join(BASE_DIR, 'templates').replace(os.sep, '/'), # 'D:/Java/Project/GettingStartBlog/templates/' )
FiaDot/programmer-competency-matrix
ProgrammerCompetencyMatrix/settings.py
Python
mit
2,486
require 'test_helper' module Cms class CategoriesHelperTest < ActionView::TestCase end end
dreamyourweb/dyw-cms
test/unit/helpers/cms/categories_helper_test.rb
Ruby
mit
96
angular.module('backAnd.services') .constant('CONSTANTS', { URL: "https://api.backand.com", DEFAULT_APP: null, VERSION : '0.1' });
backand/angularbknd
app/backand/js/services/constants.js
JavaScript
mit
162
class CommentsController < ApplicationController before_action :set_comment, only: [:show, :update, :destroy] def index render json: { comments: Comment.all }, methods: :post_id end def show render json: { comment: @comment }, methods: :post_id end def create @comment = Comment.new(comment_params) if @comment.save render json: { comment: @comment }, methods: :post_id, status: :created, location: @comment else render json: @comment.errors, status: :unprocessable_entity end end def destroy @comment.destroy head :no_content end private def set_comment @comment = Comment.find(params[:id]) end def comment_params params.require(:comment).permit(:author, :body, :post_id) end end
brunoocasali/ember-n-rails
blog-backend/app/controllers/comments_controller.rb
Ruby
mit
769
const JSUnit = imports.jsUnit; const Cairo = imports.cairo; const Everything = imports.gi.Regress; function _ts(obj) { return obj.toString().slice(8, -1); } function _createSurface() { return new Cairo.ImageSurface(Cairo.Format.ARGB32, 1, 1); } function _createContext() { return new Cairo.Context(_createSurface()); } function testContext() { let cr = _createContext(); JSUnit.assertTrue(cr instanceof Cairo.Context); } function testContextMethods() { let cr = _createContext(); JSUnit.assertTrue(cr instanceof Cairo.Context); cr.save(); cr.restore(); let surface = _createSurface(); JSUnit.assertEquals(_ts(cr.getTarget()), "CairoImageSurface"); let pattern = Cairo.SolidPattern.createRGB(1, 2, 3); cr.setSource(pattern); JSUnit.assertEquals(_ts(cr.getSource()), "CairoSolidPattern"); cr.setSourceSurface(surface, 0, 0); cr.pushGroup(); cr.popGroup(); cr.pushGroupWithContent(Cairo.Content.COLOR); cr.popGroupToSource(); cr.setSourceRGB(1, 2, 3); cr.setSourceRGBA(1, 2, 3, 4); cr.setAntialias(Cairo.Antialias.NONE); JSUnit.assertEquals("antialias", cr.getAntialias(), Cairo.Antialias.NONE); cr.setFillRule(Cairo.FillRule.EVEN_ODD); JSUnit.assertEquals("fillRule", cr.getFillRule(), Cairo.FillRule.EVEN_ODD); cr.setLineCap(Cairo.LineCap.ROUND); JSUnit.assertEquals("lineCap", cr.getLineCap(), Cairo.LineCap.ROUND); cr.setLineJoin(Cairo.LineJoin.ROUND); JSUnit.assertEquals("lineJoin", cr.getLineJoin(), Cairo.LineJoin.ROUND); cr.setLineWidth(1138); JSUnit.assertEquals("lineWidth", cr.getLineWidth(), 1138); cr.setMiterLimit(42); JSUnit.assertEquals("miterLimit", cr.getMiterLimit(), 42); cr.setOperator(Cairo.Operator.IN); JSUnit.assertEquals("operator", cr.getOperator(), Cairo.Operator.IN); cr.setTolerance(144); JSUnit.assertEquals("tolerance", cr.getTolerance(), 144); cr.clip(); cr.clipPreserve(); let rv = cr.clipExtents(); JSUnit.assertEquals("clipExtents", rv.length, 4); cr.fill(); cr.fillPreserve(); let rv = cr.fillExtents(); JSUnit.assertEquals("fillExtents", rv.length, 4); cr.mask(pattern); cr.maskSurface(surface, 0, 0); cr.paint(); cr.paintWithAlpha(1); cr.stroke(); cr.strokePreserve(); let rv = cr.strokeExtents(); JSUnit.assertEquals("strokeExtents", rv.length, 4); cr.inFill(0, 0); cr.inStroke(0, 0); cr.copyPage(); cr.showPage(); let dc = cr.getDashCount(); JSUnit.assertEquals("dashCount", dc, 0); cr.translate(10, 10); cr.scale(10, 10); cr.rotate(180); cr.identityMatrix(); let rv = cr.userToDevice(0, 0); JSUnit.assertEquals("userToDevice", rv.length, 2); let rv = cr.userToDeviceDistance(0, 0); JSUnit.assertEquals("userToDeviceDistance", rv.length, 2); let rv = cr.deviceToUser(0, 0); JSUnit.assertEquals("deviceToUser", rv.length, 2); let rv = cr.deviceToUserDistance(0, 0); JSUnit.assertEquals("deviceToUserDistance", rv.length, 2); cr.showText("foobar"); cr.moveTo(0, 0); cr.setDash([1, 0.5], 1); cr.lineTo(1, 0); cr.lineTo(1, 1); cr.lineTo(0, 1); cr.closePath(); let path = cr.copyPath(); cr.fill(); cr.appendPath(path); cr.stroke(); } function testSolidPattern() { let cr = _createContext(); let p1 = Cairo.SolidPattern.createRGB(1, 2, 3); JSUnit.assertEquals(_ts(p1), "CairoSolidPattern"); cr.setSource(p1); JSUnit.assertEquals(_ts(cr.getSource()), "CairoSolidPattern"); let p2 = Cairo.SolidPattern.createRGBA(1, 2, 3, 4); JSUnit.assertEquals(_ts(p2), "CairoSolidPattern"); cr.setSource(p2); JSUnit.assertEquals(_ts(cr.getSource()), "CairoSolidPattern"); } function testSurfacePattern() { let cr = _createContext(); let surface = _createSurface(); let p1 = new Cairo.SurfacePattern(surface); JSUnit.assertEquals(_ts(p1), "CairoSurfacePattern"); cr.setSource(p1); JSUnit.assertEquals(_ts(cr.getSource()), "CairoSurfacePattern"); } function testLinearGradient() { let cr = _createContext(); let surface = _createSurface(); let p1 = new Cairo.LinearGradient(1, 2, 3, 4); JSUnit.assertEquals(_ts(p1), "CairoLinearGradient"); cr.setSource(p1); JSUnit.assertEquals(_ts(cr.getSource()), "CairoLinearGradient"); } function testRadialGradient() { let cr = _createContext(); let surface = _createSurface(); let p1 = new Cairo.RadialGradient(1, 2, 3, 4, 5, 6); JSUnit.assertEquals(_ts(p1), "CairoRadialGradient"); cr.setSource(p1); JSUnit.assertEquals(_ts(cr.getSource()), "CairoRadialGradient"); } function testCairoSignal() { let o = new Everything.TestObj(); let called = false; o.connect('sig-with-foreign-struct', function(o, cr) { called = true; JSUnit.assertEquals(_ts(cr), "CairoContext"); }); o.emit_sig_with_foreign_struct(); JSUnit.assertTrue(called); } JSUnit.gwkjstestRun(this, JSUnit.setUp, JSUnit.tearDown);
danilocesar/gwkjs
installed-tests/js/testCairo.js
JavaScript
mit
5,061
package org.testcontainers.dockerclient; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.core.DockerClientBuilder; import com.github.dockerjava.core.DockerClientConfig; import com.github.dockerjava.netty.NettyDockerCmdExecFactory; import com.google.common.base.Throwables; import org.apache.commons.io.IOUtils; import org.jetbrains.annotations.Nullable; import org.rnorth.ducttape.TimeoutException; import org.rnorth.ducttape.ratelimits.RateLimiter; import org.rnorth.ducttape.ratelimits.RateLimiterBuilder; import org.rnorth.ducttape.unreliables.Unreliables; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.utility.TestcontainersConfiguration; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Stream; /** * Mechanism to find a viable Docker client configuration according to the host system environment. */ public abstract class DockerClientProviderStrategy { protected DockerClient client; protected DockerClientConfig config; private static final RateLimiter PING_RATE_LIMITER = RateLimiterBuilder.newBuilder() .withRate(2, TimeUnit.SECONDS) .withConstantThroughput() .build(); private static final AtomicBoolean FAIL_FAST_ALWAYS = new AtomicBoolean(false); /** * @throws InvalidConfigurationException if this strategy fails */ public abstract void test() throws InvalidConfigurationException; /** * @return a short textual description of the strategy */ public abstract String getDescription(); protected boolean isApplicable() { return true; } protected boolean isPersistable() { return true; } /** * @return highest to lowest priority value */ protected int getPriority() { return 0; } protected static final Logger LOGGER = LoggerFactory.getLogger(DockerClientProviderStrategy.class); /** * Determine the right DockerClientConfig to use for building clients by trial-and-error. * * @return a working DockerClientConfig, as determined by successful execution of a ping command */ public static DockerClientProviderStrategy getFirstValidStrategy(List<DockerClientProviderStrategy> strategies) { if (FAIL_FAST_ALWAYS.get()) { throw new IllegalStateException("Previous attempts to find a Docker environment failed. Will not retry. Please see logs and check configuration"); } List<String> configurationFailures = new ArrayList<>(); return Stream .concat( Stream .of(TestcontainersConfiguration.getInstance().getDockerClientStrategyClassName()) .filter(Objects::nonNull) .flatMap(it -> { try { Class<? extends DockerClientProviderStrategy> strategyClass = (Class) Thread.currentThread().getContextClassLoader().loadClass(it); return Stream.of(strategyClass.newInstance()); } catch (ClassNotFoundException e) { LOGGER.warn("Can't instantiate a strategy from {} (ClassNotFoundException). " + "This probably means that cached configuration refers to a client provider " + "class that is not available in this version of Testcontainers. Other " + "strategies will be tried instead.", it); return Stream.empty(); } catch (InstantiationException | IllegalAccessException e) { LOGGER.warn("Can't instantiate a strategy from {}", it, e); return Stream.empty(); } }) // Ignore persisted strategy if it's not persistable anymore .filter(DockerClientProviderStrategy::isPersistable) .peek(strategy -> LOGGER.info("Loaded {} from ~/.testcontainers.properties, will try it first", strategy.getClass().getName())), strategies .stream() .filter(DockerClientProviderStrategy::isApplicable) .sorted(Comparator.comparing(DockerClientProviderStrategy::getPriority).reversed()) ) .flatMap(strategy -> { try { strategy.test(); LOGGER.info("Found Docker environment with {}", strategy.getDescription()); if (strategy.isPersistable()) { TestcontainersConfiguration.getInstance().updateGlobalConfig("docker.client.strategy", strategy.getClass().getName()); } return Stream.of(strategy); } catch (Exception | ExceptionInInitializerError | NoClassDefFoundError e) { @Nullable String throwableMessage = e.getMessage(); @SuppressWarnings("ThrowableResultOfMethodCallIgnored") Throwable rootCause = Throwables.getRootCause(e); @Nullable String rootCauseMessage = rootCause.getMessage(); String failureDescription; if (throwableMessage != null && throwableMessage.equals(rootCauseMessage)) { failureDescription = String.format("%s: failed with exception %s (%s)", strategy.getClass().getSimpleName(), e.getClass().getSimpleName(), throwableMessage); } else { failureDescription = String.format("%s: failed with exception %s (%s). Root cause %s (%s)", strategy.getClass().getSimpleName(), e.getClass().getSimpleName(), throwableMessage, rootCause.getClass().getSimpleName(), rootCauseMessage ); } configurationFailures.add(failureDescription); LOGGER.debug(failureDescription); return Stream.empty(); } }) .findAny() .orElseThrow(() -> { LOGGER.error("Could not find a valid Docker environment. Please check configuration. Attempted configurations were:"); for (String failureMessage : configurationFailures) { LOGGER.error(" " + failureMessage); } LOGGER.error("As no valid configuration was found, execution cannot continue"); FAIL_FAST_ALWAYS.set(true); return new IllegalStateException("Could not find a valid Docker environment. Please see logs and check configuration"); }); } /** * @return a usable, tested, Docker client configuration for the host system environment */ public DockerClient getClient() { return new AuditLoggingDockerClient(client); } protected DockerClient getClientForConfig(DockerClientConfig config) { return DockerClientBuilder .getInstance(config) .withDockerCmdExecFactory(new NettyDockerCmdExecFactory()) .build(); } protected void ping(DockerClient client, int timeoutInSeconds) { try { Unreliables.retryUntilSuccess(timeoutInSeconds, TimeUnit.SECONDS, () -> { return PING_RATE_LIMITER.getWhenReady(() -> { LOGGER.debug("Pinging docker daemon..."); client.pingCmd().exec(); return true; }); }); } catch (TimeoutException e) { IOUtils.closeQuietly(client); throw e; } } public String getDockerHostIpAddress() { return DockerClientConfigUtils.getDockerHostIpAddress(this.config); } }
barrycommins/testcontainers-java
core/src/main/java/org/testcontainers/dockerclient/DockerClientProviderStrategy.java
Java
mit
8,768
package pass.core.scheduling.distributed; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import pass.core.scheduling.TaskSpecification; public class Job implements Serializable { private static final Logger LOGGER = Logger.getLogger(Job.class.getName()); private final UUID taskId; private final TaskSpecification taskSpec; public Job(UUID taskId, TaskSpecification taskSpec) { this.taskId = taskId; this.taskSpec = taskSpec; } public UUID getTaskId() { return taskId; } public TaskSpecification getTaskSpec() { return taskSpec; } public byte[] serialize() { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this); oos.flush(); return bos.toByteArray(); } catch (IOException ex) { LOGGER.log(Level.SEVERE, null, ex); return null; } } public static Job deserialize(byte[] input) { try { ByteArrayInputStream bis = new ByteArrayInputStream(input); ObjectInputStream ois = new ObjectInputStream(bis); return (Job) ois.readObject(); } catch (IOException | ClassNotFoundException ex) { LOGGER.log(Level.SEVERE, null, ex); return null; } } }
mzohreva/PASS
pass-core/src/main/java/pass/core/scheduling/distributed/Job.java
Java
mit
1,683
<?php /* * This file is part of KoolKode Security Database. * * (c) Martin Schröder <m.schroeder2007@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace KoolKode\Security\Database; use KoolKode\Database\ConnectionInterface; use KoolKode\Security\Authentication\NonceTrackerInterface; use KoolKode\Security\SecurityContextInterface; use KoolKode\Util\RandomGeneratorInterface; /** * Keeps track of nonces being used by clients in HTTP digest auth. * * @author Martin Schröder */ class DatabaseNonceTracker implements NonceTrackerInterface { protected $context; protected $conn; protected $nonceByteCount = 16; protected $nonceStrength = RandomGeneratorInterface::STRENGTH_MEDIUM; protected $lifetime = 900; protected $maxLifetime = 3600; protected $delta = 15; protected $invalidState = self::NONCE_INVALID; protected $initialized = false; protected $table = '#__security_nonce_tracker'; protected $columnNonce = 'nonce'; protected $columnCount = 'count'; protected $columnCreated = 'created'; public function __construct(SecurityContextInterface $context, ConnectionInterface $conn) { $this->context = $context; $this->conn = $conn; } /** * Set the number of random bytes being used to create a nonce. * * @param integer $byteCount */ public function setNonceByteCount($byteCount) { $this->nonceByteCount = max(4, (int)$byteCount); } /** * Set the strength of randomness being used to create nonces. * * Defaults to MEDIUM strength. * * @param integer $strength */ public function setNonceStrength($strength) { $this->nonceStrength = max(RandomGeneratorInterface::STRENGTH_LOW, (int)$strength); } /** * Set the nonce lifetime before it becomes stale. * * Defaults to 900 seconds. * * @param integer $lifetime Lifetime in seconds. */ public function setLifetime($lifetime) { $this->lifetime = (int)$lifetime; } /** * Set the maximum lifetime before a nonce is deleted. * * Defaults to 3600 seconds. * * @param integer $maxLifetime Maximum lifetime in seconds. */ public function setMaxLifetime($maxLifetime) { $this->maxLifetime = (int)$maxLifetime; } /** * Set the client nonce delta (that is half the size of the interval being used when * checking for a valid client nonce count). * * Defaults to 15. * * @param integer $delta */ public function setDelta($delta) { $this->delta = (int)$delta; } /** * Set the name of the table being used for nonce tracking. * * Defaults to "nonce_tracker". * * @param string $tableName */ public function setTableName($tableName) { $this->table = $this->conn->quoteIdentifier($tableName); } /** * Set the name of the column holding the nonce value. * * Defaults to "nonce". * * @param string $column */ public function setNonceColumn($column) { $this->columnNonce = $this->conn->quoteIdentifier($column); } /** * Set the name of the column tracking the nonce usage count. * * Defaults to "count". * * @param string $column */ public function setCountColumn($column) { $this->columnCount = $this->conn->quoteIdentifier($column); } /** * Set the name of the column holding the nonce creation timestamp. * * Defaults to "created". * * @param string $column */ public function setCreatedColumn($column) { $this->columnCreated = $this->conn->quoteIdentifier($column); } /** * Set the state to be returned when the checked nonce is invalid. * * Some clients (MS WebDAV client for example) may require returning STALE instead of INVALID in such a situation. * * @param integer $state One of NONCE_INVALID or NONCE_STALE. * * @throws \InvalidArgumentException */ public function setInvalidState($state) { switch($state) { case self::NONCE_INVALID: case self::NONCE_STALE: $this->invalidState = (int)$state; break; default: throw new \InvalidArgumentException(sprintf('State not supported for invalid nonce: %s', $state)); } } /** * {@inheritdoc} */ public function initializeTracker() { if($this->initialized) { return; } $sql = " DELETE FROM {$this->table} WHERE {$this->columnCreated} < :max OR {$this->columnCount} < 2 AND {$this->columnCreated} < :lifetime "; $stmt = $this->conn->prepare($sql); $stmt->bindValue('mac', time() - $this->maxLifetime); $stmt->bindValue('lifetime', time() - $this->lifetime); $stmt->execute(); $this->initialized = true; } /** * {@inheritdoc} */ public function createNonce() { $nonce = $this->context->getRandomGenerator()->generateHexString($this->nonceByteCount, $this->nonceStrength); // Create fresh nonce: $sql = " INSERT INTO {$this->table} ({$this->columnNonce}, {$this->columnCount}, {$this->columnCreated}) VALUES (:nonce, :count, :created) "; $stmt = $this->conn->prepare($sql); $stmt->bindValue('nonce', $nonce); $stmt->bindValue('count', 0); $stmt->bindValue('created', time()); $stmt->execute(); return $nonce; } /** * {@inheritdoc} */ public function checkNonce($nonce, $count) { $nonce = (string)$nonce; $count = (int)$count; $sql = " SELECT {$this->columnCount} AS nonce_count, {$this->columnCreated} AS nonce_created FROM {$this->table} WHERE {$this->columnNonce} = :nonce "; $stmt = $this->conn->prepare($sql); $stmt->bindValue('nonce', $nonce); $stmt->execute(); $row = $stmt->fetchNextRow(); if($row === false) { return $this->invalidState; } $nonceCount = (int)$row['nonce_count']; $nonceCreated = (int)$row['nonce_created']; // Update nonce count: $sql = " UPDATE {$this->table} SET {$this->columnCount} = {$this->columnCount} + 1 WHERE {$this->columnNonce} = :nonce "; $stmt = $this->conn->prepare($sql); $stmt->bindValue('nonce', $nonce); $stmt->execute(); // Check client nonce counter including delta range (useful when processing requests in parallel). if($count < ($nonceCount - $this->delta) || $count > ($nonceCount + $this->delta)) { return $this->invalidState; } // Check if nonce has staled out. if(($nonceCreated + $this->lifetime) < time()) { return self::NONCE_STALE; } return self::NONCE_OK; } }
koolkode/security-database
src/DatabaseNonceTracker.php
PHP
mit
6,412
Ember.Fuel.Grid.View.Toolbar = Ember.Fuel.Grid.View.ContainerBase.extend({ classNames: ['table-toolbar'], classNameBindings: ['childViews.length::hide'], childViewsBinding: 'controller.toolbar' });
redfire1539/ember-fuel
Libraries/Grid/Views/Toolbar.js
JavaScript
mit
203
<?php /* * This file is part of PHPExifTool. * * (c) 2012 Romain Neutron <imprec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Flash; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class Message extends AbstractTag { protected $Id = 'pmsg'; protected $Name = 'Message'; protected $FullName = 'Flash::Meta'; protected $GroupName = 'Flash'; protected $g0 = 'Flash'; protected $g1 = 'Flash'; protected $g2 = 'Video'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Message'; }
romainneutron/PHPExiftool
lib/PHPExiftool/Driver/Tag/Flash/Message.php
PHP
mit
764
angular.module('DashboardModule', ['ui.router', 'toastr', 'ngResource', 'angular-js-xlsx', 'angularFileUpload','ngAnimate']) //.config(function ($routeProvider, $locationProvider) { // $routeProvider // // .when('/', { // templateUrl: '/js/private/dashboard/tpl/dashboard.tpl.html', // controller: 'DashboardController' // }) // // .when('/account', { // templateUrl: '/js/private/dashboard/account/tpl/account.tpl.html', // controller: 'AccountController' // }) // ; // $locationProvider.html5Mode({enabled: true, requireBase: false}); //}) .config(['$sceDelegateProvider', function($sceDelegateProvider) { // We must whitelist the JSONP endpoint that we are using to show that we trust it $sceDelegateProvider.resourceUrlWhitelist([ 'self', 'http://localhost:1339/**' ]); }]) .config(function ($stateProvider, $urlRouterProvider, $locationProvider) { $stateProvider .state('home', { url: '/', views: { //'sidebar@': {templateUrl: '/js/private/tpl/sidebar.tpl.html'}, '@': { templateUrl: '/js/public/dashboard/tpl/dashboard.html', controller: 'DashboardController' } } }) .state('home.upload', { url: 'upload', views: { '@': { templateUrl: '/js/public/dashboard/tpl/upload.html', controller: 'DashboardController' } } }) .state('home.file.upload', { url: 'upload', views: { '@': { templateUrl: '/js/public/dashboard/tpl/upload.html', controller: 'DashboardController' } } }) //.state('home.profile.edit', { // url: '/edit', // views: { // '@': { // templateUrl: '/js/private/dashboard/tpl/edit-profile.html', // controller: 'EditProfileController' // } // } //}) // .state('home.profile.restore', { // url: 'restore', // views: { // '@': { // templateUrl: '/js/private/dashboard/tpl/restore-profile.html', // controller: 'RestoreProfileController' // } // } // }) // .state('account', { // url: '/account', // templateUrl: '/js/private/dashboard/account/tpl/account.tpl.html' // }) // .state('contact', { // url: '/contact', // // Будет автоматически вложен в безымянный ui-view // // родительского шаблона. Начиная с состояния верхнего уровня, // // шаблоном этого родительского состояния является index.html. // templateUrl: '/js/private/contacts.html' // }) // // .state('contact.detail', { // views: { // ///////////////////////////////////////////////////// // // Относительное позиционирование // // // позиционируется родительское состояние в ui-view// // ///////////////////////////////////////////////////// // // // Относительное позиционирование вида 'detail' в родительском // // состоянии 'contacts'. // // <div ui-view='detail'/> внутри contacts.html // // "detail": {}, // // // Относительное поциционирование безымянного вида в родительском // // состояния 'contacts'. // // <div ui-view/> внутри contacts.html // // "": {} // // //////////////////////////////////////////////////////////////////////////// // // Абсолютное позиционирование '@' // // // Позиционирование любых видов внутри этого состояния илипредшествующего // // //////////////////////////////////////////////////////////////////////////// // // // Абсолютное позиционирование вида 'info' в состоянии 'contacts.detail'. // // <div ui-view='info'/> внутри contacts.detail.html // //"info@contacts.detail" : { } // // // Абсолютное позиционирование вида 'detail' в состоянии 'contacts'. // // <div ui-view='detail'/> внутри contacts.html // "detail@contact": {templateUrl: '/js/private/contact.detail.tpl.html'} // // // Абсолютное позиционирование безымянного вида в родительском // // состоянии 'contacts'. // // <div ui-view/> внутри contacts.html // // "@contacts" : { } // // // Абсолютное позиционирование вида 'status' в корневом безымянном состоянии. // // <div ui-view='status'/> внутри index.html // // "status@" : { } // // // Абсолютное позиционирование безымянного вида в корневом безымянном состоянии. // // <div ui-view/> внутри index.html // // "@" : { } // } // // .state('route1.viewC', { // // url: "/route1", // // views: { // // "viewC": { template: "route1.viewA" } // // } // // }) // // .state('route2', { // // url: "/route2", // // views: { // // "viewA": { template: "route2.viewA" }, // // "viewB": { template: "route2.viewB" } // // } // // }) // }) ; }) .directive('file', function () { return { scope: { file: '=' }, link: function (scope, el, attrs) { el.bind('change', function (event) { var file = event.target.files[0]; scope.file = file ? file : undefined; scope.$apply(); }); } }; }); //.constant('CONF_MODULE', {baseUrl: '/price/:priceId'}) //.factory('Prices', function ($resource, $state, CONF_MODULE) { // var Prices = $resource( // CONF_MODULE.baseUrl, // {priceId: '@id'}, // // Определяем собственный метод update на обоих уровнях, класса и экземпляра // { // update: { // method: 'PUT' // } // } // ); //}) ;
SETTER2000/price
assets/js/public/dashboard/DashboardModule.js
JavaScript
mit
8,259
<!-- Safe sample input : execute a ls command using the function system, and put the last result in $tainted sanitize : cast via + = 0.0 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 $tainted = system('ls', $retval); $tainted += 0.0 ; echo $tainted ; ?> --> </head> <body> <h1>Hello World!</h1> </body> </html>
stivalet/PHP-Vulnerability-test-suite
XSS/CWE_79/safe/CWE_79__system__CAST-cast_float_sort_of__Unsafe_use_untrusted_data-comment.php
PHP
mit
1,275
# describe 'Users feature', type: :feature do # let!(:first_user) { create :user, name: 'Admin' } # let!(:second_user) { create :user, name: 'User' } # before do # visit root_path # click_link 'All users' # end # describe '#index' do # it 'shows page title' do # expect(page).to have_content('All users') # end # it 'shows all registered users' do # expect(page).to have_content(first_user.name) # expect(page).to have_content(first_user.email) # expect(page).to have_content(second_user.name) # expect(page).to have_content(second_user.email) # end # end # describe '#show' do # before do # click_link "Show profile of #{first_user.name}" # end # it 'redirects to user posts url' do # expect(page).to have_current_path(user_posts_path(first_user)) # end # end # end
vrtsev/LifeLog
spec/features/publications/users_feature_spec.rb
Ruby
mit
872
module App { /** * Наследуйте все директивы не имеющие html-темплейта от этого класса. * Стили будут загружаться относительно папки URL.DIRECTIVES_ROOT/<имя-директивы>. * Скоуп, элемент и атрибуты директивы доступны через св-ва $scope, $element, $attrs. * По умолчанию доступны сервисы $parse, $compile, $sce */ export class Directive extends LionSoftAngular.Directive { promiseFromResult<T>(res: T): IPromise<T> { return <any>super.promiseFromResult(res); } /** * Do not override this method. Use methods this.PreLink, this.Link, this.Compile instead. */ compile = (element, attrs, transclude) => { this.ngName = this.name || this.ngName; this.rootFolder = URL.DIRECTIVES_ROOT + this.getName(false) + "/"; this.Compile(element, attrs, transclude); return { pre: (scope, element, attrs, controller, transclude) => { this.PreLink(scope, element, attrs, controller, transclude); }, post: (scope, element, attrs, controller, transclude) => this.Link(scope, element, attrs, controller, transclude) } }; } }
lionsoft/SampleSPA
Sam/app/common/Directive.ts
TypeScript
mit
1,419
(function() { function ce(p, n, id, c, html) { var e = document.createElement(n); p.appendChild(e); if (id) e.id = id; if (c) e.className = c; if (html) e.innerHTML = html; return e; } demoModeGameboard = gameboard.extend ({ init : function(isActive, gameData, generateState, elapsedTime) { arguments.callee.$.init.call(this); this.maxTime = 120.0; var that = this; this.elapsedTime = 0; this.pastMoves = Array(); setTimeout(function() { that.startGame(); }, 100); return this.encodeBoard(); }, uninit : function() { arguments.callee.$.uninit.call(this); _('#demoModeContainer').innerHTML = ''; _('#demoModeContainer').style.display = 'none'; clearInterval(this.startInterval); clearInterval(this.confirmInterval); }, encodeBoard : function() { var boardData = arguments.callee.$.encodeBoard.call(this); return boardData; }, startRound : function() { var that = this; }, endRound : function(success) { this.elapsedTime = 0; clearInterval(this.startInterval); var target = this.captureTile.target; this.captureTile.target = null; var token = this.createToken(target.id, target.color); this.targetTile = null; this.activeTile = null; this.isActive = false; this.activeBidder = null; for (var i = 0; i < this.moveOptions.length; ++i) { this.moveOptions[i] = null; } this.render(); this.init(); }, showPossible : function() { return; }, startGame : function() { var that = this; this.isActive = false; this.captureTileIndex = Math.floor(Math.random()*this.targets.length); this.activeTarget = this.targets[this.captureTileIndex]; this.targets.splice(this.captureTileIndex, 1); var t = this.activeTarget; for (var j = 0; j < this.tiles.length; ++j) { var ti = this.tiles[j]; if (ti.targetId === t.id) { ti.target = t; this.captureTile = ti; break; } } this.render(); this.solution = null; this.simulateMove(); this.speed = 500; }, simulateMove : function() { var that = this; if (!that.solution) { that.solution = that.solve(); } var from = null; var to = null; var mover = null; if (that.solution) { if (that.solution.length == 0) { return; } var move = that.solution.splice(0, 1)[0]; from = that.tiles[move.f]; to = that.tiles[move.t]; mover = move.m; this.activeTile = from; that.showPossible(); this.pastMoves.push(move); this.speed = 500; } else { // Move pieces at random... var pieceIndex = Math.floor(Math.random()*4); var moveOption = null; that.activeTile = that.tiles[that.movers[pieceIndex].tileIndex]; that.showPossible(); do { var moveIndex = Math.floor(Math.random()*4); moveOption = that.moveOptions[moveIndex]; } while (!moveOption); from = that.activeTile; to = moveOption.endTile; mover = that.movers[pieceIndex]; this.speed = 50; } this.render(); if (from.piece != mover) { _alert('wtf'); from.piece = mover; that.render(); that.simulateMove(); return; } this.moveMover(mover, from, to, this.speed, function() { that.simulateMove();} ); } }); window['demoModeGameboard'] = demoModeGameboard; })();
nbclark/bounding-bandits
bb.demomode.js
JavaScript
mit
4,865
/*global describe, beforeEach, it*/ 'use strict'; var path = require('path'); var helpers = require('yeoman-generator').test; describe('statik generator', function () { beforeEach(function (done) { helpers.testDirectory(path.join(__dirname, 'temp'), function (err) { if (err) { return done(err); } this.app = helpers.createGenerator('statik:app', [ '../../app' ]); done(); }.bind(this)); }); it('creates expected files', function (done) { var expected = [ // add files you expect to exist here. '.jshintrc', '.editorconfig' ]; helpers.mockPrompt(this.app, { 'someOption': true }); this.app.options['skip-install'] = true; this.app.run({}, function () { helpers.assertFiles(expected); done(); }); }); });
balintgaspar/generator-statik
test/test-creation.js
JavaScript
mit
965
<?php namespace AppBundle\Repository; /** * MsvTConsecutivoRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class MsvTConsecutivoRepository extends \Doctrine\ORM\EntityRepository { //Obtiene el maximo consecutivo disponible según la sede operativa public function getLastBySede($idOrganismoTransito) { $em = $this->getEntityManager(); $dql = "SELECT MAX(c.consecutivo) AS consecutivo, c.id FROM AppBundle:MsvTConsecutivo c WHERE c.organismoTransito = :idOrganismoTransito AND c.estado = :estado GROUP BY c.organismoTransito"; $consulta = $em->createQuery($dql); $consulta->setParameters(array( 'idOrganismoTransito' => $idOrganismoTransito, 'estado' => 'DISPONIBLE', )); return $consulta->getOneOrNullResult(); } public function getBySede($identificacionUsuario) { $em = $this->getEntityManager(); $dql = "SELECT msc FROM AppBundle:MsvTConsecutivo msc, UsuarioBundle:Usuario u, AppBundle:MpersonalFuncionario mpf WHERE u.identificacion = :identificacionUsuario AND u.ciudadano = mpf.ciudadano AND mpf.sedeOperativa = msc.sedeOperativa AND msc.activo = true"; $consulta = $em->createQuery($dql); $consulta->setParameters(array( 'identificacionUsuario' => $identificacionUsuario, )); return $consulta->getResult(); } } /* SELECT consecutivo FROM msv_t_consecutivo, usuario, mpersonal_funcionario WHERE usuario.identificacion=2222 AND usuario.ciudadano_id = mpersonal_funcionario.ciudadano_id AND mpersonal_funcionario.sede_operativa_id = msv_t_consecutivo.sede_operativa_id AND msv_t_consecutivo.consecutivo = 12312300000000000000 */
edosgn/colossus-sit
src/AppBundle/Repository/MsvTConsecutivoRepository.php
PHP
mit
1,887
var gulp = require('gulp'), nodemon = require('gulp-nodemon'), plumber = require('gulp-plumber'), livereload = require('gulp-livereload'), sass = require('gulp-sass'); gulp.task('sass', function () { gulp.src('./public/stylesheets/*.scss') .pipe(plumber()) .pipe(sass()) .pipe(gulp.dest('./public/stylesheets')) .pipe(livereload()); }); gulp.task('watch', function() { gulp.watch('./public/stylesheets/*.scss', ['sass']); }); gulp.task('develop', function () { livereload.listen(); nodemon({ script: 'bin/www', ext: 'js coffee jade', stdout: false }).on('readable', function () { this.stdout.on('data', function (chunk) { if(/^Express server listening on port/.test(chunk)){ livereload.changed(__dirname); } }); this.stdout.pipe(process.stdout); this.stderr.pipe(process.stderr); }); }); gulp.task('default', [ 'sass', 'develop', 'watch' ]);
draptik/rpi-temperature-website
gulpfile.js
JavaScript
mit
936
<?php /** * aPage filter form base class. * * @package symfony * @subpackage filter * @author Your name here * @version SVN: $Id: sfDoctrineFormFilterGeneratedTemplate.php 29570 2010-05-21 14:49:47Z Kris.Wallsmith $ */ abstract class BaseaPageFormFilter extends BaseFormFilterDoctrine { public function setup() { $this->setWidgets(array( 'slug' => new sfWidgetFormFilterInput(), 'template' => new sfWidgetFormFilterInput(), 'view_is_secure' => new sfWidgetFormChoice(array('choices' => array('' => 'yes or no', 1 => 'yes', 0 => 'no'))), 'view_guest' => new sfWidgetFormChoice(array('choices' => array('' => 'yes or no', 1 => 'yes', 0 => 'no'))), 'edit_admin_lock' => new sfWidgetFormChoice(array('choices' => array('' => 'yes or no', 1 => 'yes', 0 => 'no'))), 'view_admin_lock' => new sfWidgetFormChoice(array('choices' => array('' => 'yes or no', 1 => 'yes', 0 => 'no'))), 'published_at' => new sfWidgetFormFilterDate(array('from_date' => new sfWidgetFormDate(), 'to_date' => new sfWidgetFormDate())), 'archived' => new sfWidgetFormChoice(array('choices' => array('' => 'yes or no', 1 => 'yes', 0 => 'no'))), 'admin' => new sfWidgetFormChoice(array('choices' => array('' => 'yes or no', 1 => 'yes', 0 => 'no'))), 'author_id' => new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('Author'), 'add_empty' => true)), 'deleter_id' => new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('Deleter'), 'add_empty' => true)), 'engine' => new sfWidgetFormFilterInput(), 'created_at' => new sfWidgetFormFilterDate(array('from_date' => new sfWidgetFormDate(), 'to_date' => new sfWidgetFormDate(), 'with_empty' => false)), 'updated_at' => new sfWidgetFormFilterDate(array('from_date' => new sfWidgetFormDate(), 'to_date' => new sfWidgetFormDate(), 'with_empty' => false)), 'lft' => new sfWidgetFormFilterInput(), 'rgt' => new sfWidgetFormFilterInput(), 'level' => new sfWidgetFormFilterInput(), 'a_search_documents_list' => new sfWidgetFormDoctrineChoice(array('multiple' => true, 'model' => 'aSearchDocument')), 'categories_list' => new sfWidgetFormDoctrineChoice(array('multiple' => true, 'model' => 'aCategory')), )); $this->setValidators(array( 'slug' => new sfValidatorPass(array('required' => false)), 'template' => new sfValidatorPass(array('required' => false)), 'view_is_secure' => new sfValidatorChoice(array('required' => false, 'choices' => array('', 1, 0))), 'view_guest' => new sfValidatorChoice(array('required' => false, 'choices' => array('', 1, 0))), 'edit_admin_lock' => new sfValidatorChoice(array('required' => false, 'choices' => array('', 1, 0))), 'view_admin_lock' => new sfValidatorChoice(array('required' => false, 'choices' => array('', 1, 0))), 'published_at' => new sfValidatorDateRange(array('required' => false, 'from_date' => new sfValidatorDateTime(array('required' => false, 'datetime_output' => 'Y-m-d 00:00:00')), 'to_date' => new sfValidatorDateTime(array('required' => false, 'datetime_output' => 'Y-m-d 23:59:59')))), 'archived' => new sfValidatorChoice(array('required' => false, 'choices' => array('', 1, 0))), 'admin' => new sfValidatorChoice(array('required' => false, 'choices' => array('', 1, 0))), 'author_id' => new sfValidatorDoctrineChoice(array('required' => false, 'model' => $this->getRelatedModelName('Author'), 'column' => 'id')), 'deleter_id' => new sfValidatorDoctrineChoice(array('required' => false, 'model' => $this->getRelatedModelName('Deleter'), 'column' => 'id')), 'engine' => new sfValidatorPass(array('required' => false)), 'created_at' => new sfValidatorDateRange(array('required' => false, 'from_date' => new sfValidatorDateTime(array('required' => false, 'datetime_output' => 'Y-m-d 00:00:00')), 'to_date' => new sfValidatorDateTime(array('required' => false, 'datetime_output' => 'Y-m-d 23:59:59')))), 'updated_at' => new sfValidatorDateRange(array('required' => false, 'from_date' => new sfValidatorDateTime(array('required' => false, 'datetime_output' => 'Y-m-d 00:00:00')), 'to_date' => new sfValidatorDateTime(array('required' => false, 'datetime_output' => 'Y-m-d 23:59:59')))), 'lft' => new sfValidatorSchemaFilter('text', new sfValidatorInteger(array('required' => false))), 'rgt' => new sfValidatorSchemaFilter('text', new sfValidatorInteger(array('required' => false))), 'level' => new sfValidatorSchemaFilter('text', new sfValidatorInteger(array('required' => false))), 'a_search_documents_list' => new sfValidatorDoctrineChoice(array('multiple' => true, 'model' => 'aSearchDocument', 'required' => false)), 'categories_list' => new sfValidatorDoctrineChoice(array('multiple' => true, 'model' => 'aCategory', 'required' => false)), )); $this->widgetSchema->setNameFormat('a_page_filters[%s]'); $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema); $this->setupInheritance(); parent::setup(); } public function addASearchDocumentsListColumnQuery(Doctrine_Query $query, $field, $values) { if (!is_array($values)) { $values = array($values); } if (!count($values)) { return; } $query ->leftJoin($query->getRootAlias().'.aPageToASearchDocument aPageToASearchDocument') ->andWhereIn('aPageToASearchDocument.a_search_document_id', $values) ; } public function addCategoriesListColumnQuery(Doctrine_Query $query, $field, $values) { if (!is_array($values)) { $values = array($values); } if (!count($values)) { return; } $query ->leftJoin($query->getRootAlias().'.aPageToCategory aPageToCategory') ->andWhereIn('aPageToCategory.category_id', $values) ; } public function getModelName() { return 'aPage'; } public function getFields() { return array( 'id' => 'Number', 'slug' => 'Text', 'template' => 'Text', 'view_is_secure' => 'Boolean', 'view_guest' => 'Boolean', 'edit_admin_lock' => 'Boolean', 'view_admin_lock' => 'Boolean', 'published_at' => 'Date', 'archived' => 'Boolean', 'admin' => 'Boolean', 'author_id' => 'ForeignKey', 'deleter_id' => 'ForeignKey', 'engine' => 'Text', 'created_at' => 'Date', 'updated_at' => 'Date', 'lft' => 'Number', 'rgt' => 'Number', 'level' => 'Number', 'a_search_documents_list' => 'ManyKey', 'categories_list' => 'ManyKey', ); } }
samura/asandbox
lib/filter/doctrine/apostrophePlugin/base/BaseaPageFormFilter.class.php
PHP
mit
7,433
package com.charmyin.cmstudio.basic.authorize.service; import java.util.List; import org.springframework.stereotype.Service; import com.charmyin.cmstudio.basic.authorize.vo.TreeItem; @Service public interface TreeItemService { List<TreeItem> getOrganizationWithUsers(int organizationId); }
Feolive/EmploymentWebsite
src/main/java/com/charmyin/cmstudio/basic/authorize/service/TreeItemService.java
Java
mit
300
'use strict'; const loadRule = require('../utils/load-rule'); const ContextBuilder = require('../utils/contextBuilder'); const RequestBuilder = require('../utils/requestBuilder'); const AuthenticationBuilder = require('../utils/authenticationBuilder'); const ruleName = 'require-mfa-once-per-session'; describe(ruleName, () => { let context; let rule; let user; describe('With only a login prompt completed', () => { beforeEach(() => { rule = loadRule(ruleName); const request = new RequestBuilder().build(); const authentication = new AuthenticationBuilder().build(); context = new ContextBuilder() .withRequest(request) .withAuthentication(authentication) .build(); }); it('should set a multifactor provider', (done) => { rule(user, context, (err, u, c) => { expect(c.multifactor.provider).toBe('any'); expect(c.multifactor.allowRememberBrowser).toBe(false); done(); }); }); }); describe('With a login and MFA prompt completed', () => { beforeEach(() => { rule = loadRule(ruleName); const request = new RequestBuilder().build(); const authentication = new AuthenticationBuilder() .withMethods([ { name: 'pwd', timestamp: 1434454643024 }, { name: 'mfa', timestamp: 1534454643881 } ]) .build(); context = new ContextBuilder() .withRequest(request) .withAuthentication(authentication) .build(); }); it('should not set a multifactor provider', (done) => { rule(user, context, (err, u, c) => { expect(c.multifactor).toBe(undefined); done(); }); }); }); });
auth0/rules
test/rules/require-mfa-once-per-session.test.js
JavaScript
mit
1,787
# frozen_string_literal: true require 'numbers_and_words/strategies/figures_converter/languages' require 'numbers_and_words/strategies/figures_converter/options' require 'numbers_and_words/strategies/figures_converter/decorators' module NumbersAndWords module Strategies module FiguresConverter class Base attr_accessor :options, :figures, :translations, :language, :decorator def initialize(figures, options = {}) @figures = figures.reverse @decorator = Decorators.factory(self, options) @options = Options::Proxy.new(self, options) @translations = Translations.factory @language = Languages.factory(self) end def run around { language.words } end private def around(&block) decorator.run(&block) end end end end end
kslazarev/numbers_and_words
lib/numbers_and_words/strategies/figures_converter.rb
Ruby
mit
883
using WebPlatform.Core.Data; namespace WebPlatform.Tests.Core { /// <summary> /// Defines the test entity. /// </summary> public class TestEntity : Entity { /// <summary> /// Gets or sets the caption. /// </summary> public string Caption { get; set; } } }
urahnung/webplatform
src/Tests/Core/TestEntity.cs
C#
mit
336
let base_x = {} let dictionaries = {} /// @name Encode /// @description Takes a large number and converts it to a shorter encoded string style string i.e. 1TigYx /// @arg {number} input The number to be encoded to a string /// @arg {number, string} dictionary ['DICTIONARY_52'] - The dictionary to use for the encoding /// @arg {number} padding [0] - The padding (minimum length of the generated string) base_x.encodeNumber = (input, padding, dictionary) => { let result = [] dictionary = base_x.getDictionary(dictionary) let base = dictionary.length let exponent = 1 let remaining = parseInt(input) let a, b, c, d a = b = c = d = 0 padding = padding || 0 // check if padding is being used if (padding) { remaining += Math.pow(base, padding) } // generate the encoded string while (true) { a = Math.pow(base, exponent) // 16^1 = 16 b = remaining % a // 119 % 16 = 7 | 112 % 256 = 112 c = Math.pow(base, exponent - 1) d = b / c result.push(dictionary[parseInt(d)]) remaining -= b // 119 - 7 = 112 | 112 - 112 = 0 if (remaining === 0) { break } exponent++ } return result.reverse().join('') } /// @name Encode /// @description Decodes a shortened encoded string back into a number /// @arg {number} input - The encoded string to be decoded /// @arg {number, string} dictionary ['DICTIONARY_52'] - The dictionary to use for the encoding /// @arg {number} padding [0] - The padding (minimum length of the generated string) to use base_x.decodeNumber = (input, padding, dictionary) => { let chars = input.split('').reverse() dictionary = base_x.getDictionary(dictionary) let base = dictionary.length let result = 0 let map = {} let exponent = 0 padding = padding || 0 // create a map lookup for (let i = 0; i < base; i++) { map[dictionary[i]] = i } // generate the number for (let i = 0; i < input.length; i++) { result += Math.pow(base, exponent) * map[chars[i]] exponent++ } // check if padding is being used if (padding) { result -= Math.pow(base, padding) } return result } /// @name getDictionary /// @description Gets a dictionary or returns the default dictionary of 'DICTIONARY_52' /// @arg {number, string} dictionary ['DICTIONARY_52'] - The dictionary to get /// @returns {array} base_x.getDictionary = (dictionary) => { return dictionaries[dictionary] || dictionaries['DICTIONARY_' + dictionary] || dictionaries.DICTIONARY_52 } /// @name addDictionaries /// @description Adds a new dictionary /// @arg {string} name - The name of the dictionary to add /// @arg {string, array} dictionary - The dictionary to use as an array of characters base_x.addDictionary = (name, dictionary) => { if (typeof dictionary === 'string') { dictionary = dictionary.split('') } dictionaries[name] = dictionary return } let numbers = '0123456789' let lower = 'abcdefghijklmnopqrstuvwxyz' let upper = lower.toUpperCase() // add default dictionarys // numbers and A-F only base_x.addDictionary('DICTIONARY_16', numbers + upper.slice(0, 7) ) // numbers and uppercase letters A-Z base_x.addDictionary('DICTIONARY_32', (numbers + upper).replace(/[0ilo]/gi, '') ) base_x.addDictionary('letters', upper + lower) // numbers, uppercase and lowercase B-Z minus vowels base_x.addDictionary('DICTIONARY_52', (numbers + upper).replace(/[aeiou]/gi, '') ) // numbers, uppercase and lowercase A-Z base_x.addDictionary('DICTIONARY_62', numbers + upper + lower ) // numbers, uppercase and lowercase A-Z and ~!@#$%^& (minus 0,o,O,1,i,I,l,L useful to generate passwords) base_x.addDictionary('DICTIONARY_PASS', (numbers + upper + lower + '~!@#$%^&').replace(/[01oil]/gi, '') ) // numbers, uppercase and lowercase A-Z and ~!@#$%^& (useful to generate passwords) base_x.addDictionary('DICTIONARY_70', numbers + upper + lower + '~!@#$%^&' ) // numbers, uppercase and lowercase A-Z and +"~!@#$%&*/|()=?'[]{}-_:.,; base_x.addDictionary('DICTIONARY_89', numbers + upper + lower + '+"@*#%&/|()=?~[]{}$-_.:,;<>' ) import crypto from 'crypto' base_x.encode = (data, padding = 4, dictionary = 'letters') => { let hash = crypto .createHash('md5') .update(JSON.stringify(data), 'utf8') .digest('hex') .split('') .reduce((prev, next) => prev + next.charCodeAt(), 0) return base_x.encodeNumber(hash, padding, dictionary) } let base = global.base_x = global.base_x || base_x export default base
tjbenton/docs
packages/docs-theme-default/src/base-x.js
JavaScript
mit
4,443
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Qoollo.PerformanceCounters { /// <summary> /// Контейнер стандартных счётчиков /// </summary> public static class PerfCountersDefault { private static CounterFactory _default; private static SingleInstanceCategory _defaultCategory; private static readonly object _syncObj = new object(); /// <summary> /// Фабрика для NullCounters /// </summary> public static NullCounters.NullCounterFactory NullCounterFactory { get { return NullCounters.NullCounterFactory.Instance; } } /// <summary> /// Creates DefaultFactory singleton /// </summary> private static void CreateDefaultFactory() { if (_default == null) { lock (_syncObj) { if (_default == null) _default = new InternalCounters.InternalCounterFactory(); } } } /// <summary> /// Creates DefaultCategory from DefaultFactory /// </summary> private static void CreateDefaultCategory() { if (_defaultCategory == null) { lock (_syncObj) { if (_default == null) _default = new InternalCounters.InternalCounterFactory(); if (_defaultCategory == null) _defaultCategory = _default.CreateSingleInstanceCategory("DefaultCategory", "Default category"); } } } /// <summary> /// Инстанс фабрики счётчиков. /// По умолчанию тут InternalCounterFactory /// </summary> public static CounterFactory DefaultFactory { get { if (_default == null) CreateDefaultFactory(); return _default; } } /// <summary> /// Default category to create counters in place. /// Be careful: some CounterFactories are not support this approach. /// </summary> public static SingleInstanceCategory DefaultCategory { get { if (_defaultCategory == null) CreateDefaultCategory(); return _defaultCategory; } } /// <summary> /// Задать новое значение инстанса фабрики счётчиков /// </summary> /// <param name="factory">Фабрика счётчиков</param> public static void SetDefaultFactory(CounterFactory factory) { if (factory == null) factory = new InternalCounters.InternalCounterFactory(); CounterFactory oldVal = null; lock (_syncObj) { oldVal = System.Threading.Interlocked.Exchange(ref _default, factory); System.Threading.Interlocked.Exchange(ref _defaultCategory, null); } if (oldVal != null) oldVal.Dispose(); } /// <summary> /// Сбросить значение фабрики счётчиков. /// Возвращает InternalCounterFactory. /// </summary> public static void ResetDefaultFactory() { SetDefaultFactory(new InternalCounters.InternalCounterFactory()); } /// <summary> /// Загрузить фабрику счётчиков из файла конфигурации /// </summary> /// <param name="sectionName">Имя секции в файле конфигурации</param> public static void LoadDefaultFactoryFromAppConfig(string sectionName = "PerfCountersConfigurationSection") { if (sectionName == null) throw new ArgumentNullException("sectionName"); var counters = PerfCountersInstantiationFactory.CreateCounterFactoryFromAppConfig(sectionName); SetDefaultFactory(counters); } } }
qoollo/performance-counters
src/Qoollo.PerformanceCounters/PerfCountersDefault.cs
C#
mit
4,487
<?php /* * This file is part of the Fidry\AliceDataFixtures package. * * (c) Théo FIDRY <theo.fidry@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Fidry\AliceDataFixtures\Bridge\Doctrine\PhpCrDocument; use Doctrine\ODM\PHPCR\Mapping\Annotations\Document; use Doctrine\ODM\PHPCR\Mapping\Annotations\Id; /** * @Document() * * @author Théo FIDRY <theo.fidry@gmail.com> */ class Dummy { /** * @Id() */ public $id; }
furtadodiegos/projeto_cv
vendor/theofidry/alice-data-fixtures/fixtures/Bridge/Doctrine/PhpCrDocument/Dummy.php
PHP
mit
577
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sneaking { class Sneaking { static void Main() { var roomSize = int.Parse(Console.ReadLine()); char[][] room = new char[roomSize][]; for (int row = 0; row < roomSize; row++) { room[row] = Console.ReadLine().ToCharArray(); } var commands = Console.ReadLine().ToCharArray(); //initial positions int samCurrentRow = 0; int samCurrentCol = 0; int nikoCurrentRow = 0; int nikoCurrentCol = 0; for (int row = 0; row < room.Length; row++) { if (room[row].Contains('S')) { samCurrentRow = row; samCurrentCol = Array.IndexOf(room[row], 'S'); } if (room[row].Contains('N')) { nikoCurrentRow = row; nikoCurrentCol = Array.IndexOf(room[row], 'N'); } } for (int move = 0; move < commands.Length; move++) { var samCommand = commands[move]; EnemyMove(room); if (IsSamKilled(room, samCurrentRow, samCurrentCol)) { Console.WriteLine($"Sam died at {samCurrentRow}, {samCurrentCol}"); PrintCuurentRoomState(room); break; } //sam moves switch (samCommand) { case 'U': room[samCurrentRow][samCurrentCol] = '.'; room[samCurrentRow - 1][samCurrentCol] = 'S'; samCurrentRow--; break; case 'D': room[samCurrentRow][samCurrentCol] = '.'; room[samCurrentRow + 1][samCurrentCol] = 'S'; samCurrentRow++; break; case 'L': room[samCurrentRow][samCurrentCol] = '.'; room[samCurrentRow][samCurrentCol - 1] = 'S'; samCurrentCol--; break; case 'R': room[samCurrentRow][samCurrentCol] = '.'; room[samCurrentRow][samCurrentCol + 1] = 'S'; samCurrentCol++; break; } //check if sam kills if (samCurrentRow == nikoCurrentRow) { Console.WriteLine($"Nikoladze killed!"); room[nikoCurrentRow][nikoCurrentCol] = 'X'; PrintCuurentRoomState(room); break; } } } private static void PrintCuurentRoomState(char[][] room) { for (int row = 0; row < room.Length; row++) { Console.WriteLine(string.Join("", room[row])); } } private static bool IsSamKilled(char[][] room, int samCurrentRow, int samCurrentCol) { bool isKilled = false; if (room[samCurrentRow].Contains('b')) { var enemyCol = Array.IndexOf(room[samCurrentRow], 'b'); if (samCurrentCol >= enemyCol) { room[samCurrentRow][samCurrentCol] = 'X'; isKilled = true; } } else if (room[samCurrentRow].Contains('d')) { var enemyCol = Array.IndexOf(room[samCurrentRow], 'd'); if (samCurrentCol <= enemyCol) { room[samCurrentRow][samCurrentCol] = 'X'; isKilled = true; } } return isKilled; } private static void EnemyMove(char[][] room) { for (int row = 0; row < room.Length; row++) { for (int col = 0; col < room[row].Length; col++) { var currentValue = room[row][col]; if (currentValue == 'b') { if (col < room[row].Length - 1) { room[row][col] = '.'; room[row][col + 1] = 'b'; } else { room[row][col] = 'd'; } break; } else if (currentValue == 'd') { if (col > 0) { room[row][col] = '.'; room[row][col - 1] = 'd'; } else { room[row][col] = 'b'; } break; } } } } } }
radoikoff/SoftUni
C Sharp Advanced/Adv 9 The Exam/Task2/Sneaking.cs
C#
mit
5,315
from wodcraft.api import resources # Routing def map_routes(api): api.add_resource(resources.Activity, '/api/v1.0/activities/<int:id>', endpoint='activity') api.add_resource(resources.Activities, '/api/v1.0/activities', endpoint='activities') api.add_resource(resources.Score, '/api/v1.0/scores/<int:id>', endpoint='score') api.add_resource(resources.Scores, '/api/v1.0/scores', endpoint='scores') api.add_resource(resources.Tag, '/api/v1.0/tags/<int:id>', endpoint='tag') api.add_resource(resources.Tags, '/api/v1.0/tags', endpoint='tags') api.add_resource(resources.User, '/api/v1.0/users/<int:id>', endpoint='user') api.add_resource(resources.Users, '/api/v1.0/users', endpoint='users')
the-gigi/wod-craft-server
wodcraft/api/routes.py
Python
mit
1,064
package html import "fmt" const ( NodeError NodeType = "error" NodeText NodeType = "text" NodeElement NodeType = "element" NodeComment NodeType = "comment" ) type NodeType string type Node struct { Parent *Node FirstChild *Node LastChild *Node PrevSibling *Node NextSibling *Node Type NodeType Tag string Attributes map[string]string TextContent string } func (n *Node) String() string { return fmt.Sprintf( "{Tag:%q, Parent:%p, FirstChild:%p, LastChild:%p, PrevSibling:%p, NextSibling:%p}", n.Tag, n.Parent, n.FirstChild, n.LastChild, n.PrevSibling, n.NextSibling, ) } func (n *Node) AddChild(c *Node) { c.Parent = c if n.FirstChild == nil { n.FirstChild = c n.LastChild = c return } n.LastChild.NextSibling = c c.PrevSibling = n.LastChild n.LastChild = c }
lysrt/bro
html/node.go
GO
mit
829