code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
๏ปฟusing Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Horus.Models;
namespace Horus.Data
{
public class ApplicationDbContext : IdentityDbContext<UserApplication>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
}
| HackBiacGDLucios/SafeLand | Horus/src/Horus/Data/ApplicationDbContext.cs | C# | mit | 497 |
<?php
$lang['str_herb_name'] = "์ฝ์ด๋ช
";
$lang['str_latin_name'] = "ํ๋ช
";
$lang["str_part"] = "์ฌ์ฉ ๋ถ์";
$lang["str_nature"] = "์ฑ์ง";
$lang["str_usage"] = "์ฌ์ฉ ๋ฐฉ๋ฒ";
$lang["str_taste"] = "๋ง";
$lang["str_effect"] = "ํจ๊ณผ";
$lang["str_compound"] = "์ ํจ์ฑ๋ถ";
$lang["str_side_effect"] = "์๋ ค์ง ๋ถ์์ฉ";
$lang["str_symptom"] = "๊ฐ์ ์ฆ์";
$lang["str_symptom_description"] = "๋์์ง ์ ์๋ค๊ณ ์๋ ค์ง";
$lang["str_caution"] = "์ฃผ์์ฌํญ";
$lang["str_nature_organ"] = "์ฑ์ง/์ฐ๊ฒฐ ์ฅ๊ธฐ";
$lang["str_herb_summary"] = "์์ฝ";
$lang["str_herb_description"] = "์ค๋ช
";
$lang["str_herb_experience"] = "์ฌ์ฉ ๊ฒฝํ";
$lang['str_title'] = '์ ๋ชฉ';
$lang['str_description'] = '์ค๋ช
';
$lang['str_detail_info_title'] = "์์ธ ์ ๋ณด ์
๋ ฅ";
$lang['str_comment_placeholder'] = "๋๊ธ์ ๋จ๊ฒจ์ฃผ์ธ์.";
$lang['str_existing_translations'] = '๋ฒ์ญ';
$lang["str_no_result_title"] = "์ฐ๊ด๋ ์ฝ์ด๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค.";
$lang["str_no_result_message"] = "๊ฒ์๋๊ตฌ๋ฅผ ์ฌ์ฉํด ๋ณด๋ค ์ ๊ตํ ๊ฒ์์ ํด๋ณด์ธ์. ์๋๋ฉด, ๋ค๋ฅธ ๋จ์ด๋ ์ข ๋ ์ผ๋ฐ์ ์ธ ๋จ์ด, ๋๋ ์ข ๋ ์ ์ ์์ ๋จ์ด๋ฅผ ์ฌ์ฉํด๋ณด์ธ์.";
$lang["str_username"] = "์ฌ์ฉ์ ์ด๋ฆ";
$lang["str_password"] = "๋น๋ฐ๋ฒํธ";
$lang["str_email"] = "์ด๋ฉ์ผ";
$lang["str_signin"] = "๋ก๊ทธ์ธ";
$lang["str_cancel"] = "์ทจ์";
$lang["str_add"] = "์ถ๊ฐ";
$lang['str_next'] = "๋ค์";
$lang['str_done'] = "์๋ฃ";
$lang['str_save'] = "์ ์ฅ";
$lang["str_asia"] = "์์์";
$lang["str_europe"] = "์ ๋ฝ";
$lang["str_north_america"] = "๋ถ์๋ฉ๋ฆฌ์นด";
$lang["str_south_america"] = "๋จ์๋ฉ๋ฆฌ์นด";
$lang["str_america"] = "์๋ฉ๋ฆฌ์นด";
$lang["str_africa"] = "์ํ๋ฆฌ์นด";
$lang["str_oceania"] = "์ค์ธ์๋์";
$lang["str_china"] = "์ค๊ตญ";
$lang["str_india"] = "์ธ๋";
$lang["str_korea"] = "ํ๊ตญ";
$lang["str_philippines"] = "ํ๋ฆฌํ";
$lang["str_france"] = "ํ๋์ค";
$lang['str_united_states'] = "๋ฏธ๊ตญ";
$lang['str_mexico'] = "๋ฉ์์ฝ";
$lang['str_brazil'] = "๋ธ๋ผ์ง";
$lang['str_chile'] = "์น ๋ ";
$lang['str_newzealand'] = "๋ด์ง๋๋";
$lang['str_australia'] = "ํธ์ฃผ";
$lang['str_egypt'] = "์ด์งํธ";
$lang['str_ghana'] = "๊ฐ๋";
$lang["str_user_general"] = "์ผ๋ฐ";
// $lang["str_user_advanced"] = "๊ณ ๊ธ ์ ์ ";
$lang["str_user_company"] = "๊ธฐ์
/์ ํต";
$lang["str_user_farm"] = "๋์ฅ/์์ฐ";
$lang["str_months"] = "๊ฐ์";
$lang["str_duplicate"] = '์ค๋ณต';
$lang["str_main_search_bar_placeholder"] = "์ ์ธ๊ณ์ ์ฝ์ด ์ด๋ฆ, ํจ๊ณผ, ์ง์ญ ๋ฑ์ ๊ฒ์ํด๋ณด์ธ์.";
$lang["str_error_try_again"] = "์๋ฌ๊ฐ ๋ฐ์ํ์ต๋๋ค. ๋ค์ ์๋ํด์ฃผ์ธ์.";
$lang["str_new_herbs"] = "์๋ก ์ถ๊ฐ๋ ์ฝ์ด";
$lang["str_recent_edit_herbs"] = "์ต๊ทผ ์์ ๋ ์ฝ์ด";
$lang["str_address"] = "์ฃผ์";
$lang["str_address_province"] = "์/๋";
$lang["str_address_province_description"] = "์/๋ (์: ๊ฒฝ๊ธฐ๋)";
$lang["str_address_city"] = "์ง์ญ/๋์";
$lang["str_address_city_description"] = "์ง์ญ/๋์ (์: ์ฑ๋จ์)";
$lang["str_address_address1_description"] = "๊ฑด๋ฌผ ๋ฒ์ง, ์ด๋ฆ, ๋๋ก๋ช
์ฃผ์";
$lang["str_address_address2_description"] = "์ํํธ, ํธ์ค ๋ฑ (์ ํ์ฌํญ)";
$lang["str_address_zip"] = "์ฐํธ๋ฒํธ";
$lang["str_address_country"] = "๊ตญ๊ฐ";
$lang["str_address_country_description"] = "๊ตญ๊ฐ๋ฅผ ์ ํํ์ธ์";
$lang["str_phone_number"] = "์ ํ๋ฒํธ";
$lang["str_phone_code"] = "๊ตญ๊ฐ๋ฒํธ";
$lang["str_phone_number_description"] = "์ฐ๋ฝ ๊ฐ๋ฅํ ์ ํ๋ฒํธ( '-' ์ ์ธ )";
$lang["str_mobile_number"] = "ํด๋์ ํ";
$lang["str_register_submit"] = "๋ฑ๋กํ๊ธฐ";
$lang["str_main_image"] = "๋ํ ์ด๋ฏธ์ง";
$lang["str_upload_image"] = "์ฌ์ง ์
๋ก๋";
$lang['str_remove_image'] = "ํ์ผ ์ญ์ ";
$lang['str_drop_images_here'] = "๋๋๊ทธ & ๋๋กญ์ผ๋ก ์ฌ์ง์ ์ถ๊ฐํ์ธ์.";
$lang['str_drop_images_fallback'] = "๋ฐ์ค๋ฅผ ํด๋ฆญํด ์ด๋ฏธ์ง๋ฅผ ์
๋ก๋ํด ์ฃผ์ธ์. ";
$lang['str_drop_images_here_note'] = "์์๋ฅผ ํด๋ฆญํด๋ ํ์ผ์ ์ถ๊ฐํ ์ ์์ต๋๋ค. 1MB ์ดํ์ ์ด๋ฏธ์ง๋ฅผ ์ฌ๋ ค์ฃผ์ธ์.";
$lang["err_file_max_size_pre"] = "ํ์ผ ์ฉ๋์ด ";
$lang["err_file_max_size_post"] = "์ดํ์ฌ์ผ ํฉ๋๋ค.";
$lang["err_file_max_count_pre"] = "์ด๋ฏธ์ง๋ ์ต๋ ";
$lang["err_file_max_count_post"] = "๊ฐ ๊น์ง ์
๋ก๋ ๊ฐ๋ฅํฉ๋๋ค.";
$lang['str_is_not_found'] = "์(๋ฅผ) ์ฐพ์ ์ ์์ต๋๋ค. ์ง์ ์ถ๊ฐํ๊ณ ๋ฑ๋กํด ๋ณด์ธ์!";
$lang['str_form_error_required'] = "์ด ํญ๋ชฉ์ ๋ฐ๋์ ์
๋ ฅํด์ผ ํฉ๋๋ค.";
$lang['str_form_error_required_select'] = "์ด ํญ๋ชฉ์ ๋ฐ๋์ ์ ํํด์ผ ํฉ๋๋ค.";
$lang['str_form_error_required_image'] = "์ด๋ฏธ์ง๋ฅผ ์
๋ก๋ํด์ผ ํฉ๋๋ค.";
$lang['str_form_error_numeric'] = "์๋ชป๋ ํ์์
๋๋ค. ์ซ์๊ฐ๋ง ์
๋ ฅํ์ค ์ ์์ต๋๋ค.";
$lang['str_harvest_time'] = "์ํ ์๊ธฐ";
$lang['str_organic'] = "์ ๊ธฐ๋ ์ฌ๋ฐฐ";
$lang['str_organic_certified'] = "๊ตญ๊ฐ ์ธ์ฆ ํ๋";
$lang['str_processing_method'] = "๊ฐ๊ณต ๋ฐฉ๋ฒ";
$lang['str_sowing_time'] = "ํ์ข
์๊ธฐ";
$lang['str_cultivation_time'] = "์ฌ๋ฐฐ ๊ธฐ๊ฐ";
$lang['str_growing_area'] = "๊ฒฝ์ ๋ฉด์ ";
$lang['str_min_order'] = "์ต์ ๊ตฌ๋งค ์๋";
$lang['str_price_per_kilo'] = "Kg ๋น ๊ฐ๊ฒฉ";
$lang['str_production_volume'] = "์ด๋ฒ ์์ฐ๋";
$lang['str_production_volume_kilo'] = "์ด๋ฒ ์์ฐ๋(Kg)";
$lang['str_annual_production_volume'] = "์ฐ๊ฐ ์์ฐ๋";
$lang['str_annual_production_volume_kilo'] = "์ฐ๊ฐ ์์ฐ๋(Kg)";
$lang['str_in_stock_volume'] = "์ฌ๊ณ ๋ฌผ๋";
$lang['str_in_stock_volume_kilo'] = "์ฌ๊ณ ๋ฌผ๋(Kg)";
$lang['str_product_image'] = "์ํ ์ฌ์ง";
$lang['str_view_product'] = "์ํ ๋ณด๊ธฐ";
$lang["str_show_detail"] = "์์ธํ ๋ณด๊ธฐ";
$lang["str_contact"] = "๋ฌธ์ํ๊ธฐ";
$lang["str_add_to_favorites"] = "๊ด์ฌ ์ฝ์ด ์ถ๊ฐ";
$lang['str_more_result'] = "๊ฒฐ๊ณผ ๋ ๋ณด๊ธฐ";
$lang['str_search_results'] = "๊ฒ์ ๊ฒฐ๊ณผ";
$lang['str_herb_result'] = "์ฝ์ด";
$lang['str_farm_result'] = "๋์ฅ";
$lang['str_recipe_result'] = "๋ ์ํผ";
$lang['str_average_contain'] = "ํ๊ท ํจ์ ๋";
$lang['str_images'] = "์ฌ์ง";
$lang['str_images_description'] = "ํด๋น ์ฝ์ด์ ์ฌ์ง์ ์ฌ๋ ค์ฃผ์ธ์.";
$lang['str_add_images_description'] = "์ฝ์ด์ ์ฌ์ง์ ์ถ๊ฐํ์ค ์ ์์ต๋๋ค.";
$lang['str_share_experience'] = "์ด ์ฝ์ด์ ๋ํ ๊ฒฝํ๋ด์ ๋๋์ด๋ณด์ธ์!";
$lang['str_post'] = "์ฌ๋ฆฌ๊ธฐ";
$lang['str_press_enter']= "'Enter' ํค๋ฅผ ๋๋ฌ ๊ฒ์ํ์ธ์.";
$lang['unknown_user'] = "(์ ์ ์๋ ์ ์ )";
$lang['str_login_first'] = "๋ก๊ทธ์ธํ ํ ๊ฒ์ํ ์ ์์ต๋๋ค.";
$lang['str_delete'] = "์ญ์ ";
$lang['str_edit'] = "์์ ";
$lang['str_deleted_post'] = "(์ญ์ ๋ ๊ฒ์๋ฌผ ์
๋๋ค.)";
$lang['str_cultivating_farms'] = "์ฌ๋ฐฐ์ค์ธ ๋์ฅ";
$lang['str_contact_farm'] = "๋์ฅ ๋ฌธ์ํ๊ธฐ";
$lang['str_location'] = "์์น";
$lang['str_farm_reg_date'] = "๋ฑ๋ก์ผ";
$lang['str_farm_est_date'] = "์ค๋ฆฝ์ผ";
$lang['str_click_to_register_herb'] = "์ฝ์ด ๋ฑ๋กํ๊ธฐ";
$lang['str_click_to_add_herb'] = "์ถ๊ฐํ๋ ค๋ฉด ํด๋ฆญํ์ธ์";
$lang['str_edit_profile_image_description'] = "๋์ฅ ๋ก๊ณ ๋ฅผ ๋ณ๊ฒฝํ๋ ค๋ฉด ์ด๋ฏธ์ง๋ฅผ ์
๋ก๋ํ๊ณ ์์ ์ฌํญ์ ์ ์ฅํด ์ฃผ์ธ์.";
$lang['str_basic_information'] = "๊ธฐ๋ณธ ์ ๋ณด";
$lang['str_send'] = "๋ณด๋ด๊ธฐ";
?>
| Tresint/worldherb | application/language/korean/basic_lang.php | PHP | mit | 7,951 |
# souffleur module
module Souffleur
VERSION = '0.1.0'
end
| sebastiaandegeus/souffleur | lib/souffleur/version.rb | Ruby | mit | 60 |
/*
* Wegas
* http://wegas.albasim.ch
*
* Copyright (c) 2013, 2014, 2015 School of Business and Engineering Vaud, Comem
* Licensed under the MIT License
*/
package com.wegas.core.security.persistence;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.JsonView;
import com.wegas.core.persistence.AbstractEntity;
import com.wegas.core.persistence.game.Player;
import com.wegas.core.rest.util.Views;
import javax.persistence.*;
import java.util.*;
////import javax.xml.bind.annotation.XmlTransient;
/**
* @author Francois-Xavier Aeberhard (fx at red-agent.com)
*/
@Entity
@Table(name = "users")
@NamedQueries({
@NamedQuery(name = "User.findUserPermissions", query = "SELECT DISTINCT users FROM User users JOIN users.permissions p WHERE p.value LIKE :instance")
,
@NamedQuery(name = "User.findUsersWithRole", query = "SELECT DISTINCT users FROM User users JOIN users.roles r WHERE r.id = :role_id")
,
@NamedQuery(name = "User.findUserWithPermission", query = "SELECT DISTINCT users FROM User users JOIN users.permissions p WHERE p.value LIKE :permission AND p.user.id =:userId")
})
public class User extends AbstractEntity implements Comparable<User> {
private static final long serialVersionUID = 1L;
/**
*
*/
@Id
@GeneratedValue
private Long id;
/**
*
*/
@OneToMany(mappedBy = "user", cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH} /*, orphanRemoval = true */)
@JsonManagedReference(value = "player-user")
private List<Player> players = new ArrayList<>();
/**
*
*/
@OneToMany(mappedBy = "user", cascade = {CascadeType.ALL}, orphanRemoval = true)
@JsonManagedReference(value = "user-account")
private List<AbstractAccount> accounts = new ArrayList<>();
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "user")
@JsonIgnore
private List<Permission> permissions = new ArrayList<>();
@ManyToMany
@JsonView(Views.ExtendedI.class)
@JoinTable(name = "users_roles",
joinColumns = {
@JoinColumn(name = "users_id", referencedColumnName = "id")},
inverseJoinColumns = {
@JoinColumn(name = "roles_id", referencedColumnName = "id")})
private Set<Role> roles = new HashSet<>();
/**
*
*/
public User() {
}
/**
* @param acc
*/
public User(AbstractAccount acc) {
this.addAccount(acc);
}
@Override
public Long getId() {
return id;
}
@Override
public void merge(AbstractEntity a) {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* @return all user's players
*/
//@XmlTransient
@JsonIgnore
@JsonManagedReference(value = "player-user")
public List<Player> getPlayers() {
return players;
}
/**
* @param players the players to set
*/
@JsonManagedReference(value = "player-user")
public void setPlayers(List<Player> players) {
this.players = players;
}
/**
* @return the accounts
*/
public List<AbstractAccount> getAccounts() {
return accounts;
}
/**
* @param accounts the accounts to set
*/
public void setAccounts(List<AbstractAccount> accounts) {
this.accounts = accounts;
}
/**
* @param account
*/
public final void addAccount(AbstractAccount account) {
this.accounts.add(account);
account.setUser(this);
}
/**
* @return first user account
*/
//@XmlTransient
@JsonIgnore
public final AbstractAccount getMainAccount() {
if (!this.accounts.isEmpty()) {
return this.accounts.get(0);
} else {
return null;
}
}
/**
* Shortcut for getMainAccount().getName();
*
* @return main account name or unnamed if user doesn't have any account
*/
public String getName() {
if (this.getMainAccount() != null) {
return this.getMainAccount().getName();
} else {
return "unnamed";
}
}
/**
* @return the permissions
*/
public List<Permission> getPermissions() {
return this.permissions;
}
/**
* @param permissions the permissions to set
*/
public void setPermissions(List<Permission> permissions) {
this.permissions = permissions;
for (Permission p : this.permissions) {
p.setUser(this);
}
}
public boolean removePermission(Permission permission) {
return this.permissions.remove(permission);
}
/**
* @param permission
* @return true id the permission has successfully been added
*/
public boolean addPermission(Permission permission) {
if (!this.permissions.contains(permission)) {
permission.setUser(this);
return this.permissions.add(permission);
} else {
return false;
}
}
/**
* @return the roles
*/
public Set<Role> getRoles() {
return roles;
}
/**
* @param roles the roles to set
*/
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
/**
* @param role
*/
public void addRole(Role role) {
this.roles.add(role);
}
/**
* strike out this account from the role
*
* @param role
*/
public void removeRole(Role role) {
this.roles.remove(role);
}
@Override
public int compareTo(User o) {
return this.getName().toLowerCase(Locale.ENGLISH).compareTo(o.getName().toLowerCase(Locale.ENGLISH));
}
}
| ghiringh/Wegas | wegas-core/src/main/java/com/wegas/core/security/persistence/User.java | Java | mit | 5,838 |
๏ปฟusing System;
using System.Linq.Expressions;
using Vulpecula.Scripting.Lexer;
namespace Vulpecula.Scripting.Parser.Expressions
{
// Parsing Script
// RelationalExpression
// EqualityExpression "==" RelationalExpression
// EqualityExpression "!=" RelationalExpression
internal class EqualityExpression : ExpressionBase
{
#region Overrides of ExpressionBase
public override void Parse(TokenReader reader)
{
if (!VerifyAheadKeywords(reader, "==", "!="))
{
// Relational
var expr1 = new RelationalExpression();
expr1.Parse(reader);
Children.Add(expr1);
}
else
{
// -> EqualityTail
var expr2 = new EqualityExpressionTail();
expr2.Parse(reader);
Children.Add(expr2);
}
}
public override Expression AsExpressionTree()
{
throw new NotImplementedException();
}
#endregion
}
// "==" RelationalExpression EqualityExpressionTail
// "!=" RelationalExpression EqualityExpressionTail
internal class EqualityExpressionTail : ExpressionBase
{
private int _type = 0;
#region Overrides of ExpressionBase
public override void Parse(TokenReader reader)
{
var token = AssertKeywordOr(reader, "==", "!=");
_type = token.TokenString == "==" ? 0 : 1;
// Relational
var expr1 = new RelationalExpression();
expr1.Parse(reader);
Children.Add(expr1);
// EqualityTail
var expr2 = new EqualityExpressionTail();
expr2.Parse(reader);
Children.Add(expr2);
}
public override Expression AsExpressionTree()
{
throw new NotImplementedException();
}
#endregion
}
} | fuyuno/Vulpecula | Vulpecula.Scripting/Parser/Expressions/EqualityExpression.cs | C# | mit | 1,968 |
<TS language="ca@valencia" version="2.0">
<context>
<name>AboutDialog</name>
<message>
<source>About Petecoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<source><b>Petecoin Core</b> version</source>
<translation type="unfinished"/>
</message>
<message>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<source>The Petecoin Core developers</source>
<translation type="unfinished"/>
</message>
<message>
<source>(%1-bit)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<source>Double-click to edit address or label</source>
<translation>Doble click per editar la direccio o la etiqueta</translation>
</message>
<message>
<source>Create a new address</source>
<translation>Crear nova direccio</translation>
</message>
<message>
<source>&New</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copieu l'adreรงa seleccionada al porta-retalls del sistema</translation>
</message>
<message>
<source>&Copy</source>
<translation type="unfinished"/>
</message>
<message>
<source>C&lose</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Copy Address</source>
<translation type="unfinished"/>
</message>
<message>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Delete</source>
<translation>Eliminar</translation>
</message>
<message>
<source>Choose the address to send coins to</source>
<translation type="unfinished"/>
</message>
<message>
<source>Choose the address to receive coins with</source>
<translation type="unfinished"/>
</message>
<message>
<source>C&hoose</source>
<translation type="unfinished"/>
</message>
<message>
<source>Please sending addresses</source>
<translation type="unfinished"/>
</message>
<message>
<source>Beg receiving addresses</source>
<translation type="unfinished"/>
</message>
<message>
<source>These are your Petecoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<source>These are your Petecoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy &Label</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Edit</source>
<translation type="unfinished"/>
</message>
<message>
<source>Export Address List</source>
<translation type="unfinished"/>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Exporting Failed</source>
<translation type="unfinished"/>
</message>
<message>
<source>There was an error trying to save the address list to %1.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<source>Enter passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<source>New passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<source>Repeat new passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Encrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<source>Change passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<source>Enter the old and new passphrase to the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Confirm wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR PETECOINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</message>
<message>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<source>Wallet encrypted</source>
<translation type="unfinished"/>
</message>
<message>
<source>Petecoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your petecoins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Wallet encryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation type="unfinished"/>
</message>
<message>
<source>The supplied passphrases do not match.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Wallet unlock failed</source>
<translation type="unfinished"/>
</message>
<message>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Wallet decryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<source>Sign &message...</source>
<translation type="unfinished"/>
</message>
<message>
<source>Synchronizing with network...</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Overview</source>
<translation type="unfinished"/>
</message>
<message>
<source>Node</source>
<translation type="unfinished"/>
</message>
<message>
<source>Show general overview of wallet</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Transactions</source>
<translation type="unfinished"/>
</message>
<message>
<source>Browse transaction history</source>
<translation type="unfinished"/>
</message>
<message>
<source>E&xit</source>
<translation type="unfinished"/>
</message>
<message>
<source>Quit application</source>
<translation type="unfinished"/>
</message>
<message>
<source>Show information about Petecoin</source>
<translation type="unfinished"/>
</message>
<message>
<source>About &Qt</source>
<translation type="unfinished"/>
</message>
<message>
<source>Show information about Qt</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Options...</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message>
<source>Please &sending addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<source>Beg &receiving addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<source>Open &URI...</source>
<translation type="unfinished"/>
</message>
<message>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<source>Send coins to a Petecoin address</source>
<translation type="unfinished"/>
</message>
<message>
<source>Modify configuration options for Petecoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<source>Change the passphrase used for wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<source>Petecoin</source>
<translation type="unfinished"/>
</message>
<message>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<source>Sign messages with your Petecoin addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<source>Verify messages to ensure they were signed with specified Petecoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<source>&File</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Settings</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Help</source>
<translation type="unfinished"/>
</message>
<message>
<source>Tabs toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
<message>
<source>Petecoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<source>Request payments (generates QR codes and petecoin: URIs)</source>
<translation type="unfinished"/>
</message>
<message>
<source>&About Petecoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<source>Show the list of used sending addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<source>Show the list of used receiving addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<source>Open a petecoin: URI or payment request</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<source>Show the Petecoin Core help message to get a list with possible command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<source>Petecoin client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<source>%n active connection(s) to Petecoin network</source>
<translation type="unfinished"><numerusform/><numerusform/></translation>
</message>
<message>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform/><numerusform/></translation>
</message>
<message numerus="yes">
<source>%n day(s)</source>
<translation type="unfinished"><numerusform/><numerusform/></translation>
</message>
<message numerus="yes">
<source>%n week(s)</source>
<translation type="unfinished"><numerusform/><numerusform/></translation>
</message>
<message>
<source>%1 and %2</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<source>%n year(s)</source>
<translation type="unfinished"><numerusform/><numerusform/></translation>
</message>
<message>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<source>Up to date</source>
<translation type="unfinished"/>
</message>
<message>
<source>Catching up...</source>
<translation type="unfinished"/>
</message>
<message>
<source>Sent transaction</source>
<translation type="unfinished"/>
</message>
<message>
<source>Incoming transaction</source>
<translation type="unfinished"/>
</message>
<message>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation type="unfinished"/>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation type="unfinished"/>
</message>
<message>
<source>A fatal error occurred. Petecoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Coin Control Address Selection</source>
<translation type="unfinished"/>
</message>
<message>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Change:</source>
<translation type="unfinished"/>
</message>
<message>
<source>(un)select all</source>
<translation type="unfinished"/>
</message>
<message>
<source>Tree mode</source>
<translation type="unfinished"/>
</message>
<message>
<source>List mode</source>
<translation type="unfinished"/>
</message>
<message>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<source>Confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<source>Priority</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<source>Lock unspent</source>
<translation type="unfinished"/>
</message>
<message>
<source>Unlock unspent</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<source>highest</source>
<translation type="unfinished"/>
</message>
<message>
<source>higher</source>
<translation type="unfinished"/>
</message>
<message>
<source>high</source>
<translation type="unfinished"/>
</message>
<message>
<source>medium-high</source>
<translation type="unfinished"/>
</message>
<message>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<source>low-medium</source>
<translation type="unfinished"/>
</message>
<message>
<source>low</source>
<translation type="unfinished"/>
</message>
<message>
<source>lower</source>
<translation type="unfinished"/>
</message>
<message>
<source>lowest</source>
<translation type="unfinished"/>
</message>
<message>
<source>(%1 locked)</source>
<translation type="unfinished"/>
</message>
<message>
<source>none</source>
<translation type="unfinished"/>
</message>
<message>
<source>Dust</source>
<translation type="unfinished"/>
</message>
<message>
<source>yes</source>
<translation type="unfinished"/>
</message>
<message>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<source>This label turns red, if the transaction size is greater than 1000 bytes.</source>
<translation type="unfinished"/>
</message>
<message>
<source>This means a fee of at least %1 per kB is required.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Can vary +/- 1 byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Transactions with higher priority are more likely to get included into a block.</source>
<translation type="unfinished"/>
</message>
<message>
<source>This label turns red, if the priority is smaller than "medium".</source>
<translation type="unfinished"/>
</message>
<message>
<source>This label turns red, if any recipient receives an amount smaller than %1.</source>
<translation type="unfinished"/>
</message>
<message>
<source>This means a fee of at least %1 is required.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Amounts below 0.546 times the minimum relay fee are shown as dust.</source>
<translation type="unfinished"/>
</message>
<message>
<source>This label turns red, if the change is smaller than %1.</source>
<translation type="unfinished"/>
</message>
<message>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
<message>
<source>change from %1 (%2)</source>
<translation type="unfinished"/>
</message>
<message>
<source>(change)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>Edit Address</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Label</source>
<translation type="unfinished"/>
</message>
<message>
<source>The label associated with this address list entry</source>
<translation type="unfinished"/>
</message>
<message>
<source>The address associated with this address list entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Address</source>
<translation type="unfinished"/>
</message>
<message>
<source>New receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<source>New sending address</source>
<translation type="unfinished"/>
</message>
<message>
<source>Edit receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<source>Edit sending address</source>
<translation type="unfinished"/>
</message>
<message>
<source>The entered address "%1" is already in the address book.</source>
<translation type="unfinished"/>
</message>
<message>
<source>The entered address "%1" is not a valid Petecoin address.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Could not unlock wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<source>New key generation failed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>FreespaceChecker</name>
<message>
<source>A new data directory will be created.</source>
<translation type="unfinished"/>
</message>
<message>
<source>name</source>
<translation type="unfinished"/>
</message>
<message>
<source>Directory already exists. Add %1 if you intend to create a new directory here.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Path already exists, and is not a directory.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Cannot create data directory here.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<source>Petecoin Core - Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<source>Petecoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<source>Set SSL root certificates for payment request (default: -system-)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Choose data directory on startup (default: 0)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>Intro</name>
<message>
<source>Welcome</source>
<translation type="unfinished"/>
</message>
<message>
<source>Welcome to Petecoin Core.</source>
<translation type="unfinished"/>
</message>
<message>
<source>As this is the first time the program is launched, you can choose where Petecoin Core will store its data.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Petecoin Core will download and store a copy of the Petecoin block chain. At least %1GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Use the default data directory</source>
<translation type="unfinished"/>
</message>
<message>
<source>Use a custom data directory:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Petecoin</source>
<translation type="unfinished"/>
</message>
<message>
<source>Error: Specified data directory "%1" can not be created.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<source>GB of free space available</source>
<translation type="unfinished"/>
</message>
<message>
<source>(of %1GB needed)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OpenURIDialog</name>
<message>
<source>Open URI</source>
<translation type="unfinished"/>
</message>
<message>
<source>Open payment request from URI or file</source>
<translation type="unfinished"/>
</message>
<message>
<source>URI:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Select payment request file</source>
<translation type="unfinished"/>
</message>
<message>
<source>Select payment request file to open</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Options</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Main</source>
<translation type="unfinished"/>
</message>
<message>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<source>Automatically start Petecoin Core after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Start Petecoin Core on system login</source>
<translation type="unfinished"/>
</message>
<message>
<source>Size of &database cache</source>
<translation type="unfinished"/>
</message>
<message>
<source>MB</source>
<translation type="unfinished"/>
</message>
<message>
<source>Number of script &verification threads</source>
<translation type="unfinished"/>
</message>
<message>
<source>Connect to the Petecoin network through a SOCKS proxy.</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Connect through SOCKS proxy (default proxy):</source>
<translation type="unfinished"/>
</message>
<message>
<source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Active command-line options that override above options:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<source>(0 = auto, <0 = leave that many cores free)</source>
<translation type="unfinished"/>
</message>
<message>
<source>W&allet</source>
<translation type="unfinished"/>
</message>
<message>
<source>Expert</source>
<translation type="unfinished"/>
</message>
<message>
<source>Enable coin &control features</source>
<translation type="unfinished"/>
</message>
<message>
<source>If you disable the spending of unconfirmed change, the change from a transaction cannot be used until that transaction has at least one confirmation. This also affects how your balance is computed.</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Spend unconfirmed change</source>
<translation type="unfinished"/>
</message>
<message>
<source>Automatically open the Petecoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Map port using &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</message>
<message>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation type="unfinished"/>
</message>
<message>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<source>The user interface language can be set here. This setting will take effect after restarting Petecoin Core.</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Whether to show Petecoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<source>Whether to show coin control features or not.</source>
<translation type="unfinished"/>
</message>
<message>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<source>none</source>
<translation type="unfinished"/>
</message>
<message>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<source>Client restart required to activate changes.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Client will be shutdown, do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<source>This change would require a client restart.</source>
<translation type="unfinished"/>
</message>
<message>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Petecoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<source>Available:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Your current spendable balance</source>
<translation type="unfinished"/>
</message>
<message>
<source>Pending:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source>
<translation type="unfinished"/>
</message>
<message>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<source>Total:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Your current total balance</source>
<translation type="unfinished"/>
</message>
<message>
<source><b>Recent transactions</b></source>
<translation type="unfinished"/>
</message>
<message>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<source>URI can not be parsed! This can be caused by an invalid Petecoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Requested payment amount of %1 is too small (considered dust).</source>
<translation type="unfinished"/>
</message>
<message>
<source>Payment request error</source>
<translation type="unfinished"/>
</message>
<message>
<source>Cannot start petecoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
<message>
<source>Net manager warning</source>
<translation type="unfinished"/>
</message>
<message>
<source>Your active proxy doesn't support SOCKS5, which is required for payment requests via proxy.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Payment request fetch URL is invalid: %1</source>
<translation type="unfinished"/>
</message>
<message>
<source>Payment request file handling</source>
<translation type="unfinished"/>
</message>
<message>
<source>Payment request file can not be read or processed! This can be caused by an invalid payment request file.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Unverified payment requests to custom payment scripts are unsupported.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Refund from %1</source>
<translation type="unfinished"/>
</message>
<message>
<source>Error communicating with %1: %2</source>
<translation type="unfinished"/>
</message>
<message>
<source>Payment request can not be parsed or processed!</source>
<translation type="unfinished"/>
</message>
<message>
<source>Bad response from server %1</source>
<translation type="unfinished"/>
</message>
<message>
<source>Payment acknowledged</source>
<translation type="unfinished"/>
</message>
<message>
<source>Network request error</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QObject</name>
<message>
<source>Petecoin</source>
<translation type="unfinished"/>
</message>
<message>
<source>Error: Specified data directory "%1" does not exist.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Error: Cannot parse configuration file: %1. Only use key=value syntax.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Error: Invalid combination of -regtest and -testnet.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Petecoin Core did't yet exit safely...</source>
<translation type="unfinished"/>
</message>
<message>
<source>Enter a Petecoin address (e.g. PMvgvan5TULVfJihSXXKJ4bPB8YTGKUFn3)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRImageWidget</name>
<message>
<source>&Save Image...</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Copy Image</source>
<translation type="unfinished"/>
</message>
<message>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<source>PNG Image (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<source>Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<source>General</source>
<translation type="unfinished"/>
</message>
<message>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<source>Name</source>
<translation type="unfinished"/>
</message>
<message>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Network Traffic</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Clear</source>
<translation type="unfinished"/>
</message>
<message>
<source>Totals</source>
<translation type="unfinished"/>
</message>
<message>
<source>In:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Out:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<source>Open the Petecoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<source>Welcome to the Petecoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
<message>
<source>%1 B</source>
<translation type="unfinished"/>
</message>
<message>
<source>%1 KB</source>
<translation type="unfinished"/>
</message>
<message>
<source>%1 MB</source>
<translation type="unfinished"/>
</message>
<message>
<source>%1 GB</source>
<translation type="unfinished"/>
</message>
<message>
<source>%1 m</source>
<translation type="unfinished"/>
</message>
<message>
<source>%1 h</source>
<translation type="unfinished"/>
</message>
<message>
<source>%1 h %2 m</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<source>&Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Message:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source>
<translation type="unfinished"/>
</message>
<message>
<source>R&euse an existing receiving address (not recommended)</source>
<translation type="unfinished"/>
</message>
<message>
<source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Petecoin network.</source>
<translation type="unfinished"/>
</message>
<message>
<source>An optional label to associate with the new receiving address.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Use this form to request payments. All fields are <b>optional</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Clear all fields of the form.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Clear</source>
<translation type="unfinished"/>
</message>
<message>
<source>Requested payments history</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Request payment</source>
<translation type="unfinished"/>
</message>
<message>
<source>Show the selected request (does the same as double clicking an entry)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Show</source>
<translation type="unfinished"/>
</message>
<message>
<source>Remove the selected entries from the list</source>
<translation type="unfinished"/>
</message>
<message>
<source>Remove</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy message</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy &URI</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy &Address</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Save Image...</source>
<translation type="unfinished"/>
</message>
<message>
<source>Request payment to %1</source>
<translation type="unfinished"/>
</message>
<message>
<source>Payment information</source>
<translation type="unfinished"/>
</message>
<message>
<source>URI</source>
<translation type="unfinished"/>
</message>
<message>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
<message>
<source>(no message)</source>
<translation type="unfinished"/>
</message>
<message>
<source>(no amount)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
<message>
<source>Coin Control Features</source>
<translation type="unfinished"/>
</message>
<message>
<source>Inputs...</source>
<translation type="unfinished"/>
</message>
<message>
<source>automatically selected</source>
<translation type="unfinished"/>
</message>
<message>
<source>Insufficient funds!</source>
<translation type="unfinished"/>
</message>
<message>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Change:</source>
<translation type="unfinished"/>
</message>
<message>
<source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<source>Send to multiple recipients at once</source>
<translation type="unfinished"/>
</message>
<message>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<source>Clear all fields of the form.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Confirm the send action</source>
<translation type="unfinished"/>
</message>
<message>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</message>
<message>
<source>%1 to %2</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<source>Total Amount %1 (= %2)</source>
<translation type="unfinished"/>
</message>
<message>
<source>or</source>
<translation type="unfinished"/>
</message>
<message>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<source>The amount to pay must be larger than 0.</source>
<translation type="unfinished"/>
</message>
<message>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<source>The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Warning: Invalid Petecoin address</source>
<translation type="unfinished"/>
</message>
<message>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Warning: Unknown change address</source>
<translation type="unfinished"/>
</message>
<message>
<source>Are you sure you want to send?</source>
<translation type="unfinished"/>
</message>
<message>
<source>added as transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<source>Payment request expired</source>
<translation type="unfinished"/>
</message>
<message>
<source>Invalid payment address %1</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>A&mount:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Pay &To:</source>
<translation type="unfinished"/>
</message>
<message>
<source>The address to send the payment to (e.g. PMvgvan5TULVfJihSXXKJ4bPB8YTGKUFn3)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Enter a label for this address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Choose previously used address</source>
<translation type="unfinished"/>
</message>
<message>
<source>This is a normal payment.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<source>Remove this entry</source>
<translation type="unfinished"/>
</message>
<message>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<source>This is a verified payment request.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Enter a label for this address to add it to the list of used addresses</source>
<translation type="unfinished"/>
</message>
<message>
<source>A message that was attached to the petecoin: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Petecoin network.</source>
<translation type="unfinished"/>
</message>
<message>
<source>This is an unverified payment request.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Pay To:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Memo:</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ShutdownWindow</name>
<message>
<source>Petecoin Core is shutting down...</source>
<translation type="unfinished"/>
</message>
<message>
<source>Do not shut down the computer until this window disappears.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<source>The address to sign the message with (e.g. PMvgvan5TULVfJihSXXKJ4bPB8YTGKUFn3)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Choose previously used address</source>
<translation type="unfinished"/>
</message>
<message>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<source>Sign the message to prove you own this Petecoin address</source>
<translation type="unfinished"/>
</message>
<message>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<source>The address the message was signed with (e.g. PMvgvan5TULVfJihSXXKJ4bPB8YTGKUFn3)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Verify the message to ensure it was signed with the specified Petecoin address</source>
<translation type="unfinished"/>
</message>
<message>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<source>Enter a Petecoin address (e.g. PMvgvan5TULVfJihSXXKJ4bPB8YTGKUFn3)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<source>Petecoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<source>The Petecoin Core developers</source>
<translation type="unfinished"/>
</message>
<message>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<source>KB/s</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<source>conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<source>%1/unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<source>%1 confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform/><numerusform/></translation>
</message>
<message>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform/><numerusform/></translation>
</message>
<message>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<source>Merchant</source>
<translation type="unfinished"/>
</message>
<message>
<source>Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<source>, has not been successfully broadcast yet</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform/><numerusform/></translation>
</message>
<message>
<source>unknown</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<source>Transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<source>This pane shows a detailed description of the transaction</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform/><numerusform/></translation>
</message>
<message>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<source>Confirmed (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation type="unfinished"/>
</message>
<message>
<source>Generated but not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<source>Offline</source>
<translation type="unfinished"/>
</message>
<message>
<source>Unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<source>Received from</source>
<translation type="unfinished"/>
</message>
<message>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<source>Payment to yourself</source>
<translation type="unfinished"/>
</message>
<message>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<source>(n/a)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Date and time that the transaction was received.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Type of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Destination address of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Amount removed from or added to balance.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<source>All</source>
<translation type="unfinished"/>
</message>
<message>
<source>Today</source>
<translation type="unfinished"/>
</message>
<message>
<source>This week</source>
<translation type="unfinished"/>
</message>
<message>
<source>This month</source>
<translation type="unfinished"/>
</message>
<message>
<source>Last month</source>
<translation type="unfinished"/>
</message>
<message>
<source>This year</source>
<translation type="unfinished"/>
</message>
<message>
<source>Range...</source>
<translation type="unfinished"/>
</message>
<message>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<source>To yourself</source>
<translation type="unfinished"/>
</message>
<message>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<source>Other</source>
<translation type="unfinished"/>
</message>
<message>
<source>Enter address or label to search</source>
<translation type="unfinished"/>
</message>
<message>
<source>Min amount</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<source>Edit label</source>
<translation type="unfinished"/>
</message>
<message>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<source>Export Transaction History</source>
<translation type="unfinished"/>
</message>
<message>
<source>Exporting Failed</source>
<translation type="unfinished"/>
</message>
<message>
<source>There was an error trying to save the transaction history to %1.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Exporting Successful</source>
<translation type="unfinished"/>
</message>
<message>
<source>The transaction history was successfully saved to %1.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<source>ID</source>
<translation type="unfinished"/>
</message>
<message>
<source>Range:</source>
<translation type="unfinished"/>
</message>
<message>
<source>to</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletFrame</name>
<message>
<source>No wallet has been loaded.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<source>There was an error trying to save the wallet data to %1.</source>
<translation type="unfinished"/>
</message>
<message>
<source>The wallet data was successfully saved to %1.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<source>List commands</source>
<translation type="unfinished"/>
</message>
<message>
<source>Get help for a command</source>
<translation type="unfinished"/>
</message>
<message>
<source>Options:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Specify configuration file (default: petecoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Specify pid file (default: bitcoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Specify data directory</source>
<translation type="unfinished"/>
</message>
<message>
<source>Listen for connections on <port> (default: 8333 or testnet: 18333)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<source>Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<source>Petecoin Core RPC client version</source>
<translation type="unfinished"/>
</message>
<message>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<source>Use the test network</source>
<translation type="unfinished"/>
</message>
<message>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=bitcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Petecoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<source>Continuously rate-limit free transactions to <n>*1000 bytes per minute (default:15)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Error: Listening for incoming connections failed (listen returned error %d)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Fees smaller than this are considered zero fee (for transaction creation) (default:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Flush database activity from memory pool to disk log every <n> megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<source>How thorough the block verification of -checkblocks is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<source>In this mode -genproclimit controls how many blocks are generated immediately.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Set the processor limit for when generation is on (-1 = unlimited, default: -1)</source>
<translation type="unfinished"/>
</message>
<message>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<source>Unable to bind to %s on this computer. Petecoin Core is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Petecoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<source>(default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<source>(default: wallet.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<source><category> can be:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<source>Petecoin Core Daemon</source>
<translation type="unfinished"/>
</message>
<message>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Clear list of wallet transactions (diagnostic tool; implies -rescan)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Connect through SOCKS proxy</source>
<translation type="unfinished"/>
</message>
<message>
<source>Connect to JSON-RPC on <port> (default: 8332 or testnet: 18332)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Connection options:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<source>Debugging/Testing options:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Disable safemode, override a real safe mode event (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Do not load the wallet and disable wallet RPC calls</source>
<translation type="unfinished"/>
</message>
<message>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<source>Fee per kB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<source>Fees smaller than this are considered zero fee (for relaying) (default:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Force safe mode (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<source>If <category> is not supplied, output all debugging information.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Importing...</source>
<translation type="unfinished"/>
</message>
<message>
<source>Incorrect or no genesis block found. Wrong datadir for network?</source>
<translation type="unfinished"/>
</message>
<message>
<source>Invalid -onion address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Prepend debug output with timestamp (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<source>RPC client options:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<source>Select SOCKS version for -proxy (4 or 5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Set database cache size in megabytes (%d to %d, default: %d)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Set maximum block size in bytes (default: %d)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Specify wallet file (within data directory)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Spend unconfirmed change when sending transactions (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<source>This is intended for regression testing tools and app development.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Usage (deprecated, use petecoin-cli):</source>
<translation type="unfinished"/>
</message>
<message>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<source>Wait for RPC server to start</source>
<translation type="unfinished"/>
</message>
<message>
<source>Wallet %s resides outside data directory %s</source>
<translation type="unfinished"/>
</message>
<message>
<source>Wallet options:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source>
<translation type="unfinished"/>
</message>
<message>
<source>You need to rebuild the database using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<source>Cannot obtain a lock on data directory %s. Petecoin Core is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Output debugging information (default: 0, supplying <category> is optional)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<source>Limit size of signature cache to <n> entries (default: 50000)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Log transaction priority and fee per kB when mining blocks (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Print block on startup, if found in block index</source>
<translation type="unfinished"/>
</message>
<message>
<source>Print block tree on startup (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<source>RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<source>RPC server options:</source>
<translation type="unfinished"/>
</message>
<message>
<source>Randomly drop 1 of every <n> network messages</source>
<translation type="unfinished"/>
</message>
<message>
<source>Randomly fuzz 1 of every <n> network messages</source>
<translation type="unfinished"/>
</message>
<message>
<source>Run a thread to flush wallet periodically (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Send command to Petecoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Sets the DB_PRIVATE flag in the wallet db environment (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Show all debugging options (usage: --help -help-debug)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Show benchmark information (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Start Petecoin Core Daemon</source>
<translation type="unfinished"/>
</message>
<message>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<source>Zapping all transactions from wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<source>on startup</source>
<translation type="unfinished"/>
</message>
<message>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"/>
</message>
<message>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</message>
<message>
<source>This help message</source>
<translation type="unfinished"/>
</message>
<message>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<source>Loading addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<source>Error loading wallet.dat: Wallet requires newer version of Petecoin</source>
<translation type="unfinished"/>
</message>
<message>
<source>Wallet needed to be rewritten: restart Petecoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<source>Invalid amount</source>
<translation type="unfinished"/>
</message>
<message>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<source>Loading block index...</source>
<translation type="unfinished"/>
</message>
<message>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<source>Loading wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<source>Rescanning...</source>
<translation type="unfinished"/>
</message>
<message>
<source>Done loading</source>
<translation type="unfinished"/>
</message>
<message>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS> | sjmariogolf/petecoin | src/qt/locale/bitcoin_ca@valencia.ts | TypeScript | mit | 109,401 |
import { Transform } from './transform.js';
/**
* Calculate the transform for a Cornerstone enabled element
*
* @param {EnabledElement} enabledElement The Cornerstone Enabled Element
* @param {Number} [scale] The viewport scale
* @return {Transform} The current transform
*/
export default function (enabledElement, scale) {
const transform = new Transform();
transform.translate(enabledElement.canvas.width / 2, enabledElement.canvas.height / 2);
// Apply the rotation before scaling for non square pixels
const angle = enabledElement.viewport.rotation;
if (angle !== 0) {
transform.rotate(angle * Math.PI / 180);
}
// Apply the scale
let widthScale = enabledElement.viewport.scale;
let heightScale = enabledElement.viewport.scale;
if (enabledElement.image.rowPixelSpacing < enabledElement.image.columnPixelSpacing) {
widthScale *= (enabledElement.image.columnPixelSpacing / enabledElement.image.rowPixelSpacing);
} else if (enabledElement.image.columnPixelSpacing < enabledElement.image.rowPixelSpacing) {
heightScale *= (enabledElement.image.rowPixelSpacing / enabledElement.image.columnPixelSpacing);
}
transform.scale(widthScale, heightScale);
// Unrotate to so we can translate unrotated
if (angle !== 0) {
transform.rotate(-angle * Math.PI / 180);
}
// Apply the pan offset
transform.translate(enabledElement.viewport.translation.x, enabledElement.viewport.translation.y);
// Rotate again so we can apply general scale
if (angle !== 0) {
transform.rotate(angle * Math.PI / 180);
}
if (scale !== undefined) {
// Apply the font scale
transform.scale(scale, scale);
}
// Apply Flip if required
if (enabledElement.viewport.hflip) {
transform.scale(-1, 1);
}
if (enabledElement.viewport.vflip) {
transform.scale(1, -1);
}
// Translate the origin back to the corner of the image so the event handlers can draw in image coordinate system
transform.translate(-enabledElement.image.width / 2, -enabledElement.image.height / 2);
return transform;
}
| google/cornerstone | src/internal/calculateTransform.js | JavaScript | mit | 2,065 |
module Gene
module Handlers
module Ruby
class StatementHandler
def initialize
@logger = Logem::Logger.new(self)
end
def call context, data
@logger.debug('call', data)
if data.is_a? Gene::Types::Base
"#{data.type}(#{data.data.join(', ')})"
else
data
end
end
end
end
end
end
| gcao/gene | lib/gene/handlers/ruby/statement_handler.rb | Ruby | mit | 407 |
import Express from 'express';
import compression from 'compression';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import path from 'path';
import IntlWrapper from '../client/modules/Intl/IntlWrapper';
// Webpack Requirements
import webpack from 'webpack';
import config from '../webpack.config.dev';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
// Initialize the Express App
const app = new Express();
// Run Webpack dev server in development mode
if (process.env.NODE_ENV === 'development') {
const compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
app.use(webpackHotMiddleware(compiler));
}
// React And Redux Setup
import { configureStore } from '../client/store';
import { Provider } from 'react-redux';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import Helmet from 'react-helmet';
// Import required modules
import routes from '../client/routes';
import { fetchComponentData } from './util/fetchData';
import posts from './routes/post.routes';
import medicalRights from './routes/medicalrights.routes';
import populateDB from './routes/populateDB.routes';
import dummyData from './dummyData';
import serverConfig from './config';
// Set native promises as mongoose promise
mongoose.Promise = global.Promise;
// MongoDB Connection
mongoose.connect(serverConfig.mongoURL, (error) => {
if (error) {
console.error('Please make sure Mongodb is installed and running!'); // eslint-disable-line no-console
throw error;
}
// feed some dummy data in DB.
//dummyData();
});
// Apply body Parser and server public assets and routes
app.use(compression());
app.use(bodyParser.json({ limit: '20mb' }));
app.use(bodyParser.urlencoded({ limit: '20mb', extended: false }));
app.use(Express.static(path.resolve(__dirname, '../dist')));
app.use('/api', posts);
app.use('/api', medicalRights);
app.use('/api', populateDB);
// Render Initial HTML
const renderFullPage = (html, initialState) => {
const head = Helmet.rewind();
// Import Manifests
const assetsManifest = process.env.webpackAssets && JSON.parse(process.env.webpackAssets);
const chunkManifest = process.env.webpackChunkAssets && JSON.parse(process.env.webpackChunkAssets);
return `
<!doctype html>
<html>
<head>
${head.base.toString()}
${head.title.toString()}
${head.meta.toString()}
${head.link.toString()}
${head.script.toString()}
${process.env.NODE_ENV === 'production' ? `<link rel='stylesheet' href='${assetsManifest['/app.css']}' />` : ''}
<link href='https://fonts.googleapis.com/css?family=Lato:400,300,700' rel='stylesheet' type='text/css'/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css" type='text/css'>
<link rel="shortcut icon" href="http://res.cloudinary.com/hashnode/image/upload/v1455629445/static_imgs/mern/mern-favicon-circle-fill.png" type="image/png" />
<style>
/* local page styles */
html h1 {
font-size: 26px;
margin-left: 10px;
}
html h2 {
font-size: 22px;
margin-left: 10px;
}
html h3 {
font-size: 14px;
margin-left: 10px;
}
html h4 {
font-size: 16px;
}
.progtrckr {
text-align: center;
padding-bottom: 16px;
// border-bottom: solid 1px;
}
.progtrckr li {
margin-bottom: 10px;
}
.val-err-tooltip {
background-color: red;
padding: 3px 5px 3px 10px;
font-size: 14px;
color: #fff;
}
.step {
// background-color: #ccc;
border:1px solid #e5e5e5;
min-height: 437px;
padding: 10px;
max-width: 815px;
}
html .row, html .form-horizontal .form-group {
margin: 0;
}
.footer-buttons {
margin-top: 10px;
margin-bottom: 50px;
}
html .step3 label, html .step4 label {
font-size: 20px;
text-align: left;
}
html .form-horizontal .control-label {
text-align: left;
}
.review .txt {
font-size: 20px;
text-align: left;
margin: 0;
padding: 0;
}
html body .saving {
background-color: #5cb85c;
width: 90%;
padding: 5px;
font-size: 16px;
}
code {
position: relative;
left: 12px;
line-height: 25px;
}
.eg-jump-lnk {
margin-top: 50px;
font-style: italic;
}
.lib-version {
font-size: 12px;
background-color: rgba(255, 255, 0, 0.38);
position: absolute;
right: 10px;
top: 10px;
padding: 5px;
}
html .content {
margin-left: 10px;
}
span.red {
color: #d9534f;
}
span.green {
color: #3c763d;
}
span.bold {
font-weight: bold;
}
html .hoc-alert {
margin-top: 20px;
}
html .form-block-holder {
margin-top: 20px !important;
}
ol.progtrckr {
margin: 0;
padding-bottom: 2.2rem;
list-style-type: none;
}
ol.progtrckr li {
display: inline-block;
text-align: center;
line-height: 4.5rem;
padding: 0 0.7rem;
cursor: pointer;
}
ol.progtrckr li span {
padding: 0 1.5rem;
}
@media (max-width: 650px) {
.progtrckr li span {
display: none;
}
}
.progtrckr em {
display: none;
font-weight: 700;
padding-left: 1rem;
}
@media (max-width: 650px) {
.progtrckr em {
display: inline;
}
border-bottom: solid 1px;
}
@media (max-width: 650px) {
.step {
max-height=320px;
min-height=437px;
min-width=300px;
}
}
}
ol.progtrckr li.progtrckr-todo {
color: silver;
border-bottom: 4px solid silver;
}
ol.progtrckr li.progtrckr-doing {
color: black;
border-bottom: 4px solid #33C3F0;
}
ol.progtrckr li.progtrckr-done {
color: black;
border-bottom: 4px solid #33C3F0;
}
ol.progtrckr li:after {
content: "\\00a0\\00a0";
}
ol.progtrckr li:before {
position: relative;
bottom: -3.7rem;
float: left;
left: 50%;
}
ol.progtrckr li.progtrckr-todo:before {
content: "\\039F";
color: silver;
background-color: white;
width: 1.2em;
line-height: 1.4em;
}
ol.progtrckr li.progtrckr-todo:hover:before {
color: #0FA0CE;
}
ol.progtrckr li.progtrckr-doing:before {
content: "\\2022";
color: white;
background-color: #33C3F0;
width: 1.2em;
line-height: 1.2em;
border-radius: 1.2em;
}
ol.progtrckr li.progtrckr-doing:hover:before {
color: #0FA0CE;
}
ol.progtrckr li.progtrckr-done:before {
content: "\\2713";
color: white;
background-color: #33C3F0;
width: 1.2em;
line-height: 1.2em;
border-radius: 1.2em;
}
ol.progtrckr li.progtrckr-done:hover:before {
color: #0FA0CE;
}
</style>
</head>
<body>
<div id="root">${html}</div>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
${process.env.NODE_ENV === 'production' ?
`//<![CDATA[
window.webpackManifest = ${JSON.stringify(chunkManifest)};
//]]>` : ''}
</script>
<script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/vendor.js'] : '/vendor.js'}'></script>
<script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/app.js'] : '/app.js'}'></script>
</body>
</html>
`;
};
const renderError = err => {
const softTab = '    ';
const errTrace = process.env.NODE_ENV !== 'production' ?
`:<br><br><pre style="color:red">${softTab}${err.stack.replace(/\n/g, `<br>${softTab}`)}</pre>` : '';
return renderFullPage(`Server Error${errTrace}`, {});
};
// Server Side Rendering based on routes matched by React-router.
app.use((req, res, next) => {
match({ routes, location: req.url }, (err, redirectLocation, renderProps) => {
if (err) {
return res.status(500).end(renderError(err));
}
if (redirectLocation) {
return res.redirect(302, redirectLocation.pathname + redirectLocation.search);
}
if (!renderProps) {
return next();
}
const store = configureStore();
return fetchComponentData(store, renderProps.components, renderProps.params)
.then(() => {
const initialView = renderToString(
<Provider store={store}>
<IntlWrapper>
<RouterContext {...renderProps} />
</IntlWrapper>
</Provider>
);
const finalState = store.getState();
res
.set('Content-Type', 'text/html')
.status(200)
.end(renderFullPage(initialView, finalState));
})
.catch((error) => next(error));
});
});
// start app
app.listen(serverConfig.port, (error) => {
if (!error) {
console.log(`MERN is running on port: ${serverConfig.port}! Build something amazing!`); // eslint-disable-line
}
});
export default app;
| zivkaziv/MazorTech | server/server.js | JavaScript | mit | 8,791 |
<?php
/*
* This file is part of the symfony package.
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require_once(dirname(__FILE__).'/sfYamlInline.class.php');
/**
* sfYamlDumper class.
*
* @package symfony
* @subpackage util
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfYamlDumper.class.php 2 2009-11-08 18:53:57Z kotsutsumi $
*/
class sfYamlDumper
{
/**
* Dumps a PHP value to YAML.
*
* @param mixed $input The PHP value
* @param integer $inline The level where you switch to inline YAML
* @param integer $indent The level o indentation indentation (used internally)
*
* @return string The YAML representation of the PHP value
*/
public function dump($input, $inline = 0, $indent = 0)
{
$output = '';
$prefix = $indent ? str_repeat(' ', $indent) : '';
if ($inline <= 0 || !is_array($input) || empty($input))
{
$output .= $prefix.sfYamlInline::dump($input);
}
else
{
$isAHash = array_keys($input) !== range(0, count($input) - 1);
foreach ($input as $key => $value)
{
$willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value);
$output .= sprintf('%s%s%s%s',
$prefix,
$isAHash ? sfYamlInline::dump($key).':' : '-',
$willBeInlined ? ' ' : "\n",
$this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + 2)
).($willBeInlined ? "\n" : '');
}
}
return $output;
}
}
| xenophy/xFrameworkPX | library/PHPUnit/Util/YAML/sfYamlDumper.class.php | PHP | mit | 1,667 |
from django.conf.urls import url
from . import views
from django.views.decorators.cache import cache_page
app_name = 'webinter'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^logout/$', views.logout_view, name='logout'),
]
| ipriver/0x71aBot-Web-Interface | webinter/urls.py | Python | mit | 262 |
package ninja.egg82.concurrent;
import java.util.Set;
public interface IConcurrentSet<T> extends Set<T> {
//functions
int getRemainingCapacity();
int getCapacity();
}
| egg82/Java-Lib | Collections-Lib/src/ninja/egg82/concurrent/IConcurrentSet.java | Java | mit | 172 |
package vhosts
import (
"net/http"
"strings"
"sync"
)
type VirtualHosts struct {
vhosts map[string]http.Handler
mu sync.RWMutex
}
func NewVirtualHosts(vhosts map[string]http.Handler) *VirtualHosts {
v := &VirtualHosts{}
for hosts, h := range vhosts {
for _, host := range strings.Split(hosts, " ") {
if host != "" {
v.HandleHost(h, host)
}
}
}
return v
}
func (v *VirtualHosts) ServeHTTP(w http.ResponseWriter, r *http.Request) {
v.mu.RLock()
defer v.mu.RUnlock()
if v.vhosts != nil {
if handler, ok := v.vhosts[r.Host]; ok && handler != nil {
handler.ServeHTTP(w, r)
return
}
}
http.NotFound(w, r)
}
func (v *VirtualHosts) HandleHost(handler http.Handler, hosts ...string) {
v.mu.Lock()
defer v.mu.Unlock()
if v.vhosts == nil {
v.vhosts = make(map[string]http.Handler)
}
for _, host := range hosts {
for _, h := range strings.Split(host, " ") {
if h = strings.TrimSpace(h); h != "" {
v.vhosts[h] = handler
}
}
}
}
| alxarch/go-http | vhosts/vhosts.go | GO | mit | 984 |
package com.xiaofeng;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringcloudConfigClientApplicationTests {
@Test
public void contextLoads() {
}
}
| nellochen/springboot-start | springcloud-config-client/src/test/java/com/xiaofeng/SpringcloudConfigClientApplicationTests.java | Java | mit | 346 |
#include "optionsmodel.h"
#include "bitcoinunits.h"
#include <QSettings>
#include "init.h"
#include "walletdb.h"
#include "guiutil.h"
OptionsModel::OptionsModel(QObject *parent) :
QAbstractListModel(parent)
{
Init();
}
bool static ApplyProxySettings()
{
QSettings settings;
CService addrProxy(settings.value("addrProxy", "127.0.0.1:9050").toString().toStdString());
int nSocksVersion(settings.value("nSocksVersion", 5).toInt());
if (!settings.value("fUseProxy", false).toBool()) {
addrProxy = CService();
nSocksVersion = 0;
return false;
}
if (nSocksVersion && !addrProxy.IsValid())
return false;
if (!IsLimited(NET_IPV4))
SetProxy(NET_IPV4, addrProxy, nSocksVersion);
if (nSocksVersion > 4) {
#ifdef USE_IPV6
if (!IsLimited(NET_IPV6))
SetProxy(NET_IPV6, addrProxy, nSocksVersion);
#endif
SetNameProxy(addrProxy, nSocksVersion);
}
return true;
}
void OptionsModel::Init()
{
QSettings settings;
nDefaultCurrency = settings.value("nDefaultColor", DEFAULT_COLOR).toInt();
if (nDefaultCurrency == BREAKOUT_COLOR_NONE)
{
nDefaultCurrency = DEFAULT_COLOR;
}
nDisplayUnitBrostake = settings.value("nDisplayUnitBrostake", BitcoinUnits::BTC).toInt();
nDisplayUnitBrocoin = settings.value("nDisplayUnitBrocoin", BitcoinUnits::BTC).toInt();
bDisplayAddresses = settings.value("bDisplayAddresses", false).toBool();
bDisplayGenerated = settings.value("bDisplayGenerated", false).toBool();
fMinimizeToTray = settings.value("fMinimizeToTray", false).toBool();
fMinimizeOnClose = settings.value("fMinimizeOnClose", false).toBool();
fCoinControlFeatures = settings.value("fCoinControlFeatures", false).toBool();
vTransactionFee[BREAKOUT_COLOR_BROSTAKE] = settings.value("nTransactionFeeBrostake").toLongLong();
vTransactionFee[BREAKOUT_COLOR_BROCOIN] = settings.value("nTransactionFeeBrocoin").toLongLong();
vReserveBalance[BREAKOUT_COLOR_BROSTAKE] = settings.value("nReserveBalance").toLongLong();
language = settings.value("language", "").toString();
// These are shared with core Bitcoin; we want
// command-line options to override the GUI settings:
if (settings.contains("fUseUPnP"))
SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool());
if (settings.contains("addrProxy") && settings.value("fUseProxy").toBool())
SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString());
if (settings.contains("nSocksVersion") && settings.value("fUseProxy").toBool())
SoftSetArg("-socks", settings.value("nSocksVersion").toString().toStdString());
if (settings.contains("detachDB"))
SoftSetBoolArg("-detachdb", settings.value("detachDB").toBool());
if (!language.isEmpty())
SoftSetArg("-lang", language.toStdString());
}
bool OptionsModel::Upgrade()
{
QSettings settings;
if (settings.contains("bImportFinished"))
return false; // Already upgraded
settings.setValue("bImportFinished", true);
// Move settings from old wallet.dat (if any):
CWalletDB walletdb(strWalletFileName);
QList<QString> intOptions;
intOptions << "nDisplayUnitBrostake" << "nDisplayUnitBrocoin"
<< "nTransactionFeeBrostake" << "nTransactionFeeBrocoin"
<< "nReserveBalance" << "nDefaultColor";
foreach(QString key, intOptions)
{
int value = 0;
if (walletdb.ReadSetting(key.toStdString(), value))
{
settings.setValue(key, value);
walletdb.EraseSetting(key.toStdString());
}
}
QList<QString> boolOptions;
boolOptions << "bDisplayAddresses" <<
"bDisplayGenerated" <<
"fMinimizeToTray" <<
"fMinimizeOnClose" <<
"fUseProxy" << "fUseUPnP";
foreach(QString key, boolOptions)
{
bool value = false;
if (walletdb.ReadSetting(key.toStdString(), value))
{
settings.setValue(key, value);
walletdb.EraseSetting(key.toStdString());
}
}
try
{
CAddress addrProxyAddress;
if (walletdb.ReadSetting("addrProxy", addrProxyAddress))
{
settings.setValue("addrProxy", addrProxyAddress.ToStringIPPort().c_str());
walletdb.EraseSetting("addrProxy");
}
}
catch (std::ios_base::failure &e)
{
// 0.6.0rc1 saved this as a CService, which causes failure when parsing as a CAddress
CService addrProxy;
if (walletdb.ReadSetting("addrProxy", addrProxy))
{
settings.setValue("addrProxy", addrProxy.ToStringIPPort().c_str());
walletdb.EraseSetting("addrProxy");
}
}
ApplyProxySettings();
Init();
return true;
}
int OptionsModel::rowCount(const QModelIndex & parent) const
{
return OptionIDRowCount;
}
QVariant OptionsModel::data(const QModelIndex & index, int role) const
{
if(role == Qt::EditRole)
{
QSettings settings;
switch(index.row())
{
case StartAtStartup:
return QVariant(GUIUtil::GetStartOnSystemStartup());
case MinimizeToTray:
return QVariant(fMinimizeToTray);
case MapPortUPnP:
return settings.value("fUseUPnP", GetBoolArg("-upnp", true));
case MinimizeOnClose:
return QVariant(fMinimizeOnClose);
case ProxyUse:
return settings.value("fUseProxy", false);
case ProxyIP: {
proxyType proxy;
if (GetProxy(NET_IPV4, proxy))
return QVariant(QString::fromStdString(proxy.first.ToStringIP()));
else
return QVariant(QString::fromStdString("127.0.0.1"));
}
case ProxyPort: {
proxyType proxy;
if (GetProxy(NET_IPV4, proxy))
return QVariant(proxy.first.GetPort());
else
return QVariant(9050);
}
case ProxySocksVersion:
return settings.value("nSocksVersion", 5);
case FeeBrostake:
return QVariant((qint64) vTransactionFee[BREAKOUT_COLOR_BROSTAKE]);
case FeeBrocoin:
return QVariant((qint64) vTransactionFee[BREAKOUT_COLOR_BROCOIN]);
case ReserveBalance:
return QVariant((qint64) vReserveBalance[BREAKOUT_COLOR_BROSTAKE]);
case DefaultColor:
return QVariant(nDefaultCurrency);
case DisplayUnitBrostake:
return QVariant(nDisplayUnitBrostake);
case DisplayUnitBrocoin:
return QVariant(nDisplayUnitBrocoin);
case DisplayAddresses:
return QVariant(bDisplayAddresses);
case DisplayGenerated:
return QVariant(bDisplayGenerated);
case DetachDatabases:
return QVariant(bitdb.GetDetach());
case Language:
return settings.value("language", "");
case CoinControlFeatures:
return QVariant(fCoinControlFeatures);
default:
return QVariant();
}
}
return QVariant();
}
bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role)
{
bool successful = true; /* set to false on parse error */
if(role == Qt::EditRole)
{
QSettings settings;
switch(index.row())
{
case StartAtStartup:
successful = GUIUtil::SetStartOnSystemStartup(value.toBool());
break;
case MinimizeToTray:
fMinimizeToTray = value.toBool();
settings.setValue("fMinimizeToTray", fMinimizeToTray);
break;
case MapPortUPnP:
fUseUPnP = value.toBool();
settings.setValue("fUseUPnP", fUseUPnP);
MapPort();
break;
case MinimizeOnClose:
fMinimizeOnClose = value.toBool();
settings.setValue("fMinimizeOnClose", fMinimizeOnClose);
break;
case ProxyUse:
settings.setValue("fUseProxy", value.toBool());
ApplyProxySettings();
break;
case ProxyIP: {
proxyType proxy;
proxy.first = CService("127.0.0.1", 9050);
GetProxy(NET_IPV4, proxy);
CNetAddr addr(value.toString().toStdString());
proxy.first.SetIP(addr);
settings.setValue("addrProxy", proxy.first.ToStringIPPort().c_str());
successful = ApplyProxySettings();
}
break;
case ProxyPort: {
proxyType proxy;
proxy.first = CService("127.0.0.1", 9050);
GetProxy(NET_IPV4, proxy);
proxy.first.SetPort(value.toInt());
settings.setValue("addrProxy", proxy.first.ToStringIPPort().c_str());
successful = ApplyProxySettings();
}
break;
case ProxySocksVersion: {
proxyType proxy;
proxy.second = 5;
GetProxy(NET_IPV4, proxy);
proxy.second = value.toInt();
settings.setValue("nSocksVersion", proxy.second);
successful = ApplyProxySettings();
}
break;
case FeeBrostake:
vTransactionFee[BREAKOUT_COLOR_BROSTAKE] = value.toLongLong();
settings.setValue("nTransactionFeeBrostake",
(qint64) vTransactionFee[BREAKOUT_COLOR_BROSTAKE]);
emit transactionFeeChangedBrostake(vTransactionFee[BREAKOUT_COLOR_BROSTAKE]);
break;
case FeeBrocoin:
vTransactionFee[BREAKOUT_COLOR_BROCOIN] = value.toLongLong();
settings.setValue("nTransactionFeeBrocoin",
(qint64) vTransactionFee[BREAKOUT_COLOR_BROCOIN]);
emit transactionFeeChangedBrostake(vTransactionFee[BREAKOUT_COLOR_BROCOIN]);
break;
case ReserveBalance:
vReserveBalance[BREAKOUT_COLOR_BROSTAKE] = value.toLongLong();
settings.setValue("nReserveBalance",
(qint64) vReserveBalance[BREAKOUT_COLOR_BROSTAKE]);
emit reserveBalanceChanged(vReserveBalance[BREAKOUT_COLOR_BROSTAKE]);
break;
case DefaultColor:
nDefaultCurrency = value.toInt();
settings.setValue("nDefaultColor", nDefaultCurrency);
emit defaultColorChanged(nDefaultCurrency);
break;
case DisplayUnitBrostake:
nDisplayUnitBrostake = value.toInt();
settings.setValue("nDisplayUnitBrostake", nDisplayUnitBrostake);
emit displayUnitChangedBrostake(nDisplayUnitBrostake);
break;
case DisplayUnitBrocoin:
nDisplayUnitBrocoin = value.toInt();
settings.setValue("nDisplayUnitBrocoin", nDisplayUnitBrocoin);
emit displayUnitChangedBrocoin(nDisplayUnitBrocoin);
break;
case DisplayAddresses:
bDisplayAddresses = value.toBool();
settings.setValue("bDisplayAddresses", bDisplayAddresses);
break;
case DisplayGenerated:
bDisplayGenerated = value.toBool();
settings.setValue("bDisplayGenerated", bDisplayGenerated);
break;
case DetachDatabases: {
bool fDetachDB = value.toBool();
bitdb.SetDetach(fDetachDB);
settings.setValue("detachDB", fDetachDB);
}
break;
case Language:
settings.setValue("language", value);
break;
case CoinControlFeatures: {
fCoinControlFeatures = value.toBool();
settings.setValue("fCoinControlFeatures", fCoinControlFeatures);
emit coinControlFeaturesChanged(fCoinControlFeatures);
}
break;
default:
break;
}
}
emit dataChanged(index, index);
return successful;
}
// brostake and brocoin are the only currencies that have fees
qint64 OptionsModel::getTransactionFeeBrostake()
{
return vTransactionFee[BREAKOUT_COLOR_BROSTAKE];
}
qint64 OptionsModel::getTransactionFeeBrocoin()
{
return vTransactionFee[BREAKOUT_COLOR_BROSTAKE];
}
// Brostake is the only staking currency
qint64 OptionsModel::getReserveBalance()
{
return vReserveBalance[BREAKOUT_COLOR_BROSTAKE];
}
bool OptionsModel::getCoinControlFeatures()
{
return fCoinControlFeatures;
}
bool OptionsModel::getMinimizeToTray()
{
return fMinimizeToTray;
}
bool OptionsModel::getMinimizeOnClose()
{
return fMinimizeOnClose;
}
int OptionsModel::getDefaultColor()
{
return nDefaultCurrency;
}
int OptionsModel::getDisplayUnitBrostake()
{
return nDisplayUnitBrostake;
}
int OptionsModel::getDisplayUnitBrocoin()
{
return nDisplayUnitBrocoin;
}
int OptionsModel::getDisplayUnit(int nColor)
{
switch (nColor)
{
case BREAKOUT_COLOR_BROSTAKE:
return getDisplayUnitBrostake();
case BREAKOUT_COLOR_BROCOIN:
return getDisplayUnitBrocoin();
case BREAKOUT_COLOR_SISCOIN:
return BitcoinUnits::BTC;
default:
return BitcoinUnits::BTC;
}
}
bool OptionsModel::getDisplayAddresses()
{
return bDisplayAddresses;
}
bool OptionsModel::getDisplayGenerated()
{
return bDisplayGenerated;
}
| BreakoutCoin/Breakout-Chain-Client | src/qt/optionsmodel.cpp | C++ | mit | 13,372 |
/**
* @file singleton.hpp
* @brief dynamic Singleton pattern design template class
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 8. 2
* @details singleton รรร
ร ร
รรรยธยด ร
ยฌยทยกยฝยบ
*/
#ifndef _COSSB_ARCH_SINGLETON_HPP_
#define _COSSB_ARCH_SINGLETON_HPP_
#include <iostream>
#include <utility>
using namespace std;
namespace cossb {
namespace arch {
/**
* @brief dynamic singleton design pattern
*/
template <class T>
class singleton {
public:
template<typename... Args>
static T* instance(Args... args) {
if(!_instance) {
_instance = new T(std::forward<Args>(args)...);
}
return _instance;
}
static void destroy() {
if(_instance) {
delete _instance;
_instance = nullptr;
}
}
protected:
singleton() {}
singleton(singleton const&) {}
singleton& operator=(singleton const&) { return *this; }
private:
static T* _instance;
};
template <class T> T* singleton<T>::_instance = nullptr;
} /* namespace arch */
} /* namespace cossb */
#endif /* _COSSB_ARCH_SINGLETON_HPP_ */
| bhhwang/cossb | include/arch/singleton.hpp | C++ | mit | 1,028 |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
package multiverse.server.engine;
import java.util.Collection;
import java.util.Map;
import java.util.HashMap;
import java.util.LinkedList;
import multiverse.server.util.Log;
import multiverse.server.objects.ObjectType;
import multiverse.server.engine.Searchable;
import multiverse.server.messages.SearchMessageFilter;
import multiverse.server.messages.SearchMessage;
import multiverse.msgsys.*;
/** Object search framework. You can search for objects matching your
criteria.
<p>
The platform provides the following searchable collections:
<ul>
<li>Markers - Search for markers in an instance by marker properties. Use
SearchClause {@link multiverse.server.objects.Marker.Search Marker.Search}
<li>Regions - Search for regions in an instance by region properties. Use
SearchClause {@link multiverse.server.objects.Region.Search Region.Search}
<li>Instances - Search for instances by instance properties. Use
SearchClass {@link multiverse.server.engine.PropertySearch PropertySearch}
</ul>
<p>
Plugins can register searchable object collections using
{@link #registerSearchable registerSearchable()}.
*/
public class SearchManager
{
private SearchManager() {
}
/** Search for matching objects and get selected information.
Search occurs for a single ObjectType. Information indicated
in the 'SearchSelection' is returned for objects matching
the 'SearchClause'.
<p>
The search clause is a SearchClass sub-class designed specifically
for an object type (or class of object types).
@param objectType Search for this object type
@param searchClause Object matching criteria
@param selection Information selection; only the indicated
information will be returned.
@return Collection of matching objects.
*/
public static Collection searchObjects(ObjectType objectType,
SearchClause searchClause, SearchSelection selection)
{
SearchMessage message = new SearchMessage(objectType,
searchClause, selection);
Collector collector = new Collector(message);
return collector.getResults();
}
static class Collector implements ResponseCallback
{
public Collector(SearchMessage message)
{
searchMessage = message;
}
public Collection getResults()
{
int expectedResponses = Engine.getAgent().sendBroadcastRPC(searchMessage, this);
synchronized (this) {
responders += expectedResponses;
while (responders != 0) {
try {
this.wait();
} catch (InterruptedException e) {
}
}
}
return results;
}
public synchronized void handleResponse(ResponseMessage rr)
{
responders --;
GenericResponseMessage response = (GenericResponseMessage) rr;
Collection list = (Collection)response.getData();
if (list != null)
results.addAll(list);
if (responders == 0)
this.notify();
}
Collection results = new LinkedList();
SearchMessage searchMessage;
int responders = 0;
}
/** Register a new searchable object collection.
@param objectType Collection object type.
@param searchable Object search implementation.
*/
public static void registerSearchable(ObjectType objectType,
Searchable searchable)
{
SearchMessageFilter filter = new SearchMessageFilter(objectType);
Engine.getAgent().createSubscription(filter,
new SearchMessageCallback(searchable), MessageAgent.RESPONDER);
}
/** Register object match factory. A MatcherFactory returns a
Matcher object that works for the given search clause and
object class.
@param searchClauseClass A SearchClause sub-class.
@param instanceClass Instance object class.
@param matcherFactory Can return a Matcher object capable of
running the SearchClause against the instance object.
*/
public static void registerMatcher(Class searchClauseClass,
Class instanceClass, MatcherFactory matcherFactory)
{
matchers.put(new MatcherKey(searchClauseClass,instanceClass),
matcherFactory);
}
/** Get object matcher that can apply 'searchClause' to objects of
'instanceClass'.
@param searchClause The matching criteria.
@param instanceClass Instance object class.
*/
public static Matcher getMatcher(SearchClause searchClause,
Class instanceClass)
{
MatcherFactory matcherFactory;
matcherFactory = matchers.get(new MatcherKey(searchClause.getClass(),
instanceClass));
if (matcherFactory == null) {
Log.error("runSearch: No matcher for "+searchClause.getClass()+" "+instanceClass);
return null;
}
return matcherFactory.createMatcher(searchClause);
}
static class MatcherKey {
public MatcherKey(Class qt, Class it)
{
queryType = qt;
instanceType = it;
}
public Class queryType;
public Class instanceType;
public boolean equals(Object key)
{
return (((MatcherKey)key).queryType == queryType) &&
(((MatcherKey)key).instanceType == instanceType);
}
public int hashCode()
{
return queryType.hashCode() + instanceType.hashCode();
}
}
static class SearchMessageCallback implements MessageCallback
{
public SearchMessageCallback(Searchable searchable)
{
this.searchable = searchable;
}
public void handleMessage(Message msg, int flags)
{
SearchMessage message = (SearchMessage) msg;
Collection result = null;
try {
result = searchable.runSearch(
message.getSearchClause(), message.getSearchSelection());
}
catch (Exception e) {
Log.exception("runSearch failed", e);
}
Engine.getAgent().sendObjectResponse(message, result);
}
Searchable searchable;
}
static Map<MatcherKey,MatcherFactory> matchers =
new HashMap<MatcherKey,MatcherFactory>();
}
| longde123/MultiversePlatform | server/src/multiverse/server/engine/SearchManager.java | Java | mit | 7,815 |
'use strict';
const AWS = require('aws-sdk');
let x = "/delegationset/NHKXBB6SHGKLN";
console.log(x.replace('/delegationset/', ''));
return;
const route53 = new AWS.Route53();
route53.listHostedZones({}).promise()
.then(response => {
console.log(response);
return response.HostedZones.find(hostedZone => {
return hostedZone.Name === 'manapaho.com.';
});
})
.catch(err => {
console.log(err);
})
.then(hostedZone => {
console.log(hostedZone);
});
return;
/*
route53.listReusableDelegationSets({}).promise()
.then(response => {
return response.DelegationSets.find(delegationSet => {
return delegationSet.CallerReference === 'arn:aws:lambda:us-east-1:238541850529:function:Prod-Wessels-us-east-1-Route53ReusableDelegationSet';
});
})
.catch(err => {
console.log(err);
})
.then(reusableDelegationSet => {
console.log(reusableDelegationSet);
});
return;
AWS.config.update({region: 'us-east-1'});
let stackName = 'Prod-Manapaho-us-east-1-NameServerSet';
let responseStatus = "FAILED";
let responseData = {};
let cfn = new AWS.CloudFormation();
cfn.describeStacks({StackName: stackName}).promise()
.then(data => {
console.log('333333333333333333333', JSON.stringify(data, null, 2));
data.Stacks[0].Outputs.forEach(function (output) {
responseData[output.OutputKey] = output.OutputValue;
});
responseStatus = "SUCCESS";
console.log(JSON.stringify(responseData, null, 2));
})
.catch(err => {
console.log('4444444444444444444444444');
console.log('FAILED TO DESCRIBE STACK:', err);
});
return;
const route53 = new AWS.Route53();
route53.listReusableDelegationSets({}).promise()
.then(response => {
console.log(response.DelegationSets.find(delegationSet => {
return delegationSet.CallerReference === 'arn:aws:lambda:us-east-1:238541850529:function:Prod-Manapaho-us-east-1-Route53ReusableDelegationSet';
}));
})
.catch(err => {
console.log(err);
});
return;
route53.createReusableDelegationSet({CallerReference: 'createReusableDelegationSet'}).promise()
.then(response => {
console.log('XXXXXXXX', JSON.stringify(response, null, 2));
})
.catch(err => {
console.log(err, err.stack);
});
*/
| manapaho/cloudy | .temp/test.js | JavaScript | mit | 2,248 |
const defaultEnv = process.env.NODE_ENV || 'development';
function getEnv(name = defaultEnv) {
const isProduction = name === 'production' || name === 'prod';
const isDev = !isProduction;
return { name, isProduction, isDev, getEnv };
}
const env = getEnv();
module.exports = env;
| tofishes/a-rule | utils/env.js | JavaScript | mit | 289 |
package crawler.impl;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;
import main.Constants;
import model.News;
import org.horrabin.horrorss.RssFeed;
import org.horrabin.horrorss.RssItemBean;
import org.horrabin.horrorss.RssParser;
import utils.MiscUtils;
import utils.USDateParser;
import com.google.common.collect.Lists;
import crawler.Crawler;
import dao.KeywordDAO;
import dao.NewsDAO;
import dao.mysql.MySQLKeywordDAO;
import dao.mysql.MySQLNewsDAO;
public class BaiduNewsCrawler implements Crawler{
// private static NewsDAO newsDao = new MongoNewsDAO();
// private static KeywordDAO wordDao = new MongoKeywordDAO();
private NewsDAO newsDao = new MySQLNewsDAO();
private KeywordDAO wordDao = new MySQLKeywordDAO();
@Override
public List<String> getKeywords() {
return MiscUtils.mergeKeywordList(wordDao.query());
// return wordDao.query();
}
@Override
public String buildURL(String keyword) {
// Baiduๆฐ้ป้็จRSS็ฌ่ซ็ๅฝขๅผ
String baseURL = "http://news.baidu.com/ns?word=%s&tn=newsrss&sr=0&cl=2&rn=100&ct=0";
String queryURL = null;
try {
queryURL = String.format(baseURL, URLEncoder.encode(keyword, "GB2312"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return queryURL;
}
@Override
public String fetch(String newsURL) {
// do nothing
return null;
}
@Override
public List<News> parse(String str) {
Date now = new Date();
List<News> list = Lists.newArrayList();
RssParser rss = new RssParser();
rss.setCharset("gb2312");
rss.setDateParser(new USDateParser());
try{
RssFeed feed = null;
feed = rss.load(str);
// Gets and iterate the items of the feed
List<RssItemBean> items = feed.getItems();
for(RssItemBean item : items) {
News news = new News();
news.setTitle(item.getTitle());
news.setDescription(item.getDescription());
news.setPubFrom(item.getAuthor());
news.setNewsUrl(item.getLink());
news.setDateTime(item.getPubDate().getTime());
long timeDiff = now.getTime() - item.getPubDate().getTime();
if(timeDiff <= Constants.MSEC_PER_DAY)
list.add(news);
}
}catch(Exception e){
e.printStackTrace();
}
return list;
}
@Override
public Boolean save(List<News> list) {
if(list.size() > 0 && newsDao.save(list) >= 0) {
return true;
} else
return false;
}
public static void main(String[] args) throws UnknownHostException {
}
}
| RangerWolf/Finance-News-Helper | src/crawler/impl/BaiduNewsCrawler.java | Java | mit | 2,712 |
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections.Generic;
using OpenHome.Net.Core;
namespace OpenHome.Net.Device.Providers
{
public interface IDvProviderOpenhomeOrgTestLights1 : IDisposable
{
}
/// <summary>
/// Provider for the openhome.org:TestLights:1 UPnP service
/// </summary>
public class DvProviderOpenhomeOrgTestLights1 : DvProvider, IDisposable, IDvProviderOpenhomeOrgTestLights1
{
private GCHandle iGch;
private ActionDelegate iDelegateGetCount;
private ActionDelegate iDelegateGetRoom;
private ActionDelegate iDelegateGetName;
private ActionDelegate iDelegateGetPosition;
private ActionDelegate iDelegateSetColor;
private ActionDelegate iDelegateGetColor;
private ActionDelegate iDelegateGetColorComponents;
/// <summary>
/// Constructor
/// </summary>
/// <param name="aDevice">Device which owns this provider</param>
protected DvProviderOpenhomeOrgTestLights1(DvDevice aDevice)
: base(aDevice, "openhome.org", "TestLights", 1)
{
iGch = GCHandle.Alloc(this);
}
/// <summary>
/// Signal that the action GetCount is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetCount must be overridden if this is called.</remarks>
protected void EnableActionGetCount()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetCount");
action.AddOutputParameter(new ParameterUint("Count"));
iDelegateGetCount = new ActionDelegate(DoGetCount);
EnableAction(action, iDelegateGetCount, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetRoom is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetRoom must be overridden if this is called.</remarks>
protected void EnableActionGetRoom()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetRoom");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterUint("Index"));
action.AddOutputParameter(new ParameterString("RoomName", allowedValues));
iDelegateGetRoom = new ActionDelegate(DoGetRoom);
EnableAction(action, iDelegateGetRoom, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetName is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetName must be overridden if this is called.</remarks>
protected void EnableActionGetName()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetName");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterUint("Index"));
action.AddOutputParameter(new ParameterString("FriendlyName", allowedValues));
iDelegateGetName = new ActionDelegate(DoGetName);
EnableAction(action, iDelegateGetName, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetPosition is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetPosition must be overridden if this is called.</remarks>
protected void EnableActionGetPosition()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetPosition");
action.AddInputParameter(new ParameterUint("Index"));
action.AddOutputParameter(new ParameterUint("X"));
action.AddOutputParameter(new ParameterUint("Y"));
action.AddOutputParameter(new ParameterUint("Z"));
iDelegateGetPosition = new ActionDelegate(DoGetPosition);
EnableAction(action, iDelegateGetPosition, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action SetColor is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// SetColor must be overridden if this is called.</remarks>
protected void EnableActionSetColor()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("SetColor");
action.AddInputParameter(new ParameterUint("Index"));
action.AddInputParameter(new ParameterUint("Color"));
iDelegateSetColor = new ActionDelegate(DoSetColor);
EnableAction(action, iDelegateSetColor, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetColor is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetColor must be overridden if this is called.</remarks>
protected void EnableActionGetColor()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetColor");
action.AddInputParameter(new ParameterUint("Index"));
action.AddOutputParameter(new ParameterUint("Color"));
iDelegateGetColor = new ActionDelegate(DoGetColor);
EnableAction(action, iDelegateGetColor, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetColorComponents is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetColorComponents must be overridden if this is called.</remarks>
protected void EnableActionGetColorComponents()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetColorComponents");
action.AddInputParameter(new ParameterUint("Color"));
action.AddOutputParameter(new ParameterUint("Brightness"));
action.AddOutputParameter(new ParameterUint("Red"));
action.AddOutputParameter(new ParameterUint("Green"));
action.AddOutputParameter(new ParameterUint("Blue"));
iDelegateGetColorComponents = new ActionDelegate(DoGetColorComponents);
EnableAction(action, iDelegateGetColorComponents, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// GetCount action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetCount action for the owning device.
///
/// Must be implemented iff EnableActionGetCount was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aCount"></param>
protected virtual void GetCount(IDvInvocation aInvocation, out uint aCount)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetRoom action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetRoom action for the owning device.
///
/// Must be implemented iff EnableActionGetRoom was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aIndex"></param>
/// <param name="aRoomName"></param>
protected virtual void GetRoom(IDvInvocation aInvocation, uint aIndex, out string aRoomName)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetName action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetName action for the owning device.
///
/// Must be implemented iff EnableActionGetName was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aIndex"></param>
/// <param name="aFriendlyName"></param>
protected virtual void GetName(IDvInvocation aInvocation, uint aIndex, out string aFriendlyName)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetPosition action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetPosition action for the owning device.
///
/// Must be implemented iff EnableActionGetPosition was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aIndex"></param>
/// <param name="aX"></param>
/// <param name="aY"></param>
/// <param name="aZ"></param>
protected virtual void GetPosition(IDvInvocation aInvocation, uint aIndex, out uint aX, out uint aY, out uint aZ)
{
throw (new ActionDisabledError());
}
/// <summary>
/// SetColor action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// SetColor action for the owning device.
///
/// Must be implemented iff EnableActionSetColor was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aIndex"></param>
/// <param name="aColor"></param>
protected virtual void SetColor(IDvInvocation aInvocation, uint aIndex, uint aColor)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetColor action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetColor action for the owning device.
///
/// Must be implemented iff EnableActionGetColor was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aIndex"></param>
/// <param name="aColor"></param>
protected virtual void GetColor(IDvInvocation aInvocation, uint aIndex, out uint aColor)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetColorComponents action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetColorComponents action for the owning device.
///
/// Must be implemented iff EnableActionGetColorComponents was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aColor"></param>
/// <param name="aBrightness"></param>
/// <param name="aRed"></param>
/// <param name="aGreen"></param>
/// <param name="aBlue"></param>
protected virtual void GetColorComponents(IDvInvocation aInvocation, uint aColor, out uint aBrightness, out uint aRed, out uint aGreen, out uint aBlue)
{
throw (new ActionDisabledError());
}
private static int DoGetCount(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderOpenhomeOrgTestLights1 self = (DvProviderOpenhomeOrgTestLights1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
uint count;
try
{
invocation.ReadStart();
invocation.ReadEnd();
self.GetCount(invocation, out count);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetCount");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "GetCount"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetCount", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteUint("Count", count);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetCount", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetRoom(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderOpenhomeOrgTestLights1 self = (DvProviderOpenhomeOrgTestLights1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
uint index;
string roomName;
try
{
invocation.ReadStart();
index = invocation.ReadUint("Index");
invocation.ReadEnd();
self.GetRoom(invocation, index, out roomName);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetRoom");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "GetRoom"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetRoom", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("RoomName", roomName);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetRoom", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetName(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderOpenhomeOrgTestLights1 self = (DvProviderOpenhomeOrgTestLights1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
uint index;
string friendlyName;
try
{
invocation.ReadStart();
index = invocation.ReadUint("Index");
invocation.ReadEnd();
self.GetName(invocation, index, out friendlyName);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetName");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "GetName"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetName", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("FriendlyName", friendlyName);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetName", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetPosition(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderOpenhomeOrgTestLights1 self = (DvProviderOpenhomeOrgTestLights1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
uint index;
uint x;
uint y;
uint z;
try
{
invocation.ReadStart();
index = invocation.ReadUint("Index");
invocation.ReadEnd();
self.GetPosition(invocation, index, out x, out y, out z);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetPosition");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "GetPosition"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetPosition", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteUint("X", x);
invocation.WriteUint("Y", y);
invocation.WriteUint("Z", z);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetPosition", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoSetColor(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderOpenhomeOrgTestLights1 self = (DvProviderOpenhomeOrgTestLights1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
uint index;
uint color;
try
{
invocation.ReadStart();
index = invocation.ReadUint("Index");
color = invocation.ReadUint("Color");
invocation.ReadEnd();
self.SetColor(invocation, index, color);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "SetColor");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "SetColor"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "SetColor", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "SetColor", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetColor(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderOpenhomeOrgTestLights1 self = (DvProviderOpenhomeOrgTestLights1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
uint index;
uint color;
try
{
invocation.ReadStart();
index = invocation.ReadUint("Index");
invocation.ReadEnd();
self.GetColor(invocation, index, out color);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetColor");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "GetColor"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetColor", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteUint("Color", color);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetColor", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetColorComponents(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderOpenhomeOrgTestLights1 self = (DvProviderOpenhomeOrgTestLights1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
uint color;
uint brightness;
uint red;
uint green;
uint blue;
try
{
invocation.ReadStart();
color = invocation.ReadUint("Color");
invocation.ReadEnd();
self.GetColorComponents(invocation, color, out brightness, out red, out green, out blue);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetColorComponents");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "GetColorComponents"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetColorComponents", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteUint("Brightness", brightness);
invocation.WriteUint("Red", red);
invocation.WriteUint("Green", green);
invocation.WriteUint("Blue", blue);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetColorComponents", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
/// <summary>
/// Must be called for each class instance. Must be called before Core.Library.Close().
/// </summary>
public virtual void Dispose()
{
if (DisposeProvider())
iGch.Free();
}
}
}
| DoomHammer/ohNetGenerated | OpenHome/Net/Bindings/Cs/Device/Providers/DvOpenhomeOrgTestLights1.cs | C# | mit | 25,734 |
async function arraySort() {
"use speedyjs";
const array = [1, 2];
const ascending = array.sort();
const descending = array.sort(descendingComparator);
}
function descendingComparator(a: int, b: int) {
"use speedyjs";
return b - a as number;
}
| MichaReiser/speedy.js | packages/compiler/__tests__/code-generation/cases/array/sort.ts | TypeScript | mit | 272 |
# encoding: UTF-8
"""
ไธไธชATR-RSIๆๆ ็ปๅ็ไบคๆ็ญ็ฅ๏ผ้ๅ็จๅจ่กๆ็1ๅ้ๅ5ๅ้็บฟไธใ
ๆณจๆไบ้กน๏ผ
1. ไฝ่
ไธๅฏนไบคๆ็ๅฉๅไปปไฝไฟ่ฏ๏ผ็ญ็ฅไปฃ็ ไป
ไพๅ่
2. ๆฌ็ญ็ฅ้่ฆ็จๅฐtalib๏ผๆฒกๆๅฎ่ฃ
็็จๆท่ฏทๅ
ๅ่www.vnpy.orgไธ็ๆ็จๅฎ่ฃ
3. ๅฐIF0000_1min.csv็จctaHistoryData.pyๅฏผๅ
ฅMongoDBๅ๏ผ็ดๆฅ่ฟ่กๆฌๆไปถๅณๅฏๅๆต็ญ็ฅ
"""
from ctaBase import *
from ctaTemplate import CtaTemplate
import talib
import numpy as np
########################################################################
class AtrRsiStrategy(CtaTemplate):
"""็ปๅATRๅRSIๆๆ ็ไธไธชๅ้็บฟไบคๆ็ญ็ฅ"""
className = 'AtrRsiStrategy'
author = u'็จPython็ไบคๆๅ'
# ็ญ็ฅๅๆฐ
atrLength = 22 # ่ฎก็ฎATRๆๆ ็็ชๅฃๆฐ
atrMaLength = 10 # ่ฎก็ฎATRๅ็บฟ็็ชๅฃๆฐ
rsiLength = 5 # ่ฎก็ฎRSI็็ชๅฃๆฐ
rsiEntry = 16 # RSI็ๅผไปไฟกๅท
trailingPercent = 0.8 # ็พๅๆฏ็งปๅจๆญขๆ
initDays = 10 # ๅๅงๅๆฐๆฎๆ็จ็ๅคฉๆฐ
# ็ญ็ฅๅ้
bar = None # K็บฟๅฏน่ฑก
barMinute = EMPTY_STRING # K็บฟๅฝๅ็ๅ้
bufferSize = 100 # ้่ฆ็ผๅญ็ๆฐๆฎ็ๅคงๅฐ
bufferCount = 0 # ็ฎๅๅทฒ็ป็ผๅญไบ็ๆฐๆฎ็่ฎกๆฐ
highArray = np.zeros(bufferSize) # K็บฟๆ้ซไปท็ๆฐ็ป
lowArray = np.zeros(bufferSize) # K็บฟๆไฝไปท็ๆฐ็ป
closeArray = np.zeros(bufferSize) # K็บฟๆถ็ไปท็ๆฐ็ป
atrCount = 0 # ็ฎๅๅทฒ็ป็ผๅญไบ็ATR็่ฎกๆฐ
atrArray = np.zeros(bufferSize) # ATRๆๆ ็ๆฐ็ป
atrValue = 0 # ๆๆฐ็ATRๆๆ ๆฐๅผ
atrMa = 0 # ATR็งปๅจๅนณๅ็ๆฐๅผ
rsiValue = 0 # RSIๆๆ ็ๆฐๅผ
rsiBuy = 0 # RSIไนฐๅผ้ๅผ
rsiSell = 0 # RSIๅๅผ้ๅผ
intraTradeHigh = 0 # ็งปๅจๆญขๆ็จ็ๆไปๆๅ
ๆ้ซไปท
intraTradeLow = 0 # ็งปๅจๆญขๆ็จ็ๆไปๆๅ
ๆไฝไปท
orderList = [] # ไฟๅญๅงๆไปฃ็ ็ๅ่กจ
# ๅๆฐๅ่กจ๏ผไฟๅญไบๅๆฐ็ๅ็งฐ
paramList = ['name',
'className',
'author',
'vtSymbol',
'atrLength',
'atrMaLength',
'rsiLength',
'rsiEntry',
'trailingPercent']
# ๅ้ๅ่กจ๏ผไฟๅญไบๅ้็ๅ็งฐ
varList = ['inited',
'trading',
'pos',
'atrValue',
'atrMa',
'rsiValue',
'rsiBuy',
'rsiSell']
#----------------------------------------------------------------------
def __init__(self, ctaEngine, setting):
"""Constructor"""
super(AtrRsiStrategy, self).__init__(ctaEngine, setting)
#----------------------------------------------------------------------
def onInit(self):
"""ๅๅงๅ็ญ็ฅ๏ผๅฟ
้กป็ฑ็จๆท็ปงๆฟๅฎ็ฐ๏ผ"""
self.writeCtaLog(u'%s็ญ็ฅๅๅงๅ' %self.name)
# ๅๅงๅRSIๅ
ฅๅบ้ๅผ
self.rsiBuy = 50 + self.rsiEntry
self.rsiSell = 50 - self.rsiEntry
# ่ฝฝๅ
ฅๅๅฒๆฐๆฎ๏ผๅนถ้็จๅๆพ่ฎก็ฎ็ๆนๅผๅๅงๅ็ญ็ฅๆฐๅผ
initData = self.loadBar(self.initDays)
for bar in initData:
self.onBar(bar)
self.putEvent()
#----------------------------------------------------------------------
def onStart(self):
"""ๅฏๅจ็ญ็ฅ๏ผๅฟ
้กป็ฑ็จๆท็ปงๆฟๅฎ็ฐ๏ผ"""
self.writeCtaLog(u'%s็ญ็ฅๅฏๅจ' %self.name)
self.putEvent()
#----------------------------------------------------------------------
def onStop(self):
"""ๅๆญข็ญ็ฅ๏ผๅฟ
้กป็ฑ็จๆท็ปงๆฟๅฎ็ฐ๏ผ"""
self.writeCtaLog(u'%s็ญ็ฅๅๆญข' %self.name)
self.putEvent()
#----------------------------------------------------------------------
def onTick(self, tick):
"""ๆถๅฐ่กๆ
TICKๆจ้๏ผๅฟ
้กป็ฑ็จๆท็ปงๆฟๅฎ็ฐ๏ผ"""
# ่ฎก็ฎK็บฟ
tickMinute = tick.datetime.minute
if tickMinute != self.barMinute:
if self.bar:
self.onBar(self.bar)
bar = CtaBarData()
bar.vtSymbol = tick.vtSymbol
bar.symbol = tick.symbol
bar.exchange = tick.exchange
bar.open = tick.lastPrice
bar.high = tick.lastPrice
bar.low = tick.lastPrice
bar.close = tick.lastPrice
bar.date = tick.date
bar.time = tick.time
bar.datetime = tick.datetime # K็บฟ็ๆถ้ด่ฎพไธบ็ฌฌไธไธชTick็ๆถ้ด
self.bar = bar # ่ฟ็งๅๆณไธบไบๅๅฐไธๅฑ่ฎฟ้ฎ๏ผๅ ๅฟซ้ๅบฆ
self.barMinute = tickMinute # ๆดๆฐๅฝๅ็ๅ้
else: # ๅฆๅ็ปง็ปญ็ดฏๅ ๆฐ็K็บฟ
bar = self.bar # ๅๆณๅๆ ทไธบไบๅ ๅฟซ้ๅบฆ
bar.high = max(bar.high, tick.lastPrice)
bar.low = min(bar.low, tick.lastPrice)
bar.close = tick.lastPrice
#----------------------------------------------------------------------
def onBar(self, bar):
"""ๆถๅฐBarๆจ้๏ผๅฟ
้กป็ฑ็จๆท็ปงๆฟๅฎ็ฐ๏ผ"""
# ๆค้ไนๅๅๅบ็ๅฐๆชๆไบค็ๅงๆ๏ผๅ
ๆฌ้ไปทๅๅๅๆญขๅ๏ผ
for orderID in self.orderList:
self.cancelOrder(orderID)
self.orderList = []
# ไฟๅญK็บฟๆฐๆฎ
self.closeArray[0:self.bufferSize-1] = self.closeArray[1:self.bufferSize]
self.highArray[0:self.bufferSize-1] = self.highArray[1:self.bufferSize]
self.lowArray[0:self.bufferSize-1] = self.lowArray[1:self.bufferSize]
self.closeArray[-1] = bar.close
self.highArray[-1] = bar.high
self.lowArray[-1] = bar.low
self.bufferCount += 1
if self.bufferCount < self.bufferSize:
return
# ่ฎก็ฎๆๆ ๆฐๅผ
self.atrValue = talib.ATR(self.highArray,
self.lowArray,
self.closeArray,
self.atrLength)[-1]
self.atrArray[0:self.bufferSize-1] = self.atrArray[1:self.bufferSize]
self.atrArray[-1] = self.atrValue
self.atrCount += 1
if self.atrCount < self.bufferSize:
return
self.atrMa = talib.MA(self.atrArray,
self.atrMaLength)[-1]
self.rsiValue = talib.RSI(self.closeArray,
self.rsiLength)[-1]
# ๅคๆญๆฏๅฆ่ฆ่ฟ่กไบคๆ
# ๅฝๅๆ ไปไฝ
if self.pos == 0:
self.intraTradeHigh = bar.high
self.intraTradeLow = bar.low
# ATRๆฐๅผไธ็ฉฟๅ
ถ็งปๅจๅนณๅ็บฟ๏ผ่ฏดๆ่กๆ
็ญๆๅ
ๆณขๅจๅ ๅคง
# ๅณๅคไบ่ถๅฟ็ๆฆ็่พๅคง๏ผ้ๅCTAๅผไป
if self.atrValue > self.atrMa:
# ไฝฟ็จRSIๆๆ ็่ถๅฟ่กๆ
ๆถ๏ผไผๅจ่ถ
ไนฐ่ถ
ๅๅบ้ๅ็นๅพ๏ผไฝไธบๅผไปไฟกๅท
if self.rsiValue > self.rsiBuy:
# ่ฟ้ไธบไบไฟ่ฏๆไบค๏ผ้ๆฉ่ถ
ไปท5ไธชๆดๆๆฐ็นไธๅ
self.buy(bar.close+5, 1)
return
if self.rsiValue < self.rsiSell:
self.short(bar.close-5, 1)
return
# ๆๆๅคๅคดไปไฝ
if self.pos == 1:
# ่ฎก็ฎๅคๅคดๆๆๆๅ
็ๆ้ซไปท๏ผไปฅๅ้็ฝฎๆไฝไปท
self.intraTradeHigh = max(self.intraTradeHigh, bar.high)
self.intraTradeLow = bar.low
# ่ฎก็ฎๅคๅคด็งปๅจๆญขๆ
longStop = self.intraTradeHigh * (1-self.trailingPercent/100)
# ๅๅบๆฌๅฐๆญขๆๅงๆ๏ผๅนถไธๆๅงๆๅท่ฎฐๅฝไธๆฅ๏ผ็จไบๅ็ปญๆคๅ
orderID = self.sell(longStop, 1, stop=True)
self.orderList.append(orderID)
return
# ๆๆ็ฉบๅคดไปไฝ
if self.pos == -1:
self.intraTradeLow = min(self.intraTradeLow, bar.low)
self.intraTradeHigh = bar.high
shortStop = self.intraTradeLow * (1+self.trailingPercent/100)
orderID = self.cover(shortStop, 1, stop=True)
self.orderList.append(orderID)
return
# ๅๅบ็ถๆๆดๆฐไบไปถ
self.putEvent()
#----------------------------------------------------------------------
def onOrder(self, order):
"""ๆถๅฐๅงๆๅๅๆจ้๏ผๅฟ
้กป็ฑ็จๆท็ปงๆฟๅฎ็ฐ๏ผ"""
pass
#----------------------------------------------------------------------
def onTrade(self, trade):
pass
if __name__ == '__main__':
# ๆไพ็ดๆฅๅๅปๅๆต็ๅ่ฝ
# ๅฏผๅ
ฅPyQt4็ๅ
ๆฏไธบไบไฟ่ฏmatplotlibไฝฟ็จPyQt4่ไธๆฏPySide๏ผ้ฒๆญขๅๅงๅๅบ้
from ctaBacktesting import *
from PyQt4 import QtCore, QtGui
# ๅๅปบๅๆตๅผๆ
engine = BacktestingEngine()
# ่ฎพ็ฝฎๅผๆ็ๅๆตๆจกๅผไธบK็บฟ
engine.setBacktestingMode(engine.BAR_MODE)
# ่ฎพ็ฝฎๅๆต็จ็ๆฐๆฎ่ตทๅงๆฅๆ
engine.setStartDate('20120101')
# ่ฝฝๅ
ฅๅๅฒๆฐๆฎๅฐๅผๆไธญ
engine.loadHistoryData(MINUTE_DB_NAME, 'IF0000')
# ่ฎพ็ฝฎไบงๅ็ธๅ
ณๅๆฐ
engine.setSlippage(0.2) # ่กๆ1่ทณ
engine.setRate(0.3/10000) # ไธ0.3
engine.setSize(300) # ่กๆๅ็บฆๅคงๅฐ
# ๅจๅผๆไธญๅๅปบ็ญ็ฅๅฏน่ฑก
engine.initStrategy(AtrRsiStrategy, {})
# ๅผๅง่ทๅๆต
engine.runBacktesting()
# ๆพ็คบๅๆต็ปๆ
engine.showBacktestingResult()
| lukesummer/vnpy | vn.trader/ctaAlgo/strategyAtrRsi.py | Python | mit | 9,927 |
var React = require('react-native');
var {
StyleSheet,
View,
Animated,
} = React;
var Dot = React.createClass({
propTypes: {
isPlacedCorrectly: React.PropTypes.bool.isRequired,
},
getInitialState: function() {
return {
scale: new Animated.Value(this.props.isPlacedCorrectly ? 1 : 0.1),
visible: this.props.isPlacedCorrectly,
};
},
componentWillReceiveProps: function(nextProps) {
if (!this.props.isPlacedCorrectly && nextProps.isPlacedCorrectly) {
this.animateShow();
} else if (this.props.isPlacedCorrectly && !nextProps.isPlacedCorrectly) {
this.animateHide();
}
},
animateShow: function() {
this.setState({visible: true}, () => {
Animated.timing(this.state.scale, {
toValue: 1,
duration: 100,
}).start();
});
},
animateHide: function() {
Animated.timing(this.state.scale, {
toValue: 0.1,
duration: 100,
}).start(() => this.setState({visible: false}));
},
render: function() {
if (!this.state.visible) {
return null;
}
return (
<Animated.View style={[styles.dot, {transform: [{scale: this.state.scale}]}]}/>
);
},
});
var styles = StyleSheet.create({
dot: {
backgroundColor: '#FF3366',
width: 6,
height: 6,
borderRadius: 3,
margin: 3,
},
});
module.exports = Dot;
| nosovsh/fifteen | src/Dot.js | JavaScript | mit | 1,364 |
import os
import yaml
MONGO_USERNAME = os.getenv('MONGO_USERNAME', None)
MONGO_PASSWORD = os.getenv('MONGO_PASSWORD', None)
MONGODB_HOST = os.getenv('MONGODB_HOST', '127.0.0.1')
MONGODB_PORT = int(os.getenv('MONGODB_PORT', '27017'))
MONGODB_SERVERS = os.getenv('MONGODB_SERVERS') \
or '{}:{}'.format(MONGODB_HOST, MONGODB_PORT)
MONGODB_DEFAULT_URL = 'mongodb://{}'.format(MONGODB_SERVERS)
MONGO_URL = os.getenv('MONGO_URL') or MONGODB_DEFAULT_URL
MONGO_INCLUDES = os.getenv('MONGO_INCLUDES', '')
ES_URL = os.getenv('ES_URL', 'http://localhost:9200')
ES_INDEXES = yaml.load(os.getenv('ES_INDEXES') or '{}')
ES_TIMEOUT_SECONDS = int(os.getenv('ES_TIMEOUT_SECONDS', '100'))
LOG_VERBOSITY = int(os.getenv('LOG_VERBOSITY', 2))
MONGO_CONNECTOR_CONFIG = 'mongo-connector.json'
DEFAULTS = {
'es': {
'url': ES_URL,
'indexes': ES_INDEXES
},
'mongo-connector': {
'mainAddress': MONGO_URL,
'authentication': {
'adminUsername': MONGO_USERNAME,
'password': MONGO_PASSWORD
},
'namespaces': {
'include': MONGO_INCLUDES.split(','),
},
'timezoneAware': True,
'docManagers': [
{
'docManager': 'elastic_doc_manager',
'targetURL': ES_URL,
"args": {
"clientOptions": {
"timeout": ES_TIMEOUT_SECONDS
}
}
}
],
'logging': {
'type': 'stream'
},
'verbosity': LOG_VERBOSITY,
'continueOnError': True
},
}
CONFIG_LOCATION = os.getenv('CONFIG_LOCATION')
| ymind/docker-mongo-es | conf/appconfig.py | Python | mit | 1,677 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/*
* Users of PHP 5.2 should be able to run the requirements checks.
* This is why the file and all classes must be compatible with PHP 5.2+
* (e.g. not using namespaces and closures).
*
* ************** CAUTION **************
*
* DO NOT EDIT THIS FILE as it will be overridden by Composer as part of
* the installation/update process. The original file resides in the
* SensioDistributionBundle.
*
* ************** CAUTION **************
*/
/**
* Represents a single PHP requirement, e.g. an installed extension.
* It can be a mandatory requirement or an optional recommendation.
* There is a special subclass, named PhpIniRequirement, to check a php.ini configuration.
*
* @author Tobias Schultze <http://tobion.de>
*/
class Requirement
{
private $fulfilled;
private $testMessage;
private $helpText;
private $helpHtml;
private $optional;
/**
* Constructor that initializes the requirement.
*
* @param bool $fulfilled Whether the requirement is fulfilled
* @param string $testMessage The message for testing the requirement
* @param string $helpHtml The help text formatted in HTML for resolving the problem
* @param string|null $helpText The help text (when null, it will be inferred from $helpHtml, i.e. stripped from HTML tags)
* @param bool $optional Whether this is only an optional recommendation not a mandatory requirement
*/
public function __construct($fulfilled, $testMessage, $helpHtml, $helpText = null, $optional = false)
{
$this->fulfilled = (bool) $fulfilled;
$this->testMessage = (string) $testMessage;
$this->helpHtml = (string) $helpHtml;
$this->helpText = null === $helpText ? strip_tags($this->helpHtml) : (string) $helpText;
$this->optional = (bool) $optional;
}
/**
* Returns whether the requirement is fulfilled.
*
* @return bool true if fulfilled, otherwise false
*/
public function isFulfilled()
{
return $this->fulfilled;
}
/**
* Returns the message for testing the requirement.
*
* @return string The test message
*/
public function getTestMessage()
{
return $this->testMessage;
}
/**
* Returns the help text for resolving the problem.
*
* @return string The help text
*/
public function getHelpText()
{
return $this->helpText;
}
/**
* Returns the help text formatted in HTML.
*
* @return string The HTML help
*/
public function getHelpHtml()
{
return $this->helpHtml;
}
/**
* Returns whether this is only an optional recommendation and not a mandatory requirement.
*
* @return bool true if optional, false if mandatory
*/
public function isOptional()
{
return $this->optional;
}
}
/**
* Represents a PHP requirement in form of a php.ini configuration.
*
* @author Tobias Schultze <http://tobion.de>
*/
class PhpIniRequirement extends Requirement
{
/**
* Constructor that initializes the requirement.
*
* @param string $cfgName The configuration name used for ini_get()
* @param bool|callback $evaluation Either a boolean indicating whether the configuration should evaluate to true or false,
* or a callback function receiving the configuration value as parameter to determine the fulfillment of the requirement
* @param bool $approveCfgAbsence If true the Requirement will be fulfilled even if the configuration option does not exist, i.e. ini_get() returns false.
* This is helpful for abandoned configs in later PHP versions or configs of an optional extension, like Suhosin.
* Example: You require a config to be true but PHP later removes this config and defaults it to true internally.
* @param string|null $testMessage The message for testing the requirement (when null and $evaluation is a boolean a default message is derived)
* @param string|null $helpHtml The help text formatted in HTML for resolving the problem (when null and $evaluation is a boolean a default help is derived)
* @param string|null $helpText The help text (when null, it will be inferred from $helpHtml, i.e. stripped from HTML tags)
* @param bool $optional Whether this is only an optional recommendation not a mandatory requirement
*/
public function __construct($cfgName, $evaluation, $approveCfgAbsence = false, $testMessage = null, $helpHtml = null, $helpText = null, $optional = false)
{
$cfgValue = ini_get($cfgName);
if (is_callable($evaluation)) {
if (null === $testMessage || null === $helpHtml) {
throw new InvalidArgumentException('You must provide the parameters testMessage and helpHtml for a callback evaluation.');
}
$fulfilled = call_user_func($evaluation, $cfgValue);
} else {
if (null === $testMessage) {
$testMessage = sprintf('%s %s be %s in php.ini',
$cfgName,
$optional ? 'should' : 'must',
$evaluation ? 'enabled' : 'disabled'
);
}
if (null === $helpHtml) {
$helpHtml = sprintf('Set <strong>%s</strong> to <strong>%s</strong> in php.ini<a href="#phpini">*</a>.',
$cfgName,
$evaluation ? 'on' : 'off'
);
}
$fulfilled = $evaluation == $cfgValue;
}
parent::__construct($fulfilled || ($approveCfgAbsence && false === $cfgValue), $testMessage, $helpHtml, $helpText, $optional);
}
}
/**
* A RequirementCollection represents a set of Requirement instances.
*
* @author Tobias Schultze <http://tobion.de>
*/
class RequirementCollection implements IteratorAggregate
{
private $requirements = array();
/**
* Gets the current RequirementCollection as an Iterator.
*
* @return Traversable A Traversable interface
*/
public function getIterator()
{
return new ArrayIterator($this->requirements);
}
/**
* Adds a Requirement.
*
* @param Requirement $requirement A Requirement instance
*/
public function add(Requirement $requirement)
{
$this->requirements[] = $requirement;
}
/**
* Adds a mandatory requirement.
*
* @param bool $fulfilled Whether the requirement is fulfilled
* @param string $testMessage The message for testing the requirement
* @param string $helpHtml The help text formatted in HTML for resolving the problem
* @param string|null $helpText The help text (when null, it will be inferred from $helpHtml, i.e. stripped from HTML tags)
*/
public function addRequirement($fulfilled, $testMessage, $helpHtml, $helpText = null)
{
$this->add(new Requirement($fulfilled, $testMessage, $helpHtml, $helpText, false));
}
/**
* Adds an optional recommendation.
*
* @param bool $fulfilled Whether the recommendation is fulfilled
* @param string $testMessage The message for testing the recommendation
* @param string $helpHtml The help text formatted in HTML for resolving the problem
* @param string|null $helpText The help text (when null, it will be inferred from $helpHtml, i.e. stripped from HTML tags)
*/
public function addRecommendation($fulfilled, $testMessage, $helpHtml, $helpText = null)
{
$this->add(new Requirement($fulfilled, $testMessage, $helpHtml, $helpText, true));
}
/**
* Adds a mandatory requirement in form of a php.ini configuration.
*
* @param string $cfgName The configuration name used for ini_get()
* @param bool|callback $evaluation Either a boolean indicating whether the configuration should evaluate to true or false,
* or a callback function receiving the configuration value as parameter to determine the fulfillment of the requirement
* @param bool $approveCfgAbsence If true the Requirement will be fulfilled even if the configuration option does not exist, i.e. ini_get() returns false.
* This is helpful for abandoned configs in later PHP versions or configs of an optional extension, like Suhosin.
* Example: You require a config to be true but PHP later removes this config and defaults it to true internally.
* @param string $testMessage The message for testing the requirement (when null and $evaluation is a boolean a default message is derived)
* @param string $helpHtml The help text formatted in HTML for resolving the problem (when null and $evaluation is a boolean a default help is derived)
* @param string|null $helpText The help text (when null, it will be inferred from $helpHtml, i.e. stripped from HTML tags)
*/
public function addPhpIniRequirement($cfgName, $evaluation, $approveCfgAbsence = false, $testMessage = null, $helpHtml = null, $helpText = null)
{
$this->add(new PhpIniRequirement($cfgName, $evaluation, $approveCfgAbsence, $testMessage, $helpHtml, $helpText, false));
}
/**
* Adds an optional recommendation in form of a php.ini configuration.
*
* @param string $cfgName The configuration name used for ini_get()
* @param bool|callback $evaluation Either a boolean indicating whether the configuration should evaluate to true or false,
* or a callback function receiving the configuration value as parameter to determine the fulfillment of the requirement
* @param bool $approveCfgAbsence If true the Requirement will be fulfilled even if the configuration option does not exist, i.e. ini_get() returns false.
* This is helpful for abandoned configs in later PHP versions or configs of an optional extension, like Suhosin.
* Example: You require a config to be true but PHP later removes this config and defaults it to true internally.
* @param string $testMessage The message for testing the requirement (when null and $evaluation is a boolean a default message is derived)
* @param string $helpHtml The help text formatted in HTML for resolving the problem (when null and $evaluation is a boolean a default help is derived)
* @param string|null $helpText The help text (when null, it will be inferred from $helpHtml, i.e. stripped from HTML tags)
*/
public function addPhpIniRecommendation($cfgName, $evaluation, $approveCfgAbsence = false, $testMessage = null, $helpHtml = null, $helpText = null)
{
$this->add(new PhpIniRequirement($cfgName, $evaluation, $approveCfgAbsence, $testMessage, $helpHtml, $helpText, true));
}
/**
* Adds a requirement collection to the current set of requirements.
*
* @param RequirementCollection $collection A RequirementCollection instance
*/
public function addCollection(RequirementCollection $collection)
{
$this->requirements = array_merge($this->requirements, $collection->all());
}
/**
* Returns both requirements and recommendations.
*
* @return array Array of Requirement instances
*/
public function all()
{
return $this->requirements;
}
/**
* Returns all mandatory requirements.
*
* @return array Array of Requirement instances
*/
public function getRequirements()
{
$array = array();
foreach ($this->requirements as $req) {
if (!$req->isOptional()) {
$array[] = $req;
}
}
return $array;
}
/**
* Returns the mandatory requirements that were not met.
*
* @return array Array of Requirement instances
*/
public function getFailedRequirements()
{
$array = array();
foreach ($this->requirements as $req) {
if (!$req->isFulfilled() && !$req->isOptional()) {
$array[] = $req;
}
}
return $array;
}
/**
* Returns all optional recommendations.
*
* @return array Array of Requirement instances
*/
public function getRecommendations()
{
$array = array();
foreach ($this->requirements as $req) {
if ($req->isOptional()) {
$array[] = $req;
}
}
return $array;
}
/**
* Returns the recommendations that were not met.
*
* @return array Array of Requirement instances
*/
public function getFailedRecommendations()
{
$array = array();
foreach ($this->requirements as $req) {
if (!$req->isFulfilled() && $req->isOptional()) {
$array[] = $req;
}
}
return $array;
}
/**
* Returns whether a php.ini configuration is not correct.
*
* @return bool php.ini configuration problem?
*/
public function hasPhpIniConfigIssue()
{
foreach ($this->requirements as $req) {
if (!$req->isFulfilled() && $req instanceof PhpIniRequirement) {
return true;
}
}
return false;
}
/**
* Returns the PHP configuration file (php.ini) path.
*
* @return string|false php.ini file path
*/
public function getPhpIniConfigPath()
{
return get_cfg_var('cfg_file_path');
}
}
/**
* This class specifies all requirements and optional recommendations that
* are necessary to run the Symfony Standard Edition.
*
* @author Tobias Schultze <http://tobion.de>
* @author Fabien Potencier <fabien@symfony.com>
*/
class SymfonyRequirements extends RequirementCollection
{
const REQUIRED_PHP_VERSION = '5.3.3';
/**
* Constructor that initializes the requirements.
*/
public function __construct()
{
/* mandatory requirements follow */
$installedPhpVersion = phpversion();
$this->addRequirement(
version_compare($installedPhpVersion, self::REQUIRED_PHP_VERSION, '>='),
sprintf('PHP version must be at least %s (%s installed)', self::REQUIRED_PHP_VERSION, $installedPhpVersion),
sprintf('You are running PHP version "<strong>%s</strong>", but Symfony needs at least PHP "<strong>%s</strong>" to run.
Before using Symfony, upgrade your PHP installation, preferably to the latest version.',
$installedPhpVersion, self::REQUIRED_PHP_VERSION),
sprintf('Install PHP %s or newer (installed version is %s)', self::REQUIRED_PHP_VERSION, $installedPhpVersion)
);
$this->addRequirement(
version_compare($installedPhpVersion, '5.3.16', '!='),
'PHP version must not be 5.3.16 as Symfony won\'t work properly with it',
'Install PHP 5.3.17 or newer (or downgrade to an earlier PHP version)'
);
$this->addRequirement(
is_dir(__DIR__.'/../vendor/composer'),
'Vendor libraries must be installed',
'Vendor libraries are missing. Install composer following instructions from <a href="http://getcomposer.org/">http://getcomposer.org/</a>. '.
'Then run "<strong>php composer.phar install</strong>" to install them.'
);
$cacheDir = is_dir(__DIR__.'/../var/cache') ? __DIR__.'/../var/cache' : __DIR__.'/cache';
$this->addRequirement(
is_writable($cacheDir),
'app/cache/ or var/cache/ directory must be writable',
'Change the permissions of either "<strong>app/cache/</strong>" or "<strong>var/cache/</strong>" directory so that the web server can write into it.'
);
$logsDir = is_dir(__DIR__.'/../var/logs') ? __DIR__.'/../var/logs' : __DIR__.'/logs';
$this->addRequirement(
is_writable($logsDir),
'app/logs/ or var/logs/ directory must be writable',
'Change the permissions of either "<strong>app/logs/</strong>" or "<strong>var/logs/</strong>" directory so that the web server can write into it.'
);
$this->addPhpIniRequirement(
'date.timezone', true, false,
'date.timezone setting must be set',
'Set the "<strong>date.timezone</strong>" setting in php.ini<a href="#phpini">*</a> (like Europe/Paris).'
);
if (version_compare($installedPhpVersion, self::REQUIRED_PHP_VERSION, '>=')) {
$timezones = array();
foreach (DateTimeZone::listAbbreviations() as $abbreviations) {
foreach ($abbreviations as $abbreviation) {
$timezones[$abbreviation['timezone_id']] = true;
}
}
$this->addRequirement(
isset($timezones[@date_default_timezone_get()]),
sprintf('Configured default timezone "%s" must be supported by your installation of PHP', @date_default_timezone_get()),
'Your default timezone is not supported by PHP. Check for typos in your <strong>php.ini</strong> file and have a look at the list of deprecated timezones at <a href="http://php.net/manual/en/timezones.others.php">http://php.net/manual/en/timezones.others.php</a>.'
);
}
$this->addRequirement(
function_exists('iconv'),
'iconv() must be available',
'Install and enable the <strong>iconv</strong> extension.'
);
$this->addRequirement(
function_exists('json_encode'),
'json_encode() must be available',
'Install and enable the <strong>JSON</strong> extension.'
);
$this->addRequirement(
function_exists('session_start'),
'session_start() must be available',
'Install and enable the <strong>session</strong> extension.'
);
$this->addRequirement(
function_exists('ctype_alpha'),
'ctype_alpha() must be available',
'Install and enable the <strong>ctype</strong> extension.'
);
$this->addRequirement(
function_exists('token_get_all'),
'token_get_all() must be available',
'Install and enable the <strong>Tokenizer</strong> extension.'
);
$this->addRequirement(
function_exists('simplexml_import_dom'),
'simplexml_import_dom() must be available',
'Install and enable the <strong>SimpleXML</strong> extension.'
);
if (function_exists('apc_store') && ini_get('apc.enabled')) {
if (version_compare($installedPhpVersion, '5.4.0', '>=')) {
$this->addRequirement(
version_compare(phpversion('apc'), '3.1.13', '>='),
'APC version must be at least 3.1.13 when using PHP 5.4',
'Upgrade your <strong>APC</strong> extension (3.1.13+).'
);
} else {
$this->addRequirement(
version_compare(phpversion('apc'), '3.0.17', '>='),
'APC version must be at least 3.0.17',
'Upgrade your <strong>APC</strong> extension (3.0.17+).'
);
}
}
$this->addPhpIniRequirement('detect_unicode', false);
if (extension_loaded('suhosin')) {
$this->addPhpIniRequirement(
'suhosin.executor.include.whitelist',
create_function('$cfgValue', 'return false !== stripos($cfgValue, "phar");'),
false,
'suhosin.executor.include.whitelist must be configured correctly in php.ini',
'Add "<strong>phar</strong>" to <strong>suhosin.executor.include.whitelist</strong> in php.ini<a href="#phpini">*</a>.'
);
}
if (extension_loaded('xdebug')) {
$this->addPhpIniRequirement(
'xdebug.show_exception_trace', false, true
);
$this->addPhpIniRequirement(
'xdebug.scream', false, true
);
$this->addPhpIniRecommendation(
'xdebug.max_nesting_level',
create_function('$cfgValue', 'return $cfgValue > 100;'),
true,
'xdebug.max_nesting_level should be above 100 in php.ini',
'Set "<strong>xdebug.max_nesting_level</strong>" to e.g. "<strong>250</strong>" in php.ini<a href="#phpini">*</a> to stop Xdebug\'s infinite recursion protection erroneously throwing a fatal error in your project.'
);
}
$pcreVersion = defined('PCRE_VERSION') ? (float) PCRE_VERSION : null;
$this->addRequirement(
null !== $pcreVersion,
'PCRE extension must be available',
'Install the <strong>PCRE</strong> extension (version 8.0+).'
);
if (extension_loaded('mbstring')) {
$this->addPhpIniRequirement(
'mbstring.func_overload',
create_function('$cfgValue', 'return (int) $cfgValue === 0;'),
true,
'string functions should not be overloaded',
'Set "<strong>mbstring.func_overload</strong>" to <strong>0</strong> in php.ini<a href="#phpini">*</a> to disable function overloading by the mbstring extension.'
);
}
/* optional recommendations follow */
if (file_exists(__DIR__.'/../vendor/composer')) {
require_once __DIR__.'/../vendor/autoload.php';
try {
$r = new ReflectionClass('Sensio\Bundle\DistributionBundle\SensioDistributionBundle');
$contents = file_get_contents(dirname($r->getFileName()).'/Resources/skeleton/app/SymfonyRequirements.php');
} catch (ReflectionException $e) {
$contents = '';
}
$this->addRecommendation(
file_get_contents(__FILE__) === $contents,
'Requirements file should be up-to-date',
'Your requirements file is outdated. Run composer install and re-check your configuration.'
);
}
$this->addRecommendation(
version_compare($installedPhpVersion, '5.3.4', '>='),
'You should use at least PHP 5.3.4 due to PHP bug #52083 in earlier versions',
'Your project might malfunction randomly due to PHP bug #52083 ("Notice: Trying to get property of non-object"). Install PHP 5.3.4 or newer.'
);
$this->addRecommendation(
version_compare($installedPhpVersion, '5.3.8', '>='),
'When using annotations you should have at least PHP 5.3.8 due to PHP bug #55156',
'Install PHP 5.3.8 or newer if your project uses annotations.'
);
$this->addRecommendation(
version_compare($installedPhpVersion, '5.4.0', '!='),
'You should not use PHP 5.4.0 due to the PHP bug #61453',
'Your project might not work properly due to the PHP bug #61453 ("Cannot dump definitions which have method calls"). Install PHP 5.4.1 or newer.'
);
$this->addRecommendation(
version_compare($installedPhpVersion, '5.4.11', '>='),
'When using the logout handler from the Symfony Security Component, you should have at least PHP 5.4.11 due to PHP bug #63379 (as a workaround, you can also set invalidate_session to false in the security logout handler configuration)',
'Install PHP 5.4.11 or newer if your project uses the logout handler from the Symfony Security Component.'
);
$this->addRecommendation(
(version_compare($installedPhpVersion, '5.3.18', '>=') && version_compare($installedPhpVersion, '5.4.0', '<'))
||
version_compare($installedPhpVersion, '5.4.8', '>='),
'You should use PHP 5.3.18+ or PHP 5.4.8+ to always get nice error messages for fatal errors in the development environment due to PHP bug #61767/#60909',
'Install PHP 5.3.18+ or PHP 5.4.8+ if you want nice error messages for all fatal errors in the development environment.'
);
if (null !== $pcreVersion) {
$this->addRecommendation(
$pcreVersion >= 8.0,
sprintf('PCRE extension should be at least version 8.0 (%s installed)', $pcreVersion),
'<strong>PCRE 8.0+</strong> is preconfigured in PHP since 5.3.2 but you are using an outdated version of it. Symfony probably works anyway but it is recommended to upgrade your PCRE extension.'
);
}
$this->addRecommendation(
class_exists('DomDocument'),
'PHP-DOM and PHP-XML modules should be installed',
'Install and enable the <strong>PHP-DOM</strong> and the <strong>PHP-XML</strong> modules.'
);
$this->addRecommendation(
function_exists('mb_strlen'),
'mb_strlen() should be available',
'Install and enable the <strong>mbstring</strong> extension.'
);
$this->addRecommendation(
function_exists('iconv'),
'iconv() should be available',
'Install and enable the <strong>iconv</strong> extension.'
);
$this->addRecommendation(
function_exists('utf8_decode'),
'utf8_decode() should be available',
'Install and enable the <strong>XML</strong> extension.'
);
$this->addRecommendation(
function_exists('filter_var'),
'filter_var() should be available',
'Install and enable the <strong>filter</strong> extension.'
);
if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
$this->addRecommendation(
function_exists('posix_isatty'),
'posix_isatty() should be available',
'Install and enable the <strong>php_posix</strong> extension (used to colorize the CLI output).'
);
}
$this->addRecommendation(
extension_loaded('intl'),
'intl extension should be available',
'Install and enable the <strong>intl</strong> extension (used for validators).'
);
if (extension_loaded('intl')) {
// in some WAMP server installations, new Collator() returns null
$this->addRecommendation(
null !== new Collator('fr_FR'),
'intl extension should be correctly configured',
'The intl extension does not behave properly. This problem is typical on PHP 5.3.X x64 WIN builds.'
);
// check for compatible ICU versions (only done when you have the intl extension)
if (defined('INTL_ICU_VERSION')) {
$version = INTL_ICU_VERSION;
} else {
$reflector = new ReflectionExtension('intl');
ob_start();
$reflector->info();
$output = strip_tags(ob_get_clean());
preg_match('/^ICU version +(?:=> )?(.*)$/m', $output, $matches);
$version = $matches[1];
}
$this->addRecommendation(
version_compare($version, '4.0', '>='),
'intl ICU version should be at least 4+',
'Upgrade your <strong>intl</strong> extension with a newer ICU version (4+).'
);
$this->addPhpIniRecommendation(
'intl.error_level',
create_function('$cfgValue', 'return (int) $cfgValue === 0;'),
true,
'intl.error_level should be 0 in php.ini',
'Set "<strong>intl.error_level</strong>" to "<strong>0</strong>" in php.ini<a href="#phpini">*</a> to inhibit the messages when an error occurs in ICU functions.'
);
}
$accelerator =
(extension_loaded('eaccelerator') && ini_get('eaccelerator.enable'))
||
(extension_loaded('apc') && ini_get('apc.enabled'))
||
(extension_loaded('Zend Optimizer+') && ini_get('zend_optimizerplus.enable'))
||
(extension_loaded('Zend OPcache') && ini_get('opcache.enable'))
||
(extension_loaded('xcache') && ini_get('xcache.cacher'))
||
(extension_loaded('wincache') && ini_get('wincache.ocenabled'))
;
$this->addRecommendation(
$accelerator,
'a PHP accelerator should be installed',
'Install and/or enable a <strong>PHP accelerator</strong> (highly recommended).'
);
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$this->addRecommendation(
$this->getRealpathCacheSize() > 1000,
'realpath_cache_size should be above 1024 in php.ini',
'Set "<strong>realpath_cache_size</strong>" to e.g. "<strong>1024</strong>" in php.ini<a href="#phpini">*</a> to improve performance on windows.'
);
}
$this->addPhpIniRecommendation('short_open_tag', false);
$this->addPhpIniRecommendation('magic_quotes_gpc', false, true);
$this->addPhpIniRecommendation('register_globals', false, true);
$this->addPhpIniRecommendation('session.auto_start', false);
$this->addRecommendation(
class_exists('PDO'),
'PDO should be installed',
'Install <strong>PDO</strong> (mandatory for Doctrine).'
);
if (class_exists('PDO')) {
$drivers = PDO::getAvailableDrivers();
$this->addRecommendation(
count($drivers) > 0,
sprintf('PDO should have some drivers installed (currently available: %s)', count($drivers) ? implode(', ', $drivers) : 'none'),
'Install <strong>PDO drivers</strong> (mandatory for Doctrine).'
);
}
}
/**
* Loads realpath_cache_size from php.ini and converts it to int.
*
* (e.g. 16k is converted to 16384 int)
*
* @return int
*/
protected function getRealpathCacheSize()
{
$size = ini_get('realpath_cache_size');
$size = trim($size);
$unit = strtolower(substr($size, -1, 1));
switch ($unit) {
case 'g':
return $size * 1024 * 1024 * 1024;
case 'm':
return $size * 1024 * 1024;
case 'k':
return $size * 1024;
default:
return (int) $size;
}
}
}
| olivierlb73/musicall | app/SymfonyRequirements.php | PHP | mit | 27,587 |
var namespacehryky_1_1log =
[
[ "AutoElapsed", "structhryky_1_1log_1_1_auto_elapsed.html", null ],
[ "level_type", "namespacehryky_1_1log.html#a6005efaf1fc45416ed6aa211f939993f", null ],
[ "writer_type", "namespacehryky_1_1log.html#a855ba68dea65f57a39b7a1cb03aee800", null ],
[ "write", "namespacehryky_1_1log.html#a5c7e76e7e42521f83c90fc8813f1f3ea", null ]
]; | hiroyuki-seki/hryky-codebase | doc/html/namespacehryky_1_1log.js | JavaScript | mit | 376 |
require 'spec_helper'
# Specs in this file have access to a helper object that includes
# the QuizHelper. For example:
#
# describe QuizHelper do
# describe "string concat" do
# it "concats two strings with spaces" do
# helper.concat_strings("this","that").should == "this that"
# end
# end
# end
describe QuizHelper do
pending "add some examples to (or delete) #{__FILE__}"
end
| jparbros/magnolia_cream | spec/helpers/quiz_helper_spec.rb | Ruby | mit | 400 |
/****************************************************************************
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
/**
* Base class for ccs.Bone objects.
* @class
* @extends ccs.Node
*
* @property {ccs.BoneData} boneData - The bone data
* @property {ccs.Armature} armature - The armature
* @property {ccs.Bone} parentBone - The parent bone
* @property {ccs.Armature} childArmature - The child armature
* @property {Array} childrenBone - <@readonly> All children bones
* @property {ccs.Tween} tween - <@readonly> Tween
* @property {ccs.FrameData} tweenData - <@readonly> The tween data
* @property {ccs.ColliderFilter} colliderFilter - The collider filter
* @property {ccs.DisplayManager} displayManager - The displayManager
* @property {Boolean} ignoreMovementBoneData - Indicate whether force the bone to show When CCArmature play a animation and there isn't a CCMovementBoneData of this bone in this CCMovementData.
* @property {String} name - The name of the bone
* @property {Boolean} blendDirty - Indicate whether the blend is dirty
*
*/
ccs.Bone = ccs.Node.extend(/** @lends ccs.Bone# */{
_boneData: null,
_armature: null,
_childArmature: null,
_displayManager: null,
ignoreMovementBoneData: false,
_tween: null,
_tweenData: null,
_parentBone: null,
_boneTransformDirty: false,
_worldTransform: null,
_blendFunc: 0,
blendDirty: false,
_worldInfo: null,
_armatureParentBone: null,
_dataVersion: 0,
_className: "Bone",
ctor: function () {
cc.Node.prototype.ctor.call(this);
this._tweenData = null;
this._parentBone = null;
this._armature = null;
this._childArmature = null;
this._boneData = null;
this._tween = null;
this._displayManager = null;
this.ignoreMovementBoneData = false;
this._worldTransform = cc.affineTransformMake(1, 0, 0, 1, 0, 0);
this._boneTransformDirty = true;
this._blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST);
this.blendDirty = false;
this._worldInfo = null;
this._armatureParentBone = null;
this._dataVersion = 0;
},
/**
* Initializes a CCBone with the specified name
* @param {String} name
* @return {Boolean}
*/
init: function (name) {
// cc.Node.prototype.init.call(this);
if (name) {
this._name = name;
}
this._tweenData = new ccs.FrameData();
this._tween = new ccs.Tween();
this._tween.init(this);
this._displayManager = new ccs.DisplayManager();
this._displayManager.init(this);
this._worldInfo = new ccs.BaseData();
this._boneData = new ccs.BaseData();
return true;
},
/**
* set the boneData
* @param {ccs.BoneData} boneData
*/
setBoneData: function (boneData) {
cc.assert(boneData, "_boneData must not be null");
if(this._boneData != boneData)
this._boneData = boneData;
this.setName(this._boneData.name);
this._localZOrder = this._boneData.zOrder;
this._displayManager.initDisplayList(boneData);
},
/**
* boneData getter
* @return {ccs.BoneData}
*/
getBoneData: function () {
return this._boneData;
},
/**
* set the armature
* @param {ccs.Armature} armature
*/
setArmature: function (armature) {
this._armature = armature;
if (armature) {
this._tween.setAnimation(this._armature.getAnimation());
this._dataVersion = this._armature.getArmatureData().dataVersion;
this._armatureParentBone = this._armature.getParentBone();
} else {
this._armatureParentBone = null;
}
},
/**
* armature getter
* @return {ccs.Armature}
*/
getArmature: function () {
return this._armature;
},
/**
* update worldTransform
* @param {Number} delta
*/
update: function (delta) {
if (this._parentBone)
this._boneTransformDirty = this._boneTransformDirty || this._parentBone.isTransformDirty();
if (this._armatureParentBone && !this._boneTransformDirty)
this._boneTransformDirty = this._armatureParentBone.isTransformDirty();
if (this._boneTransformDirty){
var locTweenData = this._tweenData;
if (this._dataVersion >= ccs.CONST_VERSION_COMBINED){
ccs.TransformHelp.nodeConcat(locTweenData, this._boneData);
locTweenData.scaleX -= 1;
locTweenData.scaleY -= 1;
}
var locWorldInfo = this._worldInfo;
locWorldInfo.copy(locTweenData);
locWorldInfo.x = locTweenData.x + this._position.x;
locWorldInfo.y = locTweenData.y + this._position.y;
locWorldInfo.scaleX = locTweenData.scaleX * this._scaleX;
locWorldInfo.scaleY = locTweenData.scaleY * this._scaleY;
locWorldInfo.skewX = locTweenData.skewX + this._skewX + this._rotationX;
locWorldInfo.skewY = locTweenData.skewY + this._skewY - this._rotationY;
if(this._parentBone)
this.applyParentTransform(this._parentBone);
else {
if (this._armatureParentBone)
this.applyParentTransform(this._armatureParentBone);
}
ccs.TransformHelp.nodeToMatrix(locWorldInfo, this._worldTransform);
if (this._armatureParentBone)
this._worldTransform = cc.affineTransformConcat(this._worldTransform, this._armature.getNodeToParentTransform()); //TODO TransformConcat
}
ccs.displayFactory.updateDisplay(this, delta, this._boneTransformDirty || this._armature.getArmatureTransformDirty());
for(var i=0; i<this._children.length; i++) {
var childBone = this._children[i];
childBone.update(delta);
}
this._boneTransformDirty = false;
},
applyParentTransform: function (parent) {
var locWorldInfo = this._worldInfo;
var locParentWorldTransform = parent._worldTransform;
var locParentWorldInfo = parent._worldInfo;
var x = locWorldInfo.x;
var y = locWorldInfo.y;
locWorldInfo.x = x * locParentWorldTransform.a + y * locParentWorldTransform.c + locParentWorldInfo.x;
locWorldInfo.y = x * locParentWorldTransform.b + y * locParentWorldTransform.d + locParentWorldInfo.y;
locWorldInfo.scaleX = locWorldInfo.scaleX * locParentWorldInfo.scaleX;
locWorldInfo.scaleY = locWorldInfo.scaleY * locParentWorldInfo.scaleY;
locWorldInfo.skewX = locWorldInfo.skewX + locParentWorldInfo.skewX;
locWorldInfo.skewY = locWorldInfo.skewY + locParentWorldInfo.skewY;
},
/**
* BlendFunc setter
* @param {cc.BlendFunc} blendFunc
*/
setBlendFunc: function (blendFunc) {
if (this._blendFunc.src != blendFunc.src || this._blendFunc.dst != blendFunc.dst) {
this._blendFunc = blendFunc;
this.blendDirty = true;
}
},
/**
* update display color
* @param {cc.Color} color
*/
updateDisplayedColor: function (color) {
this._realColor = cc.color(255, 255, 255);
cc.Node.prototype.updateDisplayedColor.call(this, color);
this.updateColor();
},
/**
* update display opacity
* @param {Number} opacity
*/
updateDisplayedOpacity: function (opacity) {
this._realOpacity = 255;
cc.Node.prototype.updateDisplayedOpacity.call(this, opacity);
this.updateColor();
},
/**
* update display color
*/
updateColor: function () {
var display = this._displayManager.getDisplayRenderNode();
if (display != null) {
display.setColor(
cc.color(
this._displayedColor.r * this._tweenData.r / 255,
this._displayedColor.g * this._tweenData.g / 255,
this._displayedColor.b * this._tweenData.b / 255));
display.setOpacity(this._displayedOpacity * this._tweenData.a / 255);
}
},
/**
* update display zOrder
*/
updateZOrder: function () {
if (this._armature.getArmatureData().dataVersion >= ccs.CONST_VERSION_COMBINED) {
var zorder = this._tweenData.zOrder + this._boneData.zOrder;
this.setLocalZOrder(zorder);
} else {
this.setLocalZOrder(this._tweenData.zOrder);
}
},
/**
* Add a child to this bone, and it will let this child call setParent(ccs.Bone) function to set self to it's parent
* @param {ccs.Bone} child
*/
addChildBone: function (child) {
cc.assert(child, "Argument must be non-nil");
cc.assert(!child.parentBone, "child already added. It can't be added again");
if (this._children.indexOf(child) < 0) {
this._children.push(child);
child.setParentBone(this);
}
},
/**
* Removes a child bone
* @param {ccs.Bone} bone
* @param {Boolean} recursion
*/
removeChildBone: function (bone, recursion) {
if (this._children.length > 0 && this._children.getIndex(bone) != -1 ) {
if(recursion) {
var ccbones = bone._children;
for(var i=0; i<ccbones.length; i++){
var ccBone = ccbones[i];
bone.removeChildBone(ccBone, recursion);
}
}
bone.setParentBone(null);
bone.getDisplayManager().setCurrentDecorativeDisplay(null);
cc.arrayRemoveObject(this._children, bone);
}
},
/**
* Remove itself from its parent CCBone.
* @param {Boolean} recursion
*/
removeFromParent: function (recursion) {
if (this._parentBone) {
this._parentBone.removeChildBone(this, recursion);
}
},
/**
* Set parent bone.
* If _parent is NUll, then also remove this bone from armature.
* It will not set the CCArmature, if you want to add the bone to a CCArmature, you should use ccs.Armature.addBone(bone, parentName).
* @param {ccs.Bone} parent the parent bone.
*/
setParentBone: function (parent) {
this._parentBone = parent;
},
getParentBone: function(){
return this._parentBone;
},
/**
* child armature setter
* @param {ccs.Armature} armature
*/
setChildArmature: function (armature) {
if (this._childArmature != armature) {
if (armature == null && this._childArmature)
this._childArmature.setParentBone(null);
this._childArmature = armature;
}
},
/**
* child armature getter
* @return {ccs.Armature}
*/
getChildArmature: function () {
return this._childArmature;
},
/**
* tween getter
* @return {ccs.Tween}
*/
getTween: function () {
return this._tween;
},
/**
* zOrder setter
* @param {Number} zOrder
*/
setLocalZOrder: function (zOrder) {
if (this._localZOrder != zOrder)
cc.Node.prototype.setLocalZOrder.call(this, zOrder);
},
getNodeToArmatureTransform: function(){
return this._worldTransform;
},
getNodeToWorldTransform: function(){
return cc.affineTransformConcat(this._worldTransform, this._armature.getNodeToWorldTransform());
},
/**
* get render node
* @returns {cc.Node}
*/
getDisplayRenderNode: function () {
return this._displayManager.getDisplayRenderNode();
},
/**
* get render node type
* @returns {Number}
*/
getDisplayRenderNodeType: function () {
return this._displayManager.getDisplayRenderNodeType();
},
/**
* Add display and use _displayData init the display.
* If index already have a display, then replace it.
* If index is current display index, then also change display to _index
* @param {ccs.DisplayData} displayData it include the display information, like DisplayType.
* If you want to create a sprite display, then create a CCSpriteDisplayData param
*@param {Number} index the index of the display you want to replace or add to
* -1 : append display from back
*/
addDisplay: function (displayData, index) {
index = index || 0;
return this._displayManager.addDisplay(displayData, index);
},
/**
* remove display
* @param {Number} index
*/
removeDisplay: function (index) {
this._displayManager.removeDisplay(index);
},
/**
* change display by index
* @param {Number} index
* @param {Boolean} force
*/
changeDisplayByIndex: function (index, force) {
cc.log("changeDisplayByIndex is deprecated. Use changeDisplayWithIndex instead.");
this.changeDisplayWithIndex(index, force);
},
changeDisplayByName: function(name, force){
this.changeDisplayWithName(name, force);
},
/**
* change display with index
* @param {Number} index
* @param {Boolean} force
*/
changeDisplayWithIndex: function (index, force) {
this._displayManager.changeDisplayWithIndex(index, force);
},
/**
* change display with name
* @param {String} name
* @param {Boolean} force
*/
changeDisplayWithName: function (name, force) {
this._displayManager.changeDisplayWithName(name, force);
},
getColliderDetector: function(){
var decoDisplay = this._displayManager.getCurrentDecorativeDisplay();
if (decoDisplay){
var detector = decoDisplay.getColliderDetector();
if (detector)
return detector;
}
return null;
},
/**
* collider filter setter
* @param {cc.ColliderFilter} filter
*/
setColliderFilter: function (filter) {
var displayList = this._displayManager.getDecorativeDisplayList();
for (var i = 0; i < displayList.length; i++) {
var locDecoDisplay = displayList[i];
var locDetector = locDecoDisplay.getColliderDetector();
if (locDetector) {
locDetector.setColliderFilter(filter);
}
}
},
/**
* collider filter getter
* @returns {cc.ColliderFilter}
*/
getColliderFilter: function () {
var decoDisplay = this.displayManager.getCurrentDecorativeDisplay();
if (decoDisplay) {
var detector = decoDisplay.getColliderDetector();
if (detector)
return detector.getColliderFilter();
}
return null;
},
/**
* transform dirty setter
* @param {Boolean} dirty
*/
setTransformDirty: function (dirty) {
this._boneTransformDirty = dirty;
},
/**
* transform dirty getter
* @return {Boolean}
*/
isTransformDirty: function () {
return this._boneTransformDirty;
},
/**
* displayManager dirty getter
* @return {ccs.DisplayManager}
*/
getDisplayManager: function () {
return this._displayManager;
},
/**
* When CCArmature play a animation, if there is not a CCMovementBoneData of this bone in this CCMovementData, this bone will hide.
* Set IgnoreMovementBoneData to true, then this bone will also show.
* @param {Boolean} bool
*/
setIgnoreMovementBoneData: function (bool) {
this._ignoreMovementBoneData = bool;
},
isIgnoreMovementBoneData: function(){
return this._ignoreMovementBoneData;
},
/**
* blendType getter
* @return {cc.BlendFunc}
*/
getBlendFunc: function () {
return this._blendFunc;
},
setBlendDirty: function (dirty) {
this._blendDirty = dirty;
},
isBlendDirty: function () {
return this._blendDirty;
},
/**
* tweenData getter
* @return {ccs.FrameData}
*/
getTweenData: function () {
return this._tweenData;
},
getWorldInfo: function(){
return this._worldInfo;
},
/**
* child bone getter
* @return {Array}
* @deprecated
*/
getChildrenBone: function () {
return this._children;
},
/**
* @deprecated
* return world transform
* @return {{a:0.b:0,c:0,d:0,tx:0,ty:0}}
*/
nodeToArmatureTransform: function () {
return this.getNodeToArmatureTransform();
},
/**
* @deprecated
* Returns the world affine transform matrix. The matrix is in Pixels.
* @returns {cc.AffineTransform}
*/
nodeToWorldTransform: function () {
return this.getNodeToWorldTransform();
},
/**
* @deprecated
* get the collider body list in this bone.
* @returns {*}
*/
getColliderBodyList: function () {
var detector = this.getColliderDetector();
if(detector)
return detector.getColliderBodyList();
return null;
},
/**
* ignoreMovementBoneData getter
* @return {Boolean}
*/
getIgnoreMovementBoneData: function () {
return this.isIgnoreMovementBoneData();
}
});
var _p = ccs.Bone.prototype;
// Extended properties
/** @expose */
_p.boneData;
cc.defineGetterSetter(_p, "boneData", _p.getBoneData, _p.setBoneData);
/** @expose */
_p.armature;
cc.defineGetterSetter(_p, "armature", _p.getArmature, _p.setArmature);
/** @expose */
_p.childArmature;
cc.defineGetterSetter(_p, "childArmature", _p.getChildArmature, _p.setChildArmature);
/** @expose */
_p.childrenBone;
cc.defineGetterSetter(_p, "childrenBone", _p.getChildrenBone);
/** @expose */
_p.tween;
cc.defineGetterSetter(_p, "tween", _p.getTween);
/** @expose */
_p.tweenData;
cc.defineGetterSetter(_p, "tweenData", _p.getTweenData);
/** @expose */
_p.colliderFilter;
cc.defineGetterSetter(_p, "colliderFilter", _p.getColliderFilter, _p.setColliderFilter);
_p = null;
/**
* allocates and initializes a bone.
* @constructs
* @return {ccs.Bone}
* @example
* // example
* var bone = ccs.Bone.create();
*/
ccs.Bone.create = function (name) {
var bone = new ccs.Bone();
if (bone && bone.init(name))
return bone;
return null;
}; | zry656565/MoonWarriors | frameworks/cocos2d-html5/extensions/cocostudio/armature/CCBone.js | JavaScript | mit | 19,960 |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
var util = require('util');
var msRest = require('ms-rest');
var WebResource = msRest.WebResource;
/**
* @class
* Implicit
* __NOTE__: An instance of this class is automatically created for an
* instance of the AutoRestRequiredOptionalTestService.
* Initializes a new instance of the Implicit class.
* @constructor
*
* @param {AutoRestRequiredOptionalTestService} client Reference to the service client.
*/
function Implicit(client) {
this.client = client;
}
/**
* Test implicitly required path parameter
*
* @param {string} pathParameter
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object.
* See {@link ErrorModel} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
Implicit.prototype.getRequiredPath = function (pathParameter, options, callback) {
var client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Validate
try {
if (pathParameter === null || pathParameter === undefined || typeof pathParameter.valueOf() !== 'string') {
throw new Error('pathParameter cannot be null or undefined and it must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.client.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'reqopt/implicit/required/path/{pathParameter}';
requestUrl = requestUrl.replace('{pathParameter}', encodeURIComponent(pathParameter));
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode < 200 || statusCode >= 300) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
var resultMapper = new client.models['ErrorModel']().mapper();
error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
var parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
var resultMapper = new client.models['ErrorModel']().mapper();
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
return callback(null, result, httpRequest, response);
});
};
/**
* Test implicitly optional query parameter
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.queryParameter]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
Implicit.prototype.putOptionalQuery = function (options, callback) {
var client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
var queryParameter = (options && options.queryParameter !== undefined) ? options.queryParameter : undefined;
// Validate
try {
if (queryParameter !== null && queryParameter !== undefined && typeof queryParameter.valueOf() !== 'string') {
throw new Error('queryParameter must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.client.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'reqopt/implicit/optional/query';
var queryParameters = [];
if (queryParameter !== null && queryParameter !== undefined) {
queryParameters.push('queryParameter=' + encodeURIComponent(queryParameter));
}
if (queryParameters.length > 0) {
requestUrl += '?' + queryParameters.join('&');
}
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'PUT';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 200) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
var resultMapper = new client.models['ErrorModel']().mapper();
error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
/**
* Test implicitly optional header parameter
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.queryParameter]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
Implicit.prototype.putOptionalHeader = function (options, callback) {
var client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
var queryParameter = (options && options.queryParameter !== undefined) ? options.queryParameter : undefined;
// Validate
try {
if (queryParameter !== null && queryParameter !== undefined && typeof queryParameter.valueOf() !== 'string') {
throw new Error('queryParameter must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.client.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'reqopt/implicit/optional/header';
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'PUT';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if (queryParameter !== undefined && queryParameter !== null) {
httpRequest.headers['queryParameter'] = queryParameter;
}
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 200) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
var resultMapper = new client.models['ErrorModel']().mapper();
error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
/**
* Test implicitly optional body parameter
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.bodyParameter]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
Implicit.prototype.putOptionalBody = function (options, callback) {
var client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
var bodyParameter = (options && options.bodyParameter !== undefined) ? options.bodyParameter : undefined;
// Validate
try {
if (bodyParameter !== null && bodyParameter !== undefined && typeof bodyParameter.valueOf() !== 'string') {
throw new Error('bodyParameter must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.client.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'reqopt/implicit/optional/body';
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'PUT';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
// Serialize Request
var requestContent = null;
var requestModel = null;
try {
if (bodyParameter !== null && bodyParameter !== undefined) {
var requestModelMapper = {
required: false,
serializedName: 'bodyParameter',
type: {
name: 'String'
}
};
requestModel = client.serialize(requestModelMapper, bodyParameter, 'bodyParameter');
requestContent = JSON.stringify(requestModel);
}
} catch (error) {
var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' +
'payload - "%s"', error.message, util.inspect(bodyParameter, {depth: null})));
return callback(serializationError);
}
httpRequest.body = requestContent;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 200) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
var resultMapper = new client.models['ErrorModel']().mapper();
error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
/**
* Test implicitly required path parameter
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object.
* See {@link ErrorModel} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
Implicit.prototype.getRequiredGlobalPath = function (options, callback) {
var client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Validate
try {
if (this.client.requiredGlobalPath === null || this.client.requiredGlobalPath === undefined || typeof this.client.requiredGlobalPath.valueOf() !== 'string') {
throw new Error('this.client.requiredGlobalPath cannot be null or undefined and it must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.client.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'reqopt/global/required/path/{required-global-path}';
requestUrl = requestUrl.replace('{required-global-path}', encodeURIComponent(this.client.requiredGlobalPath));
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode < 200 || statusCode >= 300) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
var resultMapper = new client.models['ErrorModel']().mapper();
error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
var parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
var resultMapper = new client.models['ErrorModel']().mapper();
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
return callback(null, result, httpRequest, response);
});
};
/**
* Test implicitly required query parameter
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object.
* See {@link ErrorModel} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
Implicit.prototype.getRequiredGlobalQuery = function (options, callback) {
var client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Validate
try {
if (this.client.requiredGlobalQuery === null || this.client.requiredGlobalQuery === undefined || typeof this.client.requiredGlobalQuery.valueOf() !== 'string') {
throw new Error('this.client.requiredGlobalQuery cannot be null or undefined and it must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.client.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'reqopt/global/required/query';
var queryParameters = [];
queryParameters.push('required-global-query=' + encodeURIComponent(this.client.requiredGlobalQuery));
if (queryParameters.length > 0) {
requestUrl += '?' + queryParameters.join('&');
}
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode < 200 || statusCode >= 300) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
var resultMapper = new client.models['ErrorModel']().mapper();
error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
var parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
var resultMapper = new client.models['ErrorModel']().mapper();
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
return callback(null, result, httpRequest, response);
});
};
/**
* Test implicitly optional query parameter
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object.
* See {@link ErrorModel} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
Implicit.prototype.getOptionalGlobalQuery = function (options, callback) {
var client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Validate
try {
if (this.client.optionalGlobalQuery !== null && this.client.optionalGlobalQuery !== undefined && typeof this.client.optionalGlobalQuery !== 'number') {
throw new Error('this.client.optionalGlobalQuery must be of type number.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.client.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'reqopt/global/optional/query';
var queryParameters = [];
if (this.client.optionalGlobalQuery !== null && this.client.optionalGlobalQuery !== undefined) {
queryParameters.push('optional-global-query=' + encodeURIComponent(this.client.optionalGlobalQuery.toString()));
}
if (queryParameters.length > 0) {
requestUrl += '?' + queryParameters.join('&');
}
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode < 200 || statusCode >= 300) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
var resultMapper = new client.models['ErrorModel']().mapper();
error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
var parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
var resultMapper = new client.models['ErrorModel']().mapper();
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
return callback(null, result, httpRequest, response);
});
};
module.exports = Implicit;
| fhoring/autorest | src/generator/AutoRest.NodeJS.Tests/Expected/AcceptanceTests/RequiredOptional/operations/implicit.js | JavaScript | mit | 31,107 |
/*!
* Bootstrap v3.3.6 (http://getbootstrap.com)
* Copyright 2011-2015 Twitter, Inc.
* Licensed under the MIT license
*/
if (typeof jQuery === 'undefined') {
throw new Error('Bootstrap\'s JavaScript requires jQuery')
}
+
function($) {
'use strict';
var version = $.fn.jquery.split(' ')[0].split('.')
if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] > 2)) {
throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3')
}
}(jQuery);
/* ========================================================================
* Bootstrap: transition.js v3.3.6
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
WebkitTransition: 'webkitTransitionEnd',
MozTransition: 'transitionend',
OTransition: 'oTransitionEnd otransitionend',
transition: 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function(duration) {
var called = false
var $el = this
$(this).one('bsTransitionEnd', function() { called = true })
var callback = function() { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function() {
$.support.transition = transitionEnd()
if (!$.support.transition) return
$.event.special.bsTransitionEnd = {
bindType: $.support.transition.end,
delegateType: $.support.transition.end,
handle: function(e) {
if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
}
}
})
}(jQuery);
/* ========================================================================
* Bootstrap: alert.js v3.3.6
* http://getbootstrap.com/javascript/#alerts
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function(el) {
$(el).on('click', dismiss, this.close)
}
Alert.VERSION = '3.3.6'
Alert.TRANSITION_DURATION = 150
Alert.prototype.close = function(e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector)
if (e) e.preventDefault()
if (!$parent.length) {
$parent = $this.closest('.alert')
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
// detach from parent, fire event then clean up data
$parent.detach().trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one('bsTransitionEnd', removeElement)
.emulateTransitionEnd(Alert.TRANSITION_DURATION) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data) $this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.alert
$.fn.alert = Plugin
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function() {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
/* ========================================================================
* Bootstrap: button.js v3.3.6
* http://getbootstrap.com/javascript/#buttons
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// BUTTON PUBLIC CLASS DEFINITION
// ==============================
var Button = function(element, options) {
this.$element = $(element)
this.options = $.extend({}, Button.DEFAULTS, options)
this.isLoading = false
}
Button.VERSION = '3.3.6'
Button.DEFAULTS = {
loadingText: 'loading...'
}
Button.prototype.setState = function(state) {
var d = 'disabled'
var $el = this.$element
var val = $el.is('input') ? 'val' : 'html'
var data = $el.data()
state += 'Text'
if (data.resetText == null) $el.data('resetText', $el[val]())
// push to event loop to allow forms to submit
setTimeout($.proxy(function() {
$el[val](data[state] == null ? this.options[state] : data[state])
if (state == 'loadingText') {
this.isLoading = true
$el.addClass(d).attr(d, d)
} else if (this.isLoading) {
this.isLoading = false
$el.removeClass(d).removeAttr(d)
}
}, this), 0)
}
Button.prototype.toggle = function() {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked')) changed = false
$parent.find('.active').removeClass('active')
this.$element.addClass('active')
} else if ($input.prop('type') == 'checkbox') {
if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false
this.$element.toggleClass('active')
}
$input.prop('checked', this.$element.hasClass('active'))
if (changed) $input.trigger('change')
} else {
this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
this.$element.toggleClass('active')
}
}
// BUTTON PLUGIN DEFINITION
// ========================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.button')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
var old = $.fn.button
$.fn.button = Plugin
$.fn.button.Constructor = Button
// BUTTON NO CONFLICT
// ==================
$.fn.button.noConflict = function() {
$.fn.button = old
return this
}
// BUTTON DATA-API
// ===============
$(document)
.on('click.bs.button.data-api', '[data-toggle^="button"]', function(e) {
var $btn = $(e.target)
if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
Plugin.call($btn, 'toggle')
if (!($(e.target).is('input[type="radio"]') || $(e.target).is('input[type="checkbox"]'))) e.preventDefault()
})
.on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function(e) {
$(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type))
})
}(jQuery);
/* ========================================================================
* Bootstrap: carousel.js v3.3.6
* http://getbootstrap.com/javascript/#carousel
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// CAROUSEL CLASS DEFINITION
// =========================
var Carousel = function(element, options) {
this.$element = $(element)
this.$indicators = this.$element.find('.carousel-indicators')
this.options = options
this.paused = null
this.sliding = null
this.interval = null
this.$active = null
this.$items = null
this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this))
this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element
.on('mouseenter.bs.carousel', $.proxy(this.pause, this))
.on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
}
Carousel.VERSION = '3.3.6'
Carousel.TRANSITION_DURATION = 600
Carousel.DEFAULTS = {
interval: 5000,
pause: 'hover',
wrap: true,
keyboard: true
}
Carousel.prototype.keydown = function(e) {
if (/input|textarea/i.test(e.target.tagName)) return
switch (e.which) {
case 37:
this.prev();
break
case 39:
this.next();
break
default:
return
}
e.preventDefault()
}
Carousel.prototype.cycle = function(e) {
e || (this.paused = false)
this.interval && clearInterval(this.interval)
this.options.interval &&
!this.paused &&
(this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
}
Carousel.prototype.getItemIndex = function(item) {
this.$items = item.parent().children('.item')
return this.$items.index(item || this.$active)
}
Carousel.prototype.getItemForDirection = function(direction, active) {
var activeIndex = this.getItemIndex(active)
var willWrap = (direction == 'prev' && activeIndex === 0) ||
(direction == 'next' && activeIndex == (this.$items.length - 1))
if (willWrap && !this.options.wrap) return active
var delta = direction == 'prev' ? -1 : 1
var itemIndex = (activeIndex + delta) % this.$items.length
return this.$items.eq(itemIndex)
}
Carousel.prototype.to = function(pos) {
var that = this
var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))
if (pos > (this.$items.length - 1) || pos < 0) return
if (this.sliding) return this.$element.one('slid.bs.carousel', function() { that.to(pos) }) // yes, "slid"
if (activeIndex == pos) return this.pause().cycle()
return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos))
}
Carousel.prototype.pause = function(e) {
e || (this.paused = true)
if (this.$element.find('.next, .prev').length && $.support.transition) {
this.$element.trigger($.support.transition.end)
this.cycle(true)
}
this.interval = clearInterval(this.interval)
return this
}
Carousel.prototype.next = function() {
if (this.sliding) return
return this.slide('next')
}
Carousel.prototype.prev = function() {
if (this.sliding) return
return this.slide('prev')
}
Carousel.prototype.slide = function(type, next) {
var $active = this.$element.find('.item.active')
var $next = next || this.getItemForDirection(type, $active)
var isCycling = this.interval
var direction = type == 'next' ? 'left' : 'right'
var that = this
if ($next.hasClass('active')) return (this.sliding = false)
var relatedTarget = $next[0]
var slideEvent = $.Event('slide.bs.carousel', {
relatedTarget: relatedTarget,
direction: direction
})
this.$element.trigger(slideEvent)
if (slideEvent.isDefaultPrevented()) return
this.sliding = true
isCycling && this.pause()
if (this.$indicators.length) {
this.$indicators.find('.active').removeClass('active')
var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
$nextIndicator && $nextIndicator.addClass('active')
}
var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
if ($.support.transition && this.$element.hasClass('slide')) {
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
$active
.one('bsTransitionEnd', function() {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function() {
that.$element.trigger(slidEvent)
}, 0)
})
.emulateTransitionEnd(Carousel.TRANSITION_DURATION)
} else {
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger(slidEvent)
}
isCycling && this.cycle()
return this
}
// CAROUSEL PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.carousel')
var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
var action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.pause().cycle()
})
}
var old = $.fn.carousel
$.fn.carousel = Plugin
$.fn.carousel.Constructor = Carousel
// CAROUSEL NO CONFLICT
// ====================
$.fn.carousel.noConflict = function() {
$.fn.carousel = old
return this
}
// CAROUSEL DATA-API
// =================
var clickHandler = function(e) {
var href
var $this = $(this)
var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
if (!$target.hasClass('carousel')) return
var options = $.extend({}, $target.data(), $this.data())
var slideIndex = $this.attr('data-slide-to')
if (slideIndex) options.interval = false
Plugin.call($target, options)
if (slideIndex) {
$target.data('bs.carousel').to(slideIndex)
}
e.preventDefault()
}
$(document)
.on('click.bs.carousel.data-api', '[data-slide]', clickHandler)
.on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler)
$(window).on('load', function() {
$('[data-ride="carousel"]').each(function() {
var $carousel = $(this)
Plugin.call($carousel, $carousel.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: collapse.js v3.3.6
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function(element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.$trigger = $('[data-toggle="collapse"][href="#' + element.id + '"],' +
'[data-toggle="collapse"][data-target="#' + element.id + '"]')
this.transitioning = null
if (this.options.parent) {
this.$parent = this.getParent()
} else {
this.addAriaAndCollapsedClass(this.$element, this.$trigger)
}
if (this.options.toggle) this.toggle()
}
Collapse.VERSION = '3.3.6'
Collapse.TRANSITION_DURATION = 350
Collapse.DEFAULTS = {
toggle: true
}
Collapse.prototype.dimension = function() {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function() {
if (this.transitioning || this.$element.hasClass('in')) return
var activesData
var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing')
if (actives && actives.length) {
activesData = actives.data('bs.collapse')
if (activesData && activesData.transitioning) return
}
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
if (actives && actives.length) {
Plugin.call(actives, 'hide')
activesData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element
.removeClass('collapse')
.addClass('collapsing')[dimension](0)
.attr('aria-expanded', true)
this.$trigger
.removeClass('collapsed')
.attr('aria-expanded', true)
this.transitioning = 1
var complete = function() {
this.$element
.removeClass('collapsing')
.addClass('collapse in')[dimension]('')
this.transitioning = 0
this.$element
.trigger('shown.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function() {
if (this.transitioning || !this.$element.hasClass('in')) return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var dimension = this.dimension()
this.$element[dimension](this.$element[dimension]())[0].offsetHeight
this.$element
.addClass('collapsing')
.removeClass('collapse in')
.attr('aria-expanded', false)
this.$trigger
.addClass('collapsed')
.attr('aria-expanded', false)
this.transitioning = 1
var complete = function() {
this.transitioning = 0
this.$element
.removeClass('collapsing')
.addClass('collapse')
.trigger('hidden.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
this.$element[dimension](0)
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)
}
Collapse.prototype.toggle = function() {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
Collapse.prototype.getParent = function() {
return $(this.options.parent)
.find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]')
.each($.proxy(function(i, element) {
var $element = $(element)
this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element)
}, this))
.end()
}
Collapse.prototype.addAriaAndCollapsedClass = function($element, $trigger) {
var isOpen = $element.hasClass('in')
$element.attr('aria-expanded', isOpen)
$trigger
.toggleClass('collapsed', !isOpen)
.attr('aria-expanded', isOpen)
}
function getTargetFromTrigger($trigger) {
var href
var target = $trigger.attr('data-target') ||
(href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
return $(target)
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false
if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.collapse
$.fn.collapse = Plugin
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function() {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function(e) {
var $this = $(this)
if (!$this.attr('data-target')) e.preventDefault()
var $target = getTargetFromTrigger($this)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $this.data()
Plugin.call($target, option)
})
}(jQuery);
/* ========================================================================
* Bootstrap: dropdown.js v3.3.6
* http://getbootstrap.com/javascript/#dropdowns
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// DROPDOWN CLASS DEFINITION
// =========================
var backdrop = '.dropdown-backdrop'
var toggle = '[data-toggle="dropdown"]'
var Dropdown = function(element) {
$(element).on('click.bs.dropdown', this.toggle)
}
Dropdown.VERSION = '3.3.6'
function getParent($this) {
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = selector && $(selector)
return $parent && $parent.length ? $parent : $this.parent()
}
function clearMenus(e) {
if (e && e.which === 3) return
$(backdrop).remove()
$(toggle).each(function() {
var $this = $(this)
var $parent = getParent($this)
var relatedTarget = { relatedTarget: this }
if (!$parent.hasClass('open')) return
if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return
$parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this.attr('aria-expanded', 'false')
$parent.removeClass('open').trigger($.Event('hidden.bs.dropdown', relatedTarget))
})
}
Dropdown.prototype.toggle = function(e) {
var $this = $(this)
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
// if mobile we use a backdrop because click events don't delegate
$(document.createElement('div'))
.addClass('dropdown-backdrop')
.insertAfter($(this))
.on('click', clearMenus)
}
var relatedTarget = { relatedTarget: this }
$parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this
.trigger('focus')
.attr('aria-expanded', 'true')
$parent
.toggleClass('open')
.trigger($.Event('shown.bs.dropdown', relatedTarget))
}
return false
}
Dropdown.prototype.keydown = function(e) {
if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return
var $this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
if (!isActive && e.which != 27 || isActive && e.which == 27) {
if (e.which == 27) $parent.find(toggle).trigger('focus')
return $this.trigger('click')
}
var desc = ' li:not(.disabled):visible a'
var $items = $parent.find('.dropdown-menu' + desc)
if (!$items.length) return
var index = $items.index(e.target)
if (e.which == 38 && index > 0) index-- // up
if (e.which == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items.eq(index).trigger('focus')
}
// DROPDOWN PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.dropdown')
if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.dropdown
$.fn.dropdown = Plugin
$.fn.dropdown.Constructor = Dropdown
// DROPDOWN NO CONFLICT
// ====================
$.fn.dropdown.noConflict = function() {
$.fn.dropdown = old
return this
}
// APPLY TO STANDARD DROPDOWN ELEMENTS
// ===================================
$(document)
.on('click.bs.dropdown.data-api', clearMenus)
.on('click.bs.dropdown.data-api', '.dropdown form', function(e) { e.stopPropagation() })
.on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
.on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown)
.on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown)
}(jQuery);
/* ========================================================================
* Bootstrap: modal.js v3.3.6
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function(element, options) {
this.options = options
this.$body = $(document.body)
this.$element = $(element)
this.$dialog = this.$element.find('.modal-dialog')
this.$backdrop = null
this.isShown = null
this.originalBodyPad = null
this.scrollbarWidth = 0
this.ignoreBackdropClick = false
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function() {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.VERSION = '3.3.6'
Modal.TRANSITION_DURATION = 300
Modal.BACKDROP_TRANSITION_DURATION = 150
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function(_relatedTarget) {
return this.isShown ? this.hide() : this.show(_relatedTarget)
}
Modal.prototype.show = function(_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.checkScrollbar()
this.setScrollbar()
this.$body.addClass('modal-open')
this.escape()
this.resize()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.$dialog.on('mousedown.dismiss.bs.modal', function() {
that.$element.one('mouseup.dismiss.bs.modal', function(e) {
if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true
})
})
this.backdrop(function() {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(that.$body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
that.adjustDialog()
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element.addClass('in')
that.enforceFocus()
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$dialog // wait for modal to slide in
.one('bsTransitionEnd', function() {
that.$element.trigger('focus').trigger(e)
})
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
that.$element.trigger('focus').trigger(e)
})
}
Modal.prototype.hide = function(e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
this.resize()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.off('click.dismiss.bs.modal')
.off('mouseup.dismiss.bs.modal')
this.$dialog.off('mousedown.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one('bsTransitionEnd', $.proxy(this.hideModal, this))
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
this.hideModal()
}
Modal.prototype.enforceFocus = function() {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function(e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
Modal.prototype.escape = function() {
if (this.isShown && this.options.keyboard) {
this.$element.on('keydown.dismiss.bs.modal', $.proxy(function(e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keydown.dismiss.bs.modal')
}
}
Modal.prototype.resize = function() {
if (this.isShown) {
$(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
} else {
$(window).off('resize.bs.modal')
}
}
Modal.prototype.hideModal = function() {
var that = this
this.$element.hide()
this.backdrop(function() {
that.$body.removeClass('modal-open')
that.resetAdjustments()
that.resetScrollbar()
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function() {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function(callback) {
var that = this
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $(document.createElement('div'))
.addClass('modal-backdrop ' + animate)
.appendTo(this.$body)
this.$element.on('click.dismiss.bs.modal', $.proxy(function(e) {
if (this.ignoreBackdropClick) {
this.ignoreBackdropClick = false
return
}
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static' ?
this.$element[0].focus() :
this.hide()
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one('bsTransitionEnd', callback)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
var callbackRemove = function() {
that.removeBackdrop()
callback && callback()
}
$.support.transition && this.$element.hasClass('fade') ?
this.$backdrop
.one('bsTransitionEnd', callbackRemove)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callbackRemove()
} else if (callback) {
callback()
}
}
// these following methods are used to handle overflowing modals
Modal.prototype.handleUpdate = function() {
this.adjustDialog()
}
Modal.prototype.adjustDialog = function() {
var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight
this.$element.css({
paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
})
}
Modal.prototype.resetAdjustments = function() {
this.$element.css({
paddingLeft: '',
paddingRight: ''
})
}
Modal.prototype.checkScrollbar = function() {
var fullWindowWidth = window.innerWidth
if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
var documentElementRect = document.documentElement.getBoundingClientRect()
fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
}
this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth
this.scrollbarWidth = this.measureScrollbar()
}
Modal.prototype.setScrollbar = function() {
var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
this.originalBodyPad = document.body.style.paddingRight || ''
if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
}
Modal.prototype.resetScrollbar = function() {
this.$body.css('padding-right', this.originalBodyPad)
}
Modal.prototype.measureScrollbar = function() { // thx walsh
var scrollDiv = document.createElement('div')
scrollDiv.className = 'modal-scrollbar-measure'
this.$body.append(scrollDiv)
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
this.$body[0].removeChild(scrollDiv)
return scrollbarWidth
}
// MODAL PLUGIN DEFINITION
// =======================
function Plugin(option, _relatedTarget) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
var old = $.fn.modal
$.fn.modal = Plugin
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function() {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function(e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target.one('show.bs.modal', function(showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function() {
$this.is(':visible') && $this.trigger('focus')
})
})
Plugin.call($target, option, this)
})
}(jQuery);
/* ========================================================================
* Bootstrap: tooltip.js v3.3.6
* http://getbootstrap.com/javascript/#tooltip
* Inspired by the original jQuery.tipsy by Jason Frame
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// TOOLTIP PUBLIC CLASS DEFINITION
// ===============================
var Tooltip = function(element, options) {
this.type = null
this.options = null
this.enabled = null
this.timeout = null
this.hoverState = null
this.$element = null
this.inState = null
this.init('tooltip', element, options)
}
Tooltip.VERSION = '3.3.6'
Tooltip.TRANSITION_DURATION = 150
Tooltip.DEFAULTS = {
animation: true,
placement: 'top',
selector: false,
template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
container: false,
viewport: {
selector: 'body',
padding: 0
}
}
Tooltip.prototype.init = function(type, element, options) {
this.enabled = true
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport))
this.inState = { click: false, hover: false, focus: false }
if (this.$element[0] instanceof document.constructor && !this.options.selector) {
throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!')
}
var triggers = this.options.trigger.split(' ')
for (var i = triggers.length; i--;) {
var trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'
var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
}
this.options.selector ?
(this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
this.fixTitle()
}
Tooltip.prototype.getDefaults = function() {
return Tooltip.DEFAULTS
}
Tooltip.prototype.getOptions = function(options) {
options = $.extend({}, this.getDefaults(), this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay,
hide: options.delay
}
}
return options
}
Tooltip.prototype.getDelegateOptions = function() {
var options = {}
var defaults = this.getDefaults()
this._options && $.each(this._options, function(key, value) {
if (defaults[key] != value) options[key] = value
})
return options
}
Tooltip.prototype.enter = function(obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
if (obj instanceof $.Event) {
self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true
}
if (self.tip().hasClass('in') || self.hoverState == 'in') {
self.hoverState = 'in'
return
}
clearTimeout(self.timeout)
self.hoverState = 'in'
if (!self.options.delay || !self.options.delay.show) return self.show()
self.timeout = setTimeout(function() {
if (self.hoverState == 'in') self.show()
}, self.options.delay.show)
}
Tooltip.prototype.isInStateTrue = function() {
for (var key in this.inState) {
if (this.inState[key]) return true
}
return false
}
Tooltip.prototype.leave = function(obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
if (obj instanceof $.Event) {
self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false
}
if (self.isInStateTrue()) return
clearTimeout(self.timeout)
self.hoverState = 'out'
if (!self.options.delay || !self.options.delay.hide) return self.hide()
self.timeout = setTimeout(function() {
if (self.hoverState == 'out') self.hide()
}, self.options.delay.hide)
}
Tooltip.prototype.show = function() {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
if (e.isDefaultPrevented() || !inDom) return
var that = this
var $tip = this.tip()
var tipId = this.getUID(this.type)
this.setContent()
$tip.attr('id', tipId)
this.$element.attr('aria-describedby', tipId)
if (this.options.animation) $tip.addClass('fade')
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
var autoToken = /\s?auto?\s?/i
var autoPlace = autoToken.test(placement)
if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
$tip
.detach()
.css({ top: 0, left: 0, display: 'block' })
.addClass(placement)
.data('bs.' + this.type, this)
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
this.$element.trigger('inserted.bs.' + this.type)
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var orgPlacement = placement
var viewportDim = this.getPosition(this.$viewport)
placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top' :
placement == 'top' && pos.top - actualHeight < viewportDim.top ? 'bottom' :
placement == 'right' && pos.right + actualWidth > viewportDim.width ? 'left' :
placement == 'left' && pos.left - actualWidth < viewportDim.left ? 'right' :
placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
var complete = function() {
var prevHoverState = that.hoverState
that.$element.trigger('shown.bs.' + that.type)
that.hoverState = null
if (prevHoverState == 'out') that.leave(that)
}
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
}
}
Tooltip.prototype.applyPlacement = function(offset, placement) {
var $tip = this.tip()
var width = $tip[0].offsetWidth
var height = $tip[0].offsetHeight
// manually read margins because getBoundingClientRect includes difference
var marginTop = parseInt($tip.css('margin-top'), 10)
var marginLeft = parseInt($tip.css('margin-left'), 10)
// we must check for NaN for ie 8/9
if (isNaN(marginTop)) marginTop = 0
if (isNaN(marginLeft)) marginLeft = 0
offset.top += marginTop
offset.left += marginLeft
// $.fn.offset doesn't round pixel values
// so we use setOffset directly with our own function B-0
$.offset.setOffset($tip[0], $.extend({
using: function(props) {
$tip.css({
top: Math.round(props.top),
left: Math.round(props.left)
})
}
}, offset), 0)
$tip.addClass('in')
// check to see if placing tip in new offset caused the tip to resize itself
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
offset.top = offset.top + height - actualHeight
}
var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)
if (delta.left) offset.left += delta.left
else offset.top += delta.top
var isVertical = /top|bottom/.test(placement)
var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'
$tip.offset(offset)
this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical)
}
Tooltip.prototype.replaceArrow = function(delta, dimension, isVertical) {
this.arrow()
.css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%')
.css(isVertical ? 'top' : 'left', '')
}
Tooltip.prototype.setContent = function() {
var $tip = this.tip()
var title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
Tooltip.prototype.hide = function(callback) {
var that = this
var $tip = $(this.$tip)
var e = $.Event('hide.bs.' + this.type)
function complete() {
if (that.hoverState != 'in') $tip.detach()
that.$element
.removeAttr('aria-describedby')
.trigger('hidden.bs.' + that.type)
callback && callback()
}
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$tip.removeClass('in')
$.support.transition && $tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
this.hoverState = null
return this
}
Tooltip.prototype.fixTitle = function() {
var $e = this.$element
if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
}
}
Tooltip.prototype.hasContent = function() {
return this.getTitle()
}
Tooltip.prototype.getPosition = function($element) {
$element = $element || this.$element
var el = $element[0]
var isBody = el.tagName == 'BODY'
var elRect = el.getBoundingClientRect()
if (elRect.width == null) {
// width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093
elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top })
}
var elOffset = isBody ? { top: 0, left: 0 } : $element.offset()
var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null
return $.extend({}, elRect, scroll, outerDims, elOffset)
}
Tooltip.prototype.getCalculatedOffset = function(placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
/* placement == 'right' */
{ top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
}
Tooltip.prototype.getViewportAdjustedDelta = function(placement, pos, actualWidth, actualHeight) {
var delta = { top: 0, left: 0 }
if (!this.$viewport) return delta
var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
var viewportDimensions = this.getPosition(this.$viewport)
if (/right|left/.test(placement)) {
var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
if (topEdgeOffset < viewportDimensions.top) { // top overflow
delta.top = viewportDimensions.top - topEdgeOffset
} else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
}
} else {
var leftEdgeOffset = pos.left - viewportPadding
var rightEdgeOffset = pos.left + viewportPadding + actualWidth
if (leftEdgeOffset < viewportDimensions.left) { // left overflow
delta.left = viewportDimensions.left - leftEdgeOffset
} else if (rightEdgeOffset > viewportDimensions.right) { // right overflow
delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
}
}
return delta
}
Tooltip.prototype.getTitle = function() {
var title
var $e = this.$element
var o = this.options
title = $e.attr('data-original-title') ||
(typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
Tooltip.prototype.getUID = function(prefix) {
do prefix += ~~(Math.random() * 1000000)
while (document.getElementById(prefix))
return prefix
}
Tooltip.prototype.tip = function() {
if (!this.$tip) {
this.$tip = $(this.options.template)
if (this.$tip.length != 1) {
throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!')
}
}
return this.$tip
}
Tooltip.prototype.arrow = function() {
return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
}
Tooltip.prototype.enable = function() {
this.enabled = true
}
Tooltip.prototype.disable = function() {
this.enabled = false
}
Tooltip.prototype.toggleEnabled = function() {
this.enabled = !this.enabled
}
Tooltip.prototype.toggle = function(e) {
var self = this
if (e) {
self = $(e.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(e.currentTarget, this.getDelegateOptions())
$(e.currentTarget).data('bs.' + this.type, self)
}
}
if (e) {
self.inState.click = !self.inState.click
if (self.isInStateTrue()) self.enter(self)
else self.leave(self)
} else {
self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
}
}
Tooltip.prototype.destroy = function() {
var that = this
clearTimeout(this.timeout)
this.hide(function() {
that.$element.off('.' + that.type).removeData('bs.' + that.type)
if (that.$tip) {
that.$tip.detach()
}
that.$tip = null
that.$arrow = null
that.$viewport = null
})
}
// TOOLTIP PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data && /destroy|hide/.test(option)) return
if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tooltip
$.fn.tooltip = Plugin
$.fn.tooltip.Constructor = Tooltip
// TOOLTIP NO CONFLICT
// ===================
$.fn.tooltip.noConflict = function() {
$.fn.tooltip = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: popover.js v3.3.6
* http://getbootstrap.com/javascript/#popovers
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// POPOVER PUBLIC CLASS DEFINITION
// ===============================
var Popover = function(element, options) {
this.init('popover', element, options)
}
if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
Popover.VERSION = '3.3.6'
Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
// NOTE: POPOVER EXTENDS tooltip.js
// ================================
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
Popover.prototype.constructor = Popover
Popover.prototype.getDefaults = function() {
return Popover.DEFAULTS
}
Popover.prototype.setContent = function() {
var $tip = this.tip()
var title = this.getTitle()
var content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events
this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
](content)
$tip.removeClass('fade top bottom left right in')
// IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
// this manually by checking the contents.
if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
}
Popover.prototype.hasContent = function() {
return this.getTitle() || this.getContent()
}
Popover.prototype.getContent = function() {
var $e = this.$element
var o = this.options
return $e.attr('data-content') ||
(typeof o.content == 'function' ?
o.content.call($e[0]) :
o.content)
}
Popover.prototype.arrow = function() {
return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
}
// POPOVER PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.popover')
var options = typeof option == 'object' && option
if (!data && /destroy|hide/.test(option)) return
if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.popover
$.fn.popover = Plugin
$.fn.popover.Constructor = Popover
// POPOVER NO CONFLICT
// ===================
$.fn.popover.noConflict = function() {
$.fn.popover = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: scrollspy.js v3.3.6
* http://getbootstrap.com/javascript/#scrollspy
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// SCROLLSPY CLASS DEFINITION
// ==========================
function ScrollSpy(element, options) {
this.$body = $(document.body)
this.$scrollElement = $(element).is(document.body) ? $(window) : $(element)
this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
this.selector = (this.options.target || '') + ' .nav li > a'
this.offsets = []
this.targets = []
this.activeTarget = null
this.scrollHeight = 0
this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this))
this.refresh()
this.process()
}
ScrollSpy.VERSION = '3.3.6'
ScrollSpy.DEFAULTS = {
offset: 10
}
ScrollSpy.prototype.getScrollHeight = function() {
return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
}
ScrollSpy.prototype.refresh = function() {
var that = this
var offsetMethod = 'offset'
var offsetBase = 0
this.offsets = []
this.targets = []
this.scrollHeight = this.getScrollHeight()
if (!$.isWindow(this.$scrollElement[0])) {
offsetMethod = 'position'
offsetBase = this.$scrollElement.scrollTop()
}
this.$body
.find(this.selector)
.map(function() {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#./.test(href) && $(href)
return ($href &&
$href.length &&
$href.is(':visible') &&
[
[$href[offsetMethod]().top + offsetBase, href]
]) || null
})
.sort(function(a, b) { return a[0] - b[0] })
.each(function() {
that.offsets.push(this[0])
that.targets.push(this[1])
})
}
ScrollSpy.prototype.process = function() {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
var scrollHeight = this.getScrollHeight()
var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height()
var offsets = this.offsets
var targets = this.targets
var activeTarget = this.activeTarget
var i
if (this.scrollHeight != scrollHeight) {
this.refresh()
}
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
}
if (activeTarget && scrollTop < offsets[0]) {
this.activeTarget = null
return this.clear()
}
for (i = offsets.length; i--;) {
activeTarget != targets[i] &&
scrollTop >= offsets[i] &&
(offsets[i + 1] === undefined || scrollTop < offsets[i + 1]) &&
this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function(target) {
this.activeTarget = target
this.clear()
var selector = this.selector +
'[data-target="' + target + '"],' +
this.selector + '[href="' + target + '"]'
var active = $(selector)
.parents('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active
.closest('li.dropdown')
.addClass('active')
}
active.trigger('activate.bs.scrollspy')
}
ScrollSpy.prototype.clear = function() {
$(this.selector)
.parentsUntil(this.options.target, '.active')
.removeClass('active')
}
// SCROLLSPY PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.scrollspy')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.scrollspy
$.fn.scrollspy = Plugin
$.fn.scrollspy.Constructor = ScrollSpy
// SCROLLSPY NO CONFLICT
// =====================
$.fn.scrollspy.noConflict = function() {
$.fn.scrollspy = old
return this
}
// SCROLLSPY DATA-API
// ==================
$(window).on('load.bs.scrollspy.data-api', function() {
$('[data-spy="scroll"]').each(function() {
var $spy = $(this)
Plugin.call($spy, $spy.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: tab.js v3.3.6
* http://getbootstrap.com/javascript/#tabs
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// TAB CLASS DEFINITION
// ====================
var Tab = function(element) {
// jscs:disable requireDollarBeforejQueryAssignment
this.element = $(element)
// jscs:enable requireDollarBeforejQueryAssignment
}
Tab.VERSION = '3.3.6'
Tab.TRANSITION_DURATION = 150
Tab.prototype.show = function() {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
if ($this.parent('li').hasClass('active')) return
var $previous = $ul.find('.active:last a')
var hideEvent = $.Event('hide.bs.tab', {
relatedTarget: $this[0]
})
var showEvent = $.Event('show.bs.tab', {
relatedTarget: $previous[0]
})
$previous.trigger(hideEvent)
$this.trigger(showEvent)
if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return
var $target = $(selector)
this.activate($this.closest('li'), $ul)
this.activate($target, $target.parent(), function() {
$previous.trigger({
type: 'hidden.bs.tab',
relatedTarget: $this[0]
})
$this.trigger({
type: 'shown.bs.tab',
relatedTarget: $previous[0]
})
})
}
Tab.prototype.activate = function(element, container, callback) {
var $active = container.find('> .active')
var transition = callback &&
$.support.transition &&
($active.length && $active.hasClass('fade') || !!container.find('> .fade').length)
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', false)
element
.addClass('active')
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu').length) {
element
.closest('li.dropdown')
.addClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
}
callback && callback()
}
$active.length && transition ?
$active
.one('bsTransitionEnd', next)
.emulateTransitionEnd(Tab.TRANSITION_DURATION) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data) $this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tab
$.fn.tab = Plugin
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function() {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
var clickHandler = function(e) {
e.preventDefault()
Plugin.call($(this), 'show')
}
$(document)
.on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler)
.on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler)
}(jQuery);
/* ========================================================================
* Bootstrap: affix.js v3.3.6
* http://getbootstrap.com/javascript/#affix
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// AFFIX CLASS DEFINITION
// ======================
var Affix = function(element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$target = $(this.options.target)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed = null
this.unpin = null
this.pinnedOffset = null
this.checkPosition()
}
Affix.VERSION = '3.3.6'
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0,
target: window
}
Affix.prototype.getState = function(scrollHeight, height, offsetTop, offsetBottom) {
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
var targetHeight = this.$target.height()
if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false
if (this.affixed == 'bottom') {
if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
}
var initializing = this.affixed == null
var colliderTop = initializing ? scrollTop : position.top
var colliderHeight = initializing ? targetHeight : height
if (offsetTop != null && scrollTop <= offsetTop) return 'top'
if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'
return false
}
Affix.prototype.getPinnedOffset = function() {
if (this.pinnedOffset) return this.pinnedOffset
this.$element.removeClass(Affix.RESET).addClass('affix')
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
return (this.pinnedOffset = position.top - scrollTop)
}
Affix.prototype.checkPositionWithEventLoop = function() {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function() {
if (!this.$element.is(':visible')) return
var height = this.$element.height()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
var scrollHeight = Math.max($(document).height(), $(document.body).height())
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element)
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)
if (this.affixed != affix) {
if (this.unpin != null) this.$element.css('top', '')
var affixType = 'affix' + (affix ? '-' + affix : '')
var e = $.Event(affixType + '.bs.affix')
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
this.affixed = affix
this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
this.$element
.removeClass(Affix.RESET)
.addClass(affixType)
.trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
}
if (affix == 'bottom') {
this.$element.offset({
top: scrollHeight - height - offsetBottom
})
}
}
// AFFIX PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.affix
$.fn.affix = Plugin
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function() {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function() {
$('[data-spy="affix"]').each(function() {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom
if (data.offsetTop != null) data.offset.top = data.offsetTop
Plugin.call($spy, data)
})
})
}(jQuery); | octapush/octapushJS | docs/assets/bootstrap/js/bootstrap.js | JavaScript | mit | 75,339 |
"use strict";
import { GW_FRAME_REQ } from "./common";
export class GW_RTC_SET_TIME_ZONE_REQ extends GW_FRAME_REQ {
// /**
// * Creates an instance of GW_RTC_SET_TIME_ZONE_REQ.
// *
// * @param {string} [TimeZoneName="localtime"] Time zone name, e.g. IANA time zones. See https://github.com/SpiritIT/timezonecomplete/blob/master/doc/API.md for further information.
// * @memberof GW_RTC_SET_TIME_ZONE_REQ
// */
// constructor(readonly TimeZoneName: string = "localtime") {
// super();
// const buff = this.Data.slice(this.offset); // View on the internal buffer makes setting the data easier
// // let timeZoneString = "";
// // // Get the time zone data
// // const tz = TimeZone.zone(this.TimeZoneName);
// // const Jan1st = DateTime.now(tz).startOfYear();
// // const currentYear = Jan1st.year();
// // if (tz.kind() !== TimeZoneKind.Proper) {
// // timeZoneString += `:${Jan1st.format("O")}`;
// // }
// // else if (!tz.hasDst()) {
// // // No daylight saving time at all -> simple offset
// // timeZoneString += `:${Jan1st.format("O")}`;
// // }
// // else {
// // const tzwoDST = TimeZone.zone(this.TimeZoneName, false); // Time zone without DST -> if offsets for Jan, 1st are the same, then we are on northern hemisphere -> 2 entries, else 3 entries
// // const startsWithRegularTime = tz.offsetForZone(currentYear, 1, 1, 0, 0, 0, 0) === tzwoDST.offsetForZone(currentYear, 1, 1, 0, 0, 0, 0);
// // const transitions = TzDatabase.instance().getTransitionsTotalOffsets(this.TimeZoneName, currentYear, currentYear + 1); // Get DST transitions for the current and the next year
// // if (transitions.length > 0 && new DateTime(transitions[0].at).year() < currentYear) {
// // transitions.shift();
// // }
// // if (startsWithRegularTime) {
// // const atDate = new DateTime(transitions[0].at, tz);
// // timeZoneString += `:${Jan1st.format("O")}:${atDate.format("O")}:${Jan1st.offset}`;
// // let isDST = true;
// // transitions.forEach(transition => {
// // // Write DST entries
// // const atDate = new DateTime(transition.at, tz);
// // let atDateUnspecific = atDate.withZone(undefined);
// // if (isDST)
// // {
// // atDateUnspecific = atDateUnspecific.sub(1, TimeUnit.Hour);
// // }
// // isDST = !isDST;
// // timeZoneString += `:${atDateUnspecific.format(":(yyyy)MMddHH")}`
// // });
// // }
// // else {
// // const atDate = new DateTime(transitions[0].at, tz);
// // timeZoneString += `:${atDate.format("O")}:${Jan1st.format("O")}:${atDate.offset}:(${currentYear})010100`;
// // let isDST = false;
// // transitions.forEach(transition => {
// // // Write DST entries
// // const atDate = new DateTime(transition.at, tz);
// // let atDateUnspecific = atDate.withZone(undefined);
// // if (isDST)
// // {
// // atDateUnspecific = atDateUnspecific.sub(1, TimeUnit.Hour);
// // }
// // isDST = !isDST;
// // timeZoneString += `:${atDateUnspecific.format(":MMddHH")}`
// // });
// // }
// // }
// // // Write resulting time zone string
// // buff.write(timeZoneString, 0, 64, "utf8");
// buff.write(TimeZoneName, 0, 64, "utf8");
// }
/**
* Creates an instance of GW_RTC_SET_TIME_ZONE_REQ.
*
* @param {string} [TimeZoneString] Time zone string, e.g. :GMT+1:GMT+2:0060:(1996)040102-0:110102-0
* @memberof GW_RTC_SET_TIME_ZONE_REQ
*/
constructor(readonly TimeZoneString: string) {
super(64);
const buff = this.Data.slice(this.offset); // View on the internal buffer makes setting the data easier
buff.write(TimeZoneString, 0, 64, "utf8");
}
} | MiSchroe/klf-200-api | src/KLF200-API/GW_RTC_SET_TIME_ZONE_REQ.ts | TypeScript | mit | 4,384 |
๏ปฟusing SoundDevices;
namespace SoundDeviceRemotes
{
public class SpeakersRemote
{
public static ISoundDevice GetSoundDevice()
{
return new Speakers();
}
}
}
| dmarkov00/Design-Patterns | Command Pattern/SoundDeviceRemotes/SpeakersRemote.cs | C# | mit | 208 |
<?php
// Composer autoloading
if (file_exists('vendor/autoload.php')) {
$loader = include 'vendor/autoload.php';
}
$zf2Path = false;
if (is_dir('vendor/ZF2/library')) {
$zf2Path = 'vendor/ZF2/library';
} elseif (getenv('ZF2_PATH')) { // Support for ZF2_PATH environment variable or git submodule
$zf2Path = getenv('ZF2_PATH');
} elseif (get_cfg_var('zf2_path')) { // Support for zf2_path directive value
$zf2Path = get_cfg_var('zf2_path');
}
if ($zf2Path) {
if (isset($loader)) {
$loader->add('Zend', $zf2Path);
} else {
include $zf2Path . '/Zend/Loader/AutoloaderFactory.php';
Zend\Loader\AutoloaderFactory::factory(array(
'Zend\Loader\StandardAutoloader' => array(
'autoregister_zf' => true
)
));
}
}
if (!class_exists('Zend\Loader\AutoloaderFactory')) {
throw new RuntimeException('Unable to load ZF2. Run `php composer.phar install` or define a ZF2_PATH environment variable.');
}
| arvind2110/ZF2-Collection-Form | init_autoloader.php | PHP | mit | 999 |
@extends('layouts.app')
@section('content')
<div class="container m-t-2">
@foreach($users as $user)
<h3><a href="/players/{{ $user->username }}">{{ $user->username }}</a></h3>
@endforeach
</div>
@endsection | g33kidd/bracket | resources/views/site/players.blade.php | PHP | mit | 213 |
๏ปฟusing Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Vehicles.Car;
public class Environment : MonoBehaviour {
[SerializeField] private GameObject cam;
[SerializeField] private GameObject car;
[SerializeField] private GameObject markers;
public GameObject cube;
private List<Vector3> markersPos;
private List<Vector3> sampledRoad;
private Vector3 lastProj;
private Vector3 currProj;
private Vector3 unitVectorAlongRoad;
private Vector3 unitVectorAlongRoadOneStepAhead;
private float nextAngle;
private float distanceFromRoad = 0.0f;
private float speedAlongRoad;
private CarController carController;
private bool collisionDetected = false;
private Camera m_cam;
private Color32[] rendered_screen = null;
private bool isUpdating = false;
internal class PairDistanceVector {
public int number;
public float dist;
public PairDistanceVector (int number, float dist) {
this.number = number;
this.dist = dist;
}
public override string ToString() {
return "Number=" + number + "; dist=" + dist;
}
}
internal class ComparePairDistanceVector : IComparer<PairDistanceVector> {
public int Compare(PairDistanceVector x, PairDistanceVector y) {
return (int)(x.dist - y.dist);
}
}
public byte[] GetFrame() {
byte[] res = Color32ArrayToByteArray(rendered_screen);
return res;
}
public Vector3 GetPosition() {
return car.transform.position;
}
public Vector3 GetForward() {
return car.transform.forward;
}
public void MakeAction(float[] actions) {
carController.Move(actions[0], actions[1], actions[1], 0f);
if (actions[2] != 0.0f) {
car.GetComponent<Rigidbody>().velocity = Vector3.zero;
car.GetComponent<Rigidbody>().angularVelocity = Vector3.zero;
SetCarPosition();
}
}
private void SetCarPosition(){
int id = UnityEngine.Random.Range(0, markersPos.Count);
car.transform.forward = GetRoadDirectionOnMarker(id);
car.transform.position = markersPos[id] + car.transform.right * 2.5f;
}
private byte[] Color32ArrayToByteArray(Color32[] colors) {
if (colors == null || colors.Length == 0)
return null;
int lengthOfColor32 = Marshal.SizeOf(typeof(Color32));
int length = lengthOfColor32 * colors.Length;
byte[] bytes = new byte[length];
GCHandle handle = default(GCHandle);
try {
handle = GCHandle.Alloc(colors, GCHandleType.Pinned);
IntPtr ptr = handle.AddrOfPinnedObject();
Marshal.Copy(ptr, bytes, 0, length);
} finally {
if (handle != default(GCHandle))
handle.Free();
}
return bytes;
}
void Start() {
carController = car.GetComponent<CarController>();
m_cam = cam.GetComponent<Camera>();
markersPos = new List<Vector3> ();
lastProj = GetPosition();
currProj = lastProj;
speedAlongRoad = 0.0f;
foreach (Transform child in markers.transform) {
markersPos.Add(child.position);
}
GenerateFileWithWaypoints();
SetCarPosition();
sampledRoad = sampleRoad();
//printCubeSpline();
}
void ComputeDistance() {
List<PairDistanceVector> distances = new List<PairDistanceVector> ();
for (int i = 0; i < sampledRoad.Count; ++i) {
distances.Add(new PairDistanceVector (i, Vector3.Distance(sampledRoad[i], GetPosition())));
}
distances.Sort(new ComparePairDistanceVector ());
// We want AB vector along the road. Therefore A must have a lower indice
// in markerPos than B (except when it's the first and last items, therefore the
// last item need to be first.
Vector3 a, b, c;
if (distances[0].number == 0 && distances[1].number == sampledRoad.Count - 1) {
a = sampledRoad[distances[1].number];
b = sampledRoad[distances[0].number];
c = sampledRoad[distances[0].number + 1];
} else if (distances[1].number == 0 && distances[0].number == sampledRoad.Count - 1) {
a = sampledRoad[distances[0].number];
b = sampledRoad[distances[1].number];
c = sampledRoad[distances[1].number + 1];
} else if (distances[0].number > distances[1].number) {
a = sampledRoad[distances[1].number];
b = sampledRoad[distances[0].number];
c = sampledRoad[(distances[0].number + 1) % sampledRoad.Count];
} else {
a = sampledRoad[distances[0].number];
b = sampledRoad[distances[1].number];
c = sampledRoad[(distances[1].number + 1) % sampledRoad.Count];
}
// u is the unit vector associated to AB
Vector3 u = (b - a).normalized;
unitVectorAlongRoad = u;
unitVectorAlongRoadOneStepAhead = (c - b).normalized;
//v is the vector associated to AC (C is the position of the car)
Vector3 v = GetPosition() - a;
// The projected point on the vector AB is (AB.AC) * AB / |AB|ยฒ + A.
// In this case with u = AB/|AB|, proj = (AC.u)*u + a
// *C
// /|
// / |
// / |
// / |
// A*----*----*B
// proj
lastProj = currProj;
currProj = Vector3.Dot(u, v) * u + a;
Vector3 diffProj = currProj - lastProj;
speedAlongRoad = Mathf.Sign(Vector3.Dot(u, diffProj)) * diffProj.magnitude;
// Square distance, Pythagorean theorem in the triangle A-C-proj
// Negative if left to the road; Positive if right to the road
distanceFromRoad = Mathf.Sign(Vector3.Cross(u, v.normalized).y) * (GetPosition() - currProj).sqrMagnitude;
// Compute the angle between AB and BC to get the next angle with the road
// Since it's control points, it's not as precise as it should be (it should be spine interpolated)
// But we get an approximation of the road shape
float angle = Mathf.Acos(Vector3.Dot(unitVectorAlongRoad, unitVectorAlongRoadOneStepAhead));
nextAngle = Mathf.Sign(Vector3.Cross(unitVectorAlongRoad, unitVectorAlongRoadOneStepAhead).y) * angle;
}
IEnumerator UpdateScreenBuffer() {
isUpdating = true;
yield return new WaitForEndOfFrame();
// Create a texture the size of the screen, RGB24 format
int width = Screen.width;
int height = Screen.height;
Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
// Read screen contents into the texture
tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
tex.Apply();
rendered_screen = tex.GetPixels32();
Destroy(tex);
isUpdating = false;
}
//Color32[] ReadScreenImmediate() {
//RenderTexture currentRT = RenderTexture.active;
//RenderTexture auxRT = new RenderTexture (Screen.width, Screen.height, 16);
//RenderTexture.active = auxRT;
//m_cam.targetTexture = auxRT;
//m_cam.Render();
//Texture2D image = new Texture2D(auxRT.width, auxRT.height);
//image.ReadPixels(new Rect(0, 0, auxRT.width, auxRT.height), 0, 0);
//image.Apply();
//RenderTexture.active = currentRT;
//m_cam.targetTexture = null;
//return image.GetPixels32();
/*Texture2D tex = cam.GetComponent<CameraCapture>().RenderResult;
if (tex == null)
return null;
return tex.GetPixels32();*/
//}
void FixedUpdate() {
if (!isUpdating) {
isUpdating = true;
StartCoroutine(UpdateScreenBuffer());
}
//byte[] aux2 = GetFrame();
//List<float> aux = GetState();
//string res = "[";
//foreach (float f in aux) {
// res += f.ToString() + ", ";
//}
//res += "]";
//print(res);
//if (aux2 == null)
// print("Frame is null...");
//else
// print("[" + aux2[0] + ";" + aux2[1] + ";" + aux2[2] + ";" + aux2[3] + "]");
}
void GenerateFileWithWaypoints() {
List<Vector3_base> data = new List<Vector3_base> ();
foreach (Vector3 v in markersPos) {
data.Add(new Vector3_base (v));
}
string json = JsonConvert.SerializeObject(data.ToArray());
string path = Application.dataPath + "/waypoints_" + SceneManager.GetActiveScene().name + ".txt";
System.IO.File.WriteAllText(path, json);
}
public List<float> GetState() {
ComputeDistance();
List<float> res = new List<float>();
res.Add(distanceFromRoad);
res.Add(speedAlongRoad);
res.AddRange(GetValues(GetPosition()));
res.AddRange(GetValues(currProj));
res.Add(Convert.ToSingle(collisionDetected));
res.AddRange(GetValues(unitVectorAlongRoad));
res.AddRange(GetValues(GetForward()));
res.Add(nextAngle);
collisionDetected = false;
return res;
}
//void FixedUpdate() {
// ComputeDistance();
// print("Next angle =" + nextAngle);
//}
private List<float> GetValues(Vector3 v){
List<float> aux = new List<float>();
aux.Add(v.x);
aux.Add(v.y);
aux.Add(v.z);
return aux;
}
public void DetectedCollision() {
collisionDetected = true;
}
private Vector3 GetRoadDirectionOnMarker(int markerId){
int next = (markerId + 1) % markersPos.Count;
int prev = markerId - 1;
if (prev == -1)
prev = markersPos.Count - 1;
return (markersPos[next] - markersPos[prev]) / (2.0f / markersPos.Count);
}
private Vector3 CatmullRom(float t, Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3) {
Vector3 m0 = (p2 - p0) / 2.0f;
Vector3 m1 = (p3 - p1) / 2.0f;
return (2 * t * t * t - 3 * t * t + 1) * p1 + (t * t * t - 2 * t * t + t) * m0 + (-2 * t * t * t + 3 * t * t) * p2 + (t * t * t - t * t) * m1;
}
private void printCubeSpline() {
for(int i = 0; i < markersPos.Count; i++) {
Instantiate(cube, markersPos[i] + Vector3.up*0.8f, Quaternion.identity);
for(float t = 0.25f; t < 1.0f; t += 0.25f) {
int aux = i - 1;
if (i - 1 < 0)
aux = markersPos.Count - 1;
Vector3 position = CatmullRom(t, markersPos[aux], markersPos[i], markersPos[(i + 1) % markersPos.Count], markersPos[(i + 2) % markersPos.Count]);
Instantiate(cube, position + Vector3.up * 0.8f, Quaternion.identity);
}
}
}
private List<Vector3> sampleRoad() {
List<Vector3> data = new List<Vector3>();
for (int i = 0; i < markersPos.Count; i++) {
// FOR SIMON : You can change the increment there to improve performance
for (float t = 0.0f; t < 1.0f; t += 0.1f) {
int aux = i - 1;
if (i - 1 < 0)
aux = markersPos.Count - 1;
Vector3 position = CatmullRom(t, markersPos[aux], markersPos[i], markersPos[(i + 1) % markersPos.Count], markersPos[(i + 2) % markersPos.Count]);
data.Add(position);
}
}
return data;
}
}
| Amathlog/rl-unity | simulator/Assets/Scripts/Environment.cs | C# | mit | 10,767 |
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe Responders::PaginateResponder do
subject(:json) do
action.call
JSON.parse(response.body)
end
let(:resource) { ArModel.all }
let(:method) { :get }
let(:params) { {format: :json} }
let(:action) { -> { send(method, :index, params: params) } }
context 'with AR resource' do
it { expect(json).to eq (1..50).to_a }
describe '?page' do
let(:params) { super().merge page: 2 }
it { expect(json).to eq (51..100).to_a }
end
describe '?page empty' do
let(:params) { super().merge page: '' }
it 'responds with first page' do
expect(json).to eq (1..50).to_a
end
end
describe '?page invalid' do
let(:params) { super().merge page: 'foobar' }
it 'responds with first page' do
expect(json).to eq (1..50).to_a
end
end
describe '?per_page' do
let(:params) { super().merge per_page: 10 }
it { expect(json).to eq (1..10).to_a }
end
describe '?per_page&page' do
let(:params) { super().merge page: 2, per_page: 10 }
it { expect(json).to eq (11..20).to_a }
end
end
context 'with array resource' do
let(:resource) do
case GEM
when 'will_paginate', 'pagy'
('AA'..'zz').to_a
when 'kaminari'
Kaminari.paginate_array ('AA'..'zz').to_a
end
end
it { expect(json).to eq ('AA'..'zz').to_a[0..49] }
describe '?page' do
let(:params) { super().merge page: 2 }
it { expect(json).to eq ('AA'..'zz').to_a[50..99] }
end
describe '?per_page' do
let(:params) { super().merge per_page: 10 }
it { expect(json).to eq ('AA'..'zz').to_a[0..9] }
end
describe '?per_page&page' do
let(:params) { super().merge page: 2, per_page: 10 }
it { expect(json).to eq ('AA'..'zz').to_a[10..19] }
end
end
context 'with AR association' do
let(:resource) { ArModel.find(1).ar_assoc_models }
it { expect(json).to eq (1..5).to_a }
end
describe 'links' do
subject(:links) do
action.call
response.links.map {|l| [l[:params][:rel], l[:url]] }.to_h
end
it { expect(links.size).to eq 3 }
it { is_expected.to include 'first' => 'http://test.host/index.json?page=1' }
it { is_expected.to include 'next' => 'http://test.host/index.json?page=2' }
it { is_expected.to include 'last' => 'http://test.host/index.json?page=14' }
context '?page' do
let(:params) { super().merge page: 2 }
it { expect(links.size).to eq 4 }
it { is_expected.to include 'first' => 'http://test.host/index.json?page=1' }
it { is_expected.to include 'prev' => 'http://test.host/index.json?page=1' }
it { is_expected.to include 'next' => 'http://test.host/index.json?page=3' }
it { is_expected.to include 'last' => 'http://test.host/index.json?page=14' }
end
context '?page=5' do
let(:params) { super().merge page: 5 }
it { expect(links.size).to eq 4 }
it { is_expected.to include 'first' => 'http://test.host/index.json?page=1' }
it { is_expected.to include 'prev' => 'http://test.host/index.json?page=4' }
it { is_expected.to include 'next' => 'http://test.host/index.json?page=6' }
it { is_expected.to include 'last' => 'http://test.host/index.json?page=14' }
end
context '?page last' do
let(:params) { super().merge page: 14 }
it { expect(links.size).to eq 3 }
it { is_expected.to include 'first' => 'http://test.host/index.json?page=1' }
it { is_expected.to include 'prev' => 'http://test.host/index.json?page=13' }
it { is_expected.to include 'last' => 'http://test.host/index.json?page=14' }
end
context '?page before last' do
let(:params) { super().merge page: 13 }
it { expect(links.size).to eq 4 }
it { is_expected.to include 'first' => 'http://test.host/index.json?page=1' }
it { is_expected.to include 'prev' => 'http://test.host/index.json?page=12' }
it { is_expected.to include 'next' => 'http://test.host/index.json?page=14' }
it { is_expected.to include 'last' => 'http://test.host/index.json?page=14' }
end
context '?per_page' do
let(:params) { super().merge page: 1, per_page: 10 }
it { expect(links.size).to eq 3 }
it { is_expected.to include 'first' => 'http://test.host/index.json?page=1&per_page=10' }
it { is_expected.to include 'next' => 'http://test.host/index.json?page=2&per_page=10' }
it { is_expected.to include 'last' => 'http://test.host/index.json?page=68&per_page=10' }
end
context '?per_page above max per page limit' do
let(:params) { super().merge page: 1, per_page: 100 }
it { expect(links.size).to eq 3 }
it { is_expected.to include 'first' => 'http://test.host/index.json?page=1&per_page=50' }
it { is_expected.to include 'next' => 'http://test.host/index.json?page=2&per_page=50' }
it { is_expected.to include 'last' => 'http://test.host/index.json?page=14&per_page=50' }
end
context 'when method is HEAD' do
let(:method) { :head }
it { expect(links.size).to eq 3 }
it { is_expected.to include 'first' => 'http://test.host/index.json?page=1' }
it { is_expected.to include 'next' => 'http://test.host/index.json?page=2' }
it { is_expected.to include 'last' => 'http://test.host/index.json?page=14' }
end
end
describe 'headers' do
subject do
action.call
response.headers.to_h
end
it { is_expected.to include 'X-Total-Pages' => '14' }
it { is_expected.to include 'X-Total-Count' => '676' }
it { is_expected.to include 'X-Per-Page' => '50' }
it { is_expected.to include 'X-Current-Page' => '1' }
context 'when method is HEAD' do
let(:method) { :head }
it { is_expected.to include 'X-Total-Pages' => '14' }
it { is_expected.to include 'X-Total-Count' => '676' }
it { is_expected.to include 'X-Per-Page' => '50' }
it { is_expected.to include 'X-Current-Page' => '1' }
end
end
end
| jgraichen/paginate-responder | spec/responders/paginate_responder_spec.rb | Ruby | mit | 6,158 |
<?php
namespace FlickrDownloadr\Tool;
class SpeedFormater
{
/** @var \FlickrDownloadr\Tool\FilesizeFormater */
private $filesizeFormater;
function __construct(\FlickrDownloadr\Tool\FilesizeFormater $filesizeFormater)
{
$this->filesizeFormater = $filesizeFormater;
}
/**
* @param int $bytes
* @param float $duration Seconds with miliseconds
* @return string
*/
public function format($bytes, $duration)
{
if ($duration == 0) {
return '';
}
$bytesPerSec = $bytes / $duration;
return $this->filesizeFormater->format($bytesPerSec) . '/s';
}
} | michalsanger/cli-flickr-downloadr | src/Tool/SpeedFormater.php | PHP | mit | 572 |
/*=============================================================================
Copyright (c) 2012, Ludo Sapiens Inc. and contributors.
See accompanying file LICENSE.txt for details.
=============================================================================*/
#include <Fusion/Widget/Canvas.h>
#include <Fusion/VM/VMObjectPool.h>
#include <CGMath/CGMath.h>
#include <Base/ADT/StringMap.h>
/*==============================================================================
UNNAME NAMESPACE
==============================================================================*/
UNNAMESPACE_BEGIN
//------------------------------------------------------------------------------
//!
inline void
execute( const VMRef& ref, Widget* widget, const RCP<Widget>& item )
{
if( ref.isValid() )
{
VMState* vm = ref.vm();
VM::push( vm, ref );
VM::pushProxy( vm, widget );
VM::pushProxy( vm, item.ptr() );
VM::ecall( vm, 2, 0 );
}
}
//------------------------------------------------------------------------------
//!
int
getCanvasRectVM( VMState* vm )
{
Canvas* canvas = (Canvas*)VM::thisPtr( vm );
VM::push( vm, canvas->canvasRect() );
return 1;
}
//------------------------------------------------------------------------------
//!
enum {
ATTRIB_GET_CANVAS_RECT,
ATTRIB_OFFSET,
ATTRIB_ONMODIFY
};
StringMap _attributes(
"getCanvasRect", ATTRIB_GET_CANVAS_RECT,
"offset", ATTRIB_OFFSET,
"onModify", ATTRIB_ONMODIFY,
""
);
//------------------------------------------------------------------------------
//!
const char* _canvas_str_ = "canvas";
UNNAMESPACE_END
NAMESPACE_BEGIN
/*==============================================================================
CLASS Canvas
==============================================================================*/
//------------------------------------------------------------------------------
//!
void
Canvas::initialize()
{
VMObjectPool::registerObject( "UI", _canvas_str_, stdCreateVM<Canvas>, stdGetVM<Canvas>, stdSetVM<Canvas> );
}
//------------------------------------------------------------------------------
//!
Canvas::Canvas()
: WidgetContainer(),
_offset(0.0f,0.0f),
_canvasRectCached( false )
{}
//------------------------------------------------------------------------------
//!
Canvas::~Canvas()
{}
//------------------------------------------------------------------------------
//!
void
Canvas::render( const RCP<Gfx::RenderNode>& rn )
{
if( isScissored() )
{
// Render the widget container.
Widget::render( rn );
// Render the contained widgets.
const int* sc = rn->current()->addScissor( (int)_scPos.x, (int)_scPos.y, (int)_scSize.x, (int)_scSize.y );
Container::ConstIterator it = _widgets.begin();
Container::ConstIterator end = _widgets.end();
for( ; it != end; ++it )
{
if( !(*it)->hidden() ) (*it)->render( rn );
}
rn->current()->setScissor( sc[0], sc[1], sc[2], sc[3] );
}
else
{
WidgetContainer::render( rn );
}
}
//------------------------------------------------------------------------------
//!
bool
Canvas::isAttribute
( const char* name ) const
{
if( _attributes[ name ] != StringMap::INVALID ) return true;
return WidgetContainer::isAttribute( name );
}
//------------------------------------------------------------------------------
//!
Vec4f
Canvas::canvasRect() const
{
if( !_canvasRectCached )
{
Container::ConstIterator it = _widgets.begin();
Container::ConstIterator end = _widgets.end();
_canvasRect = Vec4f(
_offset.x,
_offset.y,
_offset.x + actualSize().x,
_offset.y + actualSize().y
);
for( ; it != end; ++it )
{
if( (*it)->hidden() ) continue;
CGM::clampMax( _canvasRect.x, (*it)->absPosition().x );
CGM::clampMax( _canvasRect.y, (*it)->absPosition().y );
CGM::clampMin( _canvasRect.z, (*it)->absPosition().x + (*it)->actualSize().x );
CGM::clampMin( _canvasRect.w, (*it)->absPosition().y + (*it)->actualSize().y );
}
_canvasRectCached = true;
}
return _canvasRect;
}
//------------------------------------------------------------------------------
//!
void
Canvas::offset( const Vec2f& val )
{
if( val != _offset )
{
_offset = val;
modified();
markForUpdate();
}
}
//------------------------------------------------------------------------------
//!
Vec2f
Canvas::performComputeBaseSize()
{
return Vec2f( 0.0f, 0.0f );
}
//------------------------------------------------------------------------------
//!
void
Canvas::performSetGeometry()
{
Container::ConstIterator it = _widgets.begin();
Container::ConstIterator end = _widgets.end();
for( ; it != end; ++it )
{
if( (*it)->hidden() ) continue;
(*it)->geometry(
globalPosition() - _offset,
(*it)->localPosition(),
(*it)->actualBaseSize()
);
}
// Ignores flexibility of child
_canvasRectCached = false;
canvasRect();
modified();
_scPos.x = globalPosition().x + border().x;
_scPos.y = globalPosition().y + border().y;
_scSize.x = actualSize().x - border().x - border().z;
_scSize.y = actualSize().y - border().y - border().w;
}
//------------------------------------------------------------------------------
//!
void
Canvas::performSetPosition()
{
Container::ConstIterator it = _widgets.begin();
Container::ConstIterator end = _widgets.end();
for( ; it != end; ++it )
{
if( !(*it)->hidden() )
{
(*it)->position( globalPosition() - _offset, (*it)->localPosition() );
}
}
_scPos.x = globalPosition().x + border().x;
_scPos.y = globalPosition().y + border().y;
}
//------------------------------------------------------------------------------
//!
bool
Canvas::isScissored() const
{
Vec4f rect = canvasRect();
if( _offset.x > rect.x || _offset.y > rect.y ||
_offset.x + actualSize().x < rect.z ||
_offset.y + actualSize().y < rect.w )
{
return true;
}
return false;
}
//------------------------------------------------------------------------------
//!
void
Canvas::modified()
{
_onModify.exec( this );
execute( _onModifyRef, this, this );
}
//------------------------------------------------------------------------------
//!
const char*
Canvas::meta() const
{
return _canvas_str_;
}
//------------------------------------------------------------------------------
//!
void
Canvas::init( VMState* vm )
{
VM::get( vm, 1, "offset", _offset );
VM::get( vm, 1, "onModify", _onModifyRef );
// Base class init.
WidgetContainer::init( vm );
}
//------------------------------------------------------------------------------
//!
bool
Canvas::performGet( VMState* vm )
{
switch( _attributes[ VM::toCString( vm, 2 ) ] )
{
case ATTRIB_GET_CANVAS_RECT:
VM::push( vm, this, getCanvasRectVM );
return true;
case ATTRIB_OFFSET:
VM::push( vm, _offset );
return true;
case ATTRIB_ONMODIFY:
VM::push( vm, _onModifyRef );
return true;
default: break;
}
return WidgetContainer::performGet( vm );
}
//------------------------------------------------------------------------------
//!
bool
Canvas::performSet( VMState* vm )
{
switch( _attributes[ VM::toCString( vm, 2 ) ] )
{
case ATTRIB_GET_CANVAS_RECT:
return true; // read-only
case ATTRIB_OFFSET:
offset( VM::toVec2f( vm, 3 ) );
return true;
case ATTRIB_ONMODIFY:
VM::toRef( vm, 3, _onModifyRef );
return true;
default: break;
}
return WidgetContainer::performSet( vm );
}
NAMESPACE_END
| LudoSapiens/Dev | Projects/Fusion/Widget/Canvas.cpp | C++ | mit | 7,948 |
#include "Log.h"
#include "Socket.h"
#include <string.h>
#include <iostream>
#include <atomic>
#define SOCKET_MAX_CONNECTIONS 20
#if (defined __CYGWIN__ || defined __GNUC__)
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define SOCKET_HANDLE int
#define INVALID_SOCKET 0
#define SOCKET_ERROR -1
namespace {
std::string ErrorMessage (const std::string& inMethod, int inId) {
return std::string ("[Socket](") + std::to_string (inId) + std::string (") Gnu::" + inMethod + " failed");
}
}
#elif _MSC_VER >= 1800
#undef UNICODE
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#define SOCKET_HANDLE SOCKET
namespace {
std::string ErrorMessage (const std::string& inMethod, int inId) {
return std::string ("[Socket](") + std::to_string (inId) + std::string (") WinSock2::") + inMethod + std::string(" failed with code ") + std::to_string (WSAGetLastError ());
}
}
#else
static_assert (true, "Incompatible compiler");
#endif
class OS::Socket::Implementation {
public:
Implementation () :
mSocketHandle (INVALID_SOCKET),
mLatestAddrInfo (NULL),
mIsConnected (false),
mIsListening (false)
{
}
~Implementation () {
Close ();
}
public:
bool IsConnected () const {
return mIsConnected;
}
bool IsListening () const {
return mIsListening;
}
bool Initialize (SOCKET_HANDLE inSocketHandle) {
mIsListening = false;
mIsConnected = true;
mSocketHandle = inSocketHandle;
LOGDEBUG << "[Socket](" << GetId () << ") initialized";
return true;
}
bool Initialize (const std::string& inAddress, const std::string& inPort) {
mIsListening = false;
mIsConnected = false;
struct addrinfo hints;
#if (defined __CYGWIN__ || defined __GNUC__)
::memset (&hints, 0, sizeof (hints));
#else
ZeroMemory (&hints, sizeof (hints));
#endif
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the server address and port
int res = getaddrinfo (inAddress.c_str (), inPort.c_str (), &hints, &mLatestAddrInfo);
if (res != 0) {
LOGDEBUG << ErrorMessage ("getaddrinfo", GetId());
return false;
}
// Create a SOCKET for connecting to server
mSocketHandle = socket (mLatestAddrInfo->ai_family, mLatestAddrInfo->ai_socktype, mLatestAddrInfo->ai_protocol);
if (mSocketHandle == INVALID_SOCKET) {
LOGDEBUG << ErrorMessage ("socket", GetId());
return false;
}
int flag (1);
#if (defined __CYGWIN__ || defined __GNUC__)
if (setsockopt (mSocketHandle, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&flag), sizeof(flag)) < 0) {
#else
if (setsockopt (mSocketHandle, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, reinterpret_cast<char*>(&flag), sizeof(flag)) < 0) {
#endif
LOGDEBUG << ErrorMessage ("setsocketopt", GetId());
return false;
}
LOGDEBUG << "[Socket](" << GetId () << ") initialized at " << inAddress << ":" << inPort;
return true;
}
void Close () {
if (mIsConnected || mIsListening) {
if (mLatestAddrInfo != NULL) {
freeaddrinfo (mLatestAddrInfo);
mLatestAddrInfo = NULL;
}
shutdown (mSocketHandle, 2);
#if (defined __CYGWIN__ || defined __GNUC__)
close (mSocketHandle);
#else
closesocket (mSocketHandle);
#endif
LOGDEBUG << "[Socket](" << GetId () << ") closed";
}
mIsConnected = false;
mIsListening = false;
}
bool Listen () {
if (!mIsListening) {
int result = bind (mSocketHandle, mLatestAddrInfo->ai_addr, (int) mLatestAddrInfo->ai_addrlen);
if (result == SOCKET_ERROR) {
LOGDEBUG << ErrorMessage ("bind", GetId());
return false;
}
result = listen (mSocketHandle, SOCKET_MAX_CONNECTIONS);
if (result == SOCKET_ERROR) {
LOGDEBUG << ErrorMessage ("listen", GetId());
return false;
}
}
mIsListening = true;
LOGDEBUG << "[Socket](" << GetId () << ") listening...";
return true;
}
bool Accept (OS::Socket& outSocket) {
if (!mIsListening) {
return false;
}
SOCKET_HANDLE clientSocket = accept (mSocketHandle, NULL, NULL);
if (clientSocket <= 0) {
LOGDEBUG << ErrorMessage ("accept", GetId ());
return false;
}
outSocket.Initialize (clientSocket);
LOGDEBUG << "[Socket](" << GetId () << ") accepted socket " << outSocket.GetId ();
return true;
}
bool Connect () {
if (mIsConnected) {
return true;
}
// Connect to server.
int res = connect (mSocketHandle, mLatestAddrInfo->ai_addr, (int) mLatestAddrInfo->ai_addrlen);
if (res == SOCKET_ERROR) {
LOGDEBUG << ErrorMessage ("connect", GetId ());
return false;
}
LOGDEBUG << "[Socket](" << GetId () << ") connected to server";
mIsConnected = true;
return true;
}
int GetId () const {
return mSocketHandle;
}
int Send (const uint8_t* inBuffer, std::size_t inBufferSize) {
if (!mIsConnected) {
return false;
}
int result = send (mSocketHandle, reinterpret_cast<const char*>(inBuffer), inBufferSize, 0);
if (result == SOCKET_ERROR) {
LOGDEBUG << ErrorMessage ("send", GetId ());
Close ();
return -1;
}
if (result == 0) {
LOGDEBUG << "[Socket](" << GetId () << ") Failed to send any bytes";
Close ();
return -1;
}
LOGTRACE << "[Socket](" << GetId () << ") Send " << result << " bytes";
return result;
}
int Receive (uint8_t* ioBuffer, std::size_t inBufferSize) {
if (!mIsConnected) {
return false;
}
int result = recv (mSocketHandle, reinterpret_cast<char*>(ioBuffer), inBufferSize, 0);
if (result == 0) {
LOGDEBUG << "[Socket](" << GetId () << ") Received termination signal";
Close ();
return -1;
}
if (result < 0) {
LOGDEBUG << ErrorMessage ("recv", GetId());
Close ();
return -1;
}
LOGTRACE << "[Socket](" << GetId () << ") Received " << result << " bytes";
return result;
}
private:
SOCKET_HANDLE mSocketHandle;
struct addrinfo *mLatestAddrInfo;
std::atomic<bool> mIsConnected;
std::atomic<bool> mIsListening;
};
OS::Socket::Socket (const std::string& inAddress, const std::string& inPortNumber) :
mAddress (inAddress),
mPortNumber (inPortNumber),
mImpl (std::make_unique <Implementation> ())
{
}
OS::Socket::~Socket () = default;
bool OS::Socket::Initialize () {
return mImpl->Initialize (mAddress, mPortNumber);
}
bool OS::Socket::Initialize (int inHandle) {
return mImpl->Initialize (inHandle);
}
void OS::Socket::Close () {
mImpl->Close ();
}
int OS::Socket::GetId () {
return mImpl->GetId ();
}
bool OS::Socket::Listen () {
return mImpl->Listen ();
}
bool OS::Socket::Accept (OS::Socket& outSocket) {
return mImpl->Accept (outSocket);
}
bool OS::Socket::Connect () {
return mImpl->Connect ();
}
int OS::Socket::Send (const std::vector<uint8_t>& inBuffer) {
return mImpl->Send (inBuffer.data(), inBuffer.size());
}
int OS::Socket::Send (const uint8_t* inBuffer, std::size_t inBufferSize) {
return mImpl->Send (inBuffer, inBufferSize);
}
int OS::Socket::Receive (std::vector<uint8_t>& ioBuffer) {
return mImpl->Receive (ioBuffer.data(), ioBuffer.size());
}
int OS::Socket::Receive (uint8_t* ioBuffer, std::size_t inBufferSize) {
return mImpl->Receive (ioBuffer, inBufferSize);
}
bool OS::Socket::IsConnected () const {
return mImpl->IsConnected ();
}
bool OS::Socket::IsListening () const {
return mImpl->IsListening ();
} | Eelco81/server-test-project | Lib/Core/Src/Socket.cpp | C++ | mit | 8,470 |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 14 02:17:11 2017
@author: guida
"""
import json
import requests
def get_url(url):
response = requests.get(url)
content = response.content.decode("utf8")
return content
#Json parser
def get_json_from_url(url):
content = get_url(url)
js = json.loads(content)
return js | DiegoGuidaF/telegram-raspy | modules.py | Python | mit | 358 |
package com.reason.ide.console;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.DumbAwareAction;
import org.jetbrains.annotations.NotNull;
class ClearLogAction extends DumbAwareAction {
private final ConsoleView m_console;
ClearLogAction(ConsoleView console) {
super("Clear All", "Clear the contents of the logs", AllIcons.Actions.GC);
m_console = console;
}
@Override
public void update(@NotNull AnActionEvent e) {
Editor editor = e.getData(CommonDataKeys.EDITOR);
e.getPresentation().setEnabled(editor != null && editor.getDocument().getTextLength() > 0);
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
m_console.clear();
}
}
| reasonml-editor/reasonml-idea-plugin | src/com/reason/ide/console/ClearLogAction.java | Java | mit | 918 |
#region Licence
/* The MIT License (MIT)
Copyright ยฉ 2014 Francesco Pighi <francesco.pighi@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the โSoftwareโ), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
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. */
#endregion
using System;
using FluentAssertions;
using Xunit;
using Paramore.Brighter.CommandStore.Sqlite;
using Paramore.Brighter.Tests.CommandProcessors.TestDoubles;
namespace Paramore.Brighter.Tests.CommandStore.Sqlite
{
[Trait("Category", "Sqlite")]
[Collection("Sqlite CommandStore")]
public class SqliteCommandStoreAddMessageTests : IDisposable
{
private readonly SqliteTestHelper _sqliteTestHelper;
private readonly SqliteCommandStore _sqlCommandStore;
private readonly MyCommand _raisedCommand;
private MyCommand _storedCommand;
public SqliteCommandStoreAddMessageTests()
{
_sqliteTestHelper = new SqliteTestHelper();
_sqliteTestHelper.SetupCommandDb();
_sqlCommandStore = new SqliteCommandStore(new SqliteCommandStoreConfiguration(_sqliteTestHelper.ConnectionString, _sqliteTestHelper.TableName));
_raisedCommand = new MyCommand {Value = "Test"};
_sqlCommandStore.Add(_raisedCommand);
}
[Fact]
public void When_Writing_A_Message_To_The_Command_Store()
{
_storedCommand = _sqlCommandStore.Get<MyCommand>(_raisedCommand.Id);
//_should_read_the_command_from_the__sql_command_store
_storedCommand.Should().NotBeNull();
//_should_read_the_command_value
_storedCommand.Value.Should().Be(_raisedCommand.Value);
//_should_read_the_command_id
_storedCommand.Id.Should().Be(_raisedCommand.Id);
}
public void Dispose()
{
_sqliteTestHelper.CleanUpDb();
}
}
} | dstockhammer/Brighter | tests/Paramore.Brighter.Tests/CommandStore/Sqlite/When_writing_a_message_to_the_command_store.cs | C# | mit | 2,789 |
<?php
return array (
'id' => 'sonyericsson_xperia_acro_so02c_suban234',
'fallback' => 'sonyericsson_xperia_acro_ver1_sub02',
'capabilities' =>
array (
'device_os_version' => '2.3',
),
);
| cuckata23/wurfl-data | data/sonyericsson_xperia_acro_so02c_suban234.php | PHP | mit | 202 |
๏ปฟusing System;
using System.Collections.Generic;
using AutomaticTypeMapper;
using Microsoft.Xna.Framework.Graphics;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.Processing;
namespace EOLib.Graphics
{
[MappedType(BaseType = typeof(INativeGraphicsManager), IsSingleton = true)]
public sealed class NativeGraphicsManager : INativeGraphicsManager
{
private readonly Dictionary<LibraryGraphicPair, Texture2D> _cache;
private readonly object __cachelock__ = new object();
private readonly INativeGraphicsLoader _gfxLoader;
private readonly IGraphicsDeviceProvider _graphicsDeviceProvider;
public NativeGraphicsManager(INativeGraphicsLoader gfxLoader, IGraphicsDeviceProvider graphicsDeviceProvider)
{
_cache = new Dictionary<LibraryGraphicPair, Texture2D>();
_gfxLoader = gfxLoader;
_graphicsDeviceProvider = graphicsDeviceProvider;
}
public Texture2D TextureFromResource(GFXTypes file, int resourceVal, bool transparent = false, bool reloadFromFile = false)
{
Texture2D ret;
var key = new LibraryGraphicPair((int)file, 100 + resourceVal);
lock (__cachelock__)
{
if (!reloadFromFile && _cache.ContainsKey(key))
{
return _cache[key];
}
if (_cache.ContainsKey(key) && reloadFromFile)
{
if (_cache[key] != null) _cache[key].Dispose();
_cache.Remove(key);
}
}
using (var mem = new System.IO.MemoryStream())
{
using (var i = BitmapFromResource(file, resourceVal, transparent))
((Image)i).Save(mem, new PngEncoder());
ret = Texture2D.FromStream(_graphicsDeviceProvider.GraphicsDevice, mem);
}
lock (__cachelock__)
{
_cache.Add(key, ret);
}
return ret;
}
private IImage BitmapFromResource(GFXTypes file, int resourceVal, bool transparent)
{
var ret = (Image)_gfxLoader.LoadGFX(file, resourceVal);
if (transparent)
{
// TODO: 0x000000 is supposed to clip hair below it
// need to figure out how to clip this
// if (file != GFXTypes.FemaleHat && file != GFXTypes.MaleHat)
CrossPlatformMakeTransparent(ret, Color.Black);
// for hats: 0x080000 is transparent
if (file == GFXTypes.FemaleHat || file == GFXTypes.MaleHat)
{
CrossPlatformMakeTransparent(ret, Color.FromRgba(0x08, 0x00, 0x00, 0xFF));
CrossPlatformMakeTransparent(ret, Color.FromRgba(0x00, 0x08, 0x00, 0xFF));
CrossPlatformMakeTransparent(ret, Color.FromRgba(0x00, 0x00, 0x08, 0xFF));
}
}
return ret;
}
private static void CrossPlatformMakeTransparent(Image bmp, Color transparentColor)
{
var brush = new RecolorBrush(transparentColor, Color.Transparent, 0.0001f);
bmp.Mutate(x => x.Clear(brush));
}
public void Dispose()
{
lock (__cachelock__)
{
foreach (var text in _cache.Values)
{
text.Dispose();
}
_cache.Clear();
}
}
}
[Serializable]
public class GFXLoadException : Exception
{
public GFXLoadException(int resource, GFXTypes gfx)
: base($"Unable to load graphic {resource + 100} from file gfx{(int) gfx:000}.egf") { }
}
}
| ethanmoffat/EndlessClient | EOLib.Graphics/NativeGraphicsManager.cs | C# | mit | 3,895 |
๏ปฟusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Xml.Linq;
using TremAn.Decorators.AreaOfInterest;
using TremAn.Models.AreaOfInterest;
namespace TremAn.ViewModels.AreaOfInterest
{
public class TracerViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private Tracer Tracer;
public Rectangle[] Rects
{
get
{
return Tracer.Rects;
}
set
{
Tracer.Rects = value;
OnPropertyChanged("AOIRects");
}
}
public TracerViewModel(Tracer tracer)
{
setTracer(tracer);
}
public void SetAOIRectCtrlCallback(RectangleDecorator rectangleDecorator)
{
rectangleDecorator.CallBack += RectangleChanged;
}
public void RectangleChanged(Rectangle rectangle)
{
SaveAOIPosition(rectangle);
}
private void setTracer(Tracer tracer)
{
this.Tracer = tracer;
}
//Export areas of interest to xml
public XElement AreasOfInterestToXML()
{
XElement AreasOfInterestXML = new XElement("AreasOfInterest", from i in Rects
select
new XElement("AreaOfInterest",
new XAttribute("Height", i.Height),
new XAttribute("Width", i.Width),
new XAttribute("X", i.X),
new XAttribute("Y", i.Y),
new XAttribute("frameID", i.FrameID)));
return AreasOfInterestXML;
}
//Import areas of interest from xml
internal static Tracer FromXML(XElement xe)
{
IEnumerable<Rectangle> rects = from rect in xe.Descendants("AreaOfInterest")
select new Rectangle
{
X = (double)rect.Attribute("X"),
Y = (double)rect.Attribute("Y"),
Width = (double)rect.Attribute("Width"),
Height = (double)rect.Attribute("Height"),
FrameID = UInt32.Parse(rect.Attribute("frameID").Value)
};
Tracer tracer = new Tracer(rects.ToArray());
return tracer;
}
public Rectangle GetFrame(uint frameID)
{
return Rects[frameID];
}
public void SaveAOIPosition(Rectangle rectangle)
{
for (uint i = rectangle.FrameID; i < Rects.Length; i++)
{
Rects[i] = new Rectangle()
{
X = (int)rectangle.X,
Y = (int)rectangle.Y,
Width = (int)rectangle.Width,
Height = (int)rectangle.Height,
FrameID = i
};
}
}
private void OnPropertyChanged(String info)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info));
}
}
}
| binao/TremAn | TremAn/ViewModels/AreaOfInterest/TracerViewModel.cs | C# | mit | 3,740 |
module Gallery
VERSION = "0.0.1"
end
| mazharoddin/camaleon_cms_gallery | lib/gallery/version.rb | Ruby | mit | 39 |
/*-------------------------------------------------------------------------
This source file is a part of Whisperwind.(GameEngine + GamePlay + GameTools)
For the latest info, see http://lisuyong.com
Copyright (c) 2012 Suyong Li (79481268@qq.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE
-------------------------------------------------------------------------*/
#include "ABTreeSceneNode.h"
namespace Engine
{
//---------------------------------------------------------------------
void ABTreeSceneNode::updatedAABB()
{
/// TODO!
}
} | harr999y/Whisperwind | Whisperwind/Whisperwind_GeneralSceneManager/src/ABTreeSceneNode.cpp | C++ | mit | 1,526 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2014 Alan Aguiar alanjas@hotmail.com
# Copyright (c) 2012-2014 Butiรก Team butia@fing.edu.uy
# Butia is a free and open robotic platform
# www.fing.edu.uy/inco/proyectos/butia
# Facultad de Ingenierรญa - Universidad de la Repรบblica - Uruguay
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
import os
import sys
# Make sure that can import all files
abs_path = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, abs_path)
# version = 0.turtlebots_version.secondary_number
__version__ = '0.27.0'
| nvazquez/Turtlebots | plugins/butia/pybot/__init__.py | Python | mit | 1,171 |
module Transmat
class Money
module Arithmetic
def -@
Money.new currency, -amount
end
def == other
amount == other.amount && currencies_match?(other)
end
def eql? other
self == other
end
def <=> other
assert_matching_currencies other
amount <=> other.amount
end
def + other
assert_matching_currencies other
Money.new currency, amount + other.amount
end
def - other
assert_matching_currencies other
Money.new currency, amount - other.amount
end
def * exchange_rate
return self * exchange_rate.swap unless exchange_rate.currencies_match? self
exchange_rate.assert_matching_currencies self
Money(exchange_rate.counter_currency, amount.to_r * exchange_rate.rate)
end
end
end
end
| juliogreff/transmat | lib/transmat/money/arithmetic.rb | Ruby | mit | 873 |
import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
| dmateusp/PokemonGo-Bot | pokemongo_bot/cell_workers/recycle_items.py | Python | mit | 5,073 |
import org.junit.Test;
import java.util.Stack;
import static junit.framework.Assert.assertEquals;
/**
* https://leetcode.com/problems/min-stack/
*/
public class MinStack {
class StackItem {
int value;
int min;
StackItem(int value, int min) {
this.value = value;
this.min = min;
}
}
Stack<StackItem> stack = new Stack<>();
public void push(int x) {
if (stack.isEmpty()) {
stack.push(new StackItem(x, x));
} else {
int min = stack.peek().min;
if (x < min) {
min = x;
}
stack.push(new StackItem(x, min));
}
}
public void pop() {
stack.pop();
}
public int top() {
return stack.peek().value;
}
public int getMin() {
return stack.peek().min;
}
@Test
public void test() {
MinStack minStack = new MinStack();
minStack.push(10);
assertEquals(10, minStack.getMin());
assertEquals(10, minStack.top());
minStack.push(20);
assertEquals(10, minStack.getMin());
assertEquals(20, minStack.top());
minStack.push(5);
assertEquals(5, minStack.getMin());
assertEquals(5, minStack.top());
}
}
| bunnyc1986/leetcode | min-stack/src/MinStack.java | Java | mit | 1,302 |
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>js/sweetalert2.css">
<script src="<?php echo base_url(); ?>js/sweetalert2.min.js"></script>
<script>
function hapusData(education_id) {
var id = education_id;
swal({
title: 'Are You Sure ?',
text: 'This Data will be Deleted !',type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes',
cancelButtonText: 'No',
closeOnConfirm: true
}, function() {
window.location.href="<?php echo site_url('master/education/deletedata'); ?>"+"/"+id
});
}
</script>
<script type="text/javascript">
$(function() {
$(document).on("click",'.edit_button', function(e) {
var name = $(this).data('name');
var id = $(this).data('id');
//console.log(name, id)
$(".education_id").val(id);
$(".education_name").val(name);
})
});
</script>
<div class="page-container">
<!-- BEGIN PAGE HEAD -->
<div class="page-head">
<div class="container">
<!-- BEGIN PAGE TITLE -->
<div class="page-title">
<h1>Employee <small>Master Data</small></h1>
</div>
<!-- END PAGE TITLE -->
</div>
</div>
<!-- END PAGE HEAD -->
<!-- BEGIN PAGE CONTENT -->
<div class="page-content">
<div class="container">
<!-- BEGIN SAMPLE PORTLET CONFIGURATION MODAL FORM-->
<div class="modal fade" id="add" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form action="<?php echo site_url('master/education/savedata'); ?>" class="form-horizontal" method="post">
<input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title"><i class="fa fa-plus-circle"></i> Form Add Education</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label class="col-md-3 control-label">Education Name</label>
<div class="col-md-8 has-error">
<input type="text" class="form-control" placeholder="Enter Education Name" name="name" autocomplete="off" required autofocus>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-chevron-left"></span> Close</button>
</div>
</form>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<!-- Edit -->
<div class="modal fade" id="edit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form action="<?php echo site_url('master/education/updatedata'); ?>" class="form-horizontal" method="post">
<input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
<input type="hidden" class="form-control education_id" name="id">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title"><i class="fa fa-edit"></i> Form Edit Education</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label class="col-md-3 control-label">Education ID</label>
<div class="col-md-2 has-error">
<input type="text" class="form-control education_id" placeholder="" name="id" autocomplete="off" readonly>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Education Name</label>
<div class="col-md-8 has-error">
<input type="text" class="form-control education_name" placeholder="Enter Education Name" name="name" autocomplete="off" required autofocus>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Update</button>
<button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-chevron-left"></span> Close</button>
</div>
</form>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- BEGIN PAGE BREADCRUMB -->
<ul class="page-breadcrumb breadcrumb">
<li>
<a href="<?php echo base_url(); ?>">Home</a><i class="fa fa-circle"></i>
</li>
<li>
<a href="#">Employee</a>
<i class="fa fa-circle"></i>
</li>
<li>
<a href="#">Master Data</a>
<i class="fa fa-circle"></i>
</li>
<li class="active">
Education
</li>
</ul>
<!-- END PAGE BREADCRUMB -->
<!-- BEGIN PAGE CONTENT INNER -->
<div class="row">
<div class="col-md-12">
<!-- BEGIN EXAMPLE TABLE PORTLET-->
<div class="portlet light">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-folder font-blue-sharp"></i>
<span class="caption-subject font-blue-sharp bold uppercase">Education List</span>
</div>
<div class="tools">
</div>
</div>
<a data-toggle="modal" href="#add">
<button type="submit" class="btn btn-primary">
<i class="icon-plus"></i> Add Data</button>
</a>
<?php
if ($this->session->flashdata('notification')) { ?>
<script>
swal({
title: "Done",
text: "<?php echo $this->session->flashdata('notification'); ?>",
timer: 2000,
showConfirmButton: false,
type: 'success'
});
</script>
<? } ?>
<div class="portlet-body">
<table class="table table-striped table-bordered table-hover" id="sample_1">
<thead>
<tr>
<th>
Education Name
</th>
<th width="15%">
Action
</th>
</tr>
</thead>
<tbody>
<?php
foreach($daftarlist as $r) {
$education_id = $r->education_id;
?>
<tr>
<td>
<?php echo $r->education_name; ?>
</td>
<td>
<button type="button" class="btn btn-primary btn-xs edit_button" data-toggle="modal" data-target="#edit" data-id="<?php echo $r->education_id; ?>" data-name="<?php echo $r->education_name; ?>"><i class="icon-pencil"></i> Edit
</button>
<a onclick="hapusData(<?php echo $education_id; ?>)"><button class="btn btn-danger btn-xs" title="Delete Data"><i class="icon-trash"></i> Delete</button></a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
<!-- END EXAMPLE TABLE PORTLET-->
</div>
</div>
<!-- END PAGE CONTENT INNER -->
</div>
</div>
<!-- END PAGE CONTENT -->
</div> | jamboljack/hrdsystem | application/views/master/education_view.php | PHP | mit | 7,566 |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
node = parent = None
def deleteNode(self, root: TreeNode, key: int) -> TreeNode:
# search for the node and its parent
self.findNodeAndParent(root, key)
if self.node == root and not root.left and not root.right:
return None
if self.node:
self.deleteNodeHelper(self.node, self.parent)
return root
def deleteNodeHelper(self, node, parent):
# if node is a leaf
if not node.left and not node.right:
if parent:
if parent.left == node:
parent.left = None
else:
parent.right = None
return
# if node has only one child
if not node.left or not node.right:
child = node.left if not node.right else node.right
node.val = child.val
node.left = child.left
node.right = child.right
return
# node has two children
successor, succesorParent = self.getNodeSuccessor(node)
node.val = successor.val
self.deleteNodeHelper(successor, succesorParent)
def getNodeSuccessor(self, node):
succesorParent = node
successor = node.right
while successor.left:
succesorParent = successor
successor = successor.left
return successor, succesorParent
def findNodeAndParent(self, root, key):
if not root:
return
if root.val == key:
self.node = root
return
self.parent = root
if key < root.val:
self.findNodeAndParent(root.left, key)
else:
self.findNodeAndParent(root.right, key)
root = TreeNode(10)
root.left = TreeNode(3)
root.left.left = TreeNode(2)
root.left.right = TreeNode(8)
root.left.right.left = TreeNode(7)
root.left.right.right = TreeNode(9)
root.right = TreeNode(15)
root.right.left = TreeNode(13)
root.right.right = TreeNode(17)
root.right.right.right = TreeNode(19)
ob = Solution()
root = TreeNode(50)
root = ob.deleteNode(root, 50)
print(root)
| shobhitmishra/CodingProblems | LeetCode/Session3/DeleteNodeBST.py | Python | mit | 2,274 |
public class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
} else {
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}
} | caizixian/algorithm_exercise | LeetCode/104.Maximum Depth of Binary Tree.java | Java | mit | 225 |
/**
*
*/
package com.velocity.enums;
/**
* This Enum defines the values for ApplicationLocation
*
* @author Vimal Kumar
* @date 12-March-2015
*/
public enum ApplicationLocation {
HomeInternet, NotSet, OffPremises, OnPremises, Unknown
}
| nab-velocity/java-sdk | velocity-sdk/velocity-services/src/main/java/com/velocity/enums/ApplicationLocation.java | Java | mit | 249 |
/*
*
*/
package umlClassMetaModel.diagram.navigator;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.emf.common.ui.URIEditorInput;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.workspace.util.WorkspaceSynchronizer;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.navigator.CommonActionProvider;
import org.eclipse.ui.navigator.ICommonActionConstants;
import org.eclipse.ui.navigator.ICommonActionExtensionSite;
import org.eclipse.ui.navigator.ICommonViewerWorkbenchSite;
import org.eclipse.ui.part.FileEditorInput;
/**
* @generated
*/
public class UmlClassMetaModelNavigatorActionProvider extends
CommonActionProvider {
/**
* @generated
*/
private boolean myContribute;
/**
* @generated
*/
private OpenDiagramAction myOpenDiagramAction;
/**
* @generated
*/
public void init(ICommonActionExtensionSite aSite) {
super.init(aSite);
if (aSite.getViewSite() instanceof ICommonViewerWorkbenchSite) {
myContribute = true;
makeActions((ICommonViewerWorkbenchSite) aSite.getViewSite());
} else {
myContribute = false;
}
}
/**
* @generated
*/
private void makeActions(ICommonViewerWorkbenchSite viewerSite) {
myOpenDiagramAction = new OpenDiagramAction(viewerSite);
}
/**
* @generated
*/
public void fillActionBars(IActionBars actionBars) {
if (!myContribute) {
return;
}
IStructuredSelection selection = (IStructuredSelection) getContext()
.getSelection();
myOpenDiagramAction.selectionChanged(selection);
if (myOpenDiagramAction.isEnabled()) {
actionBars.setGlobalActionHandler(ICommonActionConstants.OPEN,
myOpenDiagramAction);
}
}
/**
* @generated
*/
public void fillContextMenu(IMenuManager menu) {
}
/**
* @generated
*/
private static class OpenDiagramAction extends Action {
/**
* @generated
*/
private Diagram myDiagram;
/**
* @generated
*/
private ICommonViewerWorkbenchSite myViewerSite;
/**
* @generated
*/
public OpenDiagramAction(ICommonViewerWorkbenchSite viewerSite) {
super(
umlClassMetaModel.diagram.part.Messages.NavigatorActionProvider_OpenDiagramActionName);
myViewerSite = viewerSite;
}
/**
* @generated
*/
public final void selectionChanged(IStructuredSelection selection) {
myDiagram = null;
if (selection.size() == 1) {
Object selectedElement = selection.getFirstElement();
if (selectedElement instanceof umlClassMetaModel.diagram.navigator.UmlClassMetaModelNavigatorItem) {
selectedElement = ((umlClassMetaModel.diagram.navigator.UmlClassMetaModelNavigatorItem) selectedElement)
.getView();
} else if (selectedElement instanceof IAdaptable) {
selectedElement = ((IAdaptable) selectedElement)
.getAdapter(View.class);
}
if (selectedElement instanceof Diagram) {
Diagram diagram = (Diagram) selectedElement;
if (umlClassMetaModel.diagram.edit.parts.UmlPackageEditPart.MODEL_ID
.equals(umlClassMetaModel.diagram.part.UmlClassMetaModelVisualIDRegistry
.getModelID(diagram))) {
myDiagram = diagram;
}
}
}
setEnabled(myDiagram != null);
}
/**
* @generated
*/
public void run() {
if (myDiagram == null || myDiagram.eResource() == null) {
return;
}
IEditorInput editorInput = getEditorInput(myDiagram);
IWorkbenchPage page = myViewerSite.getPage();
try {
page.openEditor(
editorInput,
umlClassMetaModel.diagram.part.UmlClassMetaModelDiagramEditor.ID);
} catch (PartInitException e) {
umlClassMetaModel.diagram.part.UmlClassMetaModelDiagramEditorPlugin
.getInstance().logError(
"Exception while openning diagram", e); //$NON-NLS-1$
}
}
/**
* @generated
*/
private static IEditorInput getEditorInput(Diagram diagram) {
Resource diagramResource = diagram.eResource();
for (EObject nextEObject : diagramResource.getContents()) {
if (nextEObject == diagram) {
return new FileEditorInput(
WorkspaceSynchronizer.getFile(diagramResource));
}
if (nextEObject instanceof Diagram) {
break;
}
}
URI uri = EcoreUtil.getURI(diagram);
String editorName = uri.lastSegment() + '#'
+ diagram.eResource().getContents().indexOf(diagram);
IEditorInput editorInput = new URIEditorInput(uri, editorName);
return editorInput;
}
}
}
| KuehneThomas/model-to-model-transformation-generator | src/MetaModels.UmlClass.diagram/src/umlClassMetaModel/diagram/navigator/UmlClassMetaModelNavigatorActionProvider.java | Java | mit | 4,850 |
var assert = require('assert');
describe('src/components/model/classes/Collection', function () {
var Collection = require('../../../../src/components/model/classes/Collection');
var collection;
var handler = function (event, changes) {
callbacks[event]++;
};
var callbacks = {
add: 0,
remove: 0,
change: 0
};
describe.only('new Collection(obj)', function () {
it('Should return a new Collection instance', function (done) {
collection = new Collection([1, 2, 3], handler);
done();
});
});
describe.only('.push(item)', function () {
it('Should call "add" callback', function (done) {
collection.push(4);
assert(callbacks.add, 1);
done();
});
});
describe.only('.unshift(item)', function () {
it('Should call "add" callback', function (done) {
collection.unshift(0);
assert(callbacks.add, 2);
done();
});
});
describe.only('.pop()', function () {
it('Should call "remove" callback', function (done) {
collection.pop();
assert(callbacks.remove, 1);
done();
});
});
describe.only('.shift()', function () {
it('Should call "remove" callback', function (done) {
collection.shift();
assert(callbacks.remove, 2);
done();
});
});
describe.only('.splice(index, number)', function () {
it('Should call "remove" callback', function (done) {
collection.splice(0, 1);
assert(callbacks.remove, 3);
done();
});
});
describe.only('.reverse()', function () {
it('Should call "change" callback', function (done) {
collection.reverse();
assert(callbacks.change, 1);
done();
});
});
describe.only('.sort()', function () {
it('Should call "change" callback', function (done) {
collection.sort(function (a, b) {
return -1;
});
assert(callbacks.change, 2);
done();
});
});
});
| moduleon/nucleon | test/components/model/classes/Collection.js | JavaScript | mit | 2,216 |
๏ปฟusing System.IO;
using System.Numerics;
using OpenSage.Mathematics;
namespace OpenSage.FileFormats.W3d
{
public sealed class W3dRingHeader
{
public uint ChunkType { get; private set; }
public uint ChunkSize { get; private set; }
public uint Version { get; private set; }
public uint Flags { get; private set; }
public bool AlignedCamera { get; private set; }
public bool Looping { get; private set; }
public string Name { get; private set; }
public Vector3 Center { get; private set; }
public Vector3 Extent { get; private set; }
public float Duration { get; private set; }
public ColorRgbF InitialColor { get; private set; }
public float InitialOpacity { get; private set; }
public Vector2 InnerScale { get; private set; }
public Vector2 OuterScale { get; private set; }
public Vector2 InnerRadii { get; private set; }
public Vector2 OuterRadii { get; private set; }
public string TextureFileName { get; private set; }
internal static W3dRingHeader Parse(BinaryReader reader)
{
var result = new W3dRingHeader
{
ChunkType = reader.ReadUInt32(),
ChunkSize = reader.ReadUInt32() & 0x7FFFFFFF,
Version = reader.ReadUInt32(),
Flags = reader.ReadUInt32()
};
result.AlignedCamera = ((result.Flags & 1) == 1);
result.Looping = ((result.Flags & 2) == 2);
result.Name = reader.ReadFixedLengthString(W3dConstants.NameLength * 2);
result.Center = reader.ReadVector3();
result.Extent = reader.ReadVector3();
result.Duration = reader.ReadSingle();
result.InitialColor = reader.ReadColorRgbF();
result.InitialOpacity = reader.ReadSingle();
result.InnerScale = reader.ReadVector2();
result.OuterScale = reader.ReadVector2();
result.InnerRadii = reader.ReadVector2();
result.OuterRadii = reader.ReadVector2();
result.TextureFileName = reader.ReadFixedLengthString(W3dConstants.NameLength * 2);
return result;
}
public void Write(BinaryWriter writer)
{
writer.Write(ChunkType);
writer.Write(ChunkSize);
writer.Write(Version);
writer.Write(Flags);
writer.WriteFixedLengthString(Name, W3dConstants.NameLength * 2);
writer.Write(Center);
writer.Write(Extent);
writer.Write(Duration);
writer.Write(InitialColor);
writer.Write(InitialOpacity);
writer.Write(InnerScale);
writer.Write(OuterScale);
writer.Write(InnerRadii);
writer.Write(OuterRadii);
writer.WriteFixedLengthString(TextureFileName, W3dConstants.NameLength * 2);
}
}
}
| feliwir/openSage | src/OpenSage.FileFormats.W3d/W3dRingHeader.cs | C# | mit | 2,978 |
/**
* boot/middleware.js
* Express middleware
*/
| swhite24/react-todo-exploration | server/boot/middleware.js | JavaScript | mit | 52 |
/*
* This file is part of TechReborn, licensed under the MIT License (MIT).
*
* Copyright (c) 2018 TechReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package techreborn.tiles;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import reborncore.api.IToolDrop;
import reborncore.api.recipe.IRecipeCrafterProvider;
import reborncore.api.tile.IInventoryProvider;
import reborncore.common.powerSystem.TilePowerAcceptor;
import reborncore.common.recipes.RecipeCrafter;
import reborncore.common.util.Inventory;
/**
* @author drcrazy
*
*/
public abstract class TileGenericMachine extends TilePowerAcceptor
implements IToolDrop, IInventoryProvider, IRecipeCrafterProvider{
public String name;
public int maxInput;
public int maxEnergy;
public Block toolDrop;
public int energySlot;
public Inventory inventory;
public RecipeCrafter crafter;
/**
* @param name String Name for a tile. Do we need it at all?
* @param maxInput int Maximum energy input, value in EU
* @param maxEnergy int Maximum energy buffer, value in EU
* @param toolDrop Block Block to drop with wrench
* @param energySlot int Energy slot to use to charge machine from battery
*/
public TileGenericMachine(String name, int maxInput, int maxEnergy, Block toolDrop, int energySlot) {
this.name = "Tile" + name;
this.maxInput = maxInput;
this.maxEnergy = maxEnergy;
this.toolDrop = toolDrop;
this.energySlot = energySlot;
checkTeir();
}
public int getProgressScaled(final int scale) {
if (crafter != null && crafter.currentTickTime != 0) {
return crafter.currentTickTime * scale / crafter.currentNeededTicks;
}
return 0;
}
// TilePowerAcceptor
@Override
public void update() {
super.update();
if (!world.isRemote) {
charge(energySlot);
}
}
@Override
public double getBaseMaxPower() {
return maxEnergy;
}
@Override
public boolean canAcceptEnergy(final EnumFacing direction) {
return true;
}
@Override
public boolean canProvideEnergy(final EnumFacing direction) {
return false;
}
@Override
public double getBaseMaxOutput() {
return 0;
}
@Override
public double getBaseMaxInput() {
return maxInput;
}
// IToolDrop
@Override
public ItemStack getToolDrop(EntityPlayer p0) {
return new ItemStack(toolDrop, 1);
}
// IInventoryProvider
@Override
public Inventory getInventory() {
return inventory;
}
// IRecipeCrafterProvider
@Override
public RecipeCrafter getRecipeCrafter() {
return crafter;
}
}
| Dimmerworld/TechReborn | src/main/java/techreborn/tiles/TileGenericMachine.java | Java | mit | 3,620 |
export const getUrlForAbsolutePath = (path: string) => {
return path.split('pages').pop().replace('.md', '')
}
export const getJobPath = (path: string) => {
return path.split('jobs').pop().replace('.md', '')
}
export const getFileNameOnly = (path: string) => {
return path.split('/').pop().replace('.md', '')
}
export const deleteTimestampFromUrl = (path: string) => {
return path.replace(/([0-9]{4})-([0-9]{2})-([0-9]{2})-/, '')
}
export const kebabCase = (string = '') =>
string
.replace(/([a-z])([A-Z])/g, '$1-$2')
.replace(/\s+/g, '-')
.replace(/[?=]/g, '')
.toLowerCase()
| bright/new-www | src/helpers/pathHelpers.ts | TypeScript | mit | 607 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package elektra;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.BufferedOutputStream;
import java.io.FileWriter;
import java.util.ResourceBundle;
import java.util.Properties;
import java.util.Date;
import java.net.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContext;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpSession;
import javax.servlet.RequestDispatcher;
import javax.mail.*;
import javax.activation.*;
import javax.mail.internet.*;
/**
*
* @author Rolfs
*/
public class WebChangeCustomerPassword extends HttpServlet
{
protected String szElektraConfig = "";
protected String szElektraServer = "";
protected String szElektraServerPort = "";
protected String szRequest = "27"; // Kundenpaรwort รคndern
protected String szVersion = "270";
protected Integer nDebug;
protected String strJSP = "";
protected String strJSPError = "";
protected String strJSPReload = "";
protected ServletContext context;
ResourceBundle resource = ResourceBundle.getBundle("elektra.Resource");
/** Adresse/Name des Mailservers, definiert in elektra.properties */
protected String szMailServer = "";
/** gewuenschte From-Adresse, definiert in elektra.properties */
protected String szMailFrom = "";
/** Liste der CC-Adressen, definiert in elektra.properties */
protected String szMailCC = "";
/** Liste der BCC-Adressen, definiert in elektra.properties */
protected String szMailBCC = "";
/** Liste der Reply-Adressen, definiert in elektra.properties */
protected String szMailReply = "";
/** Benutzer auf Mailserver: optional, definiert in elektra.properties */
protected String szMailUserName = "";
/** Passwort auf Mailserver: optional, definiert in elektra.properties */
protected String szMailUserPassword = "";
public void init(ServletConfig config) throws ServletException
{
super.init(config);
// Remember context
context = config.getServletContext();
try { szElektraConfig = context.getInitParameter("ElektraConfig"); } catch (Exception e) { e.printStackTrace(); }
if (null == szElektraConfig)
{
throw new ServletException("Servlet configuration property \"ElektraConfig\" is not defined!");
}
String szDebug = "";
try { szDebug = context.getInitParameter("Debug"); } catch (Exception e) { e.printStackTrace(); }
if (null == szDebug)
nDebug = new Integer(0);
else
nDebug = new Integer(szDebug);
// Properties laden
Properties props = new Properties();
try
{
props.load(new FileInputStream(szElektraConfig));
strJSP = props.getProperty("ChangeCustomerPasswordPage");
if (null == strJSP)
strJSP = "/jsp/webchangecustomerpassword.jsp";
strJSPError = props.getProperty("ChangeCustomerPasswordErrorPage");
if (null == strJSPError)
strJSPError = "/jsp/webchangecustomerpassworderr.jsp";
strJSPReload = props.getProperty("ChangeCustomerPasswordReloadPage");
if (null == strJSPReload)
strJSPReload = "/jsp/webchangecustomerpasswordreload.jsp";
}
catch (IOException ex)
{
ex.printStackTrace();
}
// Remember context
context = config.getServletContext();
}
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Date d = new Date(); // Getting current date
ChangeCustomerPasswordInData changecustomerpasswordData = new ChangeCustomerPasswordInData();
boolean bHeaderPrinted = false;
int nCnt = 1;
WriteDebug wd = new WriteDebug();
String szTemp = "";
HttpSession session = request.getSession();
session.getLastAccessedTime();
//
try { szTemp = request.getParameter(resource.getString("SysID")); } catch (Exception e) { wd.write(response, "Feld "+resource.getString("SysID")+" fehlt", e, nDebug); }
changecustomerpasswordData.setSysID(szTemp);
//
try { szTemp = request.getParameter(resource.getString("ClientID")); } catch (Exception e) { wd.write(response, "Feld "+resource.getString("ClientID")+" fehlt", e, nDebug); }
changecustomerpasswordData.setClientID(szTemp);
//
try { szTemp = request.getParameter("CustomerNumber"); } catch (Exception e) { wd.write(response, "Feld CustomerNumber fehlt", e, nDebug); }
if (null == szTemp)
changecustomerpasswordData.setCustomerNumber("0");
else
changecustomerpasswordData.setCustomerNumber(szTemp);
try { szTemp = request.getParameter("Password"); } catch (Exception e) { wd.write(response, "Feld Password fehlt", e, nDebug); }
changecustomerpasswordData.setCustomerPassword(szTemp);
try { szTemp = request.getParameter("NewPassword"); } catch (Exception e) { wd.write(response, "Feld NewPassword fehlt", e, nDebug); }
changecustomerpasswordData.setNewCustomerPassword(szTemp);
try { szTemp = request.getParameter("EMail"); } catch (Exception e) { wd.write(response, "Feld EMail fehlt", e, nDebug); }
changecustomerpasswordData.setEMail(szTemp);
changecustomerpasswordData.setSession(session.getId());
// Properties laden
Configuration Conf = new Configuration(context, szElektraConfig, "ElektraServerChangeCustomerPassword", changecustomerpasswordData.getSysID(), changecustomerpasswordData.getClientID(), nDebug.intValue());
szElektraServer = Conf.getServerName();
szElektraServerPort = Conf.getServerPort();
szMailServer = Conf.getMailServer();
szMailFrom = Conf.getMailFrom();
szMailCC = Conf.getMailCC();
szMailBCC = Conf.getMailBCC();
szMailReply = Conf.getMailReply();
if (null == szElektraServer)
{
wd.write(response, "Internal error!<br />System error: Elektra-Server not defined<br />", nDebug);
context.log("Elektra-Server not defined!");
}
else
{
// Daten an DB-Server senden
Socket socket = null;
ChangeCustomerPasswordOutData changecustomerpasswordOut = new ChangeCustomerPasswordOutData();
if (nDebug.intValue() > 0)
context.log(" starting ChangeCustomerpassword.");
try
{
socket = new Socket(szElektraServer, Integer.parseInt(szElektraServerPort));
if (nDebug.intValue() > 1)
context.log(" socket created.");
//BufferedInputStream is = new BufferedInputStream(socket.getInputStream());
BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream()));
BufferedOutputStream os = new BufferedOutputStream(socket.getOutputStream());
// Daten senden
try { os.write(szVersion.getBytes() ); } catch (IOException e) { e.printStackTrace(); }
os.write( 9 );
try { os.write(szRequest.getBytes() ); } catch (IOException e) { e.printStackTrace(); }
os.write( 9 );
// Encryption
try { os.write("NONE".getBytes() ); } catch (IOException e) { e.printStackTrace(); }
os.write( 9 );
// compression
try { os.write("NONE".getBytes() ); } catch (IOException e) { e.printStackTrace(); }
os.write( 9 );
try { os.write(changecustomerpasswordData.getSysID().getBytes() ); } catch (IOException e) { e.printStackTrace(); }
os.write( 9 );
try { os.write(changecustomerpasswordData.getClientID().getBytes() ); } catch (IOException e) { e.printStackTrace(); }
os.write( 9 );
try { os.write(changecustomerpasswordData.getCustomerNumber().getBytes() ); } catch (IOException e) { e.printStackTrace(); }
os.write( 9 );
try { os.write(changecustomerpasswordData.getCustomerPassword().getBytes() ); } catch (IOException e) { e.printStackTrace(); }
os.write( 9 );
try { os.write(changecustomerpasswordData.getSession().getBytes() ); } catch (IOException e) { e.printStackTrace(); }
os.write( 9 );
try { os.write(changecustomerpasswordData.getNewCustomerPassword().getBytes() ); } catch (IOException e) { e.printStackTrace(); }
os.write( 9 );
try { os.write(changecustomerpasswordData.getEMail().getBytes() ); } catch (IOException e) { e.printStackTrace(); }
os.write( 9 );
if (nDebug.intValue() > 1)
context.log(" flushing: "+os.toString());
os.flush();
// Daten senden, nun auf die Buchung warten
changecustomerpasswordOut.readSock(in, szVersion);
if (nDebug.intValue() > 4)
{
wd.write(response, "<br><h2>Getting:</h2>Error: "+changecustomerpasswordOut.getErrorCode(), nDebug );
}
if (nDebug.intValue() > 0)
context.log(" changecustomerpasswordData performed.");
request.setAttribute("changecustomerpasswordData", changecustomerpasswordData);
request.setAttribute("changecustomerpasswordOut", changecustomerpasswordOut);
// Im Fehlerfall
if (0 != changecustomerpasswordOut.getErrorCode())
{
context.log("Systemerror: "+changecustomerpasswordOut.getErrorCode());
// hole den Request Dispatcher fuer die JSP Datei
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(strJSPError);
//leite auf die JSP Datei zum Anzeigen der Liste weiter
dispatcher.forward(request, response);
}
else
{
// hole den Request Dispatcher fuer die JSP Datei
// Alles OK Password per Mail
if (null != szMailServer)
{
String szMailText = "";
String szKopfText = "";
szKopfText = szKopfText.concat("Ihr neues Password");
/*
szMailText = szMailText.concat("Seher geehrte(r) ");
szMailText = szMailText.concat(changecustomerpasswordData.getSalution());
szMailText = szMailText.concat(" ");
szMailText = szMailText.concat(changecustomerpasswordOut.getName1());
szMailText = szMailText.concat(" ");
szMailText = szMailText.concat(changecustomerpasswordOut.getName2());
szMailText = szMailText.concat(" ");
szMailText = szMailText.concat(changecustomerpasswordOut.getName3());
szMailText = szMailText.concat(",\r\n\r\n");
szMailText = szMailText.concat("anbei das geaenderte Password fรผr Ihren Kundenzugriff auf den Server von Frankfurt Ticket.\r\n\r\n");
szMailText = szMailText.concat("Ihre Kundennummer : ");
szMailText = szMailText.concat(changecustomerpasswordOut.getCustId());
szMailText = szMailText.concat("\r\n");
szMailText = szMailText.concat("Ihr geaendertes Password: ");
szMailText = szMailText.concat(changecustomerpasswordOut.getNewPassword());
szMailText = szMailText.concat("\r\n");
Mail m = new Mail(szMailServer, szMailFrom , changecustomerpasswordOut.getEMail(), szMailBCC, szMailCC, szMailReply, szKopfText, szMailText);
MailSender.getInstance().sendMail(m);
*/
}
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(strJSP);
//leite auf die JSP Datei zum Anzeigen der Liste weiter
dispatcher.forward(request, response);
}
}
catch (IOException ioex)
{
changecustomerpasswordOut.setErrorCode( -999);
changecustomerpasswordOut.setErrorMessage(ioex.getLocalizedMessage());
if ( (null != strJSPError) && !strJSPError.equals(""))
{
request.setAttribute("changecustomerpasswordData", changecustomerpasswordData);
request.setAttribute("changecustomerpasswordOut", changecustomerpasswordOut);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(strJSPError);
//leite auf die JSP Datei zum Anzeigen der Liste weiter
dispatcher.forward(request, response);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (socket != null)
{
try
{
socket.close();
}
catch (IOException ioex)
{
ioex.printStackTrace();
}
}
}
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| yanhongwang/TicketBookingSystem | src/elektra/WebChangeCustomerPassword.java | Java | mit | 14,526 |
import React from 'react';
import Status from 'components/Status';
import renderer from 'react-test-renderer';
describe('Status component', () => {
function getComponent(piecesLeftCount) {
return renderer.create(
<Status piecesLeftCount={piecesLeftCount} />
);
}
it('should show pieces left', () => {
expect(getComponent(9).toJSON()).toMatchSnapshot();
});
it('should show "Done" when no pieces left', () => {
expect(getComponent(0).toJSON()).toMatchSnapshot();
});
});
| dawid-drelichowski/puzzle-react-redux | src/js/tests/components/Status.test.js | JavaScript | mit | 507 |
package com.ke2g.cued_recall;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.List;
public class LoginActivity extends ActionBarActivity {
public static final String TAG = LoginActivity.class.getSimpleName();
private int discretization;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void doLogin(View V){
if(!getUsername().equals("")) {
Intent i = new Intent(this, returnIntent.class);
startActivityForResult(i, 1);
}
}
private ArrayList<Point> getUserPoints(String username){
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = appSharedPrefs.getString(username, "");
if(json.equals("")){
return null;
} else {
User u = gson.fromJson(json, User.class);
return u.getPoints();
}
}
private String getUserHash(String username){
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = appSharedPrefs.getString(username, "");
if(json.equals("")){
return null;
} else {
User u = gson.fromJson(json, User.class);
return u.getHash();
}
}
private void setTry(String username, int total, int invalid) {
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = appSharedPrefs.getString(username, "");
if(!json.equals("")){
User u = gson.fromJson(json, User.class);
u.setInvalidLogins(invalid);
u.setTotalLogins(total);
json = gson.toJson(u);
prefsEditor.putString(username, json);
prefsEditor.commit();
}
}
private int getTolerance(){
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
return Integer.parseInt(SP.getString("tolerance", "75"));
}
private String getUsername() {
EditText et = (EditText) findViewById(R.id.editText_login);
return et.getText().toString().trim();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
ArrayList<Point> points = data.getParcelableArrayListExtra("RESULT_CLICKS");
//check if points are the saved ones
if(getDiscretization() == 1){
if (CuedRecallIntent.areHashEqual(points, getUserHash(getUsername()), getTolerance())) {
setTry(getUsername(), 1, 0);
Toast.makeText(this, "Correct username and password", Toast.LENGTH_LONG).show();
} else {
setTry(getUsername(), 1, 1);
Toast.makeText(this, "Username and password don't match", Toast.LENGTH_LONG).show();
}
} else {
if (CuedRecallIntent.arePointsEqual(points, getUserPoints(getUsername()), getTolerance())) {
setTry(getUsername(), 1, 0);
Toast.makeText(this, "Correct username and password", Toast.LENGTH_LONG).show();
} else {
setTry(getUsername(), 1, 1);
Toast.makeText(this, "Username and password don't match", Toast.LENGTH_LONG).show();
}
}
}
}
public int getDiscretization() {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
return Integer.parseInt(SP.getString("discreType", "0"));
}
}
| ke2g/cuedRecall | app/src/main/java/com/ke2g/cued_recall/LoginActivity.java | Java | mit | 5,334 |
package BusinessLogic.ConnectionStates;
import BusinessLogic.ActualConnection;
import BusinessLogic.Message;
public class MessageMenuState implements ConnectionState{
public void dial(String key, ActualConnection connection)
{
if (key.equals("1"))
{
String output = "";
Message m = connection.currentMailbox.getCurrentMessage();
if (m == null) output += "No messages." + "\n";
else output += m.getText() + "\n";
output += ActualConnection.MESSAGE_MENU_TEXT;
connection.speakToAllUIs(output);
}
else if (key.equals("2"))
{
connection.currentMailbox.saveCurrentMessage();
connection.speakToAllUIs(ActualConnection.MESSAGE_MENU_TEXT);
}
else if (key.equals("3"))
{
connection.currentMailbox.removeCurrentMessage();
connection.speakToAllUIs(ActualConnection.MESSAGE_MENU_TEXT);
}
else if (key.equals("4"))
{
//connection.state = Connection.MAILBOX_MENU;
connection.currentState = new MailBoxMenuState();
connection.speakToAllUIs(ActualConnection.MAILBOX_MENU_TEXT);
}
}
public int getState(){
return 4;
}
}
| PatriciaRosembluth/VoiceMailSimulator | src/BusinessLogic/ConnectionStates/MessageMenuState.java | Java | mit | 1,243 |
๏ปฟnamespace Nettle.Compiler.Parsing
{
using Nettle.Compiler.Parsing.Blocks;
using System;
using System.Linq;
/// <summary>
/// Represents a model binding code block parser
/// </summary>
internal sealed class ModelBindingParser : NettleParser, IBlockParser
{
/// <summary>
/// Determines if a signature matches the block type of the parser
/// </summary>
/// <param name="signatureBody">The signature body</param>
/// <returns>True, if it matches; otherwise false</returns>
/// <remarks>
/// The signature body will match the model binding rules
/// if it is a valid binding path.
/// </remarks>
public bool Matches
(
string signatureBody
)
{
signatureBody = signatureBody.Trim();
return PathInfo.IsValidPath
(
signatureBody
);
}
/// <summary>
/// Parses the code block signature into a code block object
/// </summary>
/// <param name="templateContent">The template content</param>
/// <param name="positionOffSet">The position offset index</param>
/// <param name="signature">The block signature</param>
/// <returns>The parsed code block</returns>
public CodeBlock Parse
(
ref string templateContent,
ref int positionOffSet,
string signature
)
{
var bindingValue = NettleValueType.ModelBinding.ParseValue
(
signature
);
var bindingPath = bindingValue.ToString();
var startPosition = positionOffSet;
var endPosition = (startPosition + signature.Length);
TrimTemplate
(
ref templateContent,
ref positionOffSet,
signature
);
return new ModelBinding()
{
Signature = signature,
StartPosition = startPosition,
EndPosition = endPosition,
BindingPath = bindingPath
};
}
}
}
| craigbridges/Nettle | src/Nettle/Compiler/Parsing/ModelBindingParser.cs | C# | mit | 2,245 |
var struct_l_p_c___r_t_c___type_def =
[
[ "ALDOM", "struct_l_p_c___r_t_c___type_def.html#aae1199a3f1f40f90aba18aee4d6325fd", null ],
[ "ALDOW", "struct_l_p_c___r_t_c___type_def.html#a5f56710f005f96878defbdb8ef1333c2", null ],
[ "ALDOY", "struct_l_p_c___r_t_c___type_def.html#a4c7ceb477c4a865ae51f5052dd558667", null ],
[ "ALHOUR", "struct_l_p_c___r_t_c___type_def.html#ac56690c26258c2cf9d28d09cc3447c1d", null ],
[ "ALMIN", "struct_l_p_c___r_t_c___type_def.html#a7e45902fca36066b22f41d0ef60d3c36", null ],
[ "ALMON", "struct_l_p_c___r_t_c___type_def.html#ad22f635b8c8b51dad2956e797a4dd9d3", null ],
[ "ALSEC", "struct_l_p_c___r_t_c___type_def.html#af3ff64ab3671109971425a05194acc7c", null ],
[ "ALYEAR", "struct_l_p_c___r_t_c___type_def.html#ab7f49ad885a354164adc263629d3a555", null ],
[ "AMR", "struct_l_p_c___r_t_c___type_def.html#a13f4e9721184b326043e6c6596f87790", null ],
[ "CALIBRATION", "struct_l_p_c___r_t_c___type_def.html#abe224f8608ae3d2c5b1036bf943b6c27", null ],
[ "CCR", "struct_l_p_c___r_t_c___type_def.html#af959ddb88caef28108c2926e310a72bd", null ],
[ "CIIR", "struct_l_p_c___r_t_c___type_def.html#a0df12e53986b72fbfcdceb537f7bf20e", null ],
[ "CTIME0", "struct_l_p_c___r_t_c___type_def.html#a97fa06b91b698236cb770d9618707bef", null ],
[ "CTIME1", "struct_l_p_c___r_t_c___type_def.html#a5b1a1b981a72c6d1cd482e75f1d44de4", null ],
[ "CTIME2", "struct_l_p_c___r_t_c___type_def.html#a411e06dfdcddd3fc19170231aa3a98be", null ],
[ "DOM", "struct_l_p_c___r_t_c___type_def.html#a7c70513eabbefbc5c5dd865a01ecc487", null ],
[ "DOW", "struct_l_p_c___r_t_c___type_def.html#a61f22d3ccb1c82db258f66d7d930db35", null ],
[ "DOY", "struct_l_p_c___r_t_c___type_def.html#a7b4a3d5692df3c5062ec927cedd16734", null ],
[ "GPREG0", "struct_l_p_c___r_t_c___type_def.html#ac42f0d8452c678fa007f0e0b862fb0c6", null ],
[ "GPREG1", "struct_l_p_c___r_t_c___type_def.html#abee4ae6eab2c33bdf38985d3b8a439f1", null ],
[ "GPREG2", "struct_l_p_c___r_t_c___type_def.html#a75f852bb2980febd2af7cc583e1445ec", null ],
[ "GPREG3", "struct_l_p_c___r_t_c___type_def.html#aad058be0cc120fffbbc66ad6f7c0c731", null ],
[ "GPREG4", "struct_l_p_c___r_t_c___type_def.html#afcc8f7898dce77fdb1082ff681387692", null ],
[ "HOUR", "struct_l_p_c___r_t_c___type_def.html#a76b8d6a8b13febe4289797f34ba73998", null ],
[ "ILR", "struct_l_p_c___r_t_c___type_def.html#aba869620e961b6eb9280229dad81e458", null ],
[ "MIN", "struct_l_p_c___r_t_c___type_def.html#a7a07167f54a5412387ee581fcd6dd2e0", null ],
[ "MONTH", "struct_l_p_c___r_t_c___type_def.html#a28fb9798e07b54b1098e9efe96ac244a", null ],
[ "RESERVED0", "struct_l_p_c___r_t_c___type_def.html#ad539ffa4484980685ca2da36b54fe61d", null ],
[ "RESERVED1", "struct_l_p_c___r_t_c___type_def.html#ad9fb3ef44fb733b524dcad0dfe34290e", null ],
[ "RESERVED10", "struct_l_p_c___r_t_c___type_def.html#a2d9caf1d8be9f2169521470b6ccd0377", null ],
[ "RESERVED11", "struct_l_p_c___r_t_c___type_def.html#a11e504ee49142f46dcc67740ae9235e5", null ],
[ "RESERVED12", "struct_l_p_c___r_t_c___type_def.html#a06137f06d699f26661c55209218bcada", null ],
[ "RESERVED13", "struct_l_p_c___r_t_c___type_def.html#a17672e7a5546cef19ee778266224c193", null ],
[ "RESERVED14", "struct_l_p_c___r_t_c___type_def.html#a1b9781efee5466ce7886eae907f24e60", null ],
[ "RESERVED15", "struct_l_p_c___r_t_c___type_def.html#a781148146471db4cd7d04029e383d115", null ],
[ "RESERVED16", "struct_l_p_c___r_t_c___type_def.html#af3ff60ce094e476f447a8046d873acb0", null ],
[ "RESERVED17", "struct_l_p_c___r_t_c___type_def.html#ae98d0c41e0bb8aef875fa8b53b25af54", null ],
[ "RESERVED18", "struct_l_p_c___r_t_c___type_def.html#aae0a4a7536dc03a352e8c48436b10263", null ],
[ "RESERVED19", "struct_l_p_c___r_t_c___type_def.html#a5552e97d80fc1a5bd195a9c81b270ffc", null ],
[ "RESERVED2", "struct_l_p_c___r_t_c___type_def.html#aff8b921ce3122ac6c22dc654a4f1b7ca", null ],
[ "RESERVED20", "struct_l_p_c___r_t_c___type_def.html#af7fcad34b88077879694c020956bf69b", null ],
[ "RESERVED21", "struct_l_p_c___r_t_c___type_def.html#ae26a65f4079b1f3af0490c463e6f6e90", null ],
[ "RESERVED3", "struct_l_p_c___r_t_c___type_def.html#a1936698394c9e65033538255b609f5d5", null ],
[ "RESERVED4", "struct_l_p_c___r_t_c___type_def.html#a23568af560875ec74b660f1860e06d3b", null ],
[ "RESERVED5", "struct_l_p_c___r_t_c___type_def.html#a17b8ef27f4663f5d6b0fe9c46ab9bc3d", null ],
[ "RESERVED6", "struct_l_p_c___r_t_c___type_def.html#a585b017c54971fb297a30e3927437015", null ],
[ "RESERVED7", "struct_l_p_c___r_t_c___type_def.html#af2e6e355909e4223f7665881b0514716", null ],
[ "RESERVED8", "struct_l_p_c___r_t_c___type_def.html#a8cb0d97b1d31d1921acc7aa587d1c60b", null ],
[ "RESERVED9", "struct_l_p_c___r_t_c___type_def.html#ad8b1fadb520f7a200ee0046e110edc79", null ],
[ "RTC_AUX", "struct_l_p_c___r_t_c___type_def.html#a8a91a5b909fbba65b28d972c3164a4ed", null ],
[ "RTC_AUXEN", "struct_l_p_c___r_t_c___type_def.html#a4f807cc73e86fa24a247e0dce31512a4", null ],
[ "SEC", "struct_l_p_c___r_t_c___type_def.html#a77f4a78b486ec068e5ced41419805802", null ],
[ "YEAR", "struct_l_p_c___r_t_c___type_def.html#aaf0ddcf6e202e34e9cf7b35c584f9849", null ]
]; | NicoLingg/TemperatureSensor_DS1621 | html/struct_l_p_c___r_t_c___type_def.js | JavaScript | mit | 5,285 |
๏ปฟusing System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectile : MonoBehaviour {
public float duration = 1.0f;
public int damage = 1;
public bool destroyOnHit = false;
void Start () {
}
void Update () {
if (duration > 0.0f) {
duration -= Time.deltaTime;
} else {
Destroy(this.gameObject);
}
}
void OnTriggerEnter2D(Collider2D collision) {
PlayerControl playerController = collision.gameObject.GetComponent<PlayerControl>();
if (playerController != null && this.damage > 0) {
playerController.TakeDamage(damage);
damage = 0;
if (destroyOnHit) {
Destroy(this.gameObject);
}
}
}
}
| sasvdw/LD37 | Unity/LD37/Assets/Scripts/Items/Projectile.cs | C# | mit | 794 |
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2018 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
var RemoveTileAt = require('./RemoveTileAt');
var WorldToTileX = require('./WorldToTileX');
var WorldToTileY = require('./WorldToTileY');
/**
* Removes the tile at the given world coordinates in the specified layer and updates the layer's
* collision information.
*
* @function Phaser.Tilemaps.Components.RemoveTileAtWorldXY
* @private
* @since 3.0.0
*
* @param {number} worldX - [description]
* @param {number} worldY - [description]
* @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified
* location with null instead of a Tile with an index of -1.
* @param {boolean} [recalculateFaces=true] - [description]
* @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - [description]
* @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon.
*
* @return {Phaser.Tilemaps.Tile} The Tile object that was removed.
*/
var RemoveTileAtWorldXY = function (worldX, worldY, replaceWithNull, recalculateFaces, camera, layer)
{
var tileX = WorldToTileX(worldX, true, camera, layer);
var tileY = WorldToTileY(worldY, true, camera, layer);
return RemoveTileAt(tileX, tileY, replaceWithNull, recalculateFaces, layer);
};
module.exports = RemoveTileAtWorldXY;
| pixelpicosean/phaser | src/tilemaps/components/RemoveTileAtWorldXY.js | JavaScript | mit | 1,442 |
๏ปฟnamespace Gestion.Forms {
partial class Fibonachi {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.fib_bn = new System.Windows.Forms.Button();
this.FibTB = new System.Windows.Forms.TextBox();
this.listBox1 = new System.Windows.Forms.ListBox();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// fib_bn
//
this.fib_bn.Location = new System.Drawing.Point(118, 9);
this.fib_bn.Name = "fib_bn";
this.fib_bn.Size = new System.Drawing.Size(75, 23);
this.fib_bn.TabIndex = 0;
this.fib_bn.Text = "Calcular Hasta N";
this.fib_bn.UseVisualStyleBackColor = true;
this.fib_bn.Click += new System.EventHandler(this.fib_bn_Click);
//
// FibTB
//
this.FibTB.Location = new System.Drawing.Point(42, 12);
this.FibTB.Name = "FibTB";
this.FibTB.Size = new System.Drawing.Size(70, 20);
this.FibTB.TabIndex = 1;
//
// listBox1
//
this.listBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listBox1.FormattingEnabled = true;
this.listBox1.Location = new System.Drawing.Point(12, 39);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(181, 303);
this.listBox1.TabIndex = 2;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 15);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(27, 13);
this.label1.TabIndex = 3;
this.label1.Text = "N = ";
//
// Fibonachi
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(206, 352);
this.Controls.Add(this.label1);
this.Controls.Add(this.listBox1);
this.Controls.Add(this.FibTB);
this.Controls.Add(this.fib_bn);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Fibonachi";
this.Text = "Fibonachi";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button fib_bn;
private System.Windows.Forms.TextBox FibTB;
private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.Label label1;
}
} | Altairseven/Gestion | Forms/Fibonachi.Designer.cs | C# | mit | 3,752 |
# -*- coding: utf-8 -*-
# @Author: yancz1989
# @Date: 2017-01-17 23:43:18
# @Last Modified by: yancz1989
# @Last Modified time: 2017-02-22 20:33:29
import utilities as util
from utilities import parse_image_file, filterBoxes, voxel_2_world, mkdir
import numpy as np
import os
import json
import sys
from PIL import Image, ImageDraw
import SimpleITK as sitk
from env import *
def generate_scan_image(subset):
list_dirs = os.walk(TRUNK_DIR + subset)
jsobjs = []
output_dir = SAMPLE_DIR + subset
mkdir(output_dir)
for root, dirs, files in list_dirs:
for f in files:
if f.lower().endswith('mhd'):
key = os.path.splitext(f)[0]
numpyImage, numpyOrigin, numpySpacing = (
util.load_itk_image(
os.path.join(root, f)))
for z in range(numpyImage.shape[0]):
patch = numpyImage[z, 0:512, 0:512]
patch = util.normalizePlanes(patch)
im = Image.fromarray(patch * 255).convert('L')
output_filename = (
subset + "-" + key + "-" + str(z) + "-scan.bmp")
print(subset + '/' + output_filename)
im.save(os.path.join(
output_dir, output_filename))
jsobjs.append({
"image_path": subset + '/' + output_filename,
"rects":[]
}
)
with open(META_DIR + subset + '-scan.json', 'w') as f:
json.dump(jsobjs, f)
def get_image_map(data_root, input_file, threshold):
result_map = {}
with open(input_file) as f:
result_list = json.load(f)
for it in result_list:
key, subset, z = parse_image_file(it['file'])
src_file = os.path.join(
data_root, subset, key + ".mhd")
boxes = filterBoxes(it['box'], threshold)
if not result_map.get(src_file):
result_map[src_file] = []
result_map[src_file].append((key, z, boxes))
return result_map
def generate_result(result_map, output_file):
with open(output_file) as fout:
fout.write("seriesuid,coordX,coordY,coordZ,probability\n")
for fkey, val in result_map.items():
itkimage = sitk.ReadImage(fkey)
for it in val:
key, z, boxes = val
for box in boxes:
world_box = voxel_2_world(
[z, box[1], box[0]], itkimage)
csv_line = key + "," + str(world_box[2]) + "," + str(world_box[1]) + "," + str(world_box[0]) + "," + str(box[4])
fout.write(csv_line + "\n")
if __name__ == '__main__':
if sys.argv[1] == 'gen':
generate_scan_image(sys.argv[2])
else:
result_map = get_image_map(TRUNK_DIR, sys.argv[2], 0.01)
generate_result(result_map, OUTPUT_FILE) | yancz1989/cancer | scan.py | Python | mit | 2,610 |
# frozen_string_literal: true
class Passport
include Mongoid::Document
field :number, type: String
field :country, type: String
field :exp, as: :expiration_date, type: Date
embedded_in :person, autobuild: true
end
| mongodb/mongoid | spec/support/models/passport.rb | Ruby | mit | 227 |
/**
* Created by JiaHao on 27/10/15.
*/
var fs = require('fs');
var path = require('path');
var normalizeNewline = require('normalize-newline');
function occurenceIndexes(inp, toFind) {
var indices = [];
var element = toFind;
var idx = inp.indexOf(element);
while (idx != -1) {
indices.push(idx);
idx = inp.indexOf(element, idx + 1);
}
return indices;
}
const ANNONATION = {
start: '{',
end: '}'
};
/**
* Parses a file at a path
* @param path
* @returns {Array}
* @param annotation
*/
function parseText(path, annotation) {
var rawText = normalizeNewline(fs.readFileSync(path).toString());
var annotationToken = annotation || ANNONATION;
var startOccurances = occurenceIndexes(rawText, annotationToken.start);
var endOccurances = occurenceIndexes(rawText, annotationToken.end);
var allOccurances = startOccurances.concat(endOccurances).sort(function(a, b){return a-b});
var subtractIndexes = {};
for (var i = 0; i < allOccurances.length; i++) {
subtractIndexes[allOccurances[i]] = i;
}
var result = [];
var stack = []; // stack of start occurances
var counter = 0;
var startOccuranceCounter = 0;
var endOccuranceCounter = 0;
var startOccuranceNext;
var endOccuranceNext;
while (counter < rawText.length) {
startOccuranceNext = startOccurances[startOccuranceCounter];
endOccuranceNext = endOccurances[endOccuranceCounter];
if (counter === startOccuranceNext) {
stack.push(startOccuranceNext);
startOccuranceCounter+=1;
} else if (counter === endOccuranceNext) {
var stackNext = stack.pop();
result.push([stackNext, endOccuranceNext]);
endOccuranceCounter+=1;
}
counter += 1;
}
var subtractFunction = function (element) {
return element - subtractIndexes[element];
};
result = result.map(function (tuple) {
return tuple.map(subtractFunction);
});
return result;
}
module.exports = parseText;
if (require.main === module) {
var expected = [
[6, 10],
[35, 39],
[71, 76],
[296, 303],
[356,362]
];
var toParsePath = path.join(__dirname, '../', 'examples/annotatedData.txt');
var result = parseText(toParsePath);
}
| jiahaog/brat | lib/parser.js | JavaScript | mit | 2,364 |
module.exports.sum = function (arr, prop, exp) {
var total = 0
for (var i = 0, _len = arr.length; i < _len; i++) {
var value = arr[i][prop];
if (exp) {
if (arr[i][exp.field] == exp.value) {
total += value * 1;
}
} else {
total += value * 1;
}
}
return total
};
| inamvar/bean | util/array.js | JavaScript | mit | 375 |
/**
* @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 { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-comp-1489',
templateUrl: './comp-1489.component.html',
styleUrls: ['./comp-1489.component.css']
})
export class Comp1489Component implements OnInit {
constructor() { }
ngOnInit() {
}
}
| angular/angular-cli-stress-test | src/app/components/comp-1489/comp-1489.component.ts | TypeScript | mit | 484 |
describe('Modules.Ellipsis.js', function() {
it('should exist with expected constructures', function() {
expect(moj.Modules.CaseCreation.init).toBeDefined();
});
});
| ministryofjustice/correspondence_tool_staff | spec/javascripts/modules/EllipsisSpec.js | JavaScript | mit | 174 |
import React, { Component } from 'react'
import {
Circle,
FeatureGroup,
LayerGroup,
Map,
Popup,
Rectangle,
TileLayer,
} from '../../src'
export default class OtherLayersExample extends Component {
render () {
const center = [51.505, -0.09]
const rectangle = [
[51.49, -0.08],
[51.5, -0.06],
]
return (
<Map center={center} zoom={13}>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
/>
<LayerGroup>
<Circle center={center} fillColor='blue' radius={200} />
<Circle center={center} fillColor='red' radius={100} stroke={false} />
<LayerGroup>
<Circle center={[51.51, -0.08]} color='green' fillColor='green' radius={100} />
</LayerGroup>
</LayerGroup>
<FeatureGroup color='purple'>
<Popup>
<span>Popup in FeatureGroup</span>
</Popup>
<Circle center={[51.51, -0.06]} radius={200} />
<Rectangle bounds={rectangle} />
</FeatureGroup>
</Map>
)
}
}
| yavuzmester/react-leaflet | example/components/other-layers.js | JavaScript | mit | 1,171 |
<?php
/*
* Gwatkin, 15146508
*/
namespace cgwatkin\a3\model;
use cgwatkin\a3\exception\MySQLDatabaseException;
use mysqli;
/**
* Class Model
*
* Connects to and configures the MySQL database with dummy data for testing.
*
* Base code provided by Andrew Gilman <a.gilman@massey.ac.nz>
*
* @package cgwatkin/a3
* @author Cai Gwatkin <caigwatkin@gmail.com>
*/
class Model
{
protected $db;
function __construct()
{
$this->db = new mysqli(
DB_HOST,
DB_USER,
DB_PASS
);
if (!$this->db) {
throw new MySQLDatabaseException($this->db->connect_error, $this->db->connect_errno);
}
//----------------------------------------------------------------------------
// Creates the database and populates it with sample data
$this->db->query('CREATE DATABASE IF NOT EXISTS '.DB_NAME.';');
if (!$this->db->select_db(DB_NAME)) {
throw new MySQLDatabaseException('MySQL database not available');
}
$result = $this->db->query('SHOW TABLES LIKE "user";');
if ($result->num_rows == 0) {
// table doesn't exist
// create it and populate with sample data
$result = $this->db->query(
'CREATE TABLE user (
id INT unsigned NOT NULL UNIQUE AUTO_INCREMENT,
username VARCHAR(256) NOT NULL UNIQUE,
pwd VARCHAR(256) NOT NULL,
name VARCHAR(256) NOT NULL,
PRIMARY KEY (id)
);');
if (!$result) {
error_log($this->db->error);
throw new MySQLDatabaseException('Failed creating table: user');
}
// Add sample data, password is hashed on combination of ID and inputted password
$pwd1 = password_hash('1'.'admin', PASSWORD_DEFAULT);
$pwd2 = password_hash('2'.'TheToolman', PASSWORD_DEFAULT);
$pwd3 = password_hash('3'.'maryMARY', PASSWORD_DEFAULT);
$pwd4 = password_hash('4'.'joeyJOEY', PASSWORD_DEFAULT);
if(!$this->db->query(
"INSERT INTO user
VALUES (NULL,'admin','$pwd1','Admin'),
(NULL,'TheToolman','$pwd2','Tim Taylor'),
(NULL,'mary','$pwd3','Mary'),
(NULL,'joey','$pwd4','Joey');"
)) {
error_log($this->db->error);
throw new MySQLDatabaseException('Failed adding sample data to table: user');
}
}
$result = $this->db->query('SHOW TABLES LIKE "product";');
if ($result->num_rows == 0) {
// table doesn't exist
// create it and populate with sample data
$result = $this->db->query(
'CREATE TABLE product (
id INT UNSIGNED NOT NULL UNIQUE AUTO_INCREMENT,
sku CHAR(6) NOT NULL UNIQUE,
name VARCHAR(256) NOT NULL,
cost DECIMAL(19,2) UNSIGNED NOT NULL,
category VARCHAR(40) NOT NULL,
stock MEDIUMINT UNSIGNED NOT NULL,
PRIMARY KEY (id),
INDEX ix_product (category)
);');
if (!$result) {
error_log($this->db->error);
throw new MySQLDatabaseException('Failed creating table: product');
}
// Add sample data
if(!$this->db->query(
"INSERT INTO product
VALUES (NULL,'HMR000','Claw Hammer',5.95,'Hammer',21),
(NULL,'HMR001','Ball Pein',8.95,'Hammer',22),
(NULL,'HMR002','Club Hammer',6.95,'Hammer',13),
(NULL,'SCW000','Slot Screwdriver',9.95,'Screwdriver',13),
(NULL,'SCW001','Phillips Screwdriver',14.95,'Screwdriver',28),
(NULL,'SCW002','Pozidriv Screwdriver',14.95,'Screwdriver',40),
(NULL,'KNF000','Pocket Knife',24.95,'Knife',19),
(NULL,'KNF001','Locking Knife',24.95,'Knife',8),
(NULL,'KNF002','Craft Knife',12.95,'Knife',21),
(NULL,'TPE000','Masking Tape',8.95,'Tape',17),
(NULL,'TPE001','Duct Tape',12.95,'Tape',32),
(NULL,'TPE002','Electrical Tape',8.95,'Tape',32);"
)) {
error_log($this->db->error);
throw new MySQLDatabaseException('Failed adding sample data to table: product');
}
}
//----------------------------------------------------------------------------
}
}
| CaiGwatkin/PHP_StockControlSystem | web/src/model/Model.php | PHP | mit | 4,842 |
<?php
class Autoload
{
public static function register($path)
{
if (function_exists('__autoload')) {
spl_autoload_register('__autoload');
}
spl_autoload_register(function ($class) use(&$path)
{
set_include_path($path);
spl_autoload($class);
});
}
}
| lcp0578/helloword | library/system/Autoload.php | PHP | mit | 337 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NumberGuessing
{
partial class Program
{
public static bool doDebug = false;
static void MyDebug()
{
if (doDebug)
{
Console.WriteLine("Debug information:");
Console.Write("The number = ");
Console.WriteLine(theNumber.ToString());
Console.WriteLine("Off by: {0}", myResult.offBy);
Console.WriteLine("Guesses remaining {0}", guessesRemaining.ToString());
Console.Write("Current game state = ");
Console.WriteLine(gameState.ToString());
}
}
}
}
| zelbo/Number-Guessing | Debug.cs | C# | mit | 735 |
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe DiffFileEntity do
include RepoHelpers
let_it_be(:project) { create(:project, :repository) }
let(:repository) { project.repository }
let(:commit) { project.commit(sample_commit.id) }
let(:diff_refs) { commit.diff_refs }
let(:diff) { commit.raw_diffs.first }
let(:diff_file) { Gitlab::Diff::File.new(diff, diff_refs: diff_refs, repository: repository) }
let(:options) { {} }
let(:entity) { described_class.new(diff_file, options.reverse_merge(request: {})) }
subject { entity.as_json }
context 'when there is no merge request' do
it_behaves_like 'diff file entity'
end
context 'when there is a merge request' do
let_it_be(:merge_request) { create(:merge_request, source_project: project, target_project: project) }
let(:user) { create(:user) }
let(:code_navigation_path) { Gitlab::CodeNavigationPath.new(project, project.commit.sha) }
let(:request) { EntityRequest.new(project: project, current_user: user) }
let(:entity) { described_class.new(diff_file, options.merge(request: request, merge_request: merge_request, code_navigation_path: code_navigation_path)) }
let(:exposed_urls) { %i(edit_path view_path context_lines_path) }
it_behaves_like 'diff file entity'
it 'exposes additional attributes' do
expect(subject).to include(*exposed_urls)
expect(subject).to include(:replaced_view_path)
expect(subject).to include(:code_navigation_path)
end
it 'points all urls to merge request target project' do
response = subject
exposed_urls.each do |attribute|
expect(response[attribute]).to include(merge_request.target_project.to_param)
end
end
it 'exposes load_collapsed_diff_url if the file viewer is collapsed' do
allow(diff_file.viewer).to receive(:collapsed?) { true }
expect(subject).to include(:load_collapsed_diff_url)
end
end
describe '#parallel_diff_lines' do
let(:options) { { diff_view: :parallel } }
it 'exposes parallel diff lines correctly' do
response = subject
lines = response[:parallel_diff_lines]
# make sure at least one line is present for each side
expect(lines.map { |line| line[:right] }.compact).to be_present
expect(lines.map { |line| line[:left] }.compact).to be_present
# make sure all lines are in correct format
lines.each do |parallel_line|
expect(parallel_line[:left].as_json).to match_schema('entities/diff_line') if parallel_line[:left]
expect(parallel_line[:right].as_json).to match_schema('entities/diff_line') if parallel_line[:right]
end
end
end
end
| mmkassem/gitlabhq | spec/serializers/diff_file_entity_spec.rb | Ruby | mit | 2,686 |
from django.conf.urls import url
from audiotracks import feeds
from audiotracks import views
urlpatterns = [
url(r"^$", views.index, name="audiotracks"),
url(r"^(?P<page_number>\d+)/?$", views.index, name="audiotracks"),
url(r"^track/(?P<track_slug>.*)$", views.track_detail,
name="track_detail"),
url(r"^upload", views.upload_track, name="upload_track"),
url(r"^edit/(?P<track_id>.+)", views.edit_track, name="edit_track"),
url(r"^confirm_delete/(?P<track_id>\d+)$",
views.confirm_delete_track, name="confirm_delete_track"),
url(r"^delete$", views.delete_track, name="delete_track"),
url(r"^tracks$", views.user_index, name="user_index"),
url(r"^tracks/(?P<page_number>\d)/?$", views.user_index,
name="user_index"),
url(r"^feed/?$", feeds.choose_feed, name="tracks_feed"),
url(r"^player.js$", views.player_script, name="player_script"),
url(r"^m3u/?$", views.m3u, name="m3u"),
]
| amarandon/django-audiotracks | audiotracks/urls.py | Python | mit | 955 |
๏ปฟnamespace ProjectManagement
{
partial class EntryForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.EntrytextBox = new System.Windows.Forms.TextBox();
this.PasstextBox = new System.Windows.Forms.TextBox();
this.Entrybutton = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(116, 28);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(108, 13);
this.label1.TabIndex = 0;
this.label1.Text = "ะะพััะตะฑะธัะตะปัะบะพ ะธะผะต";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(148, 111);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(45, 13);
this.label2.TabIndex = 1;
this.label2.Text = "ะะฐัะพะปะฐ";
//
// EntrytextBox
//
this.EntrytextBox.Location = new System.Drawing.Point(85, 68);
this.EntrytextBox.Name = "EntrytextBox";
this.EntrytextBox.Size = new System.Drawing.Size(169, 20);
this.EntrytextBox.TabIndex = 2;
//
// PasstextBox
//
this.PasstextBox.Location = new System.Drawing.Point(102, 146);
this.PasstextBox.Name = "PasstextBox";
this.PasstextBox.PasswordChar = '*';
this.PasstextBox.Size = new System.Drawing.Size(135, 20);
this.PasstextBox.TabIndex = 3;
//
// Entrybutton
//
this.Entrybutton.Location = new System.Drawing.Point(131, 204);
this.Entrybutton.Name = "Entrybutton";
this.Entrybutton.Size = new System.Drawing.Size(75, 23);
this.Entrybutton.TabIndex = 4;
this.Entrybutton.Text = "ะั
ะพะด";
this.Entrybutton.UseVisualStyleBackColor = true;
this.Entrybutton.Click += new System.EventHandler(this.Entrybutton_Click);
//
// EntryForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(344, 261);
this.Controls.Add(this.Entrybutton);
this.Controls.Add(this.PasstextBox);
this.Controls.Add(this.EntrytextBox);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "EntryForm";
this.Text = "ะะพััะตะฑะธัะตะปัะบะธ ะฒั
ะพะด ะฒ ัะธััะตะผะฐัะฐ";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox EntrytextBox;
private System.Windows.Forms.TextBox PasstextBox;
private System.Windows.Forms.Button Entrybutton;
}
} | RuzmanovDev/ProjectManagementSystem | ProjectManagement/EntryForm.Designer.cs | C# | mit | 4,179 |
<?php
namespace Frontiernxt\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The roles that belong to the user.
*/
public function roles()
{
return $this->belongsToMany('Frontiernxt\Models\Role');
}
}
| codelust/laravel-skeleton | src/Models/User.php | PHP | mit | 689 |
require 'rails_helper'
RSpec.describe "Homes", type: :request do
describe "GET /homes" do
it "works! (now write some real specs)" do
get homes_path
expect(response).to have_http_status(200)
end
end
end
| ddrscott/sql_probe | spec/dummy/spec/requests/homes_spec.rb | Ruby | mit | 227 |
/**
*
*/
package com.sivalabs.jcart.common.services;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import com.sivalabs.jcart.JCartException;
/**
* @author Siva
*
*/
@Component
public class EmailService
{
private static final JCLogger logger = JCLogger.getLogger(EmailService.class);
@Autowired JavaMailSender javaMailSender;
@Value("${support.email}") String supportEmail;
public void sendEmail(String to, String subject, String content)
{
try
{
// Prepare message using a Spring helper
final MimeMessage mimeMessage = this.javaMailSender.createMimeMessage();
final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
message.setSubject(subject);
message.setFrom(supportEmail);
message.setTo(to);
message.setText(content, true /* isHtml */);
javaMailSender.send(message.getMimeMessage());
}
catch (MailException | MessagingException e)
{
logger.error(e);
throw new JCartException("Unable to send email");
}
}
}
| sivaprasadreddy/jcart | jcart-core/src/main/java/com/sivalabs/jcart/common/services/EmailService.java | Java | mit | 1,464 |
class CreateCheckInSurveys < ActiveRecord::Migration
def change
create_table :check_in_surveys do |t|
t.string :title
t.text :description
t.string :version, index: true
t.text :question_1
t.text :question_2
t.text :question_3
t.text :question_4
t.timestamps
end
end
end
| ccfapprn/network | db/migrate/20150204085338_create_check_in_surveys.rb | Ruby | mit | 331 |
/**
* Base js functions
*/
$(document).ready(function(){
//Init jQuery Masonry layout
init_masonry();
//Select menu onchange
$("#collapsed-navbar").change(function () {
window.location = $(this).val();
});
});
function init_masonry(){
var $container = $('#content');
$container.imagesLoaded( function(){
$container.masonry({
itemSelector: '.box',
isAnimated: true
});
});
}
*/
$(document).ready(function(){
//Start carousel
$('.carousel').carousel({interval:false});
}); | goldschadt/mason | assets/js/base.js | JavaScript | mit | 563 |
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Auth;
// models
use App\User;
use App\models\Student;
use App\models\Opd;
class AdminStudents extends Controller
{
/*
* E S T U D I A N T E S
* ----------------------------------------------------------------
*/
public function view($id){
$user = Auth::user();
$student = Student::find($id);
return view("admin.students.student-profile")->with([
"user" => $user,
"student" => $student
]);
}
public function add(){
$user = Auth::user();
$opds = Opd::all()->pluck('opd_name','id');
// $offer =
return view("admin.students.students-add")->with([
"user" => $user,
"opds" =>$opds,
]);
}
public function save(Request $request){
$data = $request->except('_token');
$student = Student::firstOrCreate($data);
$student->nombre_completo = $data['nombre']." ".$data['apellido_paterno']." ".$data['apellido_materno'];
$student->save();
return redirect("dashboard/estudiante/$student->id")->with("message", 'Estudiante creado correctamente');
}
public function edit($id){
$user = Auth::user();
$student = Student::with('user.opd')->find($id);
$opds = Opd::all()->pluck('opd_name','id');
return view("admin.students.students-update")->with([
"user" => $user,
"student" => $student,
"opds" =>$opds
]);
}
public function update(Request $request, $id){
$student = Student::find($id);
// update student
$student->update($request->only(['nombre', 'apellido_paterno', 'apellido_materno', 'curp', 'matricula', 'carrera','status','opd_id']));
$student->nombre_completo = $request->nombre." ".$request->apellido_paterno." ".$request->apellido_materno;
$student->save();
return redirect("dashboard/estudiante/$student->id")->with("message", 'Estudiante actualizado correctamente');
}
public function delete($id){
$student = Student::find($id);
$student->delete();
return redirect('dashboard/estudiantes')->with("message", 'Estudiante eliminado correctamente');;
}
}
| GobiernoFacil/vinculacion | app/Http/Controllers/AdminStudents.php | PHP | mit | 2,152 |
#pragma once
#include <gtest/gtest.h>
class HeroTest : public ::testing::Test
{
// Test interface
protected:
void SetUp() override
{
}
void TearDown() override
{
}
};
| H4kor/tiny-hero | test/test_hero.hh | C++ | mit | 198 |
var React = require('react');
var RulePicker = require('./RulePicker.js');
var TimePicker = require('react-time-picker');
var DatePicker = require('react-date-picker');
var RuleSummary = require("./RuleSummary.js");
var moment = require('moment');
var Tabs = require('react-simpletabs');
var RecurringSelect = React.createClass({displayName: "RecurringSelect",
getInitialState: function() {
return ({
rule: "daily",
interval: 1,
validations: null,
until: moment().format('YYYY-MM-DD'),
startTime: "10:00 AM"
});
},
handleRuleChange: function(e) {
var rule = e.target.value;
var validations = null;
if (rule === "weekly") validations = [];
if (rule === "monthly (by day of week)") {
rule = "monthly";
validations = {1: [], 2: [], 3: [], 4: []};
}
if (rule === "monthly (by day of month)") {
rule = "monthly";
validations = [];
}
this.setState({
rule: rule,
validations: validations
});
},
handleIntervalChange: function(e) {
var interval;
if (e.target.value != "") {
interval = parseInt(e.target.value);
} else {
interval = 0;
}
this.setState({
interval: interval
});
},
handleValidationsChange: function(validations) {
this.setState({
validations: validations
});
},
handleEndDateChange: function (date) {
this.setState({
until: date
});
},
handleTimeChange: function(time) {
this.setState({
startTime: time
});
},
handleSave: function(e) {
var hash = this.state;
console.log(hash.validations);
var iceCubeHash = {};
var start = moment(hash.startTime, "hh:mm a A");
var minute = start.minute();
var hour = start.hour();
var rule_type;
switch (hash.rule) {
case 'daily':
rule_type = "IceCube::DailyRule";
break;
case 'weekly':
rule_type = "IceCube::WeeklyRule";
break;
case 'monthly':
rule_type = "IceCube::MonthlyRule";
break;
case 'yearly':
rule_type = "IceCube::YearlyRule";
break;
}
var interval = hash.interval;
var validations = hash.validations == null ? {} : hash.validations;
var newValidations = {};
if (Array.isArray(validations) && rule_type == "IceCube::WeeklyRule") {
newValidations["day"] = validations
} else if (Array.isArray(validations) && rule_type == "IceCube::MonthlyRule") {
newValidations["day_of_month"] = validations;
} else if (rule_type == "IceCube::MonthlyRule") {
newValidations["day_of_week"] = validations;
}
newValidations["hour_of_day"] = hour;
newValidations["minute_of_hour"] = minute;
var until = hash.until;
iceCubeHash["rule_type"] = rule_type;
iceCubeHash["interval"] = interval;
iceCubeHash["validations"] = newValidations;
iceCubeHash["until"] = until;
this.props.onSave(JSON.stringify(iceCubeHash));
},
render: function() {
return (
React.createElement("div", {className: "recurring-select"},
React.createElement(Tabs, null,
React.createElement(Tabs.Panel, {title: "Recurrence Rule"},
React.createElement(RulePicker, {
rule: this.state.rule,
interval: this.state.interval,
validations: this.state.validations,
onRuleChange: this.handleRuleChange,
onIntervalChange: this.handleIntervalChange,
onValidationsChange: this.handleValidationsChange})
),
React.createElement(Tabs.Panel, {title: "Occurence Time"},
React.createElement(TimePicker, {value: this.state.startTime, onChange: this.handleTimeChange})
),
React.createElement(Tabs.Panel, {title: "Recurring Until"},
React.createElement(DatePicker, {minDate: moment().format("YYYY-MM-DD"), date: this.state.until, onChange: this.handleEndDateChange})
)
),
React.createElement("hr", null),
React.createElement(RuleSummary, {fields: this.state}),
React.createElement("button", {className: "btn save", onClick: this.handleSave}, "Save")
)
);
}
});
module.exports = RecurringSelect;
| colinwahl/react-recurring-select | dist/RecurringSelect.js | JavaScript | mit | 4,318 |
<?php
/* TwigBundle:Exception:exception_full.html.twig */
class __TwigTemplate_c7b8e0c7c14064ee8fe3074f2af4519e extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = $this->env->loadTemplate("TwigBundle::layout.html.twig");
$this->blocks = array(
'head' => array($this, 'block_head'),
'title' => array($this, 'block_title'),
'body' => array($this, 'block_body'),
);
}
protected function doGetParent(array $context)
{
return "TwigBundle::layout.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_head($context, array $blocks = array())
{
// line 4
echo " <link href=\"";
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/framework/css/exception.css"), "html", null, true);
echo "\" rel=\"stylesheet\" type=\"text/css\" media=\"all\" />
";
}
// line 7
public function block_title($context, array $blocks = array())
{
// line 8
echo " ";
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["exception"]) ? $context["exception"] : null), "message"), "html", null, true);
echo " (";
echo twig_escape_filter($this->env, (isset($context["status_code"]) ? $context["status_code"] : null), "html", null, true);
echo " ";
echo twig_escape_filter($this->env, (isset($context["status_text"]) ? $context["status_text"] : null), "html", null, true);
echo ")
";
}
// line 11
public function block_body($context, array $blocks = array())
{
// line 12
echo " ";
$this->env->loadTemplate("TwigBundle:Exception:exception.html.twig")->display($context);
}
public function getTemplateName()
{
return "TwigBundle:Exception:exception_full.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 40 => 7, 44 => 7, 35 => 5, 31 => 4, 43 => 8, 41 => 5, 28 => 3, 196 => 90, 183 => 82, 171 => 73, 166 => 71, 163 => 70, 158 => 67, 156 => 66, 151 => 63, 142 => 59, 138 => 57, 136 => 56, 123 => 47, 121 => 46, 117 => 44, 115 => 43, 105 => 40, 101 => 39, 91 => 31, 69 => 25, 66 => 24, 62 => 23, 49 => 19, 24 => 2, 32 => 4, 25 => 3, 22 => 2, 19 => 1, 209 => 82, 203 => 78, 199 => 76, 193 => 73, 189 => 71, 187 => 84, 182 => 68, 176 => 64, 173 => 74, 168 => 72, 164 => 60, 162 => 59, 154 => 54, 149 => 51, 147 => 50, 144 => 49, 141 => 48, 133 => 55, 130 => 41, 125 => 38, 122 => 37, 116 => 36, 112 => 42, 109 => 34, 106 => 33, 103 => 32, 99 => 30, 95 => 28, 92 => 27, 86 => 28, 82 => 22, 80 => 21, 73 => 19, 64 => 15, 60 => 13, 57 => 12, 54 => 11, 51 => 9, 48 => 9, 45 => 8, 42 => 6, 39 => 16, 36 => 5, 33 => 4, 30 => 3,);
}
}
| hechec/StoNinoSF | app/cache/prod/twig/c7/b8/e0c7c14064ee8fe3074f2af4519e.php | PHP | mit | 3,162 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = eachLimit;
var _eachOfLimit = require('./internal/eachOfLimit');
var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
var _withoutIndex = require('./internal/withoutIndex');
var _withoutIndex2 = _interopRequireDefault(_withoutIndex);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time.
*
* @name eachLimit
* @static
* @memberOf module:Collections
* @method
* @see [async.each]{@link module:Collections.each}
* @alias forEachLimit
* @category Collection
* @param {Array|Iterable|Object} coll - A colleciton to iterate over.
* @param {number} limit - The maximum number of async operations at a time.
* @param {Function} iteratee - A function to apply to each item in `coll`. The
* iteratee is passed a `callback(err)` which must be called once it has
* completed. If no error has occurred, the `callback` should be run without
* arguments or with an explicit `null` argument. The array index is not passed
* to the iteratee. Invoked with (item, callback). If you need the index, use
* `eachOfLimit`.
* @param {Function} [callback] - A callback which is called when all
* `iteratee` functions have finished, or an error occurs. Invoked with (err).
*/
function eachLimit(coll, limit, iteratee, callback) {
(0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)(iteratee), callback);
}
module.exports = exports['default'];
| muhbalhester/comex-app | node_modules/async/eachLimit.js | JavaScript | mit | 1,623 |
package cz.vhromada.utils.file.gui;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import cz.vhromada.validators.Validators;
import org.springframework.util.StringUtils;
/**
* A class represents file visitor for copying directories and files.
*/
public class CopyingFileVisitor extends SimpleFileVisitor<Path> {
/**
* Delimiter in replacing text
*/
private static final String REPLACING_TEXT_DELIMITER = ",";
/**
* Source directory
*/
private Path source;
/**
* Target directory
*/
private Path target;
/**
* Replacing patterns
*/
private List<ReplacePattern> replacePatterns;
/**
* Directories
*/
private Deque<Path> directories;
/**
* Creates a new instance of CopyingFileVisitor.
*
* @param source source directory
* @param target target directory
* @param replacingText replacing text
* @param newText new text
* @throws IllegalArgumentException if source directory is null
* or target directory is null
* or replacing text is null
* or new text is null
* or count of replacing texts is different from count of new texts
*/
public CopyingFileVisitor(final Path source, final Path target, final String replacingText, final String newText) {
Validators.validateArgumentNotNull(source, "Source");
Validators.validateArgumentNotNull(target, "Target");
Validators.validateArgumentNotNull(replacingText, "Replacing text");
Validators.validateArgumentNotNull(newText, "New text");
this.source = source;
this.target = target;
this.directories = new LinkedList<>();
this.replacePatterns = createReplacePatterns(replacingText, newText);
}
@Override
public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
final Path directory = getDirectoryName(dir);
directories.addLast(directory);
if (!Files.exists(directory)) {
Files.createDirectory(directory);
}
return super.preVisitDirectory(dir, attrs);
}
@Override
public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {
directories.removeLast();
return super.postVisitDirectory(dir, exc);
}
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
FileCopy.copy(file, directories.getLast(), replacePatterns);
return super.visitFile(file, attrs);
}
/**
* Returns created replace patters.
*
* @param replacingText replacing text
* @param newText new text
* @return created replace patters
* @throws IllegalArgumentException if count of replacing texts is different from count of new texts
*/
private static List<ReplacePattern> createReplacePatterns(final String replacingText, final String newText) {
final String[] replacingTexts = StringUtils.tokenizeToStringArray(replacingText, REPLACING_TEXT_DELIMITER);
final String[] newTexts = StringUtils.tokenizeToStringArray(newText, REPLACING_TEXT_DELIMITER);
if (replacingTexts.length != newTexts.length) {
throw new IllegalArgumentException("Count of replacing texts is different from count of new texts");
}
final List<ReplacePattern> result = new ArrayList<>();
for (int i = 0; i < replacingTexts.length; i++) {
final String source = replacingTexts[i];
final String target = newTexts[i];
result.add(new ReplacePattern(source, target));
result.add(new ReplacePattern(source.toLowerCase(), target.toLowerCase()));
result.add(new ReplacePattern(StringUtils.capitalize(source.toLowerCase()), StringUtils.capitalize(target.toLowerCase())));
result.add(new ReplacePattern(source.toUpperCase(), target.toUpperCase()));
}
return result;
}
/**
* Returns directory name.
*
* @param directory directory
* @return directory name
*/
private Path getDirectoryName(final Path directory) {
final String sourcePath = source.toAbsolutePath().toString();
final String targetPath = target.toAbsolutePath().toString();
final String directoryPath = directory.toAbsolutePath().toString();
final String result = directoryPath.replace(sourcePath, targetPath);
final String replacedResult = FileCopy.replaceText(result, replacePatterns);
return Paths.get(replacedResult);
}
}
| vhromada/File_utils | src/main/java/cz/vhromada/utils/file/gui/CopyingFileVisitor.java | Java | mit | 5,102 |
package api
import (
"net/http"
"strconv"
"time"
"gopkg.in/gin-gonic/gin.v1"
"github.com/knopt/iot/backend/api/model"
"github.com/knopt/iot/backend/error"
)
// GetStatisticsByDeviceDataType by given requests parameters
func (api *Api) GetStatisticsByDeviceDataType(context *gin.Context) {
deviceID := context.Param("id")
dateFrom := context.Param("from")
dateTo := context.Param("to")
dataType := context.Param("type")
responseStatistics, err := api.Service.GetStatistics(deviceID, dateFrom, dateTo, dataType)
if err != nil {
error.Handler(&error.Error{Code: http.StatusBadRequest, Err: err}, context)
return
}
context.IndentedJSON(http.StatusOK, responseStatistics)
}
//InsertStatistic from api statistic form
func (api *Api) InsertStatistic(context *gin.Context) {
var statisticForm model.StatisticForm
if err := context.BindJSON(&statisticForm); err != nil {
context.AbortWithError(http.StatusBadRequest, err)
return
}
err := api.Service.InsertStatistic(&statisticForm)
if err != nil {
error.Handler(&error.Error{Code: http.StatusBadRequest, Err: err}, context)
return
}
context.String(http.StatusOK, "Success")
}
//InsertStatisticInUrl from api statistic form
func (api *Api) InsertStatisticInUrl(context *gin.Context) {
var statisticForm model.StatisticForm
value := context.Param("value")
deviceID := context.Param("id")
statType := context.Param("type")
valueFloat, err := strconv.ParseFloat(value, 64)
if err != nil {
context.AbortWithError(http.StatusBadRequest, err)
return
}
statisticForm.Value = valueFloat
statisticForm.DeviceID = deviceID
statisticForm.Type = statType
statisticForm.Date = time.Now()
err = api.Service.InsertStatistic(&statisticForm)
if err != nil {
error.Handler(&error.Error{Code: http.StatusBadRequest, Err: err}, context)
return
}
context.String(http.StatusOK, "Success")
}
//GetStatisticsTypes by deviceID
func (api *Api) GetStatisticsTypes(context *gin.Context) {
deviceID := context.Param("id")
responseTypes, err := api.Service.GetStatisticsTypes(deviceID)
if err != nil {
error.Handler(&error.Error{Code: http.StatusBadRequest, Err: err}, context)
return
}
context.IndentedJSON(http.StatusOK, responseTypes)
}
| knopt/iot | backend/api/statistic.go | GO | mit | 2,234 |
angular.module('green-streak.controllers', ['LocalStorageModule'])
.controller('MenuController', function ($scope, $location, MenuService) {
// "MenuService" is a service returning mock data (services.js)
$scope.list = MenuService.all();
$scope.goTo = function (page) {
console.log('Going to ' + page);
$scope.sideMenuController.toggleLeft();
$location.url('/' + page);
};
})
.controller('AuthController', function ($scope, $ionicPlatform, $state, localStorageService) {
$scope.leftButtons = [
{
type: 'button-icon icon ion-navicon',
tap: function (e) {
$scope.sideMenuController.toggleLeft();
}
}
];
$scope.rightButtons = [];
})
.controller('IndexController', function ($scope, $ionicPlatform, $state, localStorageService) {
// var authenticated = localStorageService.get('authenticated');
// if (authenticated)
// {
// $state.go('one');
// }
$scope.navTitle = "Green Streak";
$scope.user = {userName: ''};
$scope.search = function () {
console.log("Searching for userName: " + $scope.user.userName)
localStorageService.set("userName", $scope.user.userName);
$state.go('square');
};
$scope.leftButtons = [
{
type: 'button-icon icon ion-navicon',
tap: function (e) {
$scope.sideMenuController.toggleLeft();
}
}
];
$scope.rightButtons = [];
})
.controller("CallbackController", function ($scope, $location, $state, AuthService, localStorageService) {
$scope.currentURL = $location.absUrl();
var paramPartOfURL = $scope.currentURL.slice($scope.currentURL.indexOf('code=') + 5);
var indexOfSlash = paramPartOfURL.indexOf('/');
var oAuthCode = paramPartOfURL.slice(0, indexOfSlash)
AuthService.get({'tokenId': oAuthCode}, function (success) {
localStorageService.add("authenticated", true);
$state.go('one');
}, function (error) { // error callback
localStorageService.remove("authenticated");
});
})
.controller('OneController', function ($scope, LanguageCountService) {
$scope.navTitle = "Language Data by count";
$scope.d3Data = LanguageCountService.query();
$scope.d3OnClick = function (item) {
// alert(item.name);
};
$scope.leftButtons = [
{
type: 'button-icon icon ion-navicon',
tap: function (e) {
$scope.sideMenuController.toggleLeft();
}
}
];
$scope.rightButtons = [];
})
.controller('SquareController', function ($scope, ContributionsService, localStorageService) {
$scope.navTitle = "Daily Contribution";
$scope.contributionData = ContributionsService.list({'userId': localStorageService.get("userName")}, function (success) {
var result = [];
for (var i = 0; i < success.length; i++) {
result.push(success[i][1]);
}
console.log("returning results")
$scope.contributionData = result;
});
$scope.deviceWidth = window.innerWidth || document.body.clientWidth;
$scope.deviceHeight = window.innerHeight || document.body.clientHeight;
$scope.leftButtons = [
{
type: 'button-icon icon ion-navicon',
tap: function (e) {
$scope.sideMenuController.toggleLeft();
}
}
];
$scope.rightButtons = [];
})
.controller('ThreeController', function ($scope) {
$scope.navTitle = "Page Three Title";
$scope.leftButtons = [
{
type: 'button-icon icon ion-navicon',
tap: function (e) {
$scope.sideMenuController.toggleLeft();
}
}
];
$scope.rightButtons = [];
});
| GeorgiCodes/green-streak-ui | www/js/controllers.js | JavaScript | mit | 4,242 |
<?php //-->
/**
* This file is part of the Cradle PHP Command Line
* (c) 2016-2018 Openovate Labs
*
* Copyright and license information can be found at LICENSE
* distributed with this package.
*/
namespace Cradle\Framework\CommandLine;
use Cradle\Framework\CommandLine;
use Cradle\Framework\Exception;
use Cradle\Framework\Decorator;
use Cradle\Event\EventHandler;
//enable the function
Decorator::DECORATE;
/**
* Uninstall CLI Command
*
* @vendor Scoop
* @package Framework
* @author Christian Blanquera <cblanquera@openovate.com>
* @standard PSR-2
*/
class Package
{
/**
* @const string ERROR_ARGUMENT_COUNT
*/
const ERROR_ARGUMENT_COUNT = 'Not enough arguments. Usage: cradle package vendor/package command';
/**
* @const string ERROR_BOOTSTRAP_FLAG
*/
const ERROR_BOOTSTRAP_FLAG = 'Could not determine bootstrap file. Try --bootrap=path/to/.cradle.php';
/**
* @const string ERROR_BOOTSTRAP_404
*/
const ERROR_BOOTSTRAP_404 = 'Bootstrap path %s not found';
/**
* @const string SUCCESS_MESSAGE
*/
const SUCCESS_MESSAGE = '%s has successfully completed.';
/**
* @var string|null $cwd The path from where this was called
*/
protected $cwd = null;
/**
* We need the CWD and the Schema
*
* @param string $cwd The path from where this was called
*/
public function __construct($cwd)
{
$this->cwd = $cwd;
}
/**
* Runs the CLI Generate process
*
* @param array $args CLI arguments
*
* @return void
*/
public function run($args)
{
//expecting cradle install cradle/address
// @codeCoverageIgnoreStart
if (count($args) < 3) {
CommandLine::error(self::ERROR_ARGUMENT_COUNT);
}
// @codeCoverageIgnoreEnd
//parse the data
$data = CommandLine::parseArgs(array_slice($args, 3));
$bootstrap = $this->cwd . '/.cradle.php';
//if no bootstrap
if (!file_exists($bootstrap)) {
//look for bootstrap=./path/to/bootstrap.php
//look for bootstrap=path/to/bootstrap.php
//look for bootstrap=/path/to/bootstrap.php
// @codeCoverageIgnoreStart
if (!isset($data['bootstrap'])) {
CommandLine::error(self::ERROR_BOOTSTRAP_FLAG);
}
// @codeCoverageIgnoreEnd
$bootstrap = $data['bootstrap'];
if (strpos($bootstrap, './') === 0) {
$bootstrap = substr($bootstrap, 2);
}
if (strpos($bootstrap, '/') !== 0) {
$bootstrap = $this->cwd . '/' . $bootstrap;
}
// @codeCoverageIgnoreStart
if (!file_exists($bootstrap)) {
CommandLine::error(sprintf(self::ERROR_BOOTSTRAP_404, $bootstrap));
}
// @codeCoverageIgnoreEnd
}
$cradle = cradle();
require_once($bootstrap);
try {
$cradle->package($args[1]);
} catch (Exception $e) {
//it means that the package wasn't registered
$cradle->register($args[1]);
}
//Setup a default error handler
// @codeCoverageIgnoreStart
$cradle->error(function ($request, $response, $error) {
CommandLine::error($error->getMessage() . PHP_EOL . $error->getTraceAsString());
});
// @codeCoverageIgnoreEnd
//prepare data
if (isset($data['__json'])) {
$json = $data['__json'];
unset($data['__json']);
$data = array_merge(json_decode($json, true), $data);
}
if (isset($data['__json64'])) {
$base64 = $data['__json64'];
unset($data['__json64']);
$json = base64_decode($base64);
$data = array_merge(json_decode($json, true), $data);
}
if (isset($data['__query'])) {
$query = $data['__query'];
unset($data['__query']);
parse_str($query, $query);
$data = array_merge($query, $data);
}
//case for root packages
if (strpos($args[1], '/') === 0) {
$args[1] = substr($args[1], 1);
}
list($author, $package) = explode('/', $args[1], 2);
$event = $author . '-' . $package . '-' . $args[2];
//set the the request and response
$request = $cradle->getRequest();
$response = $cradle->getResponse();
$request->setStage($data);
//see HttpTrait->render() for similar implementation
//if prepared returned false
if (!$cradle->prepare()) {
//dont do anything else
return $this;
}
if ($response->getStatus() == EventHandler::STATUS_OK) {
$continue = $cradle
->trigger($event, $request, $response)
->getEventHandler()
->getMeta();
if (!$continue) {
return $this;
}
}
if (!$response->hasContent() && $response->hasJson()) {
$json = json_encode($response->get('json'));
$response->setContent($json);
}
if ($response->hasContent()) {
CommandLine::output($response->getContent());
} else {
CommandLine::info(sprintf(self::SUCCESS_MESSAGE, $args[2]));
}
//the connection is already closed
//also remember there are no more sessions
$cradle->shutdown();
}
}
| CradlePHP/framework | src/CommandLine/Package.php | PHP | mit | 5,588 |
// Copyright (c) 2014-2017 The Innova Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "activemasternode.h"
#include "consensus/validation.h"
#include "darksend.h"
#include "init.h"
#include "governance.h"
#include "masternode.h"
#include "masternode-payments.h"
#include "masternode-sync.h"
#include "masternodeman.h"
#include "util.h"
#include <boost/lexical_cast.hpp>
CMasternode::CMasternode() :
vin(),
addr(),
pubKeyCollateralAddress(),
pubKeyMasternode(),
lastPing(),
vchSig(),
sigTime(GetAdjustedTime()),
nLastDsq(0),
nTimeLastChecked(0),
nTimeLastPaid(0),
nTimeLastWatchdogVote(0),
nActiveState(MASTERNODE_ENABLED),
nCacheCollateralBlock(0),
nBlockLastPaid(0),
nProtocolVersion(PROTOCOL_VERSION),
nPoSeBanScore(0),
nPoSeBanHeight(0),
fAllowMixingTx(true),
fUnitTest(false)
{}
CMasternode::CMasternode(CService addrNew, CTxIn vinNew, CPubKey pubKeyCollateralAddressNew, CPubKey pubKeyMasternodeNew, int nProtocolVersionIn) :
vin(vinNew),
addr(addrNew),
pubKeyCollateralAddress(pubKeyCollateralAddressNew),
pubKeyMasternode(pubKeyMasternodeNew),
lastPing(),
vchSig(),
sigTime(GetAdjustedTime()),
nLastDsq(0),
nTimeLastChecked(0),
nTimeLastPaid(0),
nTimeLastWatchdogVote(0),
nActiveState(MASTERNODE_ENABLED),
nCacheCollateralBlock(0),
nBlockLastPaid(0),
nProtocolVersion(nProtocolVersionIn),
nPoSeBanScore(0),
nPoSeBanHeight(0),
fAllowMixingTx(true),
fUnitTest(false)
{}
CMasternode::CMasternode(const CMasternode& other) :
vin(other.vin),
addr(other.addr),
pubKeyCollateralAddress(other.pubKeyCollateralAddress),
pubKeyMasternode(other.pubKeyMasternode),
lastPing(other.lastPing),
vchSig(other.vchSig),
sigTime(other.sigTime),
nLastDsq(other.nLastDsq),
nTimeLastChecked(other.nTimeLastChecked),
nTimeLastPaid(other.nTimeLastPaid),
nTimeLastWatchdogVote(other.nTimeLastWatchdogVote),
nActiveState(other.nActiveState),
nCacheCollateralBlock(other.nCacheCollateralBlock),
nBlockLastPaid(other.nBlockLastPaid),
nProtocolVersion(other.nProtocolVersion),
nPoSeBanScore(other.nPoSeBanScore),
nPoSeBanHeight(other.nPoSeBanHeight),
fAllowMixingTx(other.fAllowMixingTx),
fUnitTest(other.fUnitTest)
{}
CMasternode::CMasternode(const CMasternodeBroadcast& mnb) :
vin(mnb.vin),
addr(mnb.addr),
pubKeyCollateralAddress(mnb.pubKeyCollateralAddress),
pubKeyMasternode(mnb.pubKeyMasternode),
lastPing(mnb.lastPing),
vchSig(mnb.vchSig),
sigTime(mnb.sigTime),
nLastDsq(0),
nTimeLastChecked(0),
nTimeLastPaid(0),
nTimeLastWatchdogVote(mnb.sigTime),
nActiveState(mnb.nActiveState),
nCacheCollateralBlock(0),
nBlockLastPaid(0),
nProtocolVersion(mnb.nProtocolVersion),
nPoSeBanScore(0),
nPoSeBanHeight(0),
fAllowMixingTx(true),
fUnitTest(false)
{}
//
// When a new masternode broadcast is sent, update our information
//
bool CMasternode::UpdateFromNewBroadcast(CMasternodeBroadcast& mnb)
{
if(mnb.sigTime <= sigTime && !mnb.fRecovery) return false;
pubKeyMasternode = mnb.pubKeyMasternode;
sigTime = mnb.sigTime;
vchSig = mnb.vchSig;
nProtocolVersion = mnb.nProtocolVersion;
addr = mnb.addr;
nPoSeBanScore = 0;
nPoSeBanHeight = 0;
nTimeLastChecked = 0;
int nDos = 0;
if(mnb.lastPing == CMasternodePing() || (mnb.lastPing != CMasternodePing() && mnb.lastPing.CheckAndUpdate(this, true, nDos))) {
lastPing = mnb.lastPing;
mnodeman.mapSeenMasternodePing.insert(std::make_pair(lastPing.GetHash(), lastPing));
}
// if it matches our Masternode privkey...
if(fMasterNode && pubKeyMasternode == activeMasternode.pubKeyMasternode) {
nPoSeBanScore = -MASTERNODE_POSE_BAN_MAX_SCORE;
if(nProtocolVersion == PROTOCOL_VERSION) {
// ... and PROTOCOL_VERSION, then we've been remotely activated ...
activeMasternode.ManageState();
} else {
// ... otherwise we need to reactivate our node, do not add it to the list and do not relay
// but also do not ban the node we get this message from
LogPrintf("CMasternode::UpdateFromNewBroadcast -- wrong PROTOCOL_VERSION, re-activate your MN: message nProtocolVersion=%d PROTOCOL_VERSION=%d\n", nProtocolVersion, PROTOCOL_VERSION);
return false;
}
}
return true;
}
//
// Deterministically calculate a given "score" for a Masternode depending on how close it's hash is to
// the proof of work for that block. The further away they are the better, the furthest will win the election
// and get paid this block
//
arith_uint256 CMasternode::CalculateScore(const uint256& blockHash)
{
uint256 aux = ArithToUint256(UintToArith256(vin.prevout.hash) + vin.prevout.n);
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << blockHash;
arith_uint256 hash2 = UintToArith256(ss.GetHash());
CHashWriter ss2(SER_GETHASH, PROTOCOL_VERSION);
ss2 << blockHash;
ss2 << aux;
arith_uint256 hash3 = UintToArith256(ss2.GetHash());
return (hash3 > hash2 ? hash3 - hash2 : hash2 - hash3);
}
void CMasternode::Check(bool fForce)
{
LOCK(cs);
if(ShutdownRequested()) return;
if(!fForce && (GetTime() - nTimeLastChecked < MASTERNODE_CHECK_SECONDS)) return;
nTimeLastChecked = GetTime();
LogPrint("masternode", "CMasternode::Check -- Masternode %s is in %s state\n", vin.prevout.ToStringShort(), GetStateString());
//once spent, stop doing the checks
if(IsOutpointSpent()) return;
int nHeight = 0;
if(!fUnitTest) {
TRY_LOCK(cs_main, lockMain);
if(!lockMain) return;
CCoins coins;
if(!pcoinsTip->GetCoins(vin.prevout.hash, coins) ||
(unsigned int)vin.prevout.n>=coins.vout.size() ||
coins.vout[vin.prevout.n].IsNull()) {
nActiveState = MASTERNODE_OUTPOINT_SPENT;
LogPrint("masternode", "CMasternode::Check -- Failed to find Masternode UTXO, masternode=%s\n", vin.prevout.ToStringShort());
return;
}
nHeight = chainActive.Height();
}
if(IsPoSeBanned()) {
if(nHeight < nPoSeBanHeight) return; // too early?
// Otherwise give it a chance to proceed further to do all the usual checks and to change its state.
// Masternode still will be on the edge and can be banned back easily if it keeps ignoring mnverify
// or connect attempts. Will require few mnverify messages to strengthen its position in mn list.
LogPrintf("CMasternode::Check -- Masternode %s is unbanned and back in list now\n", vin.prevout.ToStringShort());
DecreasePoSeBanScore();
} else if(nPoSeBanScore >= MASTERNODE_POSE_BAN_MAX_SCORE) {
nActiveState = MASTERNODE_POSE_BAN;
// ban for the whole payment cycle
nPoSeBanHeight = nHeight + mnodeman.size();
LogPrintf("CMasternode::Check -- Masternode %s is banned till block %d now\n", vin.prevout.ToStringShort(), nPoSeBanHeight);
return;
}
int nActiveStatePrev = nActiveState;
bool fOurMasternode = fMasterNode && activeMasternode.pubKeyMasternode == pubKeyMasternode;
// masternode doesn't meet payment protocol requirements ...
bool fRequireUpdate = nProtocolVersion < mnpayments.GetMinMasternodePaymentsProto() ||
// or it's our own node and we just updated it to the new protocol but we are still waiting for activation ...
(fOurMasternode && nProtocolVersion < PROTOCOL_VERSION);
if(fRequireUpdate) {
nActiveState = MASTERNODE_UPDATE_REQUIRED;
if(nActiveStatePrev != nActiveState) {
LogPrint("masternode", "CMasternode::Check -- Masternode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString());
}
return;
}
// keep old masternodes on start, give them a chance to receive updates...
bool fWaitForPing = !masternodeSync.IsMasternodeListSynced() && !IsPingedWithin(MASTERNODE_MIN_MNP_SECONDS);
if(fWaitForPing && !fOurMasternode) {
// ...but if it was already expired before the initial check - return right away
if(IsExpired() || IsWatchdogExpired() || IsNewStartRequired()) {
LogPrint("masternode", "CMasternode::Check -- Masternode %s is in %s state, waiting for ping\n", vin.prevout.ToStringShort(), GetStateString());
return;
}
}
// don't expire if we are still in "waiting for ping" mode unless it's our own masternode
if(!fWaitForPing || fOurMasternode) {
if(!IsPingedWithin(MASTERNODE_NEW_START_REQUIRED_SECONDS)) {
nActiveState = MASTERNODE_NEW_START_REQUIRED;
if(nActiveStatePrev != nActiveState) {
LogPrint("masternode", "CMasternode::Check -- Masternode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString());
}
return;
}
bool fWatchdogActive = masternodeSync.IsSynced() && mnodeman.IsWatchdogActive();
bool fWatchdogExpired = (fWatchdogActive && ((GetTime() - nTimeLastWatchdogVote) > MASTERNODE_WATCHDOG_MAX_SECONDS));
LogPrint("masternode", "CMasternode::Check -- outpoint=%s, nTimeLastWatchdogVote=%d, GetTime()=%d, fWatchdogExpired=%d\n",
vin.prevout.ToStringShort(), nTimeLastWatchdogVote, GetTime(), fWatchdogExpired);
if(fWatchdogExpired) {
nActiveState = MASTERNODE_WATCHDOG_EXPIRED;
if(nActiveStatePrev != nActiveState) {
LogPrint("masternode", "CMasternode::Check -- Masternode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString());
}
return;
}
if(!IsPingedWithin(MASTERNODE_EXPIRATION_SECONDS)) {
nActiveState = MASTERNODE_EXPIRED;
if(nActiveStatePrev != nActiveState) {
LogPrint("masternode", "CMasternode::Check -- Masternode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString());
}
return;
}
}
if(lastPing.sigTime - sigTime < MASTERNODE_MIN_MNP_SECONDS) {
nActiveState = MASTERNODE_PRE_ENABLED;
if(nActiveStatePrev != nActiveState) {
LogPrint("masternode", "CMasternode::Check -- Masternode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString());
}
return;
}
nActiveState = MASTERNODE_ENABLED; // OK
if(nActiveStatePrev != nActiveState) {
LogPrint("masternode", "CMasternode::Check -- Masternode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString());
}
}
bool CMasternode::IsValidNetAddr()
{
return IsValidNetAddr(addr);
}
bool CMasternode::IsValidNetAddr(CService addrIn)
{
// TODO: regtest is fine with any addresses for now,
// should probably be a bit smarter if one day we start to implement tests for this
return Params().NetworkIDString() == CBaseChainParams::REGTEST ||
(addrIn.IsIPv4() && IsReachable(addrIn) && addrIn.IsRoutable());
}
masternode_info_t CMasternode::GetInfo()
{
masternode_info_t info;
info.vin = vin;
info.addr = addr;
info.pubKeyCollateralAddress = pubKeyCollateralAddress;
info.pubKeyMasternode = pubKeyMasternode;
info.sigTime = sigTime;
info.nLastDsq = nLastDsq;
info.nTimeLastChecked = nTimeLastChecked;
info.nTimeLastPaid = nTimeLastPaid;
info.nTimeLastWatchdogVote = nTimeLastWatchdogVote;
info.nTimeLastPing = lastPing.sigTime;
info.nActiveState = nActiveState;
info.nProtocolVersion = nProtocolVersion;
info.fInfoValid = true;
return info;
}
std::string CMasternode::StateToString(int nStateIn)
{
switch(nStateIn) {
case MASTERNODE_PRE_ENABLED: return "PRE_ENABLED";
case MASTERNODE_ENABLED: return "ENABLED";
case MASTERNODE_EXPIRED: return "EXPIRED";
case MASTERNODE_OUTPOINT_SPENT: return "OUTPOINT_SPENT";
case MASTERNODE_UPDATE_REQUIRED: return "UPDATE_REQUIRED";
case MASTERNODE_WATCHDOG_EXPIRED: return "WATCHDOG_EXPIRED";
case MASTERNODE_NEW_START_REQUIRED: return "NEW_START_REQUIRED";
case MASTERNODE_POSE_BAN: return "POSE_BAN";
default: return "UNKNOWN";
}
}
std::string CMasternode::GetStateString() const
{
return StateToString(nActiveState);
}
std::string CMasternode::GetStatus() const
{
// TODO: return smth a bit more human readable here
return GetStateString();
}
int CMasternode::GetCollateralAge()
{
int nHeight;
{
TRY_LOCK(cs_main, lockMain);
if(!lockMain || !chainActive.Tip()) return -1;
nHeight = chainActive.Height();
}
if (nCacheCollateralBlock == 0) {
int nInputAge = GetInputAge(vin);
if(nInputAge > 0) {
nCacheCollateralBlock = nHeight - nInputAge;
} else {
return nInputAge;
}
}
return nHeight - nCacheCollateralBlock;
}
void CMasternode::UpdateLastPaid(const CBlockIndex *pindex, int nMaxBlocksToScanBack)
{
if(!pindex) return;
const CBlockIndex *BlockReading = pindex;
CScript mnpayee = GetScriptForDestination(pubKeyCollateralAddress.GetID());
// LogPrint("masternode", "CMasternode::UpdateLastPaidBlock -- searching for block with payment to %s\n", vin.prevout.ToStringShort());
LOCK(cs_mapMasternodeBlocks);
for (int i = 0; BlockReading && BlockReading->nHeight > nBlockLastPaid && i < nMaxBlocksToScanBack; i++) {
if(mnpayments.mapMasternodeBlocks.count(BlockReading->nHeight) &&
mnpayments.mapMasternodeBlocks[BlockReading->nHeight].HasPayeeWithVotes(mnpayee, 2))
{
CBlock block;
if(!ReadBlockFromDisk(block, BlockReading, Params().GetConsensus())) // shouldn't really happen
continue;
CAmount nMasternodePayment = GetMasternodePayment(BlockReading->nHeight, block.vtx[0].GetValueOut());
BOOST_FOREACH(CTxOut txout, block.vtx[0].vout)
if(mnpayee == txout.scriptPubKey && nMasternodePayment == txout.nValue) {
nBlockLastPaid = BlockReading->nHeight;
nTimeLastPaid = BlockReading->nTime;
LogPrint("masternode", "CMasternode::UpdateLastPaidBlock -- searching for block with payment to %s -- found new %d\n", vin.prevout.ToStringShort(), nBlockLastPaid);
return;
}
}
if (BlockReading->pprev == NULL) { assert(BlockReading); break; }
BlockReading = BlockReading->pprev;
}
// Last payment for this masternode wasn't found in latest mnpayments blocks
// or it was found in mnpayments blocks but wasn't found in the blockchain.
// LogPrint("masternode", "CMasternode::UpdateLastPaidBlock -- searching for block with payment to %s -- keeping old %d\n", vin.prevout.ToStringShort(), nBlockLastPaid);
}
bool CMasternodeBroadcast::Create(std::string strService, std::string strKeyMasternode, std::string strTxHash, std::string strOutputIndex, std::string& strErrorRet, CMasternodeBroadcast &mnbRet, bool fOffline)
{
CTxIn txin;
CPubKey pubKeyCollateralAddressNew;
CKey keyCollateralAddressNew;
CPubKey pubKeyMasternodeNew;
CKey keyMasternodeNew;
//need correct blocks to send ping
if(!fOffline && !masternodeSync.IsBlockchainSynced()) {
strErrorRet = "Sync in progress. Must wait until sync is complete to start Masternode";
LogPrintf("CMasternodeBroadcast::Create -- %s\n", strErrorRet);
return false;
}
if(!darkSendSigner.GetKeysFromSecret(strKeyMasternode, keyMasternodeNew, pubKeyMasternodeNew)) {
strErrorRet = strprintf("Invalid masternode key %s", strKeyMasternode);
LogPrintf("CMasternodeBroadcast::Create -- %s\n", strErrorRet);
return false;
}
if(!pwalletMain->GetMasternodeVinAndKeys(txin, pubKeyCollateralAddressNew, keyCollateralAddressNew, strTxHash, strOutputIndex)) {
strErrorRet = strprintf("Could not allocate txin %s:%s for masternode %s", strTxHash, strOutputIndex, strService);
LogPrintf("CMasternodeBroadcast::Create -- %s\n", strErrorRet);
return false;
}
CService service = CService(strService);
int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort();
if(Params().NetworkIDString() == CBaseChainParams::MAIN) {
if(service.GetPort() != mainnetDefaultPort) {
strErrorRet = strprintf("Invalid port %u for masternode %s, only %d is supported on mainnet.", service.GetPort(), strService, mainnetDefaultPort);
LogPrintf("CMasternodeBroadcast::Create -- %s\n", strErrorRet);
return false;
}
} else if (service.GetPort() == mainnetDefaultPort) {
strErrorRet = strprintf("Invalid port %u for masternode %s, %d is the only supported on mainnet.", service.GetPort(), strService, mainnetDefaultPort);
LogPrintf("CMasternodeBroadcast::Create -- %s\n", strErrorRet);
return false;
}
return Create(txin, CService(strService), keyCollateralAddressNew, pubKeyCollateralAddressNew, keyMasternodeNew, pubKeyMasternodeNew, strErrorRet, mnbRet);
}
bool CMasternodeBroadcast::Create(CTxIn txin, CService service, CKey keyCollateralAddressNew, CPubKey pubKeyCollateralAddressNew, CKey keyMasternodeNew, CPubKey pubKeyMasternodeNew, std::string &strErrorRet, CMasternodeBroadcast &mnbRet)
{
// wait for reindex and/or import to finish
if (fImporting || fReindex) return false;
LogPrint("masternode", "CMasternodeBroadcast::Create -- pubKeyCollateralAddressNew = %s, pubKeyMasternodeNew.GetID() = %s\n",
CBitcoinAddress(pubKeyCollateralAddressNew.GetID()).ToString(),
pubKeyMasternodeNew.GetID().ToString());
CMasternodePing mnp(txin);
if(!mnp.Sign(keyMasternodeNew, pubKeyMasternodeNew)) {
strErrorRet = strprintf("Failed to sign ping, masternode=%s", txin.prevout.ToStringShort());
LogPrintf("CMasternodeBroadcast::Create -- %s\n", strErrorRet);
mnbRet = CMasternodeBroadcast();
return false;
}
mnbRet = CMasternodeBroadcast(service, txin, pubKeyCollateralAddressNew, pubKeyMasternodeNew, PROTOCOL_VERSION);
if(!mnbRet.IsValidNetAddr()) {
strErrorRet = strprintf("Invalid IP address, masternode=%s", txin.prevout.ToStringShort());
LogPrintf("CMasternodeBroadcast::Create -- %s\n", strErrorRet);
mnbRet = CMasternodeBroadcast();
return false;
}
mnbRet.lastPing = mnp;
if(!mnbRet.Sign(keyCollateralAddressNew)) {
strErrorRet = strprintf("Failed to sign broadcast, masternode=%s", txin.prevout.ToStringShort());
LogPrintf("CMasternodeBroadcast::Create -- %s\n", strErrorRet);
mnbRet = CMasternodeBroadcast();
return false;
}
return true;
}
bool CMasternodeBroadcast::SimpleCheck(int& nDos)
{
nDos = 0;
// make sure addr is valid
if(!IsValidNetAddr()) {
LogPrintf("CMasternodeBroadcast::SimpleCheck -- Invalid addr, rejected: masternode=%s addr=%s\n",
vin.prevout.ToStringShort(), addr.ToString());
return false;
}
// make sure signature isn't in the future (past is OK)
if (sigTime > GetAdjustedTime() + 60 * 60) {
LogPrintf("CMasternodeBroadcast::SimpleCheck -- Signature rejected, too far into the future: masternode=%s\n", vin.prevout.ToStringShort());
nDos = 1;
return false;
}
// empty ping or incorrect sigTime/unknown blockhash
if(lastPing == CMasternodePing() || !lastPing.SimpleCheck(nDos)) {
// one of us is probably forked or smth, just mark it as expired and check the rest of the rules
nActiveState = MASTERNODE_EXPIRED;
}
if(nProtocolVersion < mnpayments.GetMinMasternodePaymentsProto()) {
LogPrintf("CMasternodeBroadcast::SimpleCheck -- ignoring outdated Masternode: masternode=%s nProtocolVersion=%d\n", vin.prevout.ToStringShort(), nProtocolVersion);
return false;
}
CScript pubkeyScript;
pubkeyScript = GetScriptForDestination(pubKeyCollateralAddress.GetID());
if(pubkeyScript.size() != 25) {
LogPrintf("CMasternodeBroadcast::SimpleCheck -- pubKeyCollateralAddress has the wrong size\n");
nDos = 100;
return false;
}
CScript pubkeyScript2;
pubkeyScript2 = GetScriptForDestination(pubKeyMasternode.GetID());
if(pubkeyScript2.size() != 25) {
LogPrintf("CMasternodeBroadcast::SimpleCheck -- pubKeyMasternode has the wrong size\n");
nDos = 100;
return false;
}
if(!vin.scriptSig.empty()) {
LogPrintf("CMasternodeBroadcast::SimpleCheck -- Ignore Not Empty ScriptSig %s\n",vin.ToString());
nDos = 100;
return false;
}
int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort();
if(Params().NetworkIDString() == CBaseChainParams::MAIN) {
if(addr.GetPort() != mainnetDefaultPort) return false;
} else if(addr.GetPort() == mainnetDefaultPort) return false;
return true;
}
bool CMasternodeBroadcast::Update(CMasternode* pmn, int& nDos)
{
nDos = 0;
if(pmn->sigTime == sigTime && !fRecovery) {
// mapSeenMasternodeBroadcast in CMasternodeMan::CheckMnbAndUpdateMasternodeList should filter legit duplicates
// but this still can happen if we just started, which is ok, just do nothing here.
return false;
}
// this broadcast is older than the one that we already have - it's bad and should never happen
// unless someone is doing something fishy
if(pmn->sigTime > sigTime) {
LogPrintf("CMasternodeBroadcast::Update -- Bad sigTime %d (existing broadcast is at %d) for Masternode %s %s\n",
sigTime, pmn->sigTime, vin.prevout.ToStringShort(), addr.ToString());
return false;
}
pmn->Check();
// masternode is banned by PoSe
if(pmn->IsPoSeBanned()) {
LogPrintf("CMasternodeBroadcast::Update -- Banned by PoSe, masternode=%s\n", vin.prevout.ToStringShort());
return false;
}
// IsVnAssociatedWithPubkey is validated once in CheckOutpoint, after that they just need to match
if(pmn->pubKeyCollateralAddress != pubKeyCollateralAddress) {
LogPrintf("CMasternodeBroadcast::Update -- Got mismatched pubKeyCollateralAddress and vin\n");
nDos = 33;
return false;
}
if (!CheckSignature(nDos)) {
LogPrintf("CMasternodeBroadcast::Update -- CheckSignature() failed, masternode=%s\n", vin.prevout.ToStringShort());
return false;
}
// if ther was no masternode broadcast recently or if it matches our Masternode privkey...
if(!pmn->IsBroadcastedWithin(MASTERNODE_MIN_MNB_SECONDS) || (fMasterNode && pubKeyMasternode == activeMasternode.pubKeyMasternode)) {
// take the newest entry
LogPrintf("CMasternodeBroadcast::Update -- Got UPDATED Masternode entry: addr=%s\n", addr.ToString());
if(pmn->UpdateFromNewBroadcast((*this))) {
pmn->Check();
Relay();
}
masternodeSync.AddedMasternodeList();
}
return true;
}
bool CMasternodeBroadcast::CheckOutpoint(int& nDos)
{
// we are a masternode with the same vin (i.e. already activated) and this mnb is ours (matches our Masternode privkey)
// so nothing to do here for us
if(fMasterNode && vin.prevout == activeMasternode.vin.prevout && pubKeyMasternode == activeMasternode.pubKeyMasternode) {
return false;
}
if (!CheckSignature(nDos)) {
LogPrintf("CMasternodeBroadcast::CheckOutpoint -- CheckSignature() failed, masternode=%s\n", vin.prevout.ToStringShort());
return false;
}
{
TRY_LOCK(cs_main, lockMain);
if(!lockMain) {
// not mnb fault, let it to be checked again later
LogPrint("masternode", "CMasternodeBroadcast::CheckOutpoint -- Failed to aquire lock, addr=%s", addr.ToString());
mnodeman.mapSeenMasternodeBroadcast.erase(GetHash());
return false;
}
CCoins coins;
if(!pcoinsTip->GetCoins(vin.prevout.hash, coins) ||
(unsigned int)vin.prevout.n>=coins.vout.size() ||
coins.vout[vin.prevout.n].IsNull()) {
LogPrint("masternode", "CMasternodeBroadcast::CheckOutpoint -- Failed to find Masternode UTXO, masternode=%s\n", vin.prevout.ToStringShort());
return false;
}
if(coins.vout[vin.prevout.n].nValue != 1000 * COIN) {
LogPrint("masternode", "CMasternodeBroadcast::CheckOutpoint -- Masternode UTXO should have 1000 INNOVA, masternode=%s\n", vin.prevout.ToStringShort());
return false;
}
if(chainActive.Height() - coins.nHeight + 1 < Params().GetConsensus().nMasternodeMinimumConfirmations) {
LogPrintf("CMasternodeBroadcast::CheckOutpoint -- Masternode UTXO must have at least %d confirmations, masternode=%s\n",
Params().GetConsensus().nMasternodeMinimumConfirmations, vin.prevout.ToStringShort());
// maybe we miss few blocks, let this mnb to be checked again later
mnodeman.mapSeenMasternodeBroadcast.erase(GetHash());
return false;
}
}
LogPrint("masternode", "CMasternodeBroadcast::CheckOutpoint -- Masternode UTXO verified\n");
// make sure the vout that was signed is related to the transaction that spawned the Masternode
// - this is expensive, so it's only done once per Masternode
if(!darkSendSigner.IsVinAssociatedWithPubkey(vin, pubKeyCollateralAddress)) {
LogPrintf("CMasternodeMan::CheckOutpoint -- Got mismatched pubKeyCollateralAddress and vin\n");
nDos = 33;
return false;
}
// verify that sig time is legit in past
// should be at least not earlier than block when 1000 INNOVA tx got nMasternodeMinimumConfirmations
uint256 hashBlock = uint256();
CTransaction tx2;
GetTransaction(vin.prevout.hash, tx2, Params().GetConsensus(), hashBlock, true);
{
LOCK(cs_main);
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second) {
CBlockIndex* pMNIndex = (*mi).second; // block for 1000 INNOVA tx -> 1 confirmation
CBlockIndex* pConfIndex = chainActive[pMNIndex->nHeight + Params().GetConsensus().nMasternodeMinimumConfirmations - 1]; // block where tx got nMasternodeMinimumConfirmations
if(pConfIndex->GetBlockTime() > sigTime) {
LogPrintf("CMasternodeBroadcast::CheckOutpoint -- Bad sigTime %d (%d conf block is at %d) for Masternode %s %s\n",
sigTime, Params().GetConsensus().nMasternodeMinimumConfirmations, pConfIndex->GetBlockTime(), vin.prevout.ToStringShort(), addr.ToString());
return false;
}
}
}
return true;
}
bool CMasternodeBroadcast::Sign(CKey& keyCollateralAddress)
{
std::string strError;
std::string strMessage;
sigTime = GetAdjustedTime();
strMessage = addr.ToString(false) + boost::lexical_cast<std::string>(sigTime) +
pubKeyCollateralAddress.GetID().ToString() + pubKeyMasternode.GetID().ToString() +
boost::lexical_cast<std::string>(nProtocolVersion);
if(!darkSendSigner.SignMessage(strMessage, vchSig, keyCollateralAddress)) {
LogPrintf("CMasternodeBroadcast::Sign -- SignMessage() failed\n");
return false;
}
if(!darkSendSigner.VerifyMessage(pubKeyCollateralAddress, vchSig, strMessage, strError)) {
LogPrintf("CMasternodeBroadcast::Sign -- VerifyMessage() failed, error: %s\n", strError);
return false;
}
return true;
}
bool CMasternodeBroadcast::CheckSignature(int& nDos)
{
std::string strMessage;
std::string strError = "";
nDos = 0;
strMessage = addr.ToString(false) + boost::lexical_cast<std::string>(sigTime) +
pubKeyCollateralAddress.GetID().ToString() + pubKeyMasternode.GetID().ToString() +
boost::lexical_cast<std::string>(nProtocolVersion);
LogPrint("masternode", "CMasternodeBroadcast::CheckSignature -- strMessage: %s pubKeyCollateralAddress address: %s sig: %s\n", strMessage, CBitcoinAddress(pubKeyCollateralAddress.GetID()).ToString(), EncodeBase64(&vchSig[0], vchSig.size()));
if(!darkSendSigner.VerifyMessage(pubKeyCollateralAddress, vchSig, strMessage, strError)){
LogPrintf("CMasternodeBroadcast::CheckSignature -- Got bad Masternode announce signature, error: %s\n", strError);
nDos = 100;
return false;
}
return true;
}
void CMasternodeBroadcast::Relay()
{
CInv inv(MSG_MASTERNODE_ANNOUNCE, GetHash());
RelayInv(inv);
}
CMasternodePing::CMasternodePing(CTxIn& vinNew)
{
LOCK(cs_main);
if (!chainActive.Tip() || chainActive.Height() < 12) return;
vin = vinNew;
blockHash = chainActive[chainActive.Height() - 12]->GetBlockHash();
sigTime = GetAdjustedTime();
vchSig = std::vector<unsigned char>();
}
bool CMasternodePing::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode)
{
std::string strError;
std::string strMasterNodeSignMessage;
sigTime = GetAdjustedTime();
std::string strMessage = vin.ToString() + blockHash.ToString() + boost::lexical_cast<std::string>(sigTime);
if(!darkSendSigner.SignMessage(strMessage, vchSig, keyMasternode)) {
LogPrintf("CMasternodePing::Sign -- SignMessage() failed\n");
return false;
}
if(!darkSendSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) {
LogPrintf("CMasternodePing::Sign -- VerifyMessage() failed, error: %s\n", strError);
return false;
}
return true;
}
bool CMasternodePing::CheckSignature(CPubKey& pubKeyMasternode, int &nDos)
{
std::string strMessage = vin.ToString() + blockHash.ToString() + boost::lexical_cast<std::string>(sigTime);
std::string strError = "";
nDos = 0;
if(!darkSendSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) {
LogPrintf("CMasternodePing::CheckSignature -- Got bad Masternode ping signature, masternode=%s, error: %s\n", vin.prevout.ToStringShort(), strError);
nDos = 33;
return false;
}
return true;
}
bool CMasternodePing::SimpleCheck(int& nDos)
{
// don't ban by default
nDos = 0;
if (sigTime > GetAdjustedTime() + 60 * 60) {
LogPrintf("CMasternodePing::SimpleCheck -- Signature rejected, too far into the future, masternode=%s\n", vin.prevout.ToStringShort());
nDos = 1;
return false;
}
{
LOCK(cs_main);
BlockMap::iterator mi = mapBlockIndex.find(blockHash);
if (mi == mapBlockIndex.end()) {
LogPrint("masternode", "CMasternodePing::SimpleCheck -- Masternode ping is invalid, unknown block hash: masternode=%s blockHash=%s\n", vin.prevout.ToStringShort(), blockHash.ToString());
// maybe we stuck or forked so we shouldn't ban this node, just fail to accept this ping
// TODO: or should we also request this block?
return false;
}
}
LogPrint("masternode", "CMasternodePing::SimpleCheck -- Masternode ping verified: masternode=%s blockHash=%s sigTime=%d\n", vin.prevout.ToStringShort(), blockHash.ToString(), sigTime);
return true;
}
bool CMasternodePing::CheckAndUpdate(CMasternode* pmn, bool fFromNewBroadcast, int& nDos)
{
// don't ban by default
nDos = 0;
if (!SimpleCheck(nDos)) {
return false;
}
if (pmn == NULL) {
LogPrint("masternode", "CMasternodePing::CheckAndUpdate -- Couldn't find Masternode entry, masternode=%s\n", vin.prevout.ToStringShort());
return false;
}
if(!fFromNewBroadcast) {
if (pmn->IsUpdateRequired()) {
LogPrint("masternode", "CMasternodePing::CheckAndUpdate -- masternode protocol is outdated, masternode=%s\n", vin.prevout.ToStringShort());
return false;
}
if (pmn->IsNewStartRequired()) {
LogPrint("masternode", "CMasternodePing::CheckAndUpdate -- masternode is completely expired, new start is required, masternode=%s\n", vin.prevout.ToStringShort());
return false;
}
}
{
LOCK(cs_main);
BlockMap::iterator mi = mapBlockIndex.find(blockHash);
if ((*mi).second && (*mi).second->nHeight < chainActive.Height() - 24) {
LogPrintf("CMasternodePing::CheckAndUpdate -- Masternode ping is invalid, block hash is too old: masternode=%s blockHash=%s\n", vin.prevout.ToStringShort(), blockHash.ToString());
// nDos = 1;
return false;
}
}
LogPrint("masternode", "CMasternodePing::CheckAndUpdate -- New ping: masternode=%s blockHash=%s sigTime=%d\n", vin.prevout.ToStringShort(), blockHash.ToString(), sigTime);
// LogPrintf("mnping - Found corresponding mn for vin: %s\n", vin.prevout.ToStringShort());
// update only if there is no known ping for this masternode or
// last ping was more then MASTERNODE_MIN_MNP_SECONDS-60 ago comparing to this one
if (pmn->IsPingedWithin(MASTERNODE_MIN_MNP_SECONDS - 60, sigTime)) {
LogPrint("masternode", "CMasternodePing::CheckAndUpdate -- Masternode ping arrived too early, masternode=%s\n", vin.prevout.ToStringShort());
//nDos = 1; //disable, this is happening frequently and causing banned peers
return false;
}
if (!CheckSignature(pmn->pubKeyMasternode, nDos)) return false;
// so, ping seems to be ok
// if we are still syncing and there was no known ping for this mn for quite a while
// (NOTE: assuming that MASTERNODE_EXPIRATION_SECONDS/2 should be enough to finish mn list sync)
if(!masternodeSync.IsMasternodeListSynced() && !pmn->IsPingedWithin(MASTERNODE_EXPIRATION_SECONDS/2)) {
// let's bump sync timeout
LogPrint("masternode", "CMasternodePing::CheckAndUpdate -- bumping sync timeout, masternode=%s\n", vin.prevout.ToStringShort());
masternodeSync.AddedMasternodeList();
}
// let's store this ping as the last one
LogPrint("masternode", "CMasternodePing::CheckAndUpdate -- Masternode ping accepted, masternode=%s\n", vin.prevout.ToStringShort());
pmn->lastPing = *this;
// and update mnodeman.mapSeenMasternodeBroadcast.lastPing which is probably outdated
CMasternodeBroadcast mnb(*pmn);
uint256 hash = mnb.GetHash();
if (mnodeman.mapSeenMasternodeBroadcast.count(hash)) {
mnodeman.mapSeenMasternodeBroadcast[hash].second.lastPing = *this;
}
pmn->Check(true); // force update, ignoring cache
if (!pmn->IsEnabled()) return false;
LogPrint("masternode", "CMasternodePing::CheckAndUpdate -- Masternode ping acceepted and relayed, masternode=%s\n", vin.prevout.ToStringShort());
Relay();
return true;
}
void CMasternodePing::Relay()
{
CInv inv(MSG_MASTERNODE_PING, GetHash());
RelayInv(inv);
}
void CMasternode::AddGovernanceVote(uint256 nGovernanceObjectHash)
{
if(mapGovernanceObjectsVotedOn.count(nGovernanceObjectHash)) {
mapGovernanceObjectsVotedOn[nGovernanceObjectHash]++;
} else {
mapGovernanceObjectsVotedOn.insert(std::make_pair(nGovernanceObjectHash, 1));
}
}
void CMasternode::RemoveGovernanceObject(uint256 nGovernanceObjectHash)
{
std::map<uint256, int>::iterator it = mapGovernanceObjectsVotedOn.find(nGovernanceObjectHash);
if(it == mapGovernanceObjectsVotedOn.end()) {
return;
}
mapGovernanceObjectsVotedOn.erase(it);
}
void CMasternode::UpdateWatchdogVoteTime()
{
LOCK(cs);
nTimeLastWatchdogVote = GetTime();
}
/**
* FLAG GOVERNANCE ITEMS AS DIRTY
*
* - When masternode come and go on the network, we must flag the items they voted on to recalc it's cached flags
*
*/
void CMasternode::FlagGovernanceItemsAsDirty()
{
std::vector<uint256> vecDirty;
{
std::map<uint256, int>::iterator it = mapGovernanceObjectsVotedOn.begin();
while(it != mapGovernanceObjectsVotedOn.end()) {
vecDirty.push_back(it->first);
++it;
}
}
for(size_t i = 0; i < vecDirty.size(); ++i) {
mnodeman.AddDirtyGovernanceObjectHash(vecDirty[i]);
}
}
| innovacoin/innova | src/masternode.cpp | C++ | mit | 36,708 |
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package gin
import (
"log"
"os"
)
const GIN_MODE = "GIN_MODE"
const (
DebugMode string = "debug"
ReleaseMode string = "release"
TestMode string = "test"
)
const (
debugCode = iota
releaseCode = iota
testCode = iota
)
var gin_mode int = debugCode
var mode_name string = DebugMode
func init() {
value := os.Getenv(GIN_MODE)
if len(value) == 0 {
SetMode(DebugMode)
} else {
SetMode(value)
}
}
func SetMode(value string) {
switch value {
case DebugMode:
gin_mode = debugCode
case ReleaseMode:
gin_mode = releaseCode
case TestMode:
gin_mode = testCode
default:
log.Panic("gin mode unknown: " + value)
}
mode_name = value
}
func Mode() string {
return mode_name
}
| bfosberry/gin | mode.go | GO | mit | 875 |