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
from django.conf.urls import patterns, include, url urlpatterns = patterns('', url(r'^$', 'webinterface.view.dashboard.main'), url(r'^dashboard/$', 'webinterface.view.dashboard.main'), url(r'^login/$', 'webinterface.view.login.main'), url(r'^login/ajax/$', 'webinterface.view.login.ajax'), url(r'^settings/$', 'webinterface.view.settings.main'), url(r'^settings/ajax/$', 'webinterface.view.settings.ajax'), url(r'^orders/$', 'webinterface.view.orders.main'), url(r'^orders/ajax/$', 'webinterface.view.orders.ajax'), )
cynja/coffeenator
webinterface/urls.py
Python
gpl-3.0
551
/* SPDX-FileCopyrightText: 2009-2013 Graeme Gott <graeme@gottcode.org> SPDX-License-Identifier: GPL-3.0-or-later */ #include "hole.h" #include <QBrush> #include <QPen> #include <QRadialGradient> //----------------------------------------------------------------------------- Hole::Hole(const QPoint& position, QGraphicsItem* parent) : QGraphicsEllipseItem(0, 0, 16, 16, parent) , m_peg(nullptr) { QRadialGradient gradient(QPointF(8,8), 8); gradient.setColorAt(0, QColor(0, 0, 0, 0)); gradient.setColorAt(1, QColor(0, 0, 0, 64)); setBrush(gradient); setPen(Qt::NoPen); setZValue(1); setPos(position.x() * 20 + 2, position.y() * 20 + 2); setFlag(QGraphicsItem::ItemIsMovable, false); } //----------------------------------------------------------------------------- void Hole::setHighlight(bool highlight) { setPen(!highlight ? Qt::NoPen : QPen(Qt::yellow, 2)); } //-----------------------------------------------------------------------------
gottcode/peg-e
src/hole.cpp
C++
gpl-3.0
964
<?php /** @package verysimple::Phreeze */ /** * import supporting libraries */ require_once ("verysimple/Phreeze/IRenderEngine.php"); require_once 'Twig/Autoloader.php'; Twig_Autoloader::register (); /** * TwigRenderEngine is an implementation of IRenderEngine that uses * the Twig template engine to render views * * @package verysimple::Phreeze * @author VerySimple Inc. * @copyright 1997-2011 VerySimple, Inc. * @license http://www.gnu.org/licenses/lgpl.html LGPL * @version 1.0 */ class TwigRenderEngine implements IRenderEngine { /** @var Twig_Environment */ public $twig; /** @var Twig_Loader_Filesystem */ private $loader; private $assignments = array (); /** * * @param string $templatePath * @param string $compilePath */ function __construct($templatePath = '', $compilePath = '') { $this->loader = new Twig_Loader_Filesystem ( $templatePath ); $this->twig = new Twig_Environment ( $this->loader, array ( 'cache' => $compilePath ) ); } /** * * @see IRenderEngine::assign() */ function assign($key, $value) { return $this->assignments [$key] = $value; } /** * * @see IRenderEngine::display() */ function display($template) { if (strpos ( '.', $template ) === false) $template .= '.html'; return $this->twig->display ( $template, $this->assignments ); } /** * * @see IRenderEngine::fetch() */ function fetch($template) { if (strpos ( '.', $template ) === false) $template .= '.html'; return $this->twig->render ( $template, $this->assignments ); } /** * * @see IRenderEngine::clear() */ function clear($key) { unset ( $this->assignments [$key] ); } /** * * @see IRenderEngine::clearAll() */ function clearAll() { $this->assignments = array (); } /** * * @see IRenderEngine::getAll() */ function getAll() { return $this->assignments; } } ?>
georgetye/openemr
portal/patient/fwk/libs/verysimple/Phreeze/TwigRenderEngine.php
PHP
gpl-3.0
1,903
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2012-2015 Marco Craveiro <marco.craveiro@gmail.com> * * 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 3 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 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * 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 Street, Fifth Floor, Boston, * MA 02110-1301, USA. * */ #ifndef MASD_DOGEN_GENERATION_CPP_TYPES_FORMATTERS_SERIALIZATION_PRIMITIVE_IMPLEMENTATION_FORMATTER_HPP #define MASD_DOGEN_GENERATION_CPP_TYPES_FORMATTERS_SERIALIZATION_PRIMITIVE_IMPLEMENTATION_FORMATTER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) #pragma once #endif #include <algorithm> #include "masd.dogen.generation.cpp/types/formatters/artefact_formatter_interface.hpp" namespace masd::dogen::generation::cpp::formatters::serialization { class primitive_implementation_formatter final : public artefact_formatter_interface { public: static std::string static_id(); public: std::string id() const override; annotations::archetype_location archetype_location() const override; const coding::meta_model::name& meta_name() const override; std::string family() const override; public: std::list<std::string> inclusion_dependencies( const formattables::dependencies_builder_factory& f, const coding::meta_model::element& e) const override; inclusion_support_types inclusion_support_type() const override; boost::filesystem::path inclusion_path( const formattables::locator& l, const coding::meta_model::name& n) const override; boost::filesystem::path full_path( const formattables::locator& l, const coding::meta_model::name& n) const override; public: extraction::meta_model::artefact format(const context& ctx, const coding::meta_model::element& e) const override; }; } #endif
DomainDrivenConsulting/dogen
projects/masd.dogen.generation.cpp/include/masd.dogen.generation.cpp/types/formatters/serialization/primitive_implementation_formatter.hpp
C++
gpl-3.0
2,371
/* * Copyright (C) 2010-2019 The ESPResSo project * * This file is part of ESPResSo. * * ESPResSo 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 3 of the License, or * (at your option) any later version. * * ESPResSo is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SCRIPT_INTERFACE_CONSTRAINTS_DETAIL_FIELDS_HPP #define SCRIPT_INTERFACE_CONSTRAINTS_DETAIL_FIELDS_HPP #include "core/field_coupling/fields/AffineMap.hpp" #include "core/field_coupling/fields/Constant.hpp" #include "core/field_coupling/fields/Interpolated.hpp" #include "core/field_coupling/fields/PlaneWave.hpp" #include "ScriptInterface.hpp" #include <boost/multi_array.hpp> namespace ScriptInterface { namespace Constraints { namespace detail { using namespace ::FieldCoupling::Fields; /** * @brief ScriptInterface implementations for the * various fields provided. * * These are separated from the Constraints because * they can be reused together with the fields themselves. */ template <typename Field> struct field_params_impl; template <typename T, size_t codim> struct field_params_impl<Constant<T, codim>> { static Constant<T, codim> make(const VariantMap &params) { return Constant<T, codim>{ get_value<typename Constant<T, codim>::value_type>(params, "value")}; } template <typename This> static std::vector<AutoParameter> params(const This &this_) { return {{"value", AutoParameter::read_only, [this_]() { return this_().value(); }}}; } }; template <typename T, size_t codim> struct field_params_impl<AffineMap<T, codim>> { using jacobian_type = typename AffineMap<T, codim>::jacobian_type; using value_type = typename AffineMap<T, codim>::value_type; static AffineMap<T, codim> make(const VariantMap &params) { return AffineMap<T, codim>{ get_value<jacobian_type>(params, "A"), get_value_or<value_type>(params, "b", value_type{})}; } template <typename This> static std::vector<AutoParameter> params(const This &this_) { return {{"A", AutoParameter::read_only, [this_]() { return this_().A(); }}, {"b", AutoParameter::read_only, [this_]() { return this_().b(); }}}; } }; template <typename T, size_t codim> struct field_params_impl<PlaneWave<T, codim>> { using jacobian_type = typename PlaneWave<T, codim>::jacobian_type; using value_type = typename PlaneWave<T, codim>::value_type; static PlaneWave<T, codim> make(const VariantMap &params) { return PlaneWave<T, codim>{get_value<value_type>(params, "amplitude"), get_value<value_type>(params, "wave_vector"), get_value<T>(params, "frequency"), get_value_or<T>(params, "phase", 0.)}; } template <typename This> static std::vector<AutoParameter> params(const This &this_) { return {{"amplitude", AutoParameter::read_only, [this_]() { return this_().amplitude(); }}, {"wave_vector", AutoParameter::read_only, [this_]() { return this_().k(); }}, {"frequency", AutoParameter::read_only, [this_]() { return this_().omega(); }}, {"phase", AutoParameter::read_only, [this_]() { return this_().phase(); }}}; } }; template <typename T, size_t codim> struct field_params_impl<Interpolated<T, codim>> { static Interpolated<T, codim> make(const VariantMap &params) { auto const field_data = get_value<std::vector<double>>(params, "_field_data"); auto const field_shape = get_value<Utils::Vector3i>(params, "_field_shape"); auto const field_codim = get_value<int>(params, "_field_codim"); if (field_codim != codim) { throw std::runtime_error( "Field data has the wrong dimensions, needs to be [n, m, o, " + std::to_string(codim) + ']'); } if (*std::min_element(field_shape.begin(), field_shape.end()) < 1) { throw std::runtime_error("Field is too small, needs to be at least " "one in all directions."); } auto const grid_spacing = get_value<Utils::Vector3d>(params, "grid_spacing"); auto const origin = -0.5 * grid_spacing; using field_data_type = typename Utils::decay_to_scalar<Utils::Vector<T, codim>>::type; auto array_ref = boost::const_multi_array_ref<field_data_type, 3>( reinterpret_cast<const field_data_type *>(field_data.data()), field_shape); return Interpolated<T, codim>{array_ref, grid_spacing, origin}; } template <typename This> static std::vector<AutoParameter> params(const This &this_) { return {{"grid_spacing", AutoParameter::read_only, [this_]() { return this_().grid_spacing(); }}, {"origin", AutoParameter::read_only, [this_]() { return this_().origin(); }}, {"_field_shape", AutoParameter::read_only, [this_]() { return this_().shape(); }}, {"_field_codim", AutoParameter::read_only, []() { return static_cast<int>(codim); }}, {"_field_data", AutoParameter::read_only, [this_]() { return this_().field_data_flat(); }}}; } }; template <typename Field, typename T> static std::vector<AutoParameter> field_parameters(const T &this_) { return field_params_impl<Field>::params(this_); } template <typename Field> Field make_field(const VariantMap &params) { return field_params_impl<Field>::make(params); } } // namespace detail } // namespace Constraints } // namespace ScriptInterface #endif
psci2195/espresso-ffans
src/script_interface/constraints/fields.hpp
C++
gpl-3.0
6,017
package routes import ( "crypto/sha256" "crypto/subtle" "database/sql" "encoding/hex" "html" "log" "math" "net/http" "strconv" "strings" c "github.com/Azareal/Gosora/common" p "github.com/Azareal/Gosora/common/phrases" qgen "github.com/Azareal/Gosora/query_gen" ) // A blank list to fill out that parameter in Page for routes which don't use it var tList []interface{} func AccountLogin(w http.ResponseWriter, r *http.Request, u *c.User, h *c.Header) c.RouteError { if u.Loggedin { return c.LocalError("You're already logged in.", w, r, u) } h.Title = p.GetTitlePhrase("login") return renderTemplate("login", w, r, h, c.Page{h, tList, nil}) } // TODO: Log failed attempted logins? // TODO: Lock IPS out if they have too many failed attempts? // TODO: Log unusual countries in comparison to the country a user usually logs in from? Alert the user about this? func AccountLoginSubmit(w http.ResponseWriter, r *http.Request, u *c.User) c.RouteError { if u.Loggedin { return c.LocalError("You're already logged in.", w, r, u) } name := c.SanitiseSingleLine(r.PostFormValue("username")) uid, e, requiresExtraAuth := c.Auth.Authenticate(name, r.PostFormValue("password")) if e != nil { // TODO: uid is currently set to 0 as authenticate fetches the user by username and password. Get the actual uid, so we can alert the user of attempted logins? What if someone takes advantage of the response times to deduce if an account exists? if !c.Config.DisableLoginLog { li := &c.LoginLogItem{UID: uid, Success: false, IP: u.GetIP()} if _, ie := li.Create(); ie != nil { return c.InternalError(ie, w, r) } } return c.LocalError(e.Error(), w, r, u) } // TODO: Take 2FA into account if !c.Config.DisableLoginLog { li := &c.LoginLogItem{UID: uid, Success: true, IP: u.GetIP()} if _, e = li.Create(); e != nil { return c.InternalError(e, w, r) } } // TODO: Do we want to slacken this by only doing it when the IP changes? if requiresExtraAuth { provSession, signedSession, e := c.Auth.CreateProvisionalSession(uid) if e != nil { return c.InternalError(e, w, r) } // TODO: Use the login log ID in the provisional cookie? c.Auth.SetProvisionalCookies(w, uid, provSession, signedSession) http.Redirect(w, r, "/accounts/mfa_verify/", http.StatusSeeOther) return nil } return loginSuccess(uid, w, r, u) } func loginSuccess(uid int, w http.ResponseWriter, r *http.Request, u *c.User) c.RouteError { userPtr, err := c.Users.Get(uid) if err != nil { return c.LocalError("Bad account", w, r, u) } *u = *userPtr var session string if u.Session == "" { session, err = c.Auth.CreateSession(uid) if err != nil { return c.InternalError(err, w, r) } } else { session = u.Session } c.Auth.SetCookies(w, uid, session) if u.IsAdmin { // Is this error check redundant? We already check for the error in PreRoute for the same IP // TODO: Should we be logging this? log.Printf("#%d has logged in with IP %s", uid, u.GetIP()) } http.Redirect(w, r, "/", http.StatusSeeOther) return nil } func extractCookie(name string, r *http.Request) (string, error) { cookie, err := r.Cookie(name) if err != nil { return "", err } return cookie.Value, nil } func mfaGetCookies(r *http.Request) (uid int, provSession, signedSession string, err error) { suid, err := extractCookie("uid", r) if err != nil { return 0, "", "", err } uid, err = strconv.Atoi(suid) if err != nil { return 0, "", "", err } provSession, err = extractCookie("provSession", r) if err != nil { return 0, "", "", err } signedSession, err = extractCookie("signedSession", r) return uid, provSession, signedSession, err } func mfaVerifySession(provSession, signedSession string, uid int) bool { bProvSession := []byte(provSession) bSignedSession := []byte(signedSession) bUid := []byte(strconv.Itoa(uid)) h := sha256.New() h.Write([]byte(c.SessionSigningKeyBox.Load().(string))) h.Write(bProvSession) h.Write(bUid) expected := hex.EncodeToString(h.Sum(nil)) if subtle.ConstantTimeCompare(bSignedSession, []byte(expected)) == 1 { return true } h = sha256.New() h.Write([]byte(c.OldSessionSigningKeyBox.Load().(string))) h.Write(bProvSession) h.Write(bUid) expected = hex.EncodeToString(h.Sum(nil)) return subtle.ConstantTimeCompare(bSignedSession, []byte(expected)) == 1 } func AccountLoginMFAVerify(w http.ResponseWriter, r *http.Request, u *c.User, h *c.Header) c.RouteError { if u.Loggedin { return c.LocalError("You're already logged in.", w, r, u) } h.Title = p.GetTitlePhrase("login_mfa_verify") uid, provSession, signedSession, err := mfaGetCookies(r) if err != nil { return c.LocalError("Invalid cookie", w, r, u) } if !mfaVerifySession(provSession, signedSession, uid) { return c.LocalError("Invalid session", w, r, u) } return renderTemplate("login_mfa_verify", w, r, h, c.Page{h, tList, nil}) } func AccountLoginMFAVerifySubmit(w http.ResponseWriter, r *http.Request, u *c.User) c.RouteError { uid, provSession, signedSession, err := mfaGetCookies(r) if err != nil { return c.LocalError("Invalid cookie", w, r, u) } if !mfaVerifySession(provSession, signedSession, uid) { return c.LocalError("Invalid session", w, r, u) } token := r.PostFormValue("mfa_token") err = c.Auth.ValidateMFAToken(token, uid) if err != nil { return c.LocalError(err.Error(), w, r, u) } return loginSuccess(uid, w, r, u) } func AccountLogout(w http.ResponseWriter, r *http.Request, u *c.User) c.RouteError { c.Auth.Logout(w, u.ID) http.Redirect(w, r, "/", http.StatusSeeOther) return nil } func AccountRegister(w http.ResponseWriter, r *http.Request, u *c.User, h *c.Header) c.RouteError { if u.Loggedin { return c.LocalError("You're already logged in.", w, r, u) } h.Title = p.GetTitlePhrase("register") h.AddScriptAsync("register.js") var token string if c.Config.DisableJSAntispam { h := sha256.New() h.Write([]byte(c.JSTokenBox.Load().(string))) h.Write([]byte(u.GetIP())) token = hex.EncodeToString(h.Sum(nil)) } return renderTemplate("register", w, r, h, c.RegisterPage{h, h.Settings["activation_type"] != 2, token, nil}) } func isNumeric(data string) (numeric bool) { for _, ch := range data { if ch < 48 || ch > 57 { return false } } return true } func AccountRegisterSubmit(w http.ResponseWriter, r *http.Request, user *c.User) c.RouteError { headerLite, _ := c.SimpleUserCheck(w, r, user) // TODO: Should we push multiple validation errors to the user instead of just one? regSuccess := true regErrMsg := "" regErrReason := "" regError := func(userMsg, reason string) { regSuccess = false if regErrMsg == "" { regErrMsg = userMsg } regErrReason += reason + "|" } if r.PostFormValue("tos") != "0" { regError(p.GetErrorPhrase("register_might_be_machine"), "trap-question") } { h := sha256.New() h.Write([]byte(c.JSTokenBox.Load().(string))) h.Write([]byte(user.GetIP())) if !c.Config.DisableJSAntispam { if r.PostFormValue("golden-watch") != hex.EncodeToString(h.Sum(nil)) { regError(p.GetErrorPhrase("register_might_be_machine"), "js-antispam") } } else { if r.PostFormValue("areg") != hex.EncodeToString(h.Sum(nil)) { regError(p.GetErrorPhrase("register_might_be_machine"), "token") } } } name := c.SanitiseSingleLine(r.PostFormValue("name")) if name == "" { regError(p.GetErrorPhrase("register_need_username"), "no-username") } // This is so a numeric name won't interfere with mentioning a user by ID, there might be a better way of doing this like perhaps !@ to mean IDs and @ to mean usernames in the pre-parser nameBits := strings.Split(name, " ") if isNumeric(nameBits[0]) { regError(p.GetErrorPhrase("register_first_word_numeric"), "numeric-name") } if strings.Contains(name, "http://") || strings.Contains(name, "https://") || strings.Contains(name, "ftp://") || strings.Contains(name, "ssh://") { regError(p.GetErrorPhrase("register_url_username"), "url-name") } // TODO: Add a dedicated function for validating emails email := c.SanitiseSingleLine(r.PostFormValue("email")) if headerLite.Settings["activation_type"] == 2 && email == "" { regError(p.GetErrorPhrase("register_need_email"), "no-email") } if c.HasSuspiciousEmail(email) { regError(p.GetErrorPhrase("register_suspicious_email"), "suspicious-email") } password := r.PostFormValue("password") // ? Move this into Create()? What if we want to programatically set weak passwords for tests? err := c.WeakPassword(password, name, email) if err != nil { regError(err.Error(), "weak-password") } else { // Do the two inputted passwords match..? confirmPassword := r.PostFormValue("confirm_password") if password != confirmPassword { regError(p.GetErrorPhrase("register_password_mismatch"), "password-mismatch") } } regLog := c.RegLogItem{Username: name, Email: email, FailureReason: regErrReason, Success: regSuccess, IP: user.GetIP()} if !c.Config.DisableRegLog && regSuccess { if _, e := regLog.Create(); e != nil { return c.InternalError(e, w, r) } } if !regSuccess { return c.LocalError(regErrMsg, w, r, user) } var active bool var group int switch headerLite.Settings["activation_type"] { case 1: // Activate All active = true group = c.Config.DefaultGroup default: // Anything else. E.g. Admin Activation or Email Activation. group = c.Config.ActivationGroup } pushLog := func(reason string) error { if !c.Config.DisableRegLog { regLog.FailureReason += reason + "|" _, e := regLog.Create() return e } return nil } canonEmail := c.CanonEmail(email) uid, err := c.Users.Create(name, password, canonEmail, group, active) if err != nil { regLog.Success = false if err == c.ErrAccountExists { err = pushLog("username-exists") if err != nil { return c.InternalError(err, w, r) } return c.LocalError(p.GetErrorPhrase("register_username_unavailable"), w, r, user) } else if err == c.ErrLongUsername { err = pushLog("username-too-long") if err != nil { return c.InternalError(err, w, r) } return c.LocalError(p.GetErrorPhrase("register_username_too_long_prefix")+strconv.Itoa(c.Config.MaxUsernameLength), w, r, user) } err2 := pushLog("internal-error") if err2 != nil { return c.InternalError(err2, w, r) } return c.InternalError(err, w, r) } u, err := c.Users.Get(uid) if err == sql.ErrNoRows { return c.LocalError("You no longer exist.", w, r, user) } else if err != nil { return c.InternalError(err, w, r) } err = c.GroupPromotions.PromoteIfEligible(u, u.Level, u.Posts, u.CreatedAt) if err != nil { return c.InternalError(err, w, r) } u.CacheRemove() session, err := c.Auth.CreateSession(uid) if err != nil { return c.InternalError(err, w, r) } c.Auth.SetCookies(w, uid, session) // Check if this user actually owns this email, if email activation is on, automatically flip their account to active when the email is validated. Validation is also useful for determining whether this user should receive any alerts, etc. via email if c.Site.EnableEmails && canonEmail != "" { token, err := c.GenerateSafeString(80) if err != nil { return c.InternalError(err, w, r) } // TODO: Add an EmailStore and move this there _, err = qgen.NewAcc().Insert("emails").Columns("email,uid,validated,token").Fields("?,?,?,?").Exec(canonEmail, uid, 0, token) if err != nil { return c.InternalError(err, w, r) } err = c.SendActivationEmail(name, canonEmail, token) if err != nil { return c.LocalError(p.GetErrorPhrase("register_email_fail"), w, r, user) } } http.Redirect(w, r, "/", http.StatusSeeOther) return nil } // TODO: Figure a way of making this into middleware? func accountEditHead(titlePhrase string, w http.ResponseWriter, r *http.Request, u *c.User, h *c.Header) { h.Title = p.GetTitlePhrase(titlePhrase) h.Path = "/user/edit/" h.AddSheet(h.Theme.Name + "/account.css") h.AddScriptAsync("account.js") } func AccountEdit(w http.ResponseWriter, r *http.Request, u *c.User, h *c.Header) c.RouteError { accountEditHead("account", w, r, u, h) switch { case r.FormValue("avatar_updated") == "1": h.AddNotice("account_avatar_updated") case r.FormValue("name_updated") == "1": h.AddNotice("account_name_updated") case r.FormValue("mfa_setup_success") == "1": h.AddNotice("account_mfa_setup_success") } // TODO: Find a more efficient way of doing this mfaSetup := false _, err := c.MFAstore.Get(u.ID) if err != sql.ErrNoRows && err != nil { return c.InternalError(err, w, r) } else if err != sql.ErrNoRows { mfaSetup = true } // Normalise the score so that the user sees their relative progress to the next level rather than showing them their total score prevScore := c.GetLevelScore(u.Level) score := u.Score //score = 23 currentScore := score - prevScore nextScore := c.GetLevelScore(u.Level+1) - prevScore //perc := int(math.Ceil((float64(nextScore) / float64(currentScore)) * 100)) * 2 perc := int(math.Floor((float64(currentScore) / float64(nextScore)) * 100)) // * 2 pi := c.Account{h, "dashboard", "account_own_edit", c.AccountDashPage{h, mfaSetup, currentScore, nextScore, u.Level + 1, perc}} return renderTemplate("account", w, r, h, pi) } //edit_password func AccountEditPassword(w http.ResponseWriter, r *http.Request, u *c.User, h *c.Header) c.RouteError { accountEditHead("account_password", w, r, u, h) return renderTemplate("account_own_edit_password", w, r, h, c.Page{h, tList, nil}) } // TODO: Require re-authentication if the user hasn't logged in in a while func AccountEditPasswordSubmit(w http.ResponseWriter, r *http.Request, u *c.User) c.RouteError { _, ferr := c.SimpleUserCheck(w, r, u) if ferr != nil { return ferr } var realPassword, salt string currentPassword := r.PostFormValue("current-password") newPassword := r.PostFormValue("new-password") confirmPassword := r.PostFormValue("confirm-password") // TODO: Use a reusable statement err := qgen.NewAcc().Select("users").Columns("password,salt").Where("uid=?").QueryRow(u.ID).Scan(&realPassword, &salt) if err == sql.ErrNoRows { return c.LocalError("Your account no longer exists.", w, r, u) } else if err != nil { return c.InternalError(err, w, r) } err = c.CheckPassword(realPassword, currentPassword, salt) if err == c.ErrMismatchedHashAndPassword { return c.LocalError("That's not the correct password.", w, r, u) } else if err != nil { return c.InternalError(err, w, r) } if newPassword != confirmPassword { return c.LocalError("The two passwords don't match.", w, r, u) } c.SetPassword(u.ID, newPassword) // TODO: Limited version of WeakPassword() // Log the user out as a safety precaution c.Auth.ForceLogout(u.ID) http.Redirect(w, r, "/", http.StatusSeeOther) return nil } func AccountEditAvatarSubmit(w http.ResponseWriter, r *http.Request, u *c.User) c.RouteError { _, ferr := c.SimpleUserCheck(w, r, u) if ferr != nil { return ferr } if !u.Perms.UploadAvatars { return c.NoPermissions(w, r, u) } ext, ferr := c.UploadAvatar(w, r, u, u.ID) if ferr != nil { return ferr } ferr = c.ChangeAvatar("."+ext, w, r, u) if ferr != nil { return ferr } // TODO: Only schedule a resize if the avatar isn't tiny err := u.ScheduleAvatarResize() if err != nil { return c.InternalError(err, w, r) } http.Redirect(w, r, "/user/edit/?avatar_updated=1", http.StatusSeeOther) return nil } func AccountEditRevokeAvatarSubmit(w http.ResponseWriter, r *http.Request, u *c.User) c.RouteError { _, ferr := c.SimpleUserCheck(w, r, u) if ferr != nil { return ferr } ferr = c.ChangeAvatar("", w, r, u) if ferr != nil { return ferr } http.Redirect(w, r, "/user/edit/?avatar_updated=1", http.StatusSeeOther) return nil } func AccountEditUsernameSubmit(w http.ResponseWriter, r *http.Request, u *c.User) c.RouteError { _, ferr := c.SimpleUserCheck(w, r, u) if ferr != nil { return ferr } newName := c.SanitiseSingleLine(r.PostFormValue("new-name")) if newName == "" { return c.LocalError("You can't leave your username blank", w, r, u) } err := u.ChangeName(newName) if err != nil { return c.LocalError("Unable to change names. Does someone else already have this name?", w, r, u) } http.Redirect(w, r, "/user/edit/?name_updated=1", http.StatusSeeOther) return nil } func AccountEditMFA(w http.ResponseWriter, r *http.Request, u *c.User, h *c.Header) c.RouteError { accountEditHead("account_mfa", w, r, u, h) mfaItem, err := c.MFAstore.Get(u.ID) if err != sql.ErrNoRows && err != nil { return c.InternalError(err, w, r) } else if err == sql.ErrNoRows { return c.LocalError("Two-factor authentication hasn't been setup on your account", w, r, u) } pi := c.Page{h, tList, mfaItem.Scratch} return renderTemplate("account_own_edit_mfa", w, r, h, pi) } // If not setup, generate a string, otherwise give an option to disable mfa given the right code func AccountEditMFASetup(w http.ResponseWriter, r *http.Request, u *c.User, h *c.Header) c.RouteError { accountEditHead("account_mfa_setup", w, r, u, h) // Flash an error if mfa is already setup _, e := c.MFAstore.Get(u.ID) if e != sql.ErrNoRows && e != nil { return c.InternalError(e, w, r) } else if e != sql.ErrNoRows { return c.LocalError("You have already setup two-factor authentication", w, r, u) } // TODO: Entitise this? code, e := c.GenerateGAuthSecret() if e != nil { return c.InternalError(e, w, r) } pi := c.Page{h, tList, c.FriendlyGAuthSecret(code)} return renderTemplate("account_own_edit_mfa_setup", w, r, h, pi) } // Form should bounce the random mfa secret back and the otp to be verified server-side to reduce the chances of a bug arising on the JS side which makes every code mismatch func AccountEditMFASetupSubmit(w http.ResponseWriter, r *http.Request, u *c.User) c.RouteError { _, ferr := c.SimpleUserCheck(w, r, u) if ferr != nil { return ferr } // Flash an error if mfa is already setup _, err := c.MFAstore.Get(u.ID) if err != sql.ErrNoRows && err != nil { return c.InternalError(err, w, r) } else if err != sql.ErrNoRows { return c.LocalError("You have already setup two-factor authentication", w, r, u) } code := r.PostFormValue("code") otp := r.PostFormValue("otp") ok, err := c.VerifyGAuthToken(code, otp) if err != nil { //fmt.Println("err: ", err) return c.LocalError("Something weird happened", w, r, u) // TODO: Log this error? } // TODO: Use AJAX for this if !ok { return c.LocalError("The token isn't right", w, r, u) } // TODO: How should we handle races where a mfa key is already setup? Right now, it's a fairly generic error, maybe try parsing the error message? err = c.MFAstore.Create(code, u.ID) if err != nil { return c.InternalError(err, w, r) } http.Redirect(w, r, "/user/edit/?mfa_setup_success=1", http.StatusSeeOther) return nil } // TODO: Implement this func AccountEditMFADisableSubmit(w http.ResponseWriter, r *http.Request, u *c.User) c.RouteError { _, ferr := c.SimpleUserCheck(w, r, u) if ferr != nil { return ferr } // Flash an error if mfa is already setup mfaItem, err := c.MFAstore.Get(u.ID) if err != sql.ErrNoRows && err != nil { return c.InternalError(err, w, r) } else if err == sql.ErrNoRows { return c.LocalError("You don't have two-factor enabled on your account", w, r, u) } err = mfaItem.Delete() if err != nil { return c.InternalError(err, w, r) } http.Redirect(w, r, "/user/edit/?mfa_disabled=1", http.StatusSeeOther) return nil } func AccountEditPrivacy(w http.ResponseWriter, r *http.Request, u *c.User, h *c.Header) c.RouteError { accountEditHead("account_privacy", w, r, u, h) profileComments := u.Privacy.ShowComments receiveConvos := u.Privacy.AllowMessage enableEmbeds := !c.DefaultParseSettings.NoEmbed if u.ParseSettings != nil { enableEmbeds = !u.ParseSettings.NoEmbed } pi := c.Account{h, "privacy", "account_own_edit_privacy", c.AccountPrivacyPage{h, profileComments, receiveConvos, enableEmbeds}} return renderTemplate("account", w, r, h, pi) } func AccountEditPrivacySubmit(w http.ResponseWriter, r *http.Request, u *c.User) c.RouteError { //headerLite, _ := c.SimpleUserCheck(w, r, u) sProfileComments := r.FormValue("profile_comments") sEnableEmbeds := r.FormValue("enable_embeds") oProfileComments := r.FormValue("o_profile_comments") oEnableEmbeds := r.FormValue("o_enable_embeds") if sProfileComments != oProfileComments || sEnableEmbeds != oEnableEmbeds { profileComments, e := strconv.Atoi(sProfileComments) enableEmbeds, e2 := strconv.Atoi(sEnableEmbeds) if e != nil || e2 != nil { return c.LocalError("malformed integer", w, r, u) } e = u.UpdatePrivacy(profileComments, enableEmbeds) if e == c.ErrProfileCommentsOutOfBounds || e == c.ErrEnableEmbedsOutOfBounds { return c.LocalError(e.Error(), w, r, u) } else if e != nil { return c.InternalError(e, w, r) } } http.Redirect(w, r, "/user/edit/privacy/?updated=1", http.StatusSeeOther) return nil } func AccountEditEmail(w http.ResponseWriter, r *http.Request, u *c.User, h *c.Header) c.RouteError { accountEditHead("account_email", w, r, u, h) emails, err := c.Emails.GetEmailsByUser(u) if err != nil { return c.InternalError(err, w, r) } // Was this site migrated from another forum software? Most of them don't have multiple emails for a single user. // This also applies when the admin switches site.EnableEmails on after having it off for a while. if len(emails) == 0 && u.Email != "" { emails = append(emails, c.Email{UserID: u.ID, Email: u.Email, Validated: false, Primary: true}) } if !c.Site.EnableEmails { h.AddNotice("account_mail_disabled") } if r.FormValue("verified") == "1" { h.AddNotice("account_mail_verify_success") } pi := c.Account{h, "edit_emails", "account_own_edit_email", c.EmailListPage{h, emails}} return renderTemplate("account", w, r, h, pi) } func AccountEditEmailAddSubmit(w http.ResponseWriter, r *http.Request, u *c.User) c.RouteError { email := c.SanitiseSingleLine(r.PostFormValue("email")) canonEmail := c.CanonEmail(email) _, err := c.Emails.Get(u, canonEmail) if err == nil { return c.LocalError("You have already added this email.", w, r, u) } else if err != sql.ErrNoRows && err != nil { return c.InternalError(err, w, r) } var token string if c.Site.EnableEmails { token, err = c.GenerateSafeString(80) if err != nil { return c.InternalError(err, w, r) } } err = c.Emails.Add(u.ID, canonEmail, token) if err != nil { return c.InternalError(err, w, r) } if c.Site.EnableEmails { err = c.SendValidationEmail(u.Name, canonEmail, token) if err != nil { return c.LocalError(p.GetErrorPhrase("register_email_fail"), w, r, u) } } http.Redirect(w, r, "/user/edit/email/?added=1", http.StatusSeeOther) return nil } func AccountEditEmailRemoveSubmit(w http.ResponseWriter, r *http.Request, u *c.User) c.RouteError { headerLite, _ := c.SimpleUserCheck(w, r, u) email := c.SanitiseSingleLine(r.PostFormValue("email")) canonEmail := c.CanonEmail(email) // Quick and dirty check _, err := c.Emails.Get(u, canonEmail) if err == sql.ErrNoRows { return c.LocalError("This email isn't set on this user.", w, r, u) } else if err != nil { return c.InternalError(err, w, r) } if headerLite.Settings["activation_type"] == 2 && u.Email == canonEmail { return c.LocalError("You can't remove your primary email when mandatory email activation is enabled.", w, r, u) } err = c.Emails.Delete(u.ID, canonEmail) if err != nil { return c.InternalError(err, w, r) } http.Redirect(w, r, "/user/edit/email/?removed=1", http.StatusSeeOther) return nil } // TODO: Should we make this an AnonAction so someone can do this without being logged in? func AccountEditEmailTokenSubmit(w http.ResponseWriter, r *http.Request, user *c.User, token string) c.RouteError { header, ferr := c.UserCheck(w, r, user) if ferr != nil { return ferr } if !c.Site.EnableEmails { http.Redirect(w, r, "/user/edit/email/", http.StatusSeeOther) return nil } targetEmail := c.Email{UserID: user.ID} emails, err := c.Emails.GetEmailsByUser(user) if err == sql.ErrNoRows { return c.LocalError("A verification email was never sent for you!", w, r, user) } else if err != nil { // TODO: Better error if we don't have an email or it's not in the emails table for some reason return c.LocalError("You are not logged in", w, r, user) } for _, email := range emails { if subtle.ConstantTimeCompare([]byte(email.Token), []byte(token)) == 1 { targetEmail = email } } if len(emails) == 0 { return c.LocalError("A verification email was never sent for you!", w, r, user) } if targetEmail.Token == "" { return c.LocalError("That's not a valid token!", w, r, user) } err = c.Emails.VerifyEmail(user.Email) if err != nil { return c.InternalError(err, w, r) } // If Email Activation is on, then activate the account while we're here if header.Settings["activation_type"] == 2 { if err = user.Activate(); err != nil { return c.InternalError(err, w, r) } u2, err := c.Users.Get(user.ID) if err == sql.ErrNoRows { return c.LocalError("The user no longer exists.", w, r, user) } else if err != nil { return c.InternalError(err, w, r) } err = c.GroupPromotions.PromoteIfEligible(u2, u2.Level, u2.Posts, u2.CreatedAt) if err != nil { return c.InternalError(err, w, r) } u2.CacheRemove() } http.Redirect(w, r, "/user/edit/email/?verified=1", http.StatusSeeOther) return nil } func AccountLogins(w http.ResponseWriter, r *http.Request, u *c.User, h *c.Header) c.RouteError { accountEditHead("account_logins", w, r, u, h) page, _ := strconv.Atoi(r.FormValue("page")) perPage := 12 offset, page, lastPage := c.PageOffset(c.LoginLogs.CountUser(u.ID), page, perPage) logs, err := c.LoginLogs.GetOffset(u.ID, offset, perPage) if err != nil { return c.InternalError(err, w, r) } pageList := c.Paginate(page, lastPage, 5) pi := c.Account{h, "logins", "account_logins", c.AccountLoginsPage{h, logs, c.Paginator{pageList, page, lastPage}}} return renderTemplate("account", w, r, h, pi) } func AccountBlocked(w http.ResponseWriter, r *http.Request, user *c.User, h *c.Header) c.RouteError { accountEditHead("account_blocked", w, r, user, h) page, _ := strconv.Atoi(r.FormValue("page")) perPage := 12 offset, page, lastPage := c.PageOffset(c.UserBlocks.BlockedByCount(user.ID), page, perPage) uids, err := c.UserBlocks.BlockedByOffset(user.ID, offset, perPage) if err != nil { return c.InternalError(err, w, r) } var blocks []*c.User for _, uid := range uids { u, err := c.Users.Get(uid) if err != nil { return c.InternalError(err, w, r) } blocks = append(blocks, u) } pageList := c.Paginate(page, lastPage, 5) pi := c.Account{h, "blocked", "account_blocked", c.AccountBlocksPage{h, blocks, c.Paginator{pageList, page, lastPage}}} return renderTemplate("account", w, r, h, pi) } func LevelList(w http.ResponseWriter, r *http.Request, u *c.User, h *c.Header) c.RouteError { h.Title = p.GetTitlePhrase("account_level_list") fScores := c.GetLevels(21) levels := make([]c.LevelListItem, len(fScores)) for i, fScore := range fScores { if i == 0 { continue } var status string if u.Level > (i - 1) { status = "complete" } else if u.Level < (i - 1) { status = "future" } else { status = "inprogress" } iScore := int(math.Ceil(fScore)) //perc := int(math.Ceil((fScore/float64(u.Score))*100)) * 2 perc := int(math.Ceil((float64(u.Score) / fScore) * 100)) levels[i] = c.LevelListItem{i - 1, iScore, status, perc} } return renderTemplate("level_list", w, r, h, c.LevelListPage{h, levels[1:]}) } func Alerts(w http.ResponseWriter, r *http.Request, u *c.User, h *c.Header) c.RouteError { return nil } func AccountPasswordReset(w http.ResponseWriter, r *http.Request, u *c.User, h *c.Header) c.RouteError { if u.Loggedin { return c.LocalError("You're already logged in.", w, r, u) } if !c.Site.EnableEmails { return c.LocalError(p.GetNoticePhrase("account_mail_disabled"), w, r, u) } if r.FormValue("email_sent") == "1" { h.AddNotice("password_reset_email_sent") } h.Title = p.GetTitlePhrase("password_reset") return renderTemplate("password_reset", w, r, h, c.Page{h, tList, nil}) } // TODO: Ratelimit this func AccountPasswordResetSubmit(w http.ResponseWriter, r *http.Request, user *c.User) c.RouteError { if user.Loggedin { return c.LocalError("You're already logged in.", w, r, user) } if !c.Site.EnableEmails { return c.LocalError(p.GetNoticePhrase("account_mail_disabled"), w, r, user) } username := r.PostFormValue("username") tuser, err := c.Users.GetByName(username) if err == sql.ErrNoRows { // Someone trying to stir up trouble? http.Redirect(w, r, "/accounts/password-reset/?email_sent=1", http.StatusSeeOther) return nil } else if err != nil { return c.InternalError(err, w, r) } token, err := c.GenerateSafeString(80) if err != nil { return c.InternalError(err, w, r) } // TODO: Move these queries somewhere else var disc string err = qgen.NewAcc().Select("password_resets").Columns("createdAt").DateCutoff("createdAt", 1, "hour").QueryRow().Scan(&disc) if err != nil && err != sql.ErrNoRows { return c.InternalError(err, w, r) } if err == nil { return c.LocalError("You can only send a password reset email for a user once an hour", w, r, user) } count, err := qgen.NewAcc().Count("password_resets").DateCutoff("createdAt", 6, "hour").Total() if err != nil && err != sql.ErrNoRows { return c.InternalError(err, w, r) } if count >= 3 { return c.LocalError("You can only send a password reset email for a user three times every six hours", w, r, user) } count, err = qgen.NewAcc().Count("password_resets").DateCutoff("createdAt", 12, "hour").Total() if err != nil && err != sql.ErrNoRows { return c.InternalError(err, w, r) } if count >= 4 { return c.LocalError("You can only send a password reset email for a user four times every twelve hours", w, r, user) } err = c.PasswordResetter.Create(tuser.Email, tuser.ID, token) if err != nil { return c.InternalError(err, w, r) } var s string if c.Config.SslSchema { s = "s" } err = c.SendEmail(tuser.Email, p.GetTmplPhrase("password_reset_subject"), p.GetTmplPhrasef("password_reset_body", tuser.Name, "http"+s+"://"+c.Site.URL+"/accounts/password-reset/token/?uid="+strconv.Itoa(tuser.ID)+"&token="+token)) if err != nil { return c.LocalError(p.GetErrorPhrase("password_reset_email_fail"), w, r, user) } http.Redirect(w, r, "/accounts/password-reset/?email_sent=1", http.StatusSeeOther) return nil } func AccountPasswordResetToken(w http.ResponseWriter, r *http.Request, u *c.User, h *c.Header) c.RouteError { if u.Loggedin { return c.LocalError("You're already logged in.", w, r, u) } // TODO: Find a way to flash this notice /*if r.FormValue("token_verified") == "1" { h.AddNotice("password_reset_token_token_verified") }*/ uid, err := strconv.Atoi(r.FormValue("uid")) if err != nil { return c.LocalError("Invalid uid", w, r, u) } token := r.FormValue("token") err = c.PasswordResetter.ValidateToken(uid, token) if err == sql.ErrNoRows || err == c.ErrBadResetToken { return c.LocalError("This reset token has expired.", w, r, u) } else if err != nil { return c.InternalError(err, w, r) } _, err = c.MFAstore.Get(uid) if err != sql.ErrNoRows && err != nil { return c.InternalError(err, w, r) } mfa := err != sql.ErrNoRows h.Title = p.GetTitlePhrase("password_reset_token") return renderTemplate("password_reset_token", w, r, h, c.ResetPage{h, uid, html.EscapeString(token), mfa}) } func AccountPasswordResetTokenSubmit(w http.ResponseWriter, r *http.Request, u *c.User) c.RouteError { if u.Loggedin { return c.LocalError("You're already logged in.", w, r, u) } uid, err := strconv.Atoi(r.FormValue("uid")) if err != nil { return c.LocalError("Invalid uid", w, r, u) } if !c.Users.Exists(uid) { return c.LocalError("This reset token has expired.", w, r, u) } err = c.PasswordResetter.ValidateToken(uid, r.FormValue("token")) if err == sql.ErrNoRows || err == c.ErrBadResetToken { return c.LocalError("This reset token has expired.", w, r, u) } else if err != nil { return c.InternalError(err, w, r) } mfaToken := r.PostFormValue("mfa_token") err = c.Auth.ValidateMFAToken(mfaToken, uid) if err != nil && err != c.ErrNoMFAToken { return c.LocalError(err.Error(), w, r, u) } newPassword := r.PostFormValue("password") confirmPassword := r.PostFormValue("confirm_password") if newPassword != confirmPassword { return c.LocalError("The two passwords don't match.", w, r, u) } c.SetPassword(uid, newPassword) // TODO: Limited version of WeakPassword() err = c.PasswordResetter.FlushTokens(uid) if err != nil { return c.InternalError(err, w, r) } // Log the user out as a safety precaution c.Auth.ForceLogout(uid) //http.Redirect(w, r, "/accounts/password-reset/token/?token_verified=1", http.StatusSeeOther) http.Redirect(w, r, "/", http.StatusSeeOther) return nil }
Azareal/Gosora
routes/account.go
GO
gpl-3.0
33,125
/* * Copyright 2010-2020 OpenXcom Developers. * * This file is part of OpenXcom. * * OpenXcom 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 3 of the License, or * (at your option) any later version. * * OpenXcom is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenXcom. If not, see <http://www.gnu.org/licenses/>. */ #include "CraftEquipmentState.h" //#include <algorithm> //#include <climits> //#include <sstream> #include "../Battlescape/BattlescapeGenerator.h" #include "../Battlescape/InventoryState.h" #include "../Engine/Action.h" #include "../Engine/Game.h" #include "../Engine/LocalizedText.h" #include "../Engine/Options.h" #include "../Engine/Palette.h" #include "../Engine/Screen.h" #include "../Engine/Timer.h" #include "../Interface/Text.h" #include "../Interface/TextButton.h" #include "../Interface/TextList.h" #include "../Interface/Window.h" #include "../Menu/ErrorMessageState.h" #include "../Resource/ResourcePack.h" #include "../Ruleset/RuleArmor.h" //#include "../Ruleset/RuleCraft.h" #include "../Ruleset/RuleInterface.h" #include "../Ruleset/RuleItem.h" #include "../Ruleset/Ruleset.h" #include "../Savegame/Base.h" #include "../Savegame/Craft.h" #include "../Savegame/ItemContainer.h" #include "../Savegame/SavedBattleGame.h" #include "../Savegame/SavedGame.h" #include "../Savegame/Vehicle.h" namespace OpenXcom { /** * Initializes all the elements in the CraftEquipment screen. * @param base - pointer to the Base to get info from * @param craftId - ID of the selected craft */ CraftEquipmentState::CraftEquipmentState( Base* const base, size_t craftId) : _base(base), _craft(base->getCrafts()->at(craftId)), _rules(_game->getRuleset()), _row(0u), _unitOrder(0u), _recall(0u), _isQuickBattle(_game->getSavedGame()->getMonthsElapsed() == -1) { _window = new Window(this); _txtTitle = new Text(300, 16, 16, 8); _txtBaseLabel = new Text( 80, 9, 224, 8); _txtSpace = new Text(110, 9, 16, 26); _txtLoad = new Text(110, 9, 171, 26); _txtItem = new Text(144, 9, 16, 36); _txtStores = new Text( 50, 9, 171, 36); _txtCraft = new Text( 50, 9, 256, 36); _lstEquipment = new TextList(285, 129, 16, 45); _btnClear = new TextButton(94, 16, 16, 177); _btnInventory = new TextButton(94, 16, 113, 177); _btnOk = new TextButton(94, 16, 210, 177); setInterface("craftEquipment"); _loadColor = static_cast<Uint8>(_rules->getInterface("craftEquipment")->getElement("ammoColor")->color); add(_window, "window", "craftEquipment"); add(_txtTitle, "text", "craftEquipment"); add(_txtBaseLabel, "text", "craftEquipment"); add(_txtSpace, "text", "craftEquipment"); add(_txtLoad, "text", "craftEquipment"); add(_txtItem, "text", "craftEquipment"); add(_txtStores, "text", "craftEquipment"); add(_txtCraft, "text", "craftEquipment"); add(_lstEquipment, "list", "craftEquipment"); add(_btnClear, "button", "craftEquipment"); add(_btnInventory, "button", "craftEquipment"); add(_btnOk, "button", "craftEquipment"); if (_isQuickBattle == false) { _txtCost = new Text(150, 9, 24, -10); add(_txtCost, "text", "craftEquipment"); } centerSurfaces(); _window->setBackground(_game->getResourcePack()->getSurface("BACK04.SCR")); _btnClear->setText(tr("STR_UNLOAD_CRAFT")); _btnClear->onMouseClick( static_cast<ActionHandler>(&CraftEquipmentState::btnUnloadCraftClick)); _btnClear->onKeyboardPress( static_cast<ActionHandler>(&CraftEquipmentState::btnUnloadCraftClick), SDLK_u); _btnInventory->setText(tr("STR_LOADOUT")); _btnInventory->onMouseClick( static_cast<ActionHandler>(&CraftEquipmentState::btnInventoryClick)); _btnInventory->onKeyboardPress( static_cast<ActionHandler>(&CraftEquipmentState::btnInventoryClick), SDLK_i); _btnOk->setText(tr("STR_OK")); _btnOk->onMouseClick( static_cast<ActionHandler>(&CraftEquipmentState::btnOkClick)); _btnOk->onKeyboardPress(static_cast<ActionHandler>(&CraftEquipmentState::btnOkClick), Options::keyCancel); _btnOk->onKeyboardPress(static_cast<ActionHandler>(&CraftEquipmentState::btnOkClick), Options::keyOk); _btnOk->onKeyboardPress(static_cast<ActionHandler>(&CraftEquipmentState::btnOkClick), Options::keyOkKeypad); _txtTitle->setText(tr("STR_EQUIPMENT_FOR_CRAFT").arg(_craft->getLabel(_game->getLanguage()))); _txtTitle->setBig(); _txtBaseLabel->setAlign(ALIGN_RIGHT); _txtBaseLabel->setText(_base->getLabel()); _txtItem->setText(tr("STR_ITEM")); _txtStores->setText(tr("STR_STORES")); _txtCraft->setText(tr("STR_CRAFT")); _txtSpace->setText(tr("STR_SPACE_CREW_HWP_FREE_") .arg(_craft->getQtySoldiers()) .arg(_craft->getQtyVehicles()) .arg(_craft->getSpaceAvailable())); _lstEquipment->setColumns(3, 147,85,41); _lstEquipment->setBackground(_window); _lstEquipment->setSelectable(); _lstEquipment->setArrow(189, ARROW_HORIZONTAL); _lstEquipment->onRightArrowPress( static_cast<ActionHandler>(&CraftEquipmentState::lstRightArrowPress)); _lstEquipment->onRightArrowRelease( static_cast<ActionHandler>(&CraftEquipmentState::lstRightArrowRelease)); _lstEquipment->onLeftArrowPress( static_cast<ActionHandler>(&CraftEquipmentState::lstLeftArrowPress)); _lstEquipment->onLeftArrowRelease( static_cast<ActionHandler>(&CraftEquipmentState::lstLeftArrowRelease)); _timerLeft = new Timer(Timer::SCROLL_SLOW); _timerLeft->onTimer(static_cast<StateHandler>(&CraftEquipmentState::onLeft)); _timerRight = new Timer(Timer::SCROLL_SLOW); _timerRight->onTimer(static_cast<StateHandler>(&CraftEquipmentState::onRight)); } /** * dTor. */ CraftEquipmentState::~CraftEquipmentState() { delete _timerLeft; delete _timerRight; } /** * Resets the stuff when coming back from InventoryState. */ void CraftEquipmentState::init() { State::init(); // Reset stuff when coming back from pre-battle Inventory. const SavedBattleGame* const battleSave (_game->getSavedGame()->getBattleSave()); if (battleSave != nullptr) { _unitOrder = battleSave->getSelectedUnit()->getBattleOrder(); _game->getSavedGame()->setBattleSave(); _craft->setTactical(false); } updateList(); extra(); } /** * Updates all values. */ void CraftEquipmentState::updateList() // private. { _txtLoad->setText(tr("STR_LOAD_CAPACITY_FREE_") .arg(_craft->getLoadCapacity()) .arg(_craft->getLoadCapacity() - _craft->calcLoadCurrent())); _lstEquipment->clearList(); size_t r (0u); std::wostringstream woststr; std::wstring wst; int craftQty, clip; Uint8 color; const RuleItem* itRule; BattleType bType; const std::vector<std::string>& allItems (_rules->getItemsList()); for (std::vector<std::string>::const_iterator i = allItems.begin(); i != allItems.end(); ++i) { itRule = _rules->getItemRule(*i); bType = itRule->getBattleType(); switch (bType) { case BT_NONE: case BT_CORPSE: case BT_FUEL: break; case BT_FIREARM: case BT_AMMO: case BT_MELEE: case BT_GRENADE: // -> includes SmokeGrenade, HE-Satchel, and AlienGrenade (see Ruleset) case BT_PROXYGRENADE: case BT_MEDIKIT: case BT_SCANNER: case BT_MINDPROBE: case BT_PSIAMP: case BT_FLARE: // if (itRule->getBigSprite() > -1 // see also BattlescapeGenerator::deployXcom(). Inventory also uses this "bigSprite" trick. NOTE: Stop using the "bigSprite" trick. // if (itRule->isFixed() == false if (_game->getSavedGame()->isResearched(itRule->getRequiredResearch()) == true) { if (itRule->isFixed() == true) craftQty = _craft->getVehicleCount(*i); else craftQty = _craft->getCraftItems()->getItemQuantity(*i); if (_base->getStorageItems()->getItemQuantity(*i) != 0 || craftQty != 0) //|| isQuickBattle == true) { _items.push_back(*i); woststr.str(L""); if (_isQuickBattle == false) woststr << _base->getStorageItems()->getItemQuantity(*i); else woststr << "-"; wst = tr(*i); if (bType == BT_AMMO) // weapon clips/HWP clips { wst.insert(0u, L" "); if ((clip = itRule->getFullClip()) > 1) wst += (L" (" + Text::intWide(clip) + L")"); } else if (itRule->isFixed() == true // tank w/ Ordnance. && (clip = itRule->getFullClip()) > 0) { wst += (L" (" + Text::intWide(clip) + L")"); } _lstEquipment->addRow( 3, wst.c_str(), woststr.str().c_str(), Text::intWide(craftQty).c_str()); if (craftQty != 0) color = _lstEquipment->getSecondaryColor(); else if (bType == BT_AMMO) color = _loadColor; else color = _lstEquipment->getColor(); _lstEquipment->setRowColor(r++, color); } } } } _lstEquipment->scrollTo(_recall); } /** * Decides whether to show extra buttons -- unload-craft and Inventory -- and * whether to show tactical-costs. */ void CraftEquipmentState::extra() const // private. { const bool vis (_craft->getCraftItems()->isEmpty() == false); _btnClear->setVisible(vis || _craft->getVehicles()->empty() == false); _btnInventory->setVisible(vis && _craft->getQtySoldiers() != 0); if (_isQuickBattle == false) _txtCost->setText(tr("STR_COST_").arg(Text::formatCurrency(_craft->getOperationalCost()))); } /** * Starts moving the selected row-items to the Craft. * @param action - pointer to an Action */ void CraftEquipmentState::lstRightArrowPress(Action* action) { _row = _lstEquipment->getSelectedRow(); switch (action->getDetails()->button.button) { case SDL_BUTTON_LEFT: _error.clear(); rightByValue(1); _timerRight->setInterval(Timer::SCROLL_SLOW); _timerRight->start(); break; case SDL_BUTTON_RIGHT: _error.clear(); rightByValue(std::numeric_limits<int>::max()); } } /** * Stops moving the selected row-items to the Craft. * @param action - pointer to an Action */ void CraftEquipmentState::lstRightArrowRelease(Action* action) { if (action->getDetails()->button.button == SDL_BUTTON_LEFT) _timerRight->stop(); } /** * Starts moving the selected row-items to the Base. * @param action - pointer to an Action */ void CraftEquipmentState::lstLeftArrowPress(Action* action) { _row = _lstEquipment->getSelectedRow(); switch (action->getDetails()->button.button) { case SDL_BUTTON_LEFT: leftByValue(1); _timerLeft->setInterval(Timer::SCROLL_SLOW); _timerLeft->start(); break; case SDL_BUTTON_RIGHT: leftByValue(std::numeric_limits<int>::max()); } } /** * Stops moving the selected row-items to the Base. * @param action - pointer to an Action */ void CraftEquipmentState::lstLeftArrowRelease(Action* action) { if (action->getDetails()->button.button == SDL_BUTTON_LEFT) _timerLeft->stop(); } /** * Runs the arrow timers. */ void CraftEquipmentState::think() { State::think(); _timerLeft->think(this, nullptr); _timerRight->think(this, nullptr); } /** * Moves the selected row-items to the Craft on Timer ticks. */ void CraftEquipmentState::onRight() { _timerRight->setInterval(Timer::SCROLL_FAST); rightByValue(1); } /** * Moves a specified quantity of the selected row-items to the Craft. * @param delta - quantity to move right */ void CraftEquipmentState::rightByValue(int delta) { if (_error.empty() == false) _error.clear(); else { const std::string& itType (_items[_row]); int baseQty; if (_isQuickBattle == false) baseQty = _base->getStorageItems()->getItemQuantity(itType); else { if (delta == std::numeric_limits<int>::max()) delta = 10; baseQty = delta; } if (baseQty != 0) { bool overLoad (false); delta = std::min(delta, baseQty); const RuleItem* const itRule (_rules->getItemRule(itType)); if (itRule->isFixed() == true) // load vehicle, convert item to a vehicle { const int vhclCap (_craft->getRules()->getVehicleCapacity()); if (vhclCap != 0 || _base->isQuickDefense() == true) { int quadrants (_rules->getArmor(_rules->getUnitRule(itType)->getArmorType())->getSize()); quadrants *= quadrants; int spaceAvailable; if (_base->isQuickDefense() == true) spaceAvailable = std::numeric_limits<int>::max(); else spaceAvailable = std::min(_craft->getSpaceAvailable(), vhclCap - _craft->getQtyVehicles(true)) / quadrants; if (spaceAvailable > 0 && (_craft->getLoadCapacity() - _craft->calcLoadCurrent() >= quadrants * 10 // note: 10 is the 'load' that a single 'space' uses. || _base->isQuickDefense() == true)) { delta = std::min(delta, spaceAvailable); if (_base->isQuickDefense() == false) delta = std::min(delta, (_craft->getLoadCapacity() - _craft->calcLoadCurrent()) / (quadrants * 10)); if (itRule->getFullClip() < 1) // no Ammo required. { for (int i = 0; i != delta; ++i) { _craft->getVehicles()->push_back(new Vehicle( itRule, itRule->getFullClip(), quadrants)); } if (_isQuickBattle == false) _base->getStorageItems()->removeItem(itType, delta); } else // tank needs Ammo. { const std::string& loadType (itRule->getClipTypes()->front()); const int clipsRequired (itRule->getFullClip()), baseClips (_base->getStorageItems()->getItemQuantity(loadType)); if (_isQuickBattle == false) delta = std::min(delta, baseClips / clipsRequired); if (delta > 0) { for (int i = 0; i != delta; ++i) { _craft->getVehicles()->push_back(new Vehicle( itRule, clipsRequired, quadrants)); } if (_isQuickBattle == false) { _base->getStorageItems()->removeItem(itType, delta); _base->getStorageItems()->removeItem(loadType, clipsRequired * delta); } updateHwpLoad(loadType); } else // not enough Ammo { _timerRight->stop(); _error = tr("STR_NOT_ENOUGH_AMMO_TO_ARM_HWP") .arg(clipsRequired) .arg(tr(loadType)) .arg(tr(itRule->getType())); _game->pushState(new ErrorMessageState( _error, _palette, COLOR_ERROR, "BACK04.SCR", COLOR_ERROR_BG)); } } } else overLoad = true; } else { _error = tr("STR_NO_SUPPORT_UNITS_ALLOWED"); _game->pushState(new ErrorMessageState( _error, _palette, COLOR_ERROR, "BACK04.SCR", COLOR_ERROR_BG)); } } else if (_craft->getRules()->getItemCapacity() != 0 // load items && itRule->getBigSprite() != BIGSPRITE_NONE) { const int loadCur (_craft->calcLoadCurrent()); if (loadCur + delta > _craft->getLoadCapacity()) { overLoad = true; delta = _craft->getLoadCapacity() - loadCur; } if (delta > 0) { _craft->getCraftItems()->addItem(itType, delta); if (_isQuickBattle == false) _base->getStorageItems()->removeItem(itType, delta); } } if (overLoad == true) { _timerRight->stop(); _error = tr("STR_NO_MORE_EQUIPMENT_ALLOWED", static_cast<unsigned>(_craft->getLoadCapacity())); _game->pushState(new ErrorMessageState( _error, _palette, COLOR_ERROR, "BACK04.SCR", COLOR_ERROR_BG)); } updateListrow(); } } } /** * Moves the selected row-items to the Base on Timer ticks. */ void CraftEquipmentState::onLeft() { _timerLeft->setInterval(Timer::SCROLL_FAST); leftByValue(1); } /** * Moves a specified quantity of selected row-items to the Base. * @param delta - quantity to move left */ void CraftEquipmentState::leftByValue(int delta) { const std::string& itType (_items[_row]); const RuleItem* const itRule (_rules->getItemRule(itType)); int craftQty; if (itRule->isFixed() == true) craftQty = _craft->getVehicleCount(itType); else craftQty = _craft->getCraftItems()->getItemQuantity(itType); if (craftQty != 0) { delta = std::min(delta, craftQty); if (itRule->isFixed() == true) // convert Vehicles to storage-items { const std::string& loadType (itRule->getClipTypes()->front()); if (_isQuickBattle == false) { _base->getStorageItems()->addItem(itType, delta); if (itRule->getFullClip() > 0) _base->getStorageItems()->addItem( loadType, itRule->getFullClip() * delta); // Vehicles onboard Craft always have full clips. } for (std::vector<Vehicle*>::const_iterator i = _craft->getVehicles()->begin(); i != _craft->getVehicles()->end() && delta != 0; ) { if ((*i)->getRules() == itRule) { --delta; delete *i; i = _craft->getVehicles()->erase(i); } else ++i; } if (itRule->getFullClip() > 0) updateHwpLoad(loadType); } else { _craft->getCraftItems()->removeItem(itType, delta); if (_isQuickBattle == false) _base->getStorageItems()->addItem(itType, delta); } updateListrow(); } } /** * Updates the displayed quantities of the selected row-item in the list. */ void CraftEquipmentState::updateListrow() const // private. { const std::string& itType (_items[_row]); const RuleItem* const itRule (_rules->getItemRule(itType)); int craftQty; if (itRule->isFixed() == true) craftQty = _craft->getVehicleCount(itType); else craftQty = _craft->getCraftItems()->getItemQuantity(itType); std::wostringstream woststr; if (_isQuickBattle == false) woststr << _base->getStorageItems()->getItemQuantity(itType); else woststr << L"-"; Uint8 color; if (craftQty != 0) color = _lstEquipment->getSecondaryColor(); else if (itRule->getBattleType() == BT_AMMO) color = _loadColor; else color = _lstEquipment->getColor(); _lstEquipment->setRowColor(_row, color); _lstEquipment->setCellText(_row, 1u, woststr.str()); _lstEquipment->setCellText(_row, 2u, Text::intWide(craftQty)); _txtSpace->setText(tr("STR_SPACE_CREW_HWP_FREE_") .arg(_craft->getQtySoldiers()) .arg(_craft->getQtyVehicles()) .arg(_craft->getSpaceAvailable())); _txtLoad->setText(tr("STR_LOAD_CAPACITY_FREE_") .arg(_craft->getLoadCapacity()) .arg(_craft->getLoadCapacity() - _craft->calcLoadCurrent())); extra(); } /** * Updates list-values for HWP load. * @param loadType - reference to the load-type */ void CraftEquipmentState::updateHwpLoad(const std::string& loadType) const // private. { size_t r = 0u; for (std::vector<std::string>::const_iterator i = _items.begin(); i != _items.end(); ++i, ++r) { if (*i == loadType) { const int craftQty (_craft->getCraftItems()->getItemQuantity(loadType)); std::wostringstream woststr; if (_isQuickBattle == false) woststr << _base->getStorageItems()->getItemQuantity(loadType); else woststr << L"-"; Uint8 color; if (craftQty != 0) color = _lstEquipment->getSecondaryColor(); else color = _loadColor; _lstEquipment->setRowColor(r, color); _lstEquipment->setCellText(r, 1u, woststr.str()); _lstEquipment->setCellText(r, 2u, Text::intWide(craftQty)); break; } } } /** * Clears the contents of the Craft - moves all items back to stores. * @param action - pointer to an Action */ void CraftEquipmentState::btnUnloadCraftClick(Action*) // private. { for ( _row = 0u; _row != _items.size(); ++_row) { leftByValue(std::numeric_limits<int>::max()); } } /** * Displays the inventory for any Soldiers in the Craft. * @param action - pointer to an Action */ void CraftEquipmentState::btnInventoryClick(Action*) // private. { _recall = _lstEquipment->getScroll(); SavedBattleGame* const battleSave (new SavedBattleGame(_game->getSavedGame())); _game->getSavedGame()->setBattleSave(battleSave); BattlescapeGenerator bGen = BattlescapeGenerator(_game); bGen.runFakeInventory(_craft, nullptr, _unitOrder); _game->getScreen()->clear(); _game->pushState(new InventoryState()); } /** * Exits to the previous screen. * @param action - pointer to an Action */ void CraftEquipmentState::btnOkClick(Action*) // private. { _game->popState(); } }
kevL/0xC_kL
src/Basescape/CraftEquipmentState.cpp
C++
gpl-3.0
20,783
import numpy class DifferentialEvolutionAbstract: amount_of_individuals = None f = None p = None end_method = None def __init__(self, min_element=-1, max_element=1): self.min_element = min_element self.max_element = max_element self.f = 0.5 self.p = 0.9 self.func = None self.population = None self.func_population = None self.dim = 0 self.child_funcs = None self.cost_list = [] self.end_method = 'max_iter' def set_amount_of_individuals(self, amount_of_individuals): self.amount_of_individuals = amount_of_individuals def set_params(self, f, p): self.f = f self.p = p def set_end_method(self, end_method): self.end_method = end_method def create_population(self): # Создаем популяцию population = [] for _ in range(self.amount_of_individuals): population.append(numpy.random.uniform(self.min_element, self.max_element, self.dim)) return numpy.array(population) def choose_best_individual(self): # Данная функция находит лучшую особь в популяции func_list = list(self.func_population) best_index = func_list.index(min(func_list)) return self.population[best_index] def iteration(self): return [] def optimize(self, func, dim, end_cond, debug_pop_print=-1): return [] def return_cost_list(self): return self.cost_list
QuantumTechDevStudio/RUDNEVGAUSS
archive/solver/DifferentialEvolutionAbstract.py
Python
gpl-3.0
1,558
// // Ce fichier a été généré par l'implémentation de référence JavaTM Architecture for XML Binding (JAXB), v2.2.11 // Voir <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Toute modification apportée à ce fichier sera perdue lors de la recompilation du schéma source. // Généré le : 2017.09.18 à 11:31:40 AM CEST // package fr.gouv.api.Boamp_v230; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Classe Java pour EnumAvisImplique complex type. * * <p>Le fragment de schéma suivant indique le contenu attendu figurant dans cette classe. * * <pre> * &lt;complexType name="EnumAvisImplique"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;choice&gt; * &lt;element name="MARCHE_PUBLIC" type="{http://www.w3.org/2001/XMLSchema}anyType"/&gt; * &lt;element name="ACCORD_CADRE" type="{http://www.w3.org/2001/XMLSchema}anyType"/&gt; * &lt;element name="SAD" type="{http://www.w3.org/2001/XMLSchema}anyType"/&gt; * &lt;/choice&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EnumAvisImplique", propOrder = { "marchepublic", "accordcadre", "sad" }) public class EnumAvisImplique { @XmlElement(name = "MARCHE_PUBLIC") protected Object marchepublic; @XmlElement(name = "ACCORD_CADRE") protected Object accordcadre; @XmlElement(name = "SAD") protected Object sad; /** * Obtient la valeur de la propriété marchepublic. * * @return * possible object is * {@link Object } * */ public Object getMARCHEPUBLIC() { return marchepublic; } /** * Définit la valeur de la propriété marchepublic. * * @param value * allowed object is * {@link Object } * */ public void setMARCHEPUBLIC(Object value) { this.marchepublic = value; } /** * Obtient la valeur de la propriété accordcadre. * * @return * possible object is * {@link Object } * */ public Object getACCORDCADRE() { return accordcadre; } /** * Définit la valeur de la propriété accordcadre. * * @param value * allowed object is * {@link Object } * */ public void setACCORDCADRE(Object value) { this.accordcadre = value; } /** * Obtient la valeur de la propriété sad. * * @return * possible object is * {@link Object } * */ public Object getSAD() { return sad; } /** * Définit la valeur de la propriété sad. * * @param value * allowed object is * {@link Object } * */ public void setSAD(Object value) { this.sad = value; } }
newa0/boamp-api-quickStart
src/main/gen/fr/gouv/api/Boamp_v230/EnumAvisImplique.java
Java
gpl-3.0
3,154
import pickle from matplotlib import pyplot as plt plt.style.use('classic') import matplotlib as mpl fs = 12. fw = 'bold' mpl.rc('lines', linewidth=2., color='k') mpl.rc('font', size=fs, weight=fw, family='Arial') mpl.rc('legend', fontsize='small') import numpy def grad( x, u ) : return numpy.gradient(u) / numpy.gradient(x) date = '20160519' base = '/home/mk-sim-linux/Battery_TempGrad/Python/batt_simulation/battsimpy/' base_dir = '/home/mk-sim-linux/Battery_TempGrad/JournalPaper2/Paper2/ocv_unif35/' fig_dir = '/home/mk-sim-linux/Battery_TempGrad/JournalPaper3/modeling_paper_p3/figs/' #base_dir = '/home/m_klein/tgs_data/ocv_unif35/' #base_dir = '/Volumes/Data/Paper2/ocv_dat/' #bsp_path = '/Users/mk/Desktop/battsim/battsimpy/' nmc_rest_523 = numpy.loadtxt( base+'data/Model_nmc/Model_Pars/solid/thermodynamics/2012Yang_523NMC_dchg_restOCV.csv', delimiter=',' ) nmc_cby25_111 = numpy.loadtxt( base+'data/Model_nmc/Model_Pars/solid/thermodynamics/2012Wu_NMC111_Cby25_dchg.csv' , delimiter=',' ) nmc_YangWu_mix = numpy.loadtxt( base+'data/Model_nmc/Model_Pars/solid/thermodynamics/YangWuMix_NMC_20170607.csv' , delimiter=',' ) lfp_prada_dchg = numpy.loadtxt( base+'data/Model_v1/Model_Pars/solid/thermodynamics/2012Prada_LFP_U_dchg.csv' , delimiter=',' ) graph_hess_dchg = numpy.loadtxt( base+'data/Model_nmc/Model_Pars/solid/thermodynamics/Ua_cell4Fit_NMC_2012Yang_refx.csv' , delimiter=',' ) #graphite_Hess_discharge_x.csv #xin, Uin = 1.-lfp_prada_dchg[:,0], lfp_prada_dchg[:,1] #xin, Uin = 1.-nmc_rest_523[:,0], nmc_rest_523[:,1] xin, Uin = 1.-nmc_YangWu_mix[:,0], nmc_YangWu_mix[:,1] #xin, Uin = 1.-nmc_cby25_111[:,0], nmc_cby25_111[:,1] xin2, Uin2 = graph_hess_dchg[:,0], graph_hess_dchg[:,1]#-0.025 pfiles2 = [ base_dir+'slowOCVdat_cell4_slow_ocv_'+date+'.p', ] # Load the cell ocv c/60 data d = pickle.load( open( pfiles2[0], 'rb' ) ) max_cap = numpy.amax( d['interp']['cap'] ) x_cell, U_cell = 1-numpy.array(d['interp']['cap'])/max_cap*1., d['interp']['dchg']['volt'] # NMC 532 scale - NMC cyl cells (cell 4) #scale_x = 1.8#1.5 # 1.55 #shift_x = -.01#-.06 #-.12 scale_x = 1.42 # 1.55 shift_x = -.03 #-.12 #scale_x1 = 1.9 #shift_x1 = -.03 ## LFP Prada - (cell 2) #scale_x = 1.25 #shift_x = 1.05-scale_x # Graphite - scale NMC cyl cells (cell 4) scale_x2 = 1/.8 #1./0.83 # shift_x2 = -.06 #-.035 #scale_x2 = 1/.74 #shift_x2 = -.04 figres = 300 figname = base_dir+'ocv-plots_'+date+'.pdf' sty = [ '-', '--' ] fsz = (190./25.4,120./25.4) f1, axes = plt.subplots(1,2,figsize=fsz) a1,a2 = axes # Plot the full cell ocv a1.plot( x_cell, U_cell, '-b', label='Cell C/60 Data' ) # Plot the cathode curve for the shifted soc operating window a1.plot( xin*scale_x+shift_x, Uin, '-g', label='Cathode' ) # Plot the anode curve for the shifted soc operating window #a1t = a1.twinx() a1.plot( xin2*scale_x2+shift_x2, Uin2, '-k', label='Anode' ) # Compute the cathode ocv for the full cell soc operating window if xin[1] < xin[0] : Uc = numpy.interp( x_cell, numpy.flipud(xin*scale_x+shift_x), numpy.flipud(Uin) ) else : Uc = numpy.interp( x_cell, xin*scale_x+shift_x, Uin ) Ua = numpy.interp( x_cell, xin2*scale_x2+shift_x2, Uin2 ) # Plot the estimated full cell ocv curve for the aligned anode and cathode equilibrium curves #a1.plot( x_cell, Uc-U_cell, ':k', label='U$_{anode}$ fit' ) #a1t.set_ylim([0.,2.]) a1.plot( x_cell, Uc-Ua, ':k', label='U$_{cell}$ fit' ) # Calculate the alignment stoichs for anode and cathode Ua_out = Uc - U_cell xa_out = (x_cell-shift_x2)/scale_x2 #numpy.savetxt( base+'data/Model_v1/Model_Pars/solid/thermodynamics/Ua_lfp_2012Prada.csv', numpy.array([xa_out, Ua_out]).T, delimiter=',' ) #numpy.savetxt( base+'data/Model_v1/Model_Pars/solid/thermodynamics/Ua_nmc_2012Yang.csv', numpy.array([xa_out, Ua_out]).T, delimiter=',' ) yin = 1.-xin xc_lo = 1. - (-shift_x/scale_x) xc_hi = 1. - (1.-shift_x)/scale_x xa_lo = (-shift_x2/scale_x2) xa_hi = (1.-shift_x2)/scale_x2 # Print out the stoich limits for the anode and cathode print 'xc_lo, xc_hi:',xc_lo, xc_hi print 'xa_lo, xa_hi:',xa_lo, xa_hi a1.set_xlabel( 'State of Charge', fontsize=fs, fontweight=fw ) a1.set_ylabel( 'Voltage vs. Li [V]', fontsize=fs, fontweight=fw ) a1.set_title( 'Full and Half Cell OCV', fontsize=fs, fontweight=fw ) a1.legend(loc='best') a1.set_axisbelow(True) a1.grid(color='gray') a2.plot( x_cell, grad(x_cell, U_cell), label=r'$\frac{\partial U_{cell}}{\partial SOC}$' ) a2.plot( x_cell, -grad(x_cell, Ua), label=r'$\frac{\partial U_{anode}}{\partial SOC}$' ) a2.set_xlabel( 'State of Charge', fontsize=fs, fontweight=fw ) a2.set_ylabel( '$\partial U / \partial SOC$', fontsize=fs, fontweight=fw ) a2.set_title( 'OCV Gradients for Anode Alignment', fontsize=fs, fontweight=fw ) a2.legend(loc='best') a2.set_axisbelow(True) a2.grid(color='gray') a2.set_ylim([-0.1,1.5]) #plt.suptitle('LFP/C$_6$ Half Cell OCV Alignment', fontsize=fs, fontweight=fw) plt.suptitle('NMC/C$_6$ Half Cell OCV Alignment', fontsize=fs, fontweight=fw) plt.tight_layout(rect=[0,0.03,1,0.97]) plt.show() #f1.savefig( fig_dir+'ocv_alignment_cell2_lfp.pdf', dpi=figres) #f1.savefig( fig_dir+'ocv_alignment_cell4_nmc.pdf', dpi=figres)
matthewpklein/battsimpy
docs/extra_files/electrode_ocv_gen.py
Python
gpl-3.0
5,199
package com.idega.block.trade.stockroom.business; /** * Title: IW Trade * Description: * Copyright: Copyright (c) 2001 * Company: idega.is * @author 2000 - idega team - <br><a href="mailto:gummi@idega.is">Guðmundur Ágúst Sæmundsson</a><br><a href="mailto:gimmi@idega.is">Grímur Jónsson</a> * @version 1.0 */ public class ProductPriceException extends RuntimeException { public ProductPriceException() { super(); } public ProductPriceException(String explanation){ super(explanation); } }
idega/platform2
src/com/idega/block/trade/stockroom/business/ProductPriceException.java
Java
gpl-3.0
530
package org.istic.synthlab.core.modules.whitenoise; import org.istic.synthlab.components.IComponent; import org.istic.synthlab.core.modules.io.IOutput; import org.istic.synthlab.core.services.Factory; import org.istic.synthlab.core.services.Register; public class WhiteNoise implements IWhiteNoise { private com.jsyn.unitgen.WhiteNoise whiteNoise; private IOutput output; public WhiteNoise(IComponent component) { super(); whiteNoise = new com.jsyn.unitgen.WhiteNoise(); Register.declare(component, whiteNoise); whiteNoise.output.setName("noise_output"); output = Factory.createOutput("Out", component, this.whiteNoise.output); } @Override public IOutput getOutput() { return this.output; } public void activate() { whiteNoise.setEnabled(true); } public void deactivate() { whiteNoise.setEnabled(false); } public boolean isActivated() { return whiteNoise.isEnabled(); } }
StephaneMangin/Synth
src/main/java/org/istic/synthlab/core/modules/whitenoise/WhiteNoise.java
Java
gpl-3.0
1,003
#include <stdafx.h> #include "VertexBufferObject.h" VertexBufferObject::VertexBufferObject() { glGenBuffers(1, &_id); } VertexBufferObject::~VertexBufferObject() { glDeleteBuffers(1, &_id); } void VertexBufferObject::Bind() { glBindBuffer(GL_ARRAY_BUFFER, _id); } void VertexBufferObject::Upload(void *data, size_t size, int type) { glBufferData(GL_ARRAY_BUFFER, size, data, type); }
aomega08/PowerCraft
PowerCraft/Engine/VertexBufferObject.cpp
C++
gpl-3.0
392
import java.io.IOException; import java.net.Socket; import java.util.Scanner; public class networkRead implements Runnable { //Objects Scanner read; debugLogger myLogger; sharedData myData; arduinoWrite ardWriter; Socket pipe; //Variables String data; long startTime; long endTime; boolean dead = false; public networkRead(Socket tempSocket, sharedData tempData, debugLogger tempLog, arduinoWrite tempWriter) { pipe = tempSocket; myData = tempData; myLogger = tempLog; ardWriter = tempWriter; try { read = new Scanner(tempSocket.getInputStream()); } catch (IOException e) { myLogger.writeLog("ERROR: Failure to write to network socket!"); myLogger.writeLog("\n\n"); e.printStackTrace(); myLogger.writeLog("\n\n"); } } public void run() { data = "myData"; startTime = System.currentTimeMillis(); endTime = startTime + 2000; while (myData.getAlive()) { if(pipe.isConnected()) { if(read.hasNextLine()) { //Read data data = read.nextLine(); data = data.trim(); //Store Data in shared object myData.setReadNet(data); //Log the input myLogger.writeLog("Read From Server: \t" + data); //Pass input to arduino ardWriter.writeToSerial(data); } } if(data.equals("ping")) { startTime = System.currentTimeMillis(); endTime = startTime + 2000; } keepAlive(); data = ""; } ardWriter.writeToSerial("BB"); ardWriter.writeToSerial("EVF"); ardWriter.writeToSerial("OFF"); myLogger.writeLog("CRITICAL: CONNECTION LOST!"); } public void keepAlive() { long temp = System.currentTimeMillis(); if((temp >endTime)) { myData.setAliveArd(false); myData.setAliveNet(false); } } }
kc8hfi/mygolfcart
dev/java/src/networkRead.java
Java
gpl-3.0
1,860
#include "kalman_filter.h" #include <iostream> using Eigen::MatrixXd; using Eigen::VectorXd; KalmanFilter::KalmanFilter() {} KalmanFilter::~KalmanFilter() {} void KalmanFilter::Init(VectorXd &x_in, MatrixXd &P_in, MatrixXd &F_in, MatrixXd &H_in, MatrixXd &R_in, MatrixXd &Q_in) { x_ = x_in; P_ = P_in; F_ = F_in; H_ = H_in; R_ = R_in; Q_ = Q_in; } void KalmanFilter::Predict() { x_ = F_*x_; MatrixXd Ft = F_.transpose(); P_ = F_ * P_ * Ft + Q_; } void KalmanFilter::Update(const VectorXd &z) { VectorXd z_pred = H_ * x_; VectorXd y = z - z_pred; MatrixXd Ht = H_.transpose(); MatrixXd PHt = P_ * Ht; MatrixXd S = H_ * PHt + R_; MatrixXd Si = S.inverse(); MatrixXd K = PHt * Si; //new estimate x_ = x_ + (K * y); long long x_size = x_.size(); MatrixXd I = MatrixXd::Identity(x_size, x_size); P_ = (I - K * H_) * P_; } void KalmanFilter::UpdateEKF(const VectorXd &z) { double rho = sqrt(x_[0]*x_[0] + x_[1]*x_[1]); double phi = 0; //atan2(x_[1], x_[0]); double rho_dot; if(x_[0] != 0 || x_[1] != 0) phi = atan2(x_[1], x_[0]); if(rho != 0.0){ rho_dot = (x_[0]*x_[2] + x_[1]*x_[3])/rho; }else{ rho_dot = 0; } VectorXd z_pred(3); z_pred << rho, phi, rho_dot; VectorXd y = z - z_pred; MatrixXd Ht = Hj_.transpose(); MatrixXd PHt = P_ * Ht; MatrixXd S = Hj_ * PHt + R_; MatrixXd Si = S.inverse(); MatrixXd K = PHt * Si; //new estimate x_ = x_ + (K * y); long long x_size = x_.size(); MatrixXd I = MatrixXd::Identity(x_size, x_size); P_ = (I - K * Hj_) * P_; }
ortizjuan2/carnd-term2
CarND-Extended-Kalman-Filter-Project/src/kalman_filter.cpp
C++
gpl-3.0
1,660
var jsVars = { appBaseUrl: null, appBasePath: null, init: function () { var jsVarsAttributes = angular.element('#js-vars')[0].attributes; jsVars.appBaseUrl = jsVarsAttributes['data-base-url'].value; jsVars.appBasePath = jsVarsAttributes['data-basepath'].value; } }; jsVars.init(); var config = { basePath: jsVars.appBasePath+'/ng-front/', restServer: jsVars.appBaseUrl+'/api' }; var Question = { TYPE_QCM: 1, TYPE_FREE: 2 }; function getUTCTimestamp() { var now = new Date(); var utc_now = new Date( now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds() ); return utc_now.getTime(); } /** * Filter to create a Javascript date */ angular.module('zcpeFilters', []).filter('jsDate', function () { return function (sDate) { return new Date(sDate); } }); var zcpe = angular.module('zcpe', [ 'ngRoute', 'pascalprecht.translate', 'ngCookies', 'ngStorage', 'angular-locker', 'controllers-quizz', 'hljs', 'timer', 'zcpeFilters' ]);
Antione7/ZCEPracticeTest
web/ng-front/app.js
JavaScript
gpl-3.0
1,224
../../../../share/pyshared/jockey/xorg_driver.py
Alberto-Beralix/Beralix
i386-squashfs-root/usr/lib/python2.7/dist-packages/jockey/xorg_driver.py
Python
gpl-3.0
48
/************************************************************************* * Copyright 2009-2014 Eucalyptus Systems, Inc. * * 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; version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. * * Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta * CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you need * additional information or have any questions. * * This file may incorporate work covered under the following copyright * and permission notice: * * Software License Agreement (BSD License) * * Copyright (c) 2008, Regents of the University of California * All rights reserved. * * Redistribution and use of this software in source and binary forms, * with or without modification, are permitted provided that the * following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. USERS OF THIS SOFTWARE ACKNOWLEDGE * THE POSSIBLE PRESENCE OF OTHER OPEN SOURCE LICENSED MATERIAL, * COPYRIGHTED MATERIAL OR PATENTED MATERIAL IN THIS SOFTWARE, * AND IF ANY SUCH MATERIAL IS DISCOVERED THE PARTY DISCOVERING * IT MAY INFORM DR. RICH WOLSKI AT THE UNIVERSITY OF CALIFORNIA, * SANTA BARBARA WHO WILL THEN ASCERTAIN THE MOST APPROPRIATE REMEDY, * WHICH IN THE REGENTS' DISCRETION MAY INCLUDE, WITHOUT LIMITATION, * REPLACEMENT OF THE CODE SO IDENTIFIED, LICENSING OF THE CODE SO * IDENTIFIED, OR WITHDRAWAL OF THE CODE CAPABILITY TO THE EXTENT * NEEDED TO COMPLY WITH ANY SUCH LICENSES OR RIGHTS. * * This file may incorporate work covered under the following copyright * and permission notice: * * Copyright (c) 1999-2004, Brian Wellington. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ************************************************************************/ package com.eucalyptus.cloud.ws; import static com.eucalyptus.util.dns.DnsResolvers.DnsRequest; import java.io.DataOutputStream; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.log4j.Logger; import org.xbill.DNS.CNAMERecord; import org.xbill.DNS.Credibility; import org.xbill.DNS.DClass; import org.xbill.DNS.DNAMERecord; import org.xbill.DNS.ExtendedFlags; import org.xbill.DNS.Flags; import org.xbill.DNS.Header; import org.xbill.DNS.Message; import org.xbill.DNS.Name; import org.xbill.DNS.NameTooLongException; import org.xbill.DNS.OPTRecord; import org.xbill.DNS.Opcode; import org.xbill.DNS.RRset; import org.xbill.DNS.Rcode; import org.xbill.DNS.Record; import org.xbill.DNS.Section; import org.xbill.DNS.SetResponse; import org.xbill.DNS.TSIG; import org.xbill.DNS.TSIGRecord; import org.xbill.DNS.Type; import com.eucalyptus.dns.Zone; import com.eucalyptus.dns.Cache; import com.eucalyptus.util.Pair; import com.eucalyptus.util.dns.DnsResolvers; import com.google.common.base.Function; import com.google.common.base.Optional; public class ConnectionHandler extends Thread { static final int FLAG_DNSSECOK = 1; static final int FLAG_SIGONLY = 2; Map caches = new ConcurrentHashMap(); //Map TSIGs; byte [] generateReply(Message query, byte [] in, int length, Socket s) throws IOException { Header header; boolean badversion; int maxLength; boolean sigonly; SetResponse sr; int flags = 0; header = query.getHeader(); // if (header.getFlag(Flags.QR)) // return null; if (header.getRcode() != Rcode.NOERROR) return errorMessage(query, Rcode.FORMERR); if (header.getOpcode() != Opcode.QUERY) return errorMessage(query, Rcode.NOTIMP); Record queryRecord = query.getQuestion(); TSIGRecord queryTSIG = query.getTSIG(); TSIG tsig = null; /* if (queryTSIG != null) { tsig = (TSIG) TSIGs.get(queryTSIG.getName()); if (tsig == null || tsig.verify(query, in, length, null) != Rcode.NOERROR) return formerrMessage(in); }*/ OPTRecord queryOPT = query.getOPT(); if (queryOPT != null && queryOPT.getVersion() > 0) badversion = true; if (s != null) maxLength = 65535; else if (queryOPT != null) maxLength = Math.max(queryOPT.getPayloadSize(), 512); else maxLength = 512; if (queryOPT != null && (queryOPT.getFlags() & ExtendedFlags.DO) != 0) flags = FLAG_DNSSECOK; Message response = new Message(query.getHeader().getID()); response.getHeader().setFlag(Flags.QR); if (query.getHeader().getFlag(Flags.RD)) response.getHeader().setFlag(Flags.RD); if(queryRecord != null) { response.addRecord(queryRecord, Section.QUESTION); Name name = queryRecord.getName(); int type = queryRecord.getType(); int dclass = queryRecord.getDClass(); /* if (type == Type.AXFR && s != null) return doAXFR(name, query, tsig, queryTSIG, s); */ if (!Type.isRR(type) && type != Type.ANY) return errorMessage(query, Rcode.NOTIMP); byte rcode = addAnswer(response, name, type, dclass, 0, flags); if (rcode != Rcode.NOERROR && rcode != Rcode.NXDOMAIN) return errorMessage(query, Rcode.SERVFAIL); addAdditional(response, type, flags); if (queryOPT != null) { int optflags = (flags == FLAG_DNSSECOK) ? ExtendedFlags.DO : 0; OPTRecord opt = new OPTRecord((short)4096, rcode, (byte)0, optflags); response.addRecord(opt, Section.ADDITIONAL); } } response.setTSIG(tsig, Rcode.NOERROR, queryTSIG); return response.toWire(maxLength); } public Zone findBestZone(Name name) { Zone foundzone = null; int labels = name.labels(); for (int i = 1; i < labels; i++) { Name tname = new Name(name, i); foundzone = (Zone) ZoneManager.getZone(tname); if (foundzone != null) return foundzone; } return null; } public RRset findExactMatch(Name name, int type, int dclass, boolean glue) { Zone zone = findBestZone(name); if (zone != null) return zone.findExactMatch(name, type); else { RRset [] rrsets; Cache cache = getCache(dclass); if (glue) rrsets = cache.findAnyRecords(name, type); else rrsets = cache.findRecords(name, type); if (rrsets == null) return null; else return rrsets[0]; /* not quite right */ } } private void addGlue(Message response, Name name, int type, int flags) { RRset a = findExactMatch(name, type, DClass.IN, true); if (a == null) return; addRRset(name, response, a, Section.ADDITIONAL, flags); } private void addAdditional2(Message response, int section, int type, int flags) { Record [] records = response.getSectionArray(section); for (int i = 0; i < records.length; i++) { Record r = records[i]; Name glueName = r.getAdditionalName(); if (glueName != null) addGlue(response, glueName, type, flags); } } private final void addAdditional(Message response, int type, int flags) { addAdditional2(response, Section.ANSWER, type, flags); addAdditional2(response, Section.AUTHORITY, type, flags); } byte addAnswer( final Message response, Name name, int type, int dclass, int iterations, int flags) { SetResponse sr; byte rcode = Rcode.NOERROR; if (iterations > 6) return Rcode.NOERROR; if (type == Type.SIG || type == Type.RRSIG) { type = Type.ANY; flags |= FLAG_SIGONLY; } try { sr = DnsResolvers.findRecords( response, new DnsRequest() { @Override public Record getQuery() { return response.getQuestion( ); } @Override public InetAddress getLocalAddress() { return ConnectionHandler.getLocalInetAddress(); } @Override public InetAddress getRemoteAddress() { return ConnectionHandler.getRemoteInetAddress(); } } ); if ( sr != null ) { if ( sr.isSuccessful( ) ) { return Rcode.NOERROR; } else if ( sr.isNXDOMAIN( ) ) { return Rcode.NXDOMAIN; } } } catch ( Exception ex ) { Logger.getLogger( DnsResolvers.class ).error( ex ); } Zone zone = findBestZone(name); if (zone != null) { if (type == Type.AAAA) { addSOA(response, zone); response.getHeader().setFlag(Flags.AA); return (Rcode.NOERROR); } sr = zone.findRecords(name, type, getLocalInetAddress( )); } else { Cache cache = getCache(dclass); sr = cache.lookupRecords(name, type, Credibility.NORMAL); } if (sr.isUnknown()) { return (Rcode.SERVFAIL); } if (sr.isNXDOMAIN()) { response.getHeader().setRcode(Rcode.NXDOMAIN); if (zone != null) { addSOA(response, zone); if (iterations == 0) response.getHeader().setFlag(Flags.AA); } rcode = Rcode.NXDOMAIN; } else if (sr.isNXRRSET()) { if (zone != null) { addSOA(response, zone); if (iterations == 0) response.getHeader().setFlag(Flags.AA); } } else if (sr.isDelegation()) { RRset nsRecords = sr.getNS(); addRRset(nsRecords.getName(), response, nsRecords, Section.AUTHORITY, flags); } else if (sr.isCNAME()) { CNAMERecord cname = sr.getCNAME(); RRset rrset = new RRset(cname); addRRset(name, response, rrset, Section.ANSWER, flags); if (zone != null && iterations == 0) response.getHeader().setFlag(Flags.AA); rcode = addAnswer(response, cname.getTarget(), type, dclass, iterations + 1, flags); } else if (sr.isDNAME()) { DNAMERecord dname = sr.getDNAME(); RRset rrset = new RRset(dname); addRRset(name, response, rrset, Section.ANSWER, flags); Name newname; try { newname = name.fromDNAME(dname); } catch (NameTooLongException e) { return Rcode.YXDOMAIN; } if(newname != null) { rrset = new RRset(new CNAMERecord(name, dclass, 0, newname)); addRRset(name, response, rrset, Section.ANSWER, flags); if (zone != null && iterations == 0) response.getHeader().setFlag(Flags.AA); rcode = addAnswer(response, newname, type, dclass, iterations + 1, flags); } } else if (sr.isSuccessful()) { RRset [] rrsets = sr.answers(); if(rrsets != null) { for (int i = 0; i < rrsets.length; i++) addRRset(name, response, rrsets[i], Section.ANSWER, flags); } if (zone != null) { addNS(response, zone, flags); if (iterations == 0) response.getHeader().setFlag(Flags.AA); } else addCacheNS(response, getCache(dclass), name); } return rcode; } private final void addSOA(Message response, Zone zone) { response.addRecord(zone.getSOA(), Section.AUTHORITY); } private final void addNS(Message response, Zone zone, int flags) { RRset nsRecords = zone.getNS(); addRRset(nsRecords.getName(), response, nsRecords, Section.AUTHORITY, flags); } private final void addCacheNS(Message response, Cache cache, Name name) { SetResponse sr = cache.lookupRecords(name, Type.NS, Credibility.HINT); if (!sr.isDelegation()) return; RRset nsRecords = sr.getNS(); Iterator it = nsRecords.rrs(); while (it.hasNext()) { Record r = (Record) it.next(); response.addRecord(r, Section.AUTHORITY); } } byte [] doAXFR(Name name, Message query, TSIG tsig, TSIGRecord qtsig, Socket s) { Zone zone = (Zone) ZoneManager.getZone(name); boolean first = true; if (zone == null) return errorMessage(query, Rcode.REFUSED); Iterator it = zone.AXFR(); try { DataOutputStream dataOut; dataOut = new DataOutputStream(s.getOutputStream()); int id = query.getHeader().getID(); while (it.hasNext()) { RRset rrset = (RRset) it.next(); Message response = new Message(id); Header header = response.getHeader(); header.setFlag(Flags.QR); header.setFlag(Flags.AA); addRRset(rrset.getName(), response, rrset, Section.ANSWER, FLAG_DNSSECOK); if (tsig != null) { tsig.applyStream(response, qtsig, first); qtsig = response.getTSIG(); } first = false; byte [] out = response.toWire(); dataOut.writeShort(out.length); dataOut.write(out); } } catch (IOException ex) { System.out.println("AXFR failed"); } try { s.close(); } catch (IOException ex) { } return null; } void addRRset(Name name, Message response, RRset rrset, int section, int flags) { for (int s = 1; s <= section; s++) if (response.findRRset(name, rrset.getType(), s)) return; if ((flags & FLAG_SIGONLY) == 0) { Iterator it = rrset.rrs(); while (it.hasNext()) { Record r = (Record) it.next(); if (r.getName().isWild() && !name.isWild()) r = r.withName(name); response.addRecord(r, section); } } if ((flags & (FLAG_SIGONLY | FLAG_DNSSECOK)) != 0) { Iterator it = rrset.sigs(); while (it.hasNext()) { Record r = (Record) it.next(); if (r.getName().isWild() && !name.isWild()) r = r.withName(name); response.addRecord(r, section); } } } byte [] buildErrorMessage(Header header, int rcode, Record question) { Message response = new Message(); response.setHeader(header); for (int i = 0; i < 4; i++) response.removeAllRecords(i); if (rcode == Rcode.SERVFAIL) response.addRecord(question, Section.QUESTION); header.setRcode(rcode); return response.toWire(); } public byte [] errorMessage(Message query, int rcode) { return buildErrorMessage(query.getHeader(), rcode, query.getQuestion()); } public byte [] formerrMessage(byte [] in) { Header header; try { header = new Header(in); } catch (IOException e) { return null; } return buildErrorMessage(header, Rcode.FORMERR, null); } public Cache getCache(int dclass) { Cache c = (Cache) caches.get(new Integer(dclass)); if (c == null) { c = new Cache(dclass); caches.put(new Integer(dclass), c); } return c; } private static final ThreadLocal<Pair<InetAddress,InetAddress>> localAndRemoteInetAddresses = new ThreadLocal<>(); private static InetAddress getInetAddress( final Function<Pair<InetAddress,InetAddress>,InetAddress> extractor ) { return Optional.fromNullable( localAndRemoteInetAddresses.get( ) ).transform( extractor ).orNull( ); } static InetAddress getLocalInetAddress( ) { return getInetAddress( Pair.<InetAddress,InetAddress>left( ) ); } static InetAddress getRemoteInetAddress( ) { return getInetAddress( Pair.<InetAddress, InetAddress>right() ); } static void setLocalAndRemoteInetAddresses( InetAddress local, InetAddress remote ) { ConnectionHandler.localAndRemoteInetAddresses.set( Pair.pair( local, remote ) ); } static void clearInetAddresses( ) { ConnectionHandler.localAndRemoteInetAddresses.remove( ); } }
davenpcj5542009/eucalyptus
clc/modules/dns/src/main/java/com/eucalyptus/cloud/ws/ConnectionHandler.java
Java
gpl-3.0
17,449
const Command = require('../../structures/Command'); const request = require('node-superfetch'); const { GOOGLE_KEY } = process.env; module.exports = class ToxicityCommand extends Command { constructor(client) { super(client, { name: 'toxicity', aliases: ['perspective', 'comment-toxicity'], group: 'analyze', memberName: 'toxicity', description: 'Determines the toxicity of text.', credit: [ { name: 'Perspective API', url: 'https://www.perspectiveapi.com/#/' } ], args: [ { key: 'text', prompt: 'What text do you want to test the toxicity of?', type: 'string' } ] }); } async run(msg, { text }) { try { const { body } = await request .post('https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze') .query({ key: GOOGLE_KEY }) .send({ comment: { text }, languages: ['en'], requestedAttributes: { TOXICITY: {} } }); const toxicity = Math.round(body.attributeScores.TOXICITY.summaryScore.value * 100); if (toxicity >= 70) return msg.reply(`Likely to be perceived as toxic. (${toxicity}%)`); if (toxicity >= 40) return msg.reply(`Unsure if this will be perceived as toxic. (${toxicity}%)`); return msg.reply(`Unlikely to be perceived as toxic. (${toxicity}%)`); } catch (err) { return msg.reply(`Oh no, an error occurred: \`${err.message}\`. Try again later!`); } } };
dragonfire535/xiaobot
commands/analyze/toxicity.js
JavaScript
gpl-3.0
1,410
package org.cache2k.core; /* * #%L * cache2k core implementation * %% * Copyright (C) 2000 - 2021 headissue GmbH, Munich * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import org.cache2k.core.api.CommonMetrics; /** * @author Jens Wilke */ public interface CommonMetricsFactory { CommonMetrics.Updater create(Parameters p); interface Parameters { boolean isDisabled(); boolean isPrecise(); } }
headissue/cache2k
cache2k-core/src/main/java/org/cache2k/core/CommonMetricsFactory.java
Java
gpl-3.0
947
</div> </div> <div id="content_footer"></div> <div id="footer"> <p><? foreach($page_display as $page_i => $name) { ?><a href="<?= $page_i ?>"><?= $name ?></a> | <? } ?><a href="http://www.html5webtemplates.co.uk">design from html5webtemplates.co.uk</a></p> </div> </div> </html>
uakfdotb/mastering
style/one/footer.php
PHP
gpl-3.0
303
package com.fr.design.beans; import com.fr.stable.StringUtils; /** * * @author zhou * @since 2012-5-30下午12:12:42 */ public abstract class FurtherBasicBeanPane<T> extends BasicBeanPane<T> { /** * 是否是指定类型 * @param ob 对象 * @return 是否是指定类型 */ public abstract boolean accept(Object ob); /** * title应该是一个属性,不只是对话框的标题时用到,与其他组件结合时,也会用得到 * @return 绥化狂标题 */ @Deprecated public String title4PopupWindow(){ return StringUtils.EMPTY; } /** * 重置 */ public abstract void reset(); }
fanruan/finereport-design
designer_base/src/com/fr/design/beans/FurtherBasicBeanPane.java
Java
gpl-3.0
656
"""Holds all pytee logic."""
KonishchevDmitry/pytee
pytee/__init__.py
Python
gpl-3.0
29
/*++ Copyright (c) 1995-1996 Microsoft Corporation Module Name: lsapi.h Abstract: This module defines the 32-Bit Licensing API. The Licensing API is still pre-release (i.e. beta) code. Revision History: --*/ #ifndef LSAPI_H #define LSAPI_H #define LS_API_ENTRY WINAPI /***************************************************/ /* Standard LSAPI C status codes */ /***************************************************/ #define LS_SUCCESS ((LS_STATUS_CODE) 0x0) #define LS_BAD_HANDLE ((LS_STATUS_CODE) 0xC0001001) #define LS_INSUFFICIENT_UNITS ((LS_STATUS_CODE) 0xC0001002) #define LS_SYSTEM_UNAVAILABLE ((LS_STATUS_CODE) 0xC0001003) #define LS_LICENSE_TERMINATED ((LS_STATUS_CODE) 0xC0001004) #define LS_AUTHORIZATION_UNAVAILABLE ((LS_STATUS_CODE) 0xC0001005) #define LS_LICENSE_UNAVAILABLE ((LS_STATUS_CODE) 0xC0001006) #define LS_RESOURCES_UNAVAILABLE ((LS_STATUS_CODE) 0xC0001007) #define LS_NETWORK_UNAVAILABLE ((LS_STATUS_CODE) 0xC0001008) #define LS_TEXT_UNAVAILABLE ((LS_STATUS_CODE) 0x80001009) #define LS_UNKNOWN_STATUS ((LS_STATUS_CODE) 0xC000100A) #define LS_BAD_INDEX ((LS_STATUS_CODE) 0xC000100B) #define LS_LICENSE_EXPIRED ((LS_STATUS_CODE) 0x8000100C) #define LS_BUFFER_TOO_SMALL ((LS_STATUS_CODE) 0xC000100D) #define LS_BAD_ARG ((LS_STATUS_CODE) 0xC000100E) /* Microsoft provider-specific error codes */ // The name of the current user could not be retrieved. #define LS_NO_USERNAME ( (LS_STATUS_CODE) 0xC0002000 ) // An unexpected error occurred in a system call. #define LS_SYSTEM_ERROR ( (LS_STATUS_CODE) 0xC0002001 ) // The provider failed to properly initialize. #define LS_SYSTEM_INIT_FAILED ( (LS_STATUS_CODE) 0xC0002002 ) // An internal error has occurred in the Micrsoft provider. #define LS_INTERNAL_ERROR ( (LS_STATUS_CODE) 0xC0002002 ) /***************************************************/ /* standard LS API c datatype definitions */ /***************************************************/ typedef unsigned long LS_STATUS_CODE; typedef unsigned long LS_HANDLE; typedef char LS_STR; typedef unsigned long LS_ULONG; typedef long LS_LONG; typedef void LS_VOID; typedef struct { LS_STR MessageDigest[16]; /* a 128-bit message digest */ } LS_MSG_DIGEST; typedef struct { LS_ULONG SecretIndex; /* index of secret, X */ LS_ULONG Random; /* a random 32-bit value, R */ LS_MSG_DIGEST MsgDigest; /* the message digest h(in,R,S,Sx) */ } LS_CHALLDATA; typedef struct { LS_ULONG Protocol; /* Specifies the protocol */ LS_ULONG Size; /* size of ChallengeData structure */ LS_CHALLDATA ChallengeData; /* challenge & response */ } LS_CHALLENGE; /***************************************************/ /* Standard LSAPI C constant definitions */ /***************************************************/ #define LS_DEFAULT_UNITS ((LS_ULONG) 0xFFFFFFFF) #define LS_ANY ((LS_STR FAR *) "") #define LS_USE_LAST ((LS_ULONG) 0x0800FFFF) #define LS_INFO_NONE ((LS_ULONG) 0) #define LS_INFO_SYSTEM ((LS_ULONG) 1) #define LS_INFO_DATA ((LS_ULONG) 2) #define LS_UPDATE_PERIOD ((LS_ULONG) 3) #define LS_LICENSE_CONTEXT ((LS_ULONG) 4) #define LS_BASIC_PROTOCOL ((LS_ULONG) 0x00000001) #define LS_SQRT_PROTOCOL ((LS_ULONG) 0x00000002) #define LS_OUT_OF_BAND_PROTOCOL ((LS_ULONG) 0xFFFFFFFF) #define LS_NULL ((LS_VOID FAR *) NULL) // maximum length of a provider name returned by LSEnumProviders() #define LS_MAX_PROVIDER_NAME ( 255 ) // if returned by a call to LSQuery() against LS_UPDATE_PERIOD, // indicates that no interval recommendation is being made #define LS_NO_RECOMMENDATION ( (LS_ULONG) 0xFFFFFFFF ) /***************************************************/ /* Standard LSAPI C function definitions */ /***************************************************/ LS_STATUS_CODE LS_API_ENTRY LSRequest( LS_STR *LicenseSystem, LS_STR *PublisherName, LS_STR *ProductName, LS_STR *Version, LS_ULONG TotUnitsReserved, LS_STR *LogComment, LS_CHALLENGE *Challenge, LS_ULONG *TotUnitsGranted, LS_HANDLE *LicenseHandle ); LS_STATUS_CODE LS_API_ENTRY LSRelease( LS_HANDLE LicenseHandle, LS_ULONG TotUnitsConsumed, LS_STR *LogComment); LS_STATUS_CODE LS_API_ENTRY LSUpdate( LS_HANDLE LicenseHandle, LS_ULONG TotUnitsConsumed, LS_ULONG TotUnitsReserved, LS_STR *LogComment, LS_CHALLENGE *Challenge, LS_ULONG *TotUnitsGranted); LS_STATUS_CODE LS_API_ENTRY LSGetMessage( LS_HANDLE LicenseHandle, LS_STATUS_CODE Value, LS_STR *Buffer, LS_ULONG BufferSize); LS_STATUS_CODE LS_API_ENTRY LSQuery( LS_HANDLE LicenseHandle, LS_ULONG Information, LS_VOID *InfoBuffer, LS_ULONG BufferSize, LS_ULONG *ActualBufferSize); LS_STATUS_CODE LS_API_ENTRY LSEnumProviders( LS_ULONG Index, LS_STR *Buffer); LS_VOID LS_API_ENTRY LSFreeHandle( LS_HANDLE LicenseHandle ); /***************************************************/ /* Extension LSAPI C function definitions */ /***************************************************/ LS_STATUS_CODE LS_API_ENTRY LSInstall( LS_STR * ProviderPath ); /*++ Routine Description: Install the given DLL as a license system provider. NOTE: This API is a Microsoft extension to the LSAPI standard. Arguments: ProviderPath (LS_STR *) Path to the provider DLL to install. This should be a full path, and the DLL should be in the %SystemRoot%\System32 directory. Return Value: (LS_STATUS_CODE) LS_SUCCESS Provider is already installed or was successfully added. LS_BAD_ARG The parameters passed to the function were invalid. other An error occurred while attempting to install the provider. --*/ /***************************************************/ /* Extension LSAPI C function definitions */ /* (these will be supported only for the BETA SDK) */ /***************************************************/ // license types (node assignment, user assignment, or concurrent use assignment) typedef DWORD LS_LICENSE_TYPE; #define LS_LICENSE_TYPE_NODE ( 0 ) #define LS_LICENSE_TYPE_USER ( 1 ) #define LS_LICENSE_TYPE_SERVER ( 2 ) LS_STATUS_CODE LS_API_ENTRY LSLicenseUnitsSet( LS_STR * LicenseSystem, LS_STR * PublisherName, LS_STR * ProductName, LS_STR * Version, LS_LICENSE_TYPE LicenseType, LS_STR * UserName, LS_ULONG NumUnits, LS_ULONG NumSecrets, LS_ULONG * Secrets ); /*++ Routine Description: Set the number of units for the given license to the designated value. NOTE: This API is a Microsoft extension to the LSAPI standard, and WILL ONLY BE SUPPORTED FOR THE BETA RELEASE OF THE LSAPI SDK. Thereafter, licenses must be added using the common certicate format (CCF). APIs will be exposed to allow licenses to be auotmatically added by an application's SETUP program. Arguments: LicenseSystem (LS_STR *) License system to which to set the license information. If LS_ANY, the license will be offered to each installed license system until one returns success. PublisherName (LS_STR *) Publisher name for which to set the license info. ProductName (LS_STR *) Product name for which to set the license info. Version (LS_STR *) Product version for which to set the license info. LicenseType (LS_LICENSE_TYPE) Type of license for which to set the license info. UserName (LS_STR *) User for which to set the license info. If LS_NULL and the the license type is LS_LICENSE_TYPE_USER, the license info will be set for the user corresponding to the current thread. NumUnits (LS_ULONG) Units purchased for this license. NumSecrets (LS_ULONG) Number of application-specific secrets corresponding to this license. Secrets (LS_ULONG *) Array of application-specific secrets corresponding to this license. Return Value: (LS_STATUS_CODE) LS_SUCCESS License successfully installed. LS_BAD_ARG The parameters passed to the function were invalid. other An error occurred whil attempting to install the license. --*/ LS_STATUS_CODE LS_API_ENTRY LSLicenseUnitsGet( LS_STR * LicenseSystem, LS_STR * PublisherName, LS_STR * ProductName, LS_STR * Version, LS_STR * UserName, LS_ULONG * NumUnits ); /*++ Routine Description: Get the number of units for the given license. NOTE: This API is a Microsoft extension to the LSAPI standard, and WILL ONLY BE SUPPORTED FOR THE BETA RELEASE OF THE LSAPI SDK. Thereafter, licenses must be accessed using the common certicate format (CCF). Arguments: LicenseSystem (LS_STR *) License system for which to get the license information. If LS_ANY, each installed license system will be queried until one returns success. PublisherName (LS_STR *) Publisher name for which to get the license info. ProductName (LS_STR *) Product name for which to get the license info. Version (LS_STR *) Product version for which to get the license info. UserName (LS_STR *) User for which to get the license info. If LS_NULL and the the license type is LS_LICENSE_TYPE_USER, license info will be retrieved for the user corresponding to the current thread. NumUnits (LS_ULONG *) On return, the number of units purchased for this license. Return Value: (LS_STATUS_CODE) LS_SUCCESS Success. LS_BAD_ARG The parameters passed to the function were invalid. other An error occurred whil attempting to retrieve the license. --*/ #endif /* LSAPI_H */
dplc/dwin
dm/include/win32/LSAPI.H
C++
gpl-3.0
11,774
/* * Copyright (C) 2015 Marten Gajda <marten@dmfs.org> * * 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 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package org.dmfs.davclient.rfc7231; import org.dmfs.httpclientinterfaces.IHttpResponse; public class HttpOptions { public HttpOptions(IHttpResponse response) { } }
dmfs/jdav-client
src/org/dmfs/davclient/rfc7231/HttpOptions.java
Java
gpl-3.0
947
# ifndef CPPAD_CORE_REV_JAC_SPARSITY_HPP # define CPPAD_CORE_REV_JAC_SPARSITY_HPP /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-17 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the GNU General Public License Version 3. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ /* $begin rev_jac_sparsity$$ $spell Jacobian jac bool const rc cpp $$ $section Reverse Mode Jacobian Sparsity Patterns$$ $head Syntax$$ $icode%f%.rev_jac_sparsity( %pattern_in%, %transpose%, %dependency%, %internal_bool%, %pattern_out% )%$$ $head Purpose$$ We use $latex F : \B{R}^n \rightarrow \B{R}^m$$ to denote the $cref/AD function/glossary/AD Function/$$ corresponding to the operation sequence stored in $icode f$$. Fix $latex R \in \B{R}^{\ell \times m}$$ and define the function $latex \[ J(x) = R * F^{(1)} ( x ) \] $$ Given the $cref/sparsity pattern/glossary/Sparsity Pattern/$$ for $latex R$$, $code rev_jac_sparsity$$ computes a sparsity pattern for $latex J(x)$$. $head x$$ Note that the sparsity pattern $latex J(x)$$ corresponds to the operation sequence stored in $icode f$$ and does not depend on the argument $icode x$$. (The operation sequence may contain $cref CondExp$$ and $cref VecAD$$ operations.) $head SizeVector$$ The type $icode SizeVector$$ is a $cref SimpleVector$$ class with $cref/elements of type/SimpleVector/Elements of Specified Type/$$ $code size_t$$. $head f$$ The object $icode f$$ has prototype $codei% ADFun<%Base%> %f% %$$ $head pattern_in$$ The argument $icode pattern_in$$ has prototype $codei% const sparse_rc<%SizeVector%>& %pattern_in% %$$ see $cref sparse_rc$$. If $icode transpose$$ it is false (true), $icode pattern_in$$ is a sparsity pattern for $latex R$$ ($latex R^\R{T}$$). $head transpose$$ This argument has prototype $codei% bool %transpose% %$$ See $cref/pattern_in/rev_jac_sparsity/pattern_in/$$ above and $cref/pattern_out/rev_jac_sparsity/pattern_out/$$ below. $head dependency$$ This argument has prototype $codei% bool %dependency% %$$ see $cref/pattern_out/rev_jac_sparsity/pattern_out/$$ below. $head internal_bool$$ If this is true, calculations are done with sets represented by a vector of boolean values. Otherwise, a vector of sets of integers is used. $head pattern_out$$ This argument has prototype $codei% sparse_rc<%SizeVector%>& %pattern_out% %$$ This input value of $icode pattern_out$$ does not matter. If $icode transpose$$ it is false (true), upon return $icode pattern_out$$ is a sparsity pattern for $latex J(x)$$ ($latex J(x)^\R{T}$$). If $icode dependency$$ is true, $icode pattern_out$$ is a $cref/dependency pattern/dependency.cpp/Dependency Pattern/$$ instead of sparsity pattern. $head Sparsity for Entire Jacobian$$ Suppose that $latex R$$ is the $latex m \times m$$ identity matrix. In this case, $icode pattern_out$$ is a sparsity pattern for $latex F^{(1)} ( x )$$ ( $latex F^{(1)} (x)^\R{T}$$ ) if $icode transpose$$ is false (true). $head Example$$ $children% example/sparse/rev_jac_sparsity.cpp %$$ The file $cref rev_jac_sparsity.cpp$$ contains an example and test of this operation. It returns true if it succeeds and false otherwise. $end ----------------------------------------------------------------------------- */ # include <cppad/core/ad_fun.hpp> # include <cppad/local/sparse_internal.hpp> namespace CppAD { // BEGIN_CPPAD_NAMESPACE /*! Reverse Jacobian sparsity patterns. \tparam Base is the base type for this recording. \tparam SizeVector is the simple vector with elements of type size_t that is used for row, column index sparsity patterns. \param pattern_in is the sparsity pattern for for R or R^T depending on transpose. \param transpose Is the input and returned sparsity pattern transposed. \param dependency Are the derivatives with respect to left and right of the expression below considered to be non-zero: \code CondExpRel(left, right, if_true, if_false) \endcode This is used by the optimizer to obtain the correct dependency relations. \param internal_bool If this is true, calculations are done with sets represented by a vector of boolean values. Otherwise, a vector of standard sets is used. \param pattern_out The value of transpose is false (true), the return value is a sparsity pattern for J(x) ( J(x)^T ) where \f[ J(x) = R * F^{(1)} (x) \f] Here F is the function corresponding to the operation sequence and x is any argument value. */ template <class Base> template <class SizeVector> void ADFun<Base>::rev_jac_sparsity( const sparse_rc<SizeVector>& pattern_in , bool transpose , bool dependency , bool internal_bool , sparse_rc<SizeVector>& pattern_out ) { // number or rows, columns, and non-zeros in pattern_in size_t nr_in = pattern_in.nr(); size_t nc_in = pattern_in.nc(); // size_t ell = nr_in; size_t m = nc_in; if( transpose ) std::swap(ell, m); // CPPAD_ASSERT_KNOWN( m == Range() , "rev_jac_sparsity: number columns in R " "is not equal number of dependent variables." ); // number of independent variables size_t n = Domain(); // bool zero_empty = true; bool input_empty = true; if( internal_bool ) { // allocate memory for bool sparsity calculation // (sparsity pattern is emtpy after a resize) local::sparse_pack internal_jac; internal_jac.resize(num_var_tape_, ell); // // set sparsity patttern for dependent variables local::set_internal_sparsity( zero_empty , input_empty , ! transpose , dep_taddr_ , internal_jac , pattern_in ); // compute sparsity for other variables local::RevJacSweep( dependency, n, num_var_tape_, &play_, internal_jac ); // get sparstiy pattern for independent variables local::get_internal_sparsity( ! transpose, ind_taddr_, internal_jac, pattern_out ); } else { // allocate memory for bool sparsity calculation // (sparsity pattern is emtpy after a resize) local::sparse_list internal_jac; internal_jac.resize(num_var_tape_, ell); // // set sparsity patttern for dependent variables local::set_internal_sparsity( zero_empty , input_empty , ! transpose , dep_taddr_ , internal_jac , pattern_in ); // compute sparsity for other variables local::RevJacSweep( dependency, n, num_var_tape_, &play_, internal_jac ); // get sparstiy pattern for independent variables local::get_internal_sparsity( ! transpose, ind_taddr_, internal_jac, pattern_out ); } return; } } // END_CPPAD_NAMESPACE # endif
modsim/CADET-semi-analytic
ThirdParty/cppad/cppad/core/rev_jac_sparsity.hpp
C++
gpl-3.0
7,000
export const getIsAdmin = (state) => state.session.user?.administrator; export const getUserId = (state) => state.session.user?.id; export const getDevices = (state) => Object.values(state.devices.items); export const getPosition = (id) => (state) => state.positions.items[id];
tananaev/traccar-web
modern/src/common/selectors.js
JavaScript
gpl-3.0
281
package edu.stanford.rsl.conrad.numerics; import Jama.Matrix; import Jama.util.*; /** Singular Value Decomposition. <P> For an m-by-n matrix A, the singular value decomposition is an m-by-(m or n) orthogonal matrix U, a (m or n)-by-n diagonal matrix S, and an n-by-n orthogonal matrix V so that A = U*S*V'. <P> The singular values, sigma[k] = S[k][k], are ordered so that sigma[0] >= sigma[1] >= ... >= sigma[n-1]. <P> The singular value decompostion always exists, so the constructor will never fail. The matrix condition number and the effective numerical rank can be computed from this decomposition. <P> This class is mainly based on SingularValueDecomposition class in Jama in which SVD sometimes fails on cases m < n. The bug has been fixed by Ron Boisvert <boisvert@nist.gov>. Details of what were fixed can be found below: http://cio.nist.gov/esd/emaildir/lists/jama/msg01431.html http://cio.nist.gov/esd/emaildir/lists/jama/msg01430.html http://metamerist.blogspot.com/2008/04/svd-for-vertically-challenged.html Then, small changes were made to be compatible with CONRAD. @author Jang-Hwan Choi */ public class DecompositionSVD implements java.io.Serializable { /** * */ private static final long serialVersionUID = 201880439875521920L; /* ------------------------ Class variables * ------------------------ */ /** Arrays for internal storage of U and V. @serial internal storage of U. @serial internal storage of V. */ private double[][] U, V; /** Array for internal storage of singular values. @serial internal storage of singular values. */ private double[] s; /** Row and column dimensions. @serial row dimension. @serial column dimension. @serial U column dimension. */ private int m, n, ncu; /** Column specification of matrix U @serial U column dimension toggle */ private boolean thin; /** * <b>Old Constructor</b><br> * Construct the singular value decomposition * Structure to access U, S and V. * @param Arg Rectangular matrix * */ public DecompositionSVD (SimpleMatrix Arg) { this(Arg,true,true,true); } /* ------------------------ Constructor * ------------------------ */ /** * Construct the singular value decomposition, i.e. a * structure to access U, S and V. * @param Arg Rectangular matrix * @param thin If true U is economy sized * @param wantu If true generate the U matrix * @param wantv If true generate the V matrix * */ public DecompositionSVD (SimpleMatrix Arg, boolean thin, boolean wantu, boolean wantv) { // Derived from LINPACK code. // Initialize. double[][] A = Arg.copyAsDoubleArray(); m = Arg.getRows(); n = Arg.getCols(); this.thin = thin; ncu = thin?Math.min(m,n):m; s = new double [Math.min(m+1,n)]; if (wantu) U = new double [m][ncu]; if (wantv) V = new double [n][n]; double[] e = new double [n]; double[] work = new double [m]; // Reduce A to bidiagonal form, storing the diagonal elements // in s and the super-diagonal elements in e. int nct = Math.min(m-1,n); int nrt = Math.max(0,Math.min(n-2,m)); int lu = Math.max(nct,nrt); for (int k = 0; k < lu; k++) { if (k < nct) { // Compute the transformation for the k-th column and // place the k-th diagonal in s[k]. // Compute 2-norm of k-th column without under/overflow. s[k] = 0; for (int i = k; i < m; i++) { s[k] = Maths.hypot(s[k],A[i][k]); } if (s[k] != 0.0) { if (A[k][k] < 0.0) { s[k] = -s[k]; } for (int i = k; i < m; i++) { A[i][k] /= s[k]; } A[k][k] += 1.0; } s[k] = -s[k]; } for (int j = k+1; j < n; j++) { if ((k < nct) & (s[k] != 0.0)) { // Apply the transformation. double t = 0; for (int i = k; i < m; i++) { t += A[i][k]*A[i][j]; } t = -t/A[k][k]; for (int i = k; i < m; i++) { A[i][j] += t*A[i][k]; } } // Place the k-th row of A into e for the // subsequent calculation of the row transformation. e[j] = A[k][j]; } if (wantu & (k < nct)) { // Place the transformation in U for subsequent back // multiplication. for (int i = k; i < m; i++) { U[i][k] = A[i][k]; } } if (k < nrt) { // Compute the k-th row transformation and place the // k-th super-diagonal in e[k]. // Compute 2-norm without under/overflow. e[k] = 0; for (int i = k+1; i < n; i++) { e[k] = Maths.hypot(e[k],e[i]); } if (e[k] != 0.0) { if (e[k+1] < 0.0) { e[k] = -e[k]; } for (int i = k+1; i < n; i++) { e[i] /= e[k]; } e[k+1] += 1.0; } e[k] = -e[k]; if ((k+1 < m) & (e[k] != 0.0)) { // Apply the transformation. for (int i = k+1; i < m; i++) { work[i] = 0.0; } for (int j = k+1; j < n; j++) { for (int i = k+1; i < m; i++) { work[i] += e[j]*A[i][j]; } } for (int j = k+1; j < n; j++) { double t = -e[j]/e[k+1]; for (int i = k+1; i < m; i++) { A[i][j] += t*work[i]; } } } if (wantv) { // Place the transformation in V for subsequent // back multiplication. for (int i = k+1; i < n; i++) { V[i][k] = e[i]; } } } } // Set up the final bidiagonal matrix or order p. int p = Math.min(n,m+1); if (nct < n) { s[nct] = A[nct][nct]; } if (m < p) { s[p-1] = 0.0; } if (nrt+1 < p) { e[nrt] = A[nrt][p-1]; } e[p-1] = 0.0; // If required, generate U. if (wantu) { for (int j = nct; j < ncu; j++) { for (int i = 0; i < m; i++) { U[i][j] = 0.0; } U[j][j] = 1.0; } for (int k = nct-1; k >= 0; k--) { if (s[k] != 0.0) { for (int j = k+1; j < ncu; j++) { double t = 0; for (int i = k; i < m; i++) { t += U[i][k]*U[i][j]; } t = -t/U[k][k]; for (int i = k; i < m; i++) { U[i][j] += t*U[i][k]; } } for (int i = k; i < m; i++ ) { U[i][k] = -U[i][k]; } U[k][k] += 1.0; for (int i = 0; i < k-1; i++) { U[i][k] = 0.0; } } else { for (int i = 0; i < m; i++) { U[i][k] = 0.0; } U[k][k] = 1.0; } } } // If required, generate V. if (wantv) { for (int k = n-1; k >= 0; k--) { if ((k < nrt) & (e[k] != 0.0)) { for (int j = k+1; j < n; j++) { double t = 0; for (int i = k+1; i < n; i++) { t += V[i][k]*V[i][j]; } t = -t/V[k+1][k]; for (int i = k+1; i < n; i++) { V[i][j] += t*V[i][k]; } } } for (int i = 0; i < n; i++) { V[i][k] = 0.0; } V[k][k] = 1.0; } } // Main iteration loop for the singular values. int pp = p-1; int iter = 0; double eps = Math.pow(2.0,-52.0); double tiny = Math.pow(2.0,-966.0); while (p > 0) { int k,kase; // Here is where a test for too many iterations would go. // This section of the program inspects for // negligible elements in the s and e arrays. On // completion the variables kase and k are set as follows. // kase = 1 if s(p) and e[k-1] are negligible and k<p // kase = 2 if s(k) is negligible and k<p // kase = 3 if e[k-1] is negligible, k<p, and // s(k), ..., s(p) are not negligible (qr step). // kase = 4 if e(p-1) is negligible (convergence). for (k = p-2; k >= -1; k--) { if (k == -1) { break; } if (Math.abs(e[k]) <= tiny + eps*(Math.abs(s[k]) + Math.abs(s[k+1]))) { e[k] = 0.0; break; } } if (k == p-2) { kase = 4; } else { int ks; for (ks = p-1; ks >= k; ks--) { if (ks == k) { break; } double t = (ks != p ? Math.abs(e[ks]) : 0.) + (ks != k+1 ? Math.abs(e[ks-1]) : 0.); if (Math.abs(s[ks]) <= tiny + eps*t) { s[ks] = 0.0; break; } } if (ks == k) { kase = 3; } else if (ks == p-1) { kase = 1; } else { kase = 2; k = ks; } } k++; // Perform the task indicated by kase. switch (kase) { // Deflate negligible s(p). case 1: { double f = e[p-2]; e[p-2] = 0.0; for (int j = p-2; j >= k; j--) { double t = Maths.hypot(s[j],f); double cs = s[j]/t; double sn = f/t; s[j] = t; if (j != k) { f = -sn*e[j-1]; e[j-1] = cs*e[j-1]; } if (wantv) { for (int i = 0; i < n; i++) { t = cs*V[i][j] + sn*V[i][p-1]; V[i][p-1] = -sn*V[i][j] + cs*V[i][p-1]; V[i][j] = t; } } } } break; // Split at negligible s(k). case 2: { double f = e[k-1]; e[k-1] = 0.0; for (int j = k; j < p; j++) { double t = Maths.hypot(s[j],f); double cs = s[j]/t; double sn = f/t; s[j] = t; f = -sn*e[j]; e[j] = cs*e[j]; if (wantu) { for (int i = 0; i < m; i++) { t = cs*U[i][j] + sn*U[i][k-1]; U[i][k-1] = -sn*U[i][j] + cs*U[i][k-1]; U[i][j] = t; } } } } break; // Perform one qr step. case 3: { // Calculate the shift. double scale = Math.max(Math.max(Math.max(Math.max( Math.abs(s[p-1]),Math.abs(s[p-2])),Math.abs(e[p-2])), Math.abs(s[k])),Math.abs(e[k])); double sp = s[p-1]/scale; double spm1 = s[p-2]/scale; double epm1 = e[p-2]/scale; double sk = s[k]/scale; double ek = e[k]/scale; double b = ((spm1 + sp)*(spm1 - sp) + epm1*epm1)/2.0; double c = (sp*epm1)*(sp*epm1); double shift = 0.0; if ((b != 0.0) | (c != 0.0)) { shift = Math.sqrt(b*b + c); if (b < 0.0) { shift = -shift; } shift = c/(b + shift); } double f = (sk + sp)*(sk - sp) + shift; double g = sk*ek; // Chase zeros. for (int j = k; j < p-1; j++) { double t = Maths.hypot(f,g); double cs = f/t; double sn = g/t; if (j != k) { e[j-1] = t; } f = cs*s[j] + sn*e[j]; e[j] = cs*e[j] - sn*s[j]; g = sn*s[j+1]; s[j+1] = cs*s[j+1]; if (wantv) { for (int i = 0; i < n; i++) { t = cs*V[i][j] + sn*V[i][j+1]; V[i][j+1] = -sn*V[i][j] + cs*V[i][j+1]; V[i][j] = t; } } t = Maths.hypot(f,g); cs = f/t; sn = g/t; s[j] = t; f = cs*e[j] + sn*s[j+1]; s[j+1] = -sn*e[j] + cs*s[j+1]; g = sn*e[j+1]; e[j+1] = cs*e[j+1]; if (wantu && (j < m-1)) { for (int i = 0; i < m; i++) { t = cs*U[i][j] + sn*U[i][j+1]; U[i][j+1] = -sn*U[i][j] + cs*U[i][j+1]; U[i][j] = t; } } } e[p-2] = f; iter++; } break; // Convergence. case 4: { // Make the singular values positive. if (s[k] <= 0.0) { s[k] = (s[k] < 0.0 ? -s[k] : 0.0); if (wantv) { for (int i = 0; i < n; i++) { V[i][k] = -V[i][k]; } } } // Order the singular values. while (k < pp) { if (s[k] >= s[k+1]) { break; } double t = s[k]; s[k] = s[k+1]; s[k+1] = t; if (wantv && (k < n-1)) { for (int i = 0; i < n; i++) { t = V[i][k+1]; V[i][k+1] = V[i][k]; V[i][k] = t; } } if (wantu && (k < m-1)) { for (int i = 0; i < m; i++) { t = U[i][k+1]; U[i][k+1] = U[i][k]; U[i][k] = t; } } k++; } iter = 0; p--; } break; } } A = null; } /* ------------------------ Public Methods * ------------------------ */ /** Return the left singular vectors @return U */ public SimpleMatrix getU () { return U==null?null:(new SimpleMatrix(new Matrix(U,m,m>=n?(thin?Math.min(m+1,n):ncu):ncu))); } /** Return the right singular vectors @return V */ public SimpleMatrix getV () { return V==null?null:new SimpleMatrix(new Matrix(V,n,n)); } /** Return the one-dimensional array of singular values @return diagonal of S. */ public double[] getSingularValues () { return s; } /** Return the diagonal matrix of singular values @return S */ public SimpleMatrix getS () { SimpleMatrix X = new SimpleMatrix(new Matrix(m>=n?(thin?n:ncu):ncu,n)); for (int i = Math.min(m,n)-1; i>=0; i--) X.setElementValue(i, i, s[i]); return X; } /** Return the diagonal matrix of the reciprocals of the singular values @return S+ */ public SimpleMatrix getreciprocalS () { SimpleMatrix X = new SimpleMatrix(new Matrix(n,m>=n?(thin?n:ncu):ncu)); for (int i = Math.min(m,n)-1; i>=0; i--) X.setElementValue(i, i, s[i]==0.0?0.0:1.0/s[i]); return X; } /** Return the Moore-Penrose (generalized) inverse * Slightly modified version of Kim van der Linde's code @param omit if true tolerance based omitting of negligible singular values @return A+ */ public SimpleMatrix inverse(boolean omit) { double[][] inverse = new double[n][m]; if(rank()> 0) { double[] reciprocalS = new double[s.length]; if (omit) { double tol = Math.max(m,n)*s[0]*Math.pow(2.0,-52.0); for (int i = s.length-1;i>=0;i--) reciprocalS[i] = Math.abs(s[i])<tol?0.0:1.0/s[i]; } else for (int i=s.length-1;i>=0;i--) reciprocalS[i] = s[i]==0.0?0.0:1.0/s[i]; int min = Math.min(n, ncu); for (int i = n-1; i >= 0; i--) for (int j = m-1; j >= 0; j--) for (int k = min-1; k >= 0; k--) inverse[i][j] += V[i][k] * reciprocalS[k] * U[j][k]; } return new SimpleMatrix(new Matrix(inverse)); } /** Two norm @return max(S) */ public double norm2 () { return s[0]; } /** Two norm condition number @return max(S)/min(S) */ public double cond () { return s[0]/s[Math.min(m,n)-1]; } /** Effective numerical matrix rank @return Number of nonnegligible singular values. */ public int rank () { double tol = Math.max(m,n)*s[0]*Math.pow(2.0,-52.0); int r = 0; for (int i = 0; i < s.length; i++) { if (s[i] > tol) { r++; } } return r; } } /* * Copyright (C) 2010-2014 Jang-Hwan Choi * CONRAD is developed as an Open Source project under the GNU General Public License (GPL). */
YixingHuang/CONRAD
src/edu/stanford/rsl/conrad/numerics/DecompositionSVD.java
Java
gpl-3.0
14,143
package net.sourceforge.seqware.common.util.filetools.lock; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.channels.FileLock; import java.nio.charset.StandardCharsets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p> * LockingFileTools class. * </p> * * @author boconnor * @version $Id: $Id */ public class LockingFileTools { private static final Logger LOGGER = LoggerFactory.getLogger(LockingFileTools.class); private static final int RETRIES = 100; public static boolean lockAndAppend(File file, String output) { return lockAndWrite(file, output, true); } /** * Try to acquire lock. If we can, write the String to file and then release the lock * * @param file * a {@link java.io.File} object. * @param output * a {@link java.lang.String} object. * @param append * @return a boolean. */ public static boolean lockAndWrite(File file, String output, boolean append) { for (int i = 0; i < RETRIES; i++) { try { try (FileOutputStream fos = new FileOutputStream(file, append)) { FileLock fl = fos.getChannel().tryLock(); if (fl != null) { try (OutputStreamWriter fw = new OutputStreamWriter(fos, StandardCharsets.UTF_8)) { fw.append(output); fl.release(); } // LOGGER.info("LockingFileTools.lockAndWrite Locked, appended, and released for file: "+file.getAbsolutePath()+" value: "+output); return true; } else { LOGGER.info("LockingFileTools.lockAndWrite Can't get lock for " + file.getAbsolutePath() + " try number " + i + " of " + RETRIES); // sleep for 2 seconds before trying again Thread.sleep(2000); } } } catch (IOException | InterruptedException e) { LOGGER.error("LockingFileTools.lockAndWrite Attempt " + i + " Exception with LockingFileTools: " + e.getMessage(), e); } } LOGGER.error("LockingFileTools.lockAndWrite Unable to get lock for " + file.getAbsolutePath() + " gave up after " + RETRIES + " tries"); return false; } }
oicr-gsi/niassa
seqware-common/src/main/java/net/sourceforge/seqware/common/util/filetools/lock/LockingFileTools.java
Java
gpl-3.0
2,474
<?php App::uses('AppController', 'Controller'); class CentrosController extends AppController { var $name = 'Centros'; public $uses = array('Centro', 'Titulacion'); var $paginate = array('Centro' => array('limit' => 4, 'order' => 'Centro.cue ASC')); public function beforeFilter() { parent::beforeFilter(); //Si el usuario tiene un rol de superadmin le damos acceso a todo. //Si no es así (se trata de un usuario "admin o usuario") tendrá acceso sólo a las acciones que les correspondan. if($this->Auth->user('role') === 'superadmin') { $this->Auth->allow(); } elseif (($this->Auth->user('role') === 'admin') || ($this->Auth->user('role') === 'usuario')) { $this->Auth->allow('index', 'view', 'autocompleteCentro', 'autocompleteSeccionDependiente'); } } function index() { $this->Centro->recursive = -1; $this->paginate['Centro']['limit'] = 4; $this->paginate['Centro']['order'] = array('Centro.nivel' => 'ASC'); $this->redirectToNamed(); $conditions = array(); if(!empty($this->params['named']['cue'])) { $conditions['Centro.cue ='] = $this->params['named']['cue']; } $centros = $this->paginate('Centro', $conditions); $this->set(compact('centros')); $this->loadModel('Ciudad'); $ciudades = $this->Ciudad->find('list', array('fields' => array('nombre'))); $this->set('ciudades', $ciudades); } function view($id = null) { if (!$id) { $this->Session->setFlash('Centro no valido', 'default', array('class' => 'alert alert-danger')); $this->redirect(array('action' => 'index')); } $this->set('centro', $this->Centro->read(null, $id)); $this->loadModel('Barrio'); $barrios = $this->Barrio->find('list', array('fields' => array('nombre'))); $this->set('barrios', $barrios); $this->loadModel('Ciudad'); $ciudades = $this->Ciudad->find('list', array('fields' => array('nombre'))); $this->set('ciudades', $ciudades); $this->loadModel('Departamento'); $departamentos = $this->Departamento->find('list', array('fields' => array('nombre'))); $this->set('departamentos', $departamentos); } function add() { //abort if cancel button was pressed if(isset($this->params['data']['cancel'])){ $this->Session->setFlash('Los cambios no fueron guardados. Agregación cancelada.', 'default', array('class' => 'alert alert-warning')); $this->redirect( array( 'action' => 'index' )); } if (!empty($this->data)) { $this->Centro->create(); if ($this->Centro->save($this->data)) { $this->Session->setFlash('El centro ha sido grabado', 'default', array('class' => 'alert alert-success')); //$this->redirect(array('action' => 'index')); $inserted_id = $this->Centro->id; $this->redirect(array('action' => 'view', $inserted_id)); } else { $this->Session->setFlash('El centro no fue grabado. Intentelo nuevamente.', 'default', array('class' => 'alert alert-danger')); } } $empleados = $this->Centro->Empleado->find('list', array('fields'=>array('id', 'nombre_completo_empleado'))); $this->set(compact('empleados')); $this->loadModel('Barrio'); $barrios = $this->Barrio->find('list', array('fields' => array('nombre'))); $this->set('barrios', $barrios); $this->loadModel('Ciudad'); $ciudades = $this->Ciudad->find('list', array('fields' => array('nombre'))); $this->set('ciudades', $ciudades); $this->loadModel('Departamento'); $departamentos = $this->Departamento->find('list', array('fields' => array('nombre'))); $this->set('departamentos', $departamentos); } function edit($id = null) { if (!$id && empty($this->data)) { $this->Session->setFlash('Centro no valido', 'default', array('class' => 'alert alert-warning')); $this->redirect(array('action' => 'index')); } if (!empty($this->data)) { //abort if cancel button was pressed if(isset($this->params['data']['cancel'])){ $this->Session->setFlash('Los cambios no fueron guardados. Edición cancelada.', 'default', array('class' => 'alert alert-warning')); $this->redirect( array( 'action' => 'index' )); } if ($this->Centro->save($this->data)) { $this->Session->setFlash('El centro ha sido grabado', 'default', array('class' => 'alert alert-success')); //$this->redirect(array('action' => 'index')); $inserted_id = $this->Centro->id; $this->redirect(array('action' => 'view', $inserted_id)); } else { $this->Session->setFlash('El centro no fue grabado. Intentelo nuevamente.', 'default', array('class' => 'alert alert-danger')); } } if (empty($this->data)) { $this->data = $this->Centro->read(null, $id); } $empleados = $this->Centro->Empleado->find('list', array('fields'=>array('id', 'nombre_completo_empleado'))); $titulacions = $this->Titulacion->find('list'); $this->set(compact('titulacions', $titulacions)); $this->set(compact('empleados')); $this->loadModel('Barrio'); $barrios = $this->Barrio->find('list', array('fields' => array('nombre'))); $this->set('barrios', $barrios); $this->loadModel('Ciudad'); $ciudades = $this->Ciudad->find('list', array('fields' => array('nombre'))); $this->set('ciudades', $ciudades); $this->loadModel('Departamento'); $departamentos = $this->Departamento->find('list', array('fields' => array('nombre'))); $this->set('departamentos', $departamentos); } function delete($id = null) { if (!$id) { $this->Session->setFlash('id no valido para centro', 'default', array('class' => 'alert alert-warning')); $this->redirect(array('action'=>'index')); } if ($this->Centro->delete($id)) { $this->Session->setFlash('El centro ha sido borrado', 'default', array('class' => 'alert alert-success')); $this->redirect(array('action'=>'index')); } $this->Session->setFlash('El centro no fue borrado. Intentelo nuevamente.', 'default', array('class' => 'alert alert-danger')); $this->redirect(array('action' => 'index')); } /* function imprimir($id = null) { $this->idEmpty($id,'index'); $centro = $this->Centro->read(null, $id); $this->__createCentroPDF($centro); } */ public function listarCiudad($id) { if (is_numeric($id)) { $this->layout = 'ajax'; $this->loadModel('Ciudad'); $lista_Ciudad=$this->Ciudad->find('list',array('conditions' => array('departamento_id' => $id))); $this->set('lista_Ciudad',$lista_Ciudad); } echo json_encode($lista_Ciudad); $this->autoRender = false; } public function listarBarrios($id) { if (is_numeric($id)) { $this->layout = 'ajax'; $this->loadModel('Barrio'); $lista_barrios=$this->Barrio->find('list',array('conditions' => array('ciudad_id' => $id))); $this->set('lista_barrios',$lista_barrios); } echo json_encode($lista_barrios); $this->autoRender = false; } // metodos privados. /* function __createCentroPDF($centro) { App::import(null,null,true,array(),'vendors/tcpdf/examples/example_001',false); Configure::write('debug',0); $this->layout = 'pdf'; /* esto utilizara el layout 'pdf.ctp' */ /* Operaciones que deseamos realizar y variables que pasaremos a la vista. $this->render(); } */ public function autocompleteCentro() { $term = null; $conditions = array(); $term = $this->request->query('term'); // Primero obtiene el termino a buscar if(!empty($term)) { // Si el termino es numerico, filtro por cue if(is_numeric($term)) { $conditions[] = array('cue LIKE ' => '%'.$term.'%'); } else { // Se esta buscando por nombre del centro $terminos = explode(' ', trim($term)); $terminos = array_diff($terminos,array('')); foreach($terminos as $termino) { $conditions[] = array('sigla LIKE' => '%' . $termino . '%'); } } } $centro = $this->Centro->find('all', array( 'recursive' => -1, 'conditions' => $conditions, 'fields' => array('id', 'sigla')) ); $this->RequestHandler->respondAs('json'); // Responde con el header correspondiente a json echo json_encode($centro); $this->autoRender = false; } public function autocompleteSeccionDependiente() { $id = $this->request->query('id'); $this->loadModel('Curso'); $secciones = $this->Curso->find('list', array( 'recursive'=>-1, 'fields'=>array('id','nombre_completo_curso'), 'conditions'=>array( 'centro_id'=>$id) )); $this->RequestHandler->respondAs('json'); // Responde con el header correspondiente a json $this->autoRender = false; echo json_encode($secciones); } } ?>
santiagogil/siep
Controller/CentrosController.php
PHP
gpl-3.0
8,553
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Gdata * @subpackage Gdata * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: EntryLink.php,v 1.1.2.3 2011-05-30 08:30:46 root Exp $ */ /** * @see Zend_Gdata_Extension */ require_once 'Zend/Gdata/Extension.php'; /** * @see Zend_Gdata_Entry */ require_once 'Zend/Gdata/Entry.php'; /** * Represents the gd:entryLink element * * @category Zend * @package Zend_Gdata * @subpackage Gdata * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Gdata_Extension_EntryLink extends Zend_Gdata_Extension { protected $_rootElement = 'entryLink'; protected $_href = null; protected $_readOnly = null; protected $_rel = null; protected $_entry = null; public function __construct($href = null, $rel = null, $readOnly = null, $entry = null) { parent::__construct(); $this->_href = $href; $this->_readOnly = $readOnly; $this->_rel = $rel; $this->_entry = $entry; } public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) { $element = parent::getDOM($doc, $majorVersion, $minorVersion); if ($this->_href !== null) { $element->setAttribute('href', $this->_href); } if ($this->_readOnly !== null) { $element->setAttribute('readOnly', ($this->_readOnly ? "true" : "false")); } if ($this->_rel !== null) { $element->setAttribute('rel', $this->_rel); } if ($this->_entry !== null) { $element->appendChild($this->_entry->getDOM($element->ownerDocument)); } return $element; } protected function takeChildFromDOM($child) { $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; switch ($absoluteNodeName) { case $this->lookupNamespace('atom') . ':' . 'entry'; $entry = new Zend_Gdata_Entry(); $entry->transferFromDOM($child); $this->_entry = $entry; break; default: parent::takeChildFromDOM($child); break; } } protected function takeAttributeFromDOM($attribute) { switch ($attribute->localName) { case 'href': $this->_href = $attribute->nodeValue; break; case 'readOnly': if ($attribute->nodeValue == "true") { $this->_readOnly = true; } else if ($attribute->nodeValue == "false") { $this->_readOnly = false; } else { throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for gCal:selected#value."); } break; case 'rel': $this->_rel = $attribute->nodeValue; break; default: parent::takeAttributeFromDOM($attribute); } } /** * @return string */ public function getHref() { return $this->_href; } public function setHref($value) { $this->_href = $value; return $this; } public function getReadOnly() { return $this->_readOnly; } public function setReadOnly($value) { $this->_readOnly = $value; return $this; } public function getRel() { return $this->_rel; } public function setRel($value) { $this->_rel = $value; return $this; } public function getEntry() { return $this->_entry; } public function setEntry($value) { $this->_entry = $value; return $this; } }
MailCleaner/MailCleaner
www/framework/Zend/Gdata/Extension/EntryLink.php
PHP
gpl-3.0
4,414
# PiTimer - Python Hardware Programming Education Project For Raspberry Pi # Copyright (C) 2015 Jason Birch # # 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 3 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 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 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, see <http://www.gnu.org/licenses/>. #/****************************************************************************/ #/* PiTimer - Step 8 - Controlling physical relays. */ #/* ------------------------------------------------------------------------ */ #/* V1.00 - 2015-07-04 - Jason Birch */ #/* ------------------------------------------------------------------------ */ #/* Class to handle user input, output display and interface state machine. */ #/****************************************************************************/ import string import operator import datetime import SystemTime import Schedule import ScheduleItem # Constants to define current user interface display. STATE_MAIN_MENU = 0 STATE_ADD_SCHEDULE = 1 STATE_DEL_SCHEDULE = 2 STATE_RELAY_STATES = 3 STATE_SCHEDULE = 4 STATE_SET_SYSTEM_TIME = 5 STATE_SHUTDOWN = 6 # Constants to define display modes. MODE_STANDARD = 0 MODE_CONFIRM = 1 class UserInterface: def __init__(self, NewWIndow, NewThisSchedule, NewThisRelays): # Store a reference to the system window class to display onto. self.ThisWindow = NewWIndow # Store a reference to the schedule class to display schedule inforamtion. self.ThisSchedule = NewThisSchedule # Store a reference to the relays class to display relay inforamtion. self.ThisRelays = NewThisRelays # Create an instance of the system time class, to display the system time. self.ThisSystemTime = SystemTime.SystemTime() # Display application splash screen on initialisation. self.DisplaySplash() # Buffer for input strings. self.InputBuffer = "" # List position, moved by user. self.SelectPos = 0 self.SelectID = 0 # Display the initial user interface, the main menu. self.InterfaceState = STATE_MAIN_MENU #/***************************************************/ #/* Display a splash screen for application startup */ #/* to show information about this application. */ #/***************************************************/ def DisplaySplash(self): self.ThisWindow.clear() self.ThisWindow.refresh() print("{:^20}".format("PiTimer") + "\r") print("{:^20}".format("2015-06-23") + "\r") print("{:^20}".format("Version 1.00") + "\r") print("{:^20}".format("(C) Jason Birch") + "\r") self.ThisWindow.refresh() #/***********************************************************************/ #/* Distribute key press events to the current user interface function. */ #/***********************************************************************/ def KeyPress(self, KeyCode): Result = KeyCode if self.InterfaceState == STATE_MAIN_MENU: Result = self.KeysMainMenu(KeyCode) elif self.InterfaceState == STATE_ADD_SCHEDULE: Result = self.KeysAddSchedule(KeyCode) elif self.InterfaceState == STATE_DEL_SCHEDULE: Result = self.KeysDelSchedule(KeyCode) elif self.InterfaceState == STATE_SCHEDULE: Result = self.KeysSchedule(KeyCode) elif self.InterfaceState == STATE_RELAY_STATES: Result = self.KeysRelayStates(KeyCode) elif self.InterfaceState == STATE_SET_SYSTEM_TIME: Result = self.KeysSetSystemTime(KeyCode) return Result #/****************************************************************/ #/* Certain user interface displays need to update every second. */ #/****************************************************************/ def DisplayRefresh(self): if self.InterfaceState == STATE_MAIN_MENU: self.DisplayMainMenu() elif self.InterfaceState == STATE_ADD_SCHEDULE: self.DisplayAddSchedule() elif self.InterfaceState == STATE_DEL_SCHEDULE: self.DisplayDelSchedule() elif self.InterfaceState == STATE_SCHEDULE: self.DisplaySchedule() elif self.InterfaceState == STATE_RELAY_STATES: self.DisplayRelayStates() elif self.InterfaceState == STATE_SET_SYSTEM_TIME: self.DisplaySetSystemTime() #/*******************************************************/ #/* Change the current user interface to a new display. */ #/*******************************************************/ def SetInterfaceState(self, NewInterfaceState): # Start on standard display mode. self.Mode = MODE_STANDARD # Clear the input buffer. self.InputBuffer = "" # Reset list selection position. self.SelectPos =0 self.SelectID = 0 self.InterfaceState = NewInterfaceState if self.InterfaceState == STATE_MAIN_MENU: self.DisplayMainMenu() elif self.InterfaceState == STATE_ADD_SCHEDULE: self.DisplayAddSchedule() elif self.InterfaceState == STATE_DEL_SCHEDULE: self.DisplayDelSchedule() elif self.InterfaceState == STATE_SCHEDULE: self.DisplaySchedule() elif self.InterfaceState == STATE_RELAY_STATES: self.DisplayRelayStates() elif self.InterfaceState == STATE_SET_SYSTEM_TIME: self.DisplaySetSystemTime() #/*********************************************************/ #/* Provided the input from the user and a mask to define */ #/* how to display the input, format a string to display. */ #/*********************************************************/ def GetMaskedInput(self, Mask, Input): InputCount = 0 Result = "" for Char in Mask: if Char == "#" and len(Input) > InputCount: Result += Input[InputCount:InputCount + 1] InputCount += 1 else: Result += Char return Result #/************************************************/ #/* Gather the input required for an input mask. */ #/************************************************/ def KeyMaskedInput(self, Mask, Input, KeyCode): # If a valid key is pressed, add to the input buffer. if len(Input) < Mask.count("#") and KeyCode >= ord("0") and KeyCode <= ord("9"): Input += chr(KeyCode) # If delete key is pressed, delete the last entered key. elif KeyCode == 127 and len(Input) > 0: Input = Input[:-1] return Input #/*****************************/ #/* MAIN MENU user interface. */ #/*****************************/ def DisplayMainMenu(self): self.ThisWindow.clear() self.ThisWindow.refresh() print("{:>20}".format(self.ThisSystemTime.SystemTimeString()) + "\r") print("{:^20}".format("1 Add 4 Schedule") + "\r") print("{:^20}".format("2 Delete 5 Set Time") + "\r") print("{:^20}".format("3 Relays 6 Shutdown") + "\r") self.ThisWindow.refresh() def KeysMainMenu(self, KeyCode): Result = KeyCode # If menu item 1 is selected, change to display add schedule. if KeyCode == ord("1"): self.SetInterfaceState(STATE_ADD_SCHEDULE) # If menu item 2 is selected, change to display del schedule. if KeyCode == ord("2"): self.SetInterfaceState(STATE_DEL_SCHEDULE) # If menu item 3 is selected, change to display relay states. if KeyCode == ord("3"): self.SetInterfaceState(STATE_RELAY_STATES) # If menu item 4 is selected, change to display schedule. if KeyCode == ord("4"): self.SetInterfaceState(STATE_SCHEDULE) # If menu item 5 is selected, change to display set system time. if KeyCode == ord("5"): self.SetInterfaceState(STATE_SET_SYSTEM_TIME) # If menu item 6 is selected, return ESC key to the application main loop. if KeyCode == ord("6"): Result = 27 return Result #/********************************/ #/* RELAY STATES user interface. */ #/********************************/ def DisplayRelayStates(self): self.ThisWindow.clear() self.ThisWindow.refresh() self.ThisRelays.DisplayRelayStates() self.ThisWindow.refresh() def KeysRelayStates(self, KeyCode): Result = KeyCode # If enter key is pressed, change to display main menu. if KeyCode == 10: self.SetInterfaceState(STATE_MAIN_MENU) return Result #/********************************/ #/* ADD SCHEDULE user interface. */ #/********************************/ def DisplayAddSchedule(self): self.ThisWindow.clear() self.ThisWindow.refresh() print("{:^20}".format("ADD SCHEDULE") + "\r") print(self.GetMaskedInput("####-##-## ##:##:##\r\nPeriod ### ##:##:##\r\nRelay ## State #\r", self.InputBuffer)) self.ThisWindow.refresh() def KeysAddSchedule(self, KeyCode): Result = KeyCode self.InputBuffer = self.KeyMaskedInput("####-##-## ##:##:## ### ##:##:## ## #", self.InputBuffer, KeyCode) # If enter key is pressed, change to display main menu. if KeyCode == 10: # If full user input has been gathered, add a schedule item. if len(self.InputBuffer) == 26: # Parse user input. UserInput = self.GetMaskedInput("####-##-## ##:##:## ### ##:##:## ## #", self.InputBuffer) RelayState = { "0":ScheduleItem.RELAY_OFF, "1":ScheduleItem.RELAY_ON, "2":ScheduleItem.RELAY_TOGGLE, }.get(UserInput[36:37], ScheduleItem.RELAY_TOGGLE) PeriodSeconds = string.atoi(UserInput[30:32]) + 60 * string.atoi(UserInput[27:29]) + 60 * 60 * string.atoi(UserInput[24:26]) + 24 * 60 * 60 * string.atoi(UserInput[20:23]) PeriodDays = operator.div(PeriodSeconds, 24 * 60 * 60) PeriodSeconds = operator.mod(PeriodSeconds, 24 * 60 * 60) # Add schedule item, ignore errors from invalid data entered. try: self.ThisSchedule.AddSchedule(string.atoi(UserInput[33:35]), datetime.datetime(string.atoi(UserInput[0:4]), string.atoi(UserInput[5:7]), string.atoi(UserInput[8:10]), string.atoi(UserInput[11:13]), string.atoi(UserInput[14:16]), string.atoi(UserInput[17:19])), RelayState, datetime.timedelta(PeriodDays, PeriodSeconds)) except: print("") self.ThisWindow.refresh() self.SetInterfaceState(STATE_MAIN_MENU) return Result #/********************************/ #/* DEL SCHEDULE user interface. */ #/********************************/ def DisplayDelSchedule(self): self.ThisWindow.clear() self.ThisWindow.refresh() if self.Mode == MODE_STANDARD: print("{:^20}".format("DELETE SCHEDULE") + "\r") print("\r") if self.ThisSchedule.GetItemCount(): self.SelectID = self.ThisSchedule.DisplaySchedule(self.SelectPos, 1) else: print("{:^20}".format("Empty") + "\r") elif self.Mode == MODE_CONFIRM: print("{:^20}".format("DELETE SCHEDULE") + "\r") print("\r") print("{:^20}".format("ARE YOU SURE?") + "\r") print("{:^20}".format("(4=N, 6=Y)") + "\r") self.ThisWindow.refresh() def KeysDelSchedule(self, KeyCode): Result = KeyCode if self.Mode == MODE_STANDARD: # If a key at the top of the keypad is pressed, move up the list. if (KeyCode == ord("1") or KeyCode == ord("2") or KeyCode == ord("3")) and self.SelectPos > 0: self.SelectPos -= 1 # If a key at the bottom of the keypad is pressed, move down the list. elif (KeyCode == ord("0") or KeyCode == ord("7") or KeyCode == ord("8") or KeyCode == ord("9")) and self.SelectPos < self.ThisSchedule.GetItemCount() - 1: self.SelectPos += 1 # If enter key is pressed, enter confirm mode. if KeyCode == 10: if self.ThisSchedule.GetItemCount(): self.Mode = MODE_CONFIRM else: self.SetInterfaceState(STATE_MAIN_MENU) # If delete key is pressed, change to display main menu. if KeyCode == 127: self.SetInterfaceState(STATE_MAIN_MENU) elif self.Mode == MODE_CONFIRM: if KeyCode == ord("4"): self.SetInterfaceState(STATE_MAIN_MENU) elif KeyCode == ord("6"): self.ThisSchedule.DelSchedule(self.SelectID) self.SetInterfaceState(STATE_MAIN_MENU) return Result #/************************************/ #/* CURRENT SCHEDULE user interface. */ #/************************************/ def DisplaySchedule(self): self.ThisWindow.clear() self.ThisWindow.refresh() if self.ThisSchedule.GetItemCount(): self.ThisSchedule.DisplaySchedule(self.SelectPos, 2) else: print("\r") print("{:^20}".format("Empty") + "\r") self.ThisWindow.refresh() def KeysSchedule(self, KeyCode): Result = KeyCode # If a key at the top of the keypad is pressed, move up the list. if (KeyCode == ord("1") or KeyCode == ord("2") or KeyCode == ord("3")) and self.SelectPos > 0: self.SelectPos -= 1 # If a key at the bottom of the keypad is pressed, move down the list. elif (KeyCode == ord("0") or KeyCode == ord("7") or KeyCode == ord("8") or KeyCode == ord("9")) and self.SelectPos < self.ThisSchedule.GetItemCount() - 1: self.SelectPos += 1 # If enter key is pressed, change to display main menu. elif KeyCode == 10: self.SetInterfaceState(STATE_MAIN_MENU) return Result #/***********************************/ #/* SET SYSTEM TIME user interface. */ #/***********************************/ def DisplaySetSystemTime(self): self.ThisWindow.clear() self.ThisWindow.refresh() print("{:^20}".format("SET SYSTEM TIME") + "\r") print(self.GetMaskedInput("####-##-## ##:##:##\r", self.InputBuffer)) self.ThisWindow.refresh() def KeysSetSystemTime(self, KeyCode): Result = KeyCode self.InputBuffer = self.KeyMaskedInput("####-##-## ##:##:##", self.InputBuffer, KeyCode) # If enter key is pressed, change to display main menu. if KeyCode == 10: # If full user input has been gathered, set the system time. if len(self.InputBuffer) == 14: # BOOKMARK: THIS IS A PLACEHOLDER FOR WHEN THE CLOCK MODLUE IS IMPLEMENTED. self.ThisSystemTime.SetSystemTime(self.GetMaskedInput("####-##-## ##:##:##", self.InputBuffer)) self.SetInterfaceState(STATE_MAIN_MENU) return Result
BirchJD/RPiTimer
PiTimer_Step-8/UserInterface.py
Python
gpl-3.0
14,823
/******************************************************************************** -- Halo Dev Controls Copyright © 2011 Jesus7Freak 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 3 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 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 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, see <http://www.gnu.org/licenses/>. ********************************************************************************* File: CMDParser.cpp Project: HDC Author: Jesus7Freak Date: 11/22/2011 Game: Halo and Halo Custom Edition Version: all *********************************************************************************/ #include "dllmain.h" wchar_t *FailLocalCmd = L"Failed: Local Command Only.", *FailSvCmd = L"Failed: Server Command Only.", *FailInvalNum = L"Failed: Invalid number(s).", *FailInvalBool = L"Failed: Invalid boolean.", *FailBadSpawn = L"Failed: Unable to create Object(s) next to %s", //*FailBadExec = L"Failed: Execution failed, is dev enabled?.", *FailPlyrNtFnd = L"Failed: Player(s) not found.", *FailBadTeleLoc = L"Failed: Teleport location is not defined.", *FailMissingLoc = L"Failed: Missing teleport location name.", *FailNoSpaces = L"Failed: No spaces allowed in teleport location name.", *FailLowAdminLvl = L"Failed: %s has a higher admin level.", *FailPlyrNtSpwn = L"Failed: %s hasn't respawned.", *FailPlyrNtInVeh = L"Failed: %s is not in a vehicle.", *FailPlyrNoWep = L"Failed: %s does not have a weapon."; //kill messages wchar_t *SuccededKillMsgs[8] = { L"%s was given lethal injection", L"%s was sent to a gas chamber", L"%s was killed by firing squad", L"%s was killed by hanging", L"%s was killed by The Guardians", L"THIS IS SPARTA!!!!!!!!! (%s gets kicked into a bottomless pit)", L"%s was killed by a vehicle", L"GIVE UP GIVE UP AND FEED THE MACHINE!!!!!!! (%s was fed to the machine)" }; typedef BOOL (__fastcall *CmdFunc)(wchar_t *cmd_args, short exec_player_index); CmdFunc HaloCmdFuncs[HALO_CMDS_SIZE] = { Halo::CommandHelp, Halo::ListCommands, Halo::ListTeleportLocs, Halo::EnableConsole, Halo::EnableDevMode, Halo::CheatsDeathless, Halo::CheatsInfiniteAmmo, Halo::CheatsBottomlessClip, Halo::ShowHudFunc, Halo::LetterBoxFunc, Halo::RiderEjectionFunc, Halo::CheatsOmnipotent, Halo::CheatsJetPack, Halo::CheatsBumpPossession, Halo::CheatsSuperJump, Halo::CheatsMedusa, Halo::CheatsReflexiveDamage, Halo::CheatsXboxController, Halo::ShowWireFrame, Halo::ShowFog, Halo::ShowFogPlane, Halo::ShowFPS, Halo::Game_Speed, Halo::Rapid_Fire, Halo::Time_Freeze, Halo::Grav_Boots, Halo::Vehicle_NTR, Halo::Marines_HUD }; CmdFunc RpgCmdFuncs[RPGB_CMDS_SIZE] = { RPG::Environment_Day, RPG::Environment_Rain, RPG::Environment_Night, RPG::AirBase_Alarm, RPG::AirBase_LockDown, RPG::Fire_Halo, RPG::LockDown_Timer, RPG::Halo_Timer }; CmdFunc PlayerCmdFuncs[PLAYER_CMDS_SIZE] = { Player::Speed, Player::ActiveCamo, Player::Suspend, Player::Teleport, Player::Jump_Teleport, Player::Velocity, Player::Ammo, Player::Battery, Player::Health, Player::Shield, Player::AFK, Player::Team_Change, Player::Kick, Player::Ban, Player::Kill, Player::Eject, Player::Flip_Vehicle, Player::Admin, Player::Set_Teleport_Loc, Player::Spawn_Biped, Player::Spawn_Hog, Player::Spawn_All_Vehicles, Player::Spawn_All_Weapons, Player::Spawn_All_Powerups, Player::Copy_Vehicle, Player::Copy_Weapon, Player::Destroy_Objects_Mode, Player::Destroy_Weapon, Player::Say, Player::ObjectScale }; CmdFunc *AllCmdFuncs[CMD_SET_SIZE] = { PlayerCmdFuncs, HaloCmdFuncs, RpgCmdFuncs }; int ParseCMDStrPlayers(wchar_t *cmd_str, short* player_index_array, int &pi_found) { int max_players_to_find, wchars_processed = 0; HaloCE_lib::DATA_HEADER *Players = *Players_ptr; int NumOfPlayers = Players->NumOfItems; if (pi_found) { max_players_to_find = pi_found; pi_found = 0; } else max_players_to_find = NumOfPlayers; if (*cmd_str == L'\"') { cmd_str++; wchars_processed += 2; } for (int pi = 0, vpi = 0; pi_found < max_players_to_find && vpi < NumOfPlayers; pi++) { if (!players[pi].PlayerID) continue; else vpi++; int j = 0; wchar_t *player_name = players[pi].PlayerName0; bool str_contain_search = false; for (int i = 0; i < HaloCE_lib::PlayerNameMaxSize; i++) { wchar_t cmd_str_wchar = cmd_str[j]; if (cmd_str_wchar == L'*') { wchar_t next_wchar = cmd_str[j + 1]; if (!next_wchar || next_wchar == L' ' || next_wchar == L'\"') { wchars_processed = j; player_index_array[pi_found++] = pi; break; } else { cmd_str_wchar = cmd_str[++j]; str_contain_search = true; } } if (cmd_str_wchar == L'?') continue; if (cmd_str_wchar != player_name[i]) { if (!str_contain_search) break; else continue; } if (!player_name[i + 1]) { wchars_processed = j; player_index_array[pi_found++] = pi; break; } j++; } } if (pi_found > 0) wchars_processed += 1; else wchars_processed = 0; return wchars_processed; } //functions calling this need to test if first CMD_CALL_INFO::cmd[0] == '/' DWORD __fastcall CMDParser(wchar_t *cmd_str, short exec_player_index) { if (!TempAdmin[exec_player_index]) return FALSE; int cmd_name_length = 0; while (cmd_str[cmd_name_length] && cmd_str[cmd_name_length++] != L' '); wchar_t *add_space = &cmd_str[cmd_name_length]; if (!add_space[0]) { add_space[1] = 0; add_space[0] = ' '; cmd_name_length++; } bool found = false; BOOL succeded = FALSE; for (int cmd_group_i = 0; !found && cmd_group_i < CMD_SET_SIZE; cmd_group_i++) { CMDsLib::COMMANDS *cmd_group = CMDsLib::all_commands[cmd_group_i]; char **cmd_strs = cmd_group->cmd_strs; int group_size = cmd_group->size; CmdFunc *CmdGroupFuncs = AllCmdFuncs[cmd_group_i]; for (int i = 0; i < group_size; i++) { //skip the / as it already has been check by the hook if (str_cmpAW(&cmd_strs[i][1], cmd_str, cmd_name_length)) { found = true; succeded = (*CmdGroupFuncs[i])(&cmd_str[cmd_name_length], exec_player_index); break; } } } return succeded; } BOOL __fastcall Halo::CommandHelp(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; //uses the space like a null terminator short cmd_arg_length = 0; while (cmd_args[cmd_arg_length]) cmd_arg_length++; cmd_args[cmd_arg_length + 1] = 0; cmd_args[cmd_arg_length] = ' '; wchar_t *chat_header = NULL, *chat_usage = NULL, *chat_descript = NULL; for (int cmd_group_i = 0; !chat_header && cmd_group_i < 3; cmd_group_i++) { CMDsLib::COMMANDS *cmd_group = CMDsLib::all_commands[cmd_group_i]; char **cmd_strs = cmd_group->cmd_strs; int group_size = cmd_group->size; for (int i = 0; !chat_header && i < group_size; i++) { if (str_cmpAW(cmd_strs[i], cmd_args, cmd_arg_length)) { CMDsLib::CMD_DESCRIPT *pCDS = cmd_group->cmd_descripts; chat_header = pCDS[i].cmd_header; chat_usage = pCDS[i].cmd_usage; chat_descript = pCDS[i].cmd_descript; break; } } } if (!chat_header && str_cmpAW("[pExpression] ", cmd_args, cmd_arg_length)) { HaloSay(L"example use of [pExpression]: Shadow, AoO Aurora, N®Þ»Jedi", exec_player_index); HaloSay(L"/spd Shadow 4 - normal use", exec_player_index); HaloSay(L"/spd \"AoO Aurora\" 4 - use quotes when the name has spaces", exec_player_index); HaloSay(L"/spd ????Jedi 4 - use ? when you don't know the character", exec_player_index); chat_header = L"/spd *Jedi 4 - all players with Jedi at the end of their name"; chat_usage = L"/spd AoO* 4 - all players with AoO at the beggining of their name"; chat_descript = L"/spd * 4 - all players"; } //defualt to help desciption else if (!chat_header) { CMDsLib::CMD_DESCRIPT *pCDS = CMDsLib::halo_cmd_descripts; chat_header = pCDS[0].cmd_header; chat_usage = pCDS[0].cmd_usage; } if (chat_header) succeded = TRUE; else chat_header = L"Failed: command not found."; HaloSay(chat_header, exec_player_index); if (chat_usage) HaloSay(chat_usage, exec_player_index); if (chat_descript) HaloSay(chat_descript, exec_player_index); return succeded; } BOOL __fastcall Halo::ListCommands(wchar_t *cmd_args, short exec_player_index) { int list_i = 0; wchar_t list_str[128]; list_str[list_i++] = ' '; for (int cmd_group_i = 0; cmd_group_i < 3; cmd_group_i++) { CMDsLib::COMMANDS *cmd_group = CMDsLib::all_commands[cmd_group_i]; char **cmd_strs = cmd_group->cmd_strs; int group_size = cmd_group->size; for (int i = 0; i < group_size; i++) { char *cmd_str = cmd_strs[i]; int j = 0; char _char = ' '; do { list_str[list_i++] = (wchar_t)_char; _char = cmd_str[j++]; }while (_char); if (list_i > 112) { list_str[list_i] = 0;//add null terminator HaloSay(list_str, exec_player_index); list_i = 1; } } //print the last line of the group if (list_i > 1) { list_str[list_i] = 0;//add null terminator HaloSay(list_str, exec_player_index); list_i = 1; } } return TRUE; } BOOL __fastcall Halo::ListTeleportLocs(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; int list_i = 0; //seems like a good idea wchar_t list_str[128]; list_str[list_i++] = ' '; unsigned int map_i = 0; if (FindMapIndex(&maps_tele_sites, Current_Map_Str, map_i)) { int loc_num = maps_tele_sites[map_i].teleport_locations.size(); TELEPORT_LOCATION *locs = &maps_tele_sites[map_i].teleport_locations[0]; for (int loc_i = 0; loc_i < loc_num; loc_i++) { wchar_t *loc_str = locs[loc_i].teleport_loc_name; int j = 0; wchar_t _wchar = L' '; do { list_str[list_i++] = _wchar; _wchar = loc_str[j++]; }while (_wchar); //extra padding list_str[list_i++] = L' '; if (list_i > 112) { list_str[list_i] = 0;//add null terminator HaloSay(list_str, exec_player_index); list_i = 1; } } //print the last line of the group if (list_i > 1) { list_str[list_i] = 0;//add null terminator HaloSay(list_str, exec_player_index); } succeded = TRUE; } else HaloSay( L"Failed: Their are no teleport locations defined, for this map.", exec_player_index);//, Current_Map_Str); is not a wchar_t* return succeded; } BOOL __fastcall Halo::EnableConsole(wchar_t *cmd_args, short exec_player_index) { //host only cmd if (exec_player_index) { HaloSay(FailLocalCmd, exec_player_index); return FALSE; } BOOL succeded = FALSE; BOOL _bool; if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { *Console_enabled = (BYTE)_bool; succeded = TRUE; } else HaloSay(FailInvalBool, exec_player_index); return succeded; } BOOL __fastcall Halo::EnableDevMode(wchar_t *cmd_args, short exec_player_index) { if (running_gt != haloce) { HaloSay(L"Failed: Halo Custom Edition only command", exec_player_index); return FALSE; } //host only cmd if (exec_player_index) { HaloSay(FailLocalCmd, exec_player_index); return FALSE; } BOOL succeded = FALSE; BOOL _bool; if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { *Dev_enabled = (BYTE)_bool; succeded = TRUE; } else HaloSay(FailInvalBool, exec_player_index); return succeded; } BOOL __fastcall Halo::CheatsDeathless(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL; BOOL _bool; if (!*cmd_args) { _bool = cheats->Deathless; GenericMsg = L"Deathless is set at %i"; } else if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { cheats->Deathless = (BYTE)_bool; succeded = TRUE; GenericMsg = L"Deathless has been set to %i"; } else GenericMsg = FailInvalBool; HaloSay(GenericMsg, exec_player_index, _bool); return succeded; } BOOL __fastcall Halo::CheatsInfiniteAmmo(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL; BOOL _bool; if (!*cmd_args) { _bool = cheats->Infinite_Ammo; GenericMsg = L"Infinite Ammo is set at %i"; } else if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { cheats->Infinite_Ammo = (BYTE)_bool; succeded = TRUE; GenericMsg = L"Infinite Ammo has been set to %i"; } else GenericMsg = FailInvalBool; HaloSay(GenericMsg, exec_player_index, _bool); return succeded; } BOOL __fastcall Halo::CheatsBottomlessClip(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL; BOOL _bool; if (!*cmd_args) { _bool = cheats->Bottomless_Clip; GenericMsg = L"Bottomless Clip is set at %i"; } else if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { cheats->Bottomless_Clip = (BYTE)_bool; succeded = TRUE; GenericMsg = L"Bottomless Clip has been set to %i"; } else GenericMsg = FailInvalBool; HaloSay(GenericMsg, exec_player_index, _bool); return succeded; } BOOL __fastcall Halo::ShowHudFunc(wchar_t *cmd_args, short exec_player_index) { //host only cmd if (exec_player_index) { HaloSay(FailLocalCmd, exec_player_index); return FALSE; } BOOL succeded = FALSE; BOOL _bool; if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { *ShowHud = (BYTE)_bool; succeded = TRUE; } else HaloSay(FailInvalBool, exec_player_index); return succeded; } BOOL __fastcall Halo::LetterBoxFunc(wchar_t *cmd_args, short exec_player_index) { //host only cmd if (exec_player_index) { HaloSay(FailLocalCmd, exec_player_index); return FALSE; } BOOL succeded = FALSE; BOOL _bool; if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { *LetterBox = (BYTE)_bool; succeded = TRUE; } else HaloSay(FailInvalBool, exec_player_index); return succeded; } BOOL __fastcall Halo::RiderEjectionFunc(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL; BOOL _bool; if (!*cmd_args) { _bool = *RiderEjection; GenericMsg = L"Rider Ejection is set at %i"; } else if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { *RiderEjection = (BYTE)_bool; succeded = TRUE; GenericMsg = L"Rider Ejection has been set to %i"; } else GenericMsg = FailInvalBool; HaloSay(GenericMsg, exec_player_index, _bool); return succeded; } BOOL __fastcall Halo::CheatsOmnipotent(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL; BOOL _bool; if (!*cmd_args) { _bool = cheats->Omnipotent; GenericMsg = L"Omnipotent is set at %i"; } else if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { cheats->Omnipotent = (BYTE)_bool; succeded = TRUE; GenericMsg = L"Omnipotent has been set to %i"; } else GenericMsg = FailInvalBool; HaloSay(GenericMsg, exec_player_index, _bool); return succeded; } BOOL __fastcall Halo::CheatsJetPack(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL; BOOL _bool; if (!*cmd_args) { _bool = !cheats->JetPack; GenericMsg = L"Fall Damage is set at %i"; } else if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { cheats->JetPack = !(BYTE)_bool; succeded = TRUE; GenericMsg = L"Fall Damage has been set to %i"; } else GenericMsg = FailInvalBool; HaloSay(GenericMsg, exec_player_index, _bool); return succeded; } BOOL __fastcall Halo::CheatsBumpPossession(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL; BOOL _bool; if (!*cmd_args) { _bool = cheats->Bmp_Possession; GenericMsg = L"Bump Possession is set at %i"; } else if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { cheats->Bmp_Possession = (BYTE)_bool; succeded = TRUE; GenericMsg = L"Bump Possession has been set to %i"; } else GenericMsg = FailInvalBool; HaloSay(GenericMsg, exec_player_index, _bool); return succeded; } BOOL __fastcall Halo::CheatsSuperJump(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL; BOOL _bool; if (!*cmd_args) { _bool = cheats->Super_jump; GenericMsg = L"Super Jump is set at %i"; } else if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { cheats->Super_jump = (BYTE)_bool; succeded = TRUE; GenericMsg = L"Super Jump has been set to %i"; } else GenericMsg = FailInvalBool; HaloSay(GenericMsg, exec_player_index, _bool); return succeded; } BOOL __fastcall Halo::CheatsReflexiveDamage(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; BOOL _bool; if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { cheats->Reflexive_damage = (BYTE)_bool; succeded = TRUE; } else HaloSay(FailInvalBool, exec_player_index); return succeded; } BOOL __fastcall Halo::CheatsMedusa(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL; BOOL _bool; if (!*cmd_args) { _bool = cheats->Medusa; GenericMsg = L"Medusa is set at %i"; } else if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { cheats->Medusa = (BYTE)_bool; succeded = TRUE; GenericMsg = L"Medusa has been set to %i"; } else GenericMsg = FailInvalBool; HaloSay(GenericMsg, exec_player_index, _bool); return succeded; } BOOL __fastcall Halo::CheatsXboxController(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; BOOL _bool; if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { cheats->Controller = (BYTE)_bool; succeded = TRUE; } else HaloSay(FailInvalBool, exec_player_index); return succeded; } BOOL __fastcall Halo::ShowWireFrame(wchar_t *cmd_args, short exec_player_index) { //host only cmd if (exec_player_index) { HaloSay(FailLocalCmd, exec_player_index); return FALSE; } BOOL succeded = FALSE; BOOL _bool; if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { rasterizer->WireFrame = (BYTE)_bool; succeded = TRUE; } else HaloSay(FailInvalBool, exec_player_index); return succeded; } BOOL __fastcall Halo::ShowFog(wchar_t *cmd_args, short exec_player_index) { //host only cmd if (exec_player_index) { HaloSay(FailLocalCmd, exec_player_index); return FALSE; } BOOL succeded = FALSE; BOOL _bool; if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { rasterizer->FogAtmosphere = (BYTE)_bool; succeded = TRUE; } else HaloSay(FailInvalBool, exec_player_index); return succeded; } BOOL __fastcall Halo::ShowFogPlane(wchar_t *cmd_args, short exec_player_index) { //host only cmd if (exec_player_index) { HaloSay(FailLocalCmd, exec_player_index); return FALSE; } BOOL succeded = FALSE; BOOL _bool; if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { rasterizer->FogPlane = (BYTE)_bool; succeded = TRUE; } else HaloSay(FailInvalBool, exec_player_index); return succeded; } BOOL __fastcall Halo::ShowFPS(wchar_t *cmd_args, short exec_player_index) { //host only cmd if (exec_player_index) { HaloSay(FailLocalCmd, exec_player_index); return FALSE; } BOOL succeded = FALSE; BOOL _bool; if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { rasterizer->FPS = (BYTE)_bool; succeded = TRUE; } else HaloSay(FailInvalBool, exec_player_index); return succeded; } BOOL __fastcall Halo::Game_Speed(wchar_t *cmd_args, short exec_player_index) { //host only cmd if (exec_player_index) { HaloSay(FailLocalCmd, exec_player_index); return FALSE; } BOOL succeded = FALSE; wchar_t *GenericMsg = NULL; float fnumber; if (!*cmd_args) { fnumber = *game_speed; GenericMsg = L"Game Speed is set at %.2f"; } else if (CMDsLib::ParseStrFloat(cmd_args, &fnumber)) { *game_speed = fnumber; succeded = TRUE; GenericMsg = L"Game Speed has been set to %.2f"; } else GenericMsg = FailInvalBool; HaloSay(GenericMsg, exec_player_index, fnumber); return succeded; } BOOL __fastcall Halo::Rapid_Fire(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL; BOOL _bool; if (!*cmd_args) { _bool = ckbx_rapid_fire_CheckedChanged(-1); GenericMsg = L"Rapid Fire is set at %i"; } else if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { ckbx_rapid_fire_CheckedChanged((BYTE)_bool); succeded = TRUE; GenericMsg = L"Rapid Fire has been set to %i"; } else GenericMsg = FailInvalBool; HaloSay(GenericMsg, exec_player_index, _bool); return succeded; } BOOL __fastcall Halo::Time_Freeze(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL; BOOL _bool; if (!*cmd_args) { _bool = ckbx_time_freeze_CheckedChanged(-1); GenericMsg = L"Time Freeze is set at %i"; } else if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { ckbx_time_freeze_CheckedChanged((BYTE)_bool); succeded = TRUE; GenericMsg = L"Time Freeze has been set to %i"; } else GenericMsg = FailInvalBool; HaloSay(GenericMsg, exec_player_index, _bool); return succeded; } BOOL __fastcall Halo::Grav_Boots(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL; BOOL _bool; if (!*cmd_args) { _bool = ckbx_grav_boots_CheckedChanged(-1); GenericMsg = L"Grav Boots is set at %i"; } else if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { ckbx_grav_boots_CheckedChanged((BYTE)_bool); succeded = TRUE; GenericMsg = L"Grav Boots has been set to %i"; } else GenericMsg = FailInvalBool; HaloSay(GenericMsg, exec_player_index, _bool); return succeded; } BOOL __fastcall Halo::Vehicle_NTR(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL; BOOL _bool; if (!*cmd_args) { _bool = ckbx_vehicle_ntr_CheckedChanged(-1); GenericMsg = L"Vehicle Team Restriction is set at %i"; } else if (CMDsLib::ParseStrBool(cmd_args, &_bool)) { ckbx_vehicle_ntr_CheckedChanged((BYTE)_bool); succeded = TRUE; GenericMsg = L"Vehicle Team Restriction has been set to %i"; } else GenericMsg = FailInvalBool; HaloSay(GenericMsg, exec_player_index, _bool); return succeded; } /*BOOL __stdcall Halo::Execute_Console_Func(CMD_CALL_INFO *pCCI) { BOOL succeded = FALSE; char *console_cmd = &Chat_Buffer_64A[cmd_info_array_index][pCCI->cmd_name_length]; //for names with quotes if (*console_cmd == '\"') { int last_char_i = pCCI->cmd_length - pCCI->cmd_name_length - 1; if (console_cmd[last_char_i] == '\"') { console_cmd[last_char_i] = 0; console_cmd++; } } //this would be bad if this was allowed if (!str_cmpA(console_cmd, "quit")) { //if (!Console(cmd)) // HaloSay(FailBadExec); __asm { PUSH 0 //compiler puts this on the stack, not a register... MOV EDI,[console_cmd]; CALL DWORD PTR [Console_func_address] ADD ESP,4 TEST AL,AL JNE SHORT console_succeded } HaloSay(FailBadExec, exec_player_index); __asm { console_succeded: MOV succeded,TRUE } } return succeded; }*/ BOOL __fastcall Halo::Marines_HUD(wchar_t *cmd_args, short exec_player_index) { //host only cmd if (exec_player_index) { HaloSay(FailLocalCmd, exec_player_index); return FALSE; } BOOL succeded = FALSE; int number = 0; if (CMDsLib::ParseStrInt(cmd_args, &number)) { if (MV_chkBx_CheckedChanged(number)) succeded = TRUE; } else HaloSay(FailInvalNum, exec_player_index); return succeded; } BOOL __fastcall RPG::Environment_Day(wchar_t *cmd_args, short exec_player_index) { if (!rpgb6_2_running) { HaloSay(L"Failed: rpg_beta6_2 only command", exec_player_index); return FALSE; } short *setting = (short*)((*HS_Globals_ptr)->FirstItem + HCE_Lib::rpg_beta6_2_hs_global::setting_offset); if (*setting != 0) { *setting = 0; HaloSay(L"*the sun has come up*", -1); } return TRUE; } BOOL __fastcall RPG::Environment_Rain(wchar_t *cmd_args, short exec_player_index) { if (!rpgb6_2_running) { HaloSay(L"Failed: rpg_beta6_2 only command", exec_player_index); return FALSE; } short *setting = (short*)((*HS_Globals_ptr)->FirstItem + HCE_Lib::rpg_beta6_2_hs_global::setting_offset); if (*setting != 1) { *setting = 1; HaloSay(L"*a dense fog covers the entire area as it starts to rain*", -1); } return TRUE; } BOOL __fastcall RPG::Environment_Night(wchar_t *cmd_args, short exec_player_index) { if (!rpgb6_2_running) { HaloSay(L"Failed: rpg_beta6_2 only command", exec_player_index); return FALSE; } short *setting = (short*)((*HS_Globals_ptr)->FirstItem + HCE_Lib::rpg_beta6_2_hs_global::setting_offset); if (*setting != 2) { *setting = 2; HaloSay(L"*the sun has gone down*", -1); } return TRUE; } BOOL __fastcall RPG::AirBase_Alarm(wchar_t *cmd_args, short exec_player_index) { if (!rpgb6_2_running) { HaloSay(L"Failed: rpg_beta6_2 only command", exec_player_index); return FALSE; } BOOL succeded = FALSE; wchar_t *GenericMsg; bool *alarmed = (bool*)((*HS_Globals_ptr)->FirstItem + HCE_Lib::rpg_beta6_2_hs_global::alarmed_offset); bool *alarm_control_2 = (bool*)((*Device_Groups_ptr)->FirstItem + HCE_Lib::rpg_beta6_2_device_groups::alarm_control_2_offset); int number = 0; if (CMDsLib::ParseStrBool(cmd_args, &number)) { if (number == 1) { if (!*alarmed) *alarm_control_2 = true; GenericMsg = L"The Levis Station's alarm has been triggered."; } else if (number == 0) { if (*alarmed) *alarm_control_2 = true; GenericMsg = L"The Levis Station's alarm has been switched off."; } succeded = TRUE; } else GenericMsg = FailInvalNum; HaloSay(GenericMsg, -1); return succeded; } BOOL __fastcall RPG::AirBase_LockDown(wchar_t *cmd_args, short exec_player_index) { if (!rpgb6_2_running) { HaloSay(L"Failed: rpg_beta6_2 only command", exec_player_index); return FALSE; } BOOL succeded = FALSE; wchar_t *GenericMsg; bool *locked = (bool*)((*HS_Globals_ptr)->FirstItem + HCE_Lib::rpg_beta6_2_hs_global::locked_offset); bool *lock_control = (bool*)((*Device_Groups_ptr)->FirstItem + HCE_Lib::rpg_beta6_2_device_groups::lock_control_offset); if (!*locked) { *lock_control = true; succeded = TRUE; GenericMsg = L"Levis Station's lockdown procedures have been initiated."; } else GenericMsg = L"Failed: Levis Station has already been locked down."; HaloSay(GenericMsg, -1); return succeded; } BOOL __fastcall RPG::Fire_Halo(wchar_t *cmd_args, short exec_player_index) { if (!rpgb6_2_running) { HaloSay(L"Failed: rpg_beta6_2 only command", exec_player_index); return FALSE; } BOOL succeded = FALSE; wchar_t *GenericMsg; bool *nuked = (bool*)((*HS_Globals_ptr)->FirstItem + HCE_Lib::rpg_beta6_2_hs_global::nuked_offset); bool *boom_control = (bool*)((*Device_Groups_ptr)->FirstItem + HCE_Lib::rpg_beta6_2_device_groups::boom_control_offset); if (!*nuked) { *boom_control = true; succeded = TRUE; GenericMsg = L"Halo will be fired when someone is in close proximity to the control room."; } else GenericMsg = L"Failed: Halo is not ready to fire."; HaloSay(GenericMsg, -1); return succeded; } BOOL __fastcall RPG::LockDown_Timer(wchar_t *cmd_args, short exec_player_index) { if (!rpgb6_2_running) { HaloSay(L"Failed: rpg_beta6_2 only command", exec_player_index); return FALSE; } BOOL succeded = FALSE; wchar_t *GenericMsg = NULL; short *lock_timer = (short*)((*HS_Globals_ptr)->FirstItem + HCE_Lib::rpg_beta6_2_hs_global::lock_timer_offset); int number; //displayer info if (!*cmd_args) { succeded = TRUE; GenericMsg = L"lock_timer var is set at %i seconds."; } else if (CMDsLib::ParseStrInt(cmd_args, &number)) { *lock_timer = (short)(number * 30); succeded = TRUE; GenericMsg = L"lock_timer var has been set to %i seconds."; } else GenericMsg = FailInvalNum; HaloSay(GenericMsg, exec_player_index, *lock_timer / 30); return succeded; } BOOL __fastcall RPG::Halo_Timer(wchar_t *cmd_args, short exec_player_index) { if (!rpgb6_2_running) { HaloSay(L"Failed: rpg_beta6_2 only command", exec_player_index); return FALSE; } BOOL succeded = FALSE; wchar_t *GenericMsg = NULL; short *boom_timer = (short*)((*HS_Globals_ptr)->FirstItem + HCE_Lib::rpg_beta6_2_hs_global::boom_timer_offset); int number; //displayer info if (!*cmd_args) { succeded = TRUE; GenericMsg = L"boom_timer var is set at %i seconds."; } else if (CMDsLib::ParseStrInt(cmd_args, &number)) { *boom_timer = (short)(number * 30); succeded = TRUE; GenericMsg = L"boom_timer var has been set to %i seconds."; } else GenericMsg = FailInvalNum; HaloSay(GenericMsg, exec_player_index, *boom_timer / 30); return succeded; } inline DWORD GetObj(short obj_index) { DWORD obj_address = NULL; if(obj_index != -1)//valid index? if (objects[obj_index].ObjectID)//valid ID? obj_address = objects[obj_index].Object_ptr; return obj_address; } inline HaloCE_lib::SPARTAN* GetPlayerObj(short player_index) { return (HaloCE_lib::SPARTAN*)GetObj(players[player_index].PlayerObjTag.Index); } inline HaloCE_lib::VEHICLE_OBJECT* GetPlayerVehObj(HaloCE_lib::SPARTAN* player_obj) { HaloCE_lib::VEHICLE_OBJECT *veh_obj_address = NULL; if (player_obj->VehicleTag.Index != -1) veh_obj_address = (HaloCE_lib::VEHICLE_OBJECT*)GetObj(player_obj->VehicleTag.Index); return veh_obj_address; } inline bool KillPlayer(short player_index) { bool succeded = false; HaloCE_lib::SPARTAN *player_object = GetPlayerObj(player_index); if(player_object) { player_object->KillPlayer = 0x20; succeded = true; } return succeded; } //HaloCE_lib::OBJECT_TAG CreateObject(HaloCE_lib::OBJECT_TAG ObjTypeTag, float coordinates[3]) void __declspec(naked) CreateObject() { //HaloCE_lib::OBJECT_TAG NewObjTag; __asm { PUSH 0x3F800000 PUSH 0x3F800000 PUSH 0x3F800000 PUSH 0x3F800000 PUSH 0x3F800000 PUSH 0x3F800000 PUSH 0x3F800000 PUSH 0x3F800000 PUSH 0x3F800000 PUSH 0x3F800000 PUSH 0x3F800000 PUSH 0x3F800000 //spin vector PUSH 0//0x3F800000 PUSH 0 PUSH 0 //m_Scale PUSH 0x3F800000//0xBF800000 PUSH 0x80000000 PUSH 0x80000000 //m_LowerRot PUSH 0 PUSH 0//0xBEEDC4BB PUSH 0x3F800000//0x3F62B8A6 //m_Velocity? PUSH 0 PUSH 0 PUSH 0 PUSH 0 //coordinates PUSH DWORD PTR [ECX+8]//0x42DD6B85//0x42DF3BE8 PUSH DWORD PTR [ECX+4]//0x441BDE9D//0x441D0C44 PUSH DWORD PTR [ECX]//0xC3933039//0xC38D246E PUSH 0x0000FFFF PUSH 0 PUSH 0xFFFFFFFF PUSH 0xFFFFFFFF PUSH 0 PUSH EDX ;//ObjTypeTag MOV EDX,ESP PUSH ECX;//saving ECX too PUSH 0 PUSH EDX CALL DWORD PTR [CreateObj_func_address] ADD ESP,8 POP ECX POP EDX ;//restore EDX ADD ESP,84h RETN } //return NewObjTag; } BOOL __fastcall Player::Speed(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL; short Player_Indexes[16]; int pi_found = 0; int arg_len; if ((arg_len = ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found))) { cmd_args += arg_len; float fnumber = 0; //displayer info if (!*cmd_args) { for (int i = 0; i < pi_found; i++) { HaloCE_lib::STATIC_PLAYER *pSP = &players[Player_Indexes[i]]; HaloSay( L"%s's speed modifier is %.2f", exec_player_index, pSP->PlayerName0, pSP->SpeedModifier); } succeded = TRUE; } else if (CMDsLib::ParseStrFloat(++cmd_args, &fnumber)) { for (int i = 0; i < pi_found; i++) { HaloCE_lib::STATIC_PLAYER *pSP = &players[Player_Indexes[i]]; wchar_t *SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { HaloCE_lib::SPARTAN *player_object = GetPlayerObj(Player_Indexes[i]), *vehicle_object; if (player_object && (vehicle_object = (HaloCE_lib::SPARTAN*)GetPlayerVehObj(player_object))) { //vehicle_object; __asm { MOV EDX,vehicle_object MOV EDX,DWORD PTR [EDX] AND EDX,0xFFFF SHL EDX,5 MOV ECX,0x00816DE4; MOV ECX,DWORD PTR [ECX] MOV EAX,DWORD PTR [EDX+ECX+14h] MOV EDX,fnumber MOV DWORD PTR [EAX+2F8h],EDX } SpecificMsg = L"%s's vehicle's speed modifier has been set to %.2f"; } else { pSP->SpeedModifier = fnumber; SpecificMsg = L"%s's speed modifier has been set to %.2f"; } succeded = TRUE; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, pSP->PlayerName0, fnumber); } } } else GenericMsg = FailInvalNum; } else GenericMsg = FailPlyrNtFnd; if (GenericMsg) HaloSay(GenericMsg, exec_player_index); return succeded; } BOOL __fastcall Player::ActiveCamo(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL; short Player_Indexes[16]; int pi_found = 0; int arg_len; if ((arg_len = ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found))) { int seconds; if (CMDsLib::ParseStrInt((++cmd_args += arg_len), &seconds)) { short durration = seconds * 30; //halo time units = 30 * seconds for (int i = 0; i < pi_found; i++) { wchar_t *SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { HaloCE_lib::SPARTAN *player_object = GetPlayerObj(Player_Indexes[i]); if (player_object) { //player_object->IsInvisible = buffer_num; DWORD playertag = players[Player_Indexes[i]].PlayerID; playertag <<= 16; playertag |= Player_Indexes[i]; __asm { MOVSX EDX,durration PUSH EDX PUSH 0 MOV EBX,playertag CALL DWORD PTR [ActiveCamo_func_address] ADD ESP,8 MOV succeded,TRUE } SpecificMsg = L"%s has been given active camouflage for %i seconds"; } else SpecificMsg = FailPlyrNtSpwn; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0, durration / 30); } } } else GenericMsg = FailInvalNum; } else GenericMsg = FailPlyrNtFnd; if (GenericMsg) HaloSay(GenericMsg, exec_player_index); return succeded; } BOOL __fastcall Player::Suspend(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL; BOOL suspend; short Player_Indexes[16]; int pi_found = 0; int arg_len; if ((arg_len = ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found))) { if (CMDsLib::ParseStrBool((++cmd_args += arg_len), &suspend)) { for (int i = 0; i < pi_found; i++) { wchar_t *SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { HaloCE_lib::SPARTAN *player_object = GetPlayerObj(Player_Indexes[i]); if (player_object) { //HaloCE_lib::SPARTAN *vehicle_object = (HaloCE_lib::SPARTAN*)GetPlayerVehObj(player_object); //if (vehicle_object) player_object = vehicle_object; player_object->IsSuspended = (BYTE)suspend; succeded = TRUE; if (suspend) SpecificMsg = L"%s is now suspended."; else SpecificMsg = L"%s is now unsuspended."; } else SpecificMsg = FailPlyrNtSpwn; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0); } } } else GenericMsg = FailInvalNum; } else GenericMsg = FailPlyrNtFnd; if (GenericMsg) HaloSay(GenericMsg, exec_player_index); return succeded; } BOOL __fastcall Player::Teleport(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL, *SpecificMsg = NULL, *teleport_to; short Player_Indexes[16]; int pi_found = 0; float coordinates[3]; int teleport_type = 0; int arg_len; if (str_cmpW(cmd_args, L"remove ", 7)) { cmd_args += 7; if (*cmd_args) { unsigned int map_i = 0, tele_loc_i = 0; if (FindMapIndex(&maps_tele_sites, Current_Map_Str, map_i) && FindTeleLocNameIndex(&maps_tele_sites[map_i].teleport_locations, cmd_args, tele_loc_i)) { std::vector<TELEPORT_LOCATION> *tl = &maps_tele_sites[map_i].teleport_locations; tl->erase(tl->begin() + tele_loc_i); //delete map if their are no more locs if (!tl->size()) maps_tele_sites.erase(maps_tele_sites.begin() + map_i); WriteLocationsToFile(LocationsFilePath, &maps_tele_sites); SpecificMsg = L"\"%s\" has been removed."; } else SpecificMsg = FailBadTeleLoc; } else SpecificMsg = FailMissingLoc; HaloSay( SpecificMsg, exec_player_index, cmd_args); } else if ((arg_len = ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found))) { cmd_args += arg_len; int arg_count = CMDsLib::GetCMDArgCount(cmd_args); if (arg_count == 3) { //use x y z coordinates int arg_len; if ((arg_len = CMDsLib::ParseStrFloat(++cmd_args, &coordinates[0])) && (arg_len = CMDsLib::ParseStrFloat((++cmd_args += arg_len), &coordinates[1])) && CMDsLib::ParseStrFloat((++cmd_args += arg_len), &coordinates[2])) { teleport_type = 1; } else GenericMsg = FailInvalNum; } else if (arg_count == 1) { int pi2_to_find = 1; short player2_index; if (ParseCMDStrPlayers(++cmd_args, &player2_index, pi2_to_find)) { HaloCE_lib::SPARTAN *player2_object = GetPlayerObj(player2_index); if (player2_object) { //if player is in a vehicle, use vehicle's coords_or_vectors HaloCE_lib::SPARTAN *vehicle_object = (HaloCE_lib::SPARTAN*)GetPlayerVehObj(player2_object); if (vehicle_object) player2_object = vehicle_object; for (int i = 0; i < 3; i++) coordinates[i] = player2_object->m_World[i]; teleport_to = players[player2_index].PlayerName0; teleport_type = 2; } } if (!teleport_type) { unsigned int map_i = 0, tele_loc_i = 0; if (FindMapIndex(&maps_tele_sites, Current_Map_Str, map_i) && FindTeleLocNameIndex(&maps_tele_sites[map_i].teleport_locations, cmd_args, tele_loc_i)) { TELEPORT_LOCATION *pTL = &maps_tele_sites[map_i].teleport_locations[tele_loc_i]; for (int i = 0; i < 3; i++) coordinates[i] = pTL->coordinates[i]; teleport_to = pTL->teleport_loc_name; teleport_type = 3; } else GenericMsg = FailBadTeleLoc; } } } else GenericMsg = FailPlyrNtFnd; if (GenericMsg) HaloSay(GenericMsg, exec_player_index); if (teleport_type) { for (int i = 0; i < pi_found; i++) { if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { HaloCE_lib::SPARTAN *player_object = GetPlayerObj(Player_Indexes[i]); if (player_object) { //if player is in a vehicle, use vehicle's coords_or_vectors HaloCE_lib::SPARTAN *vehicle_object = (HaloCE_lib::SPARTAN*)GetPlayerVehObj(player_object); if (vehicle_object) player_object = vehicle_object; player_object->m_World[0] = coordinates[0]; player_object->m_World[1] = coordinates[1]; player_object->m_World[2] = coordinates[2] + 1 * i; succeded = TRUE; switch (teleport_type) { case 1: HaloSay( L"%s has been teleported to %.2fx %.2fy %.2fz", exec_player_index, players[Player_Indexes[i]].PlayerName0, coordinates[0], coordinates[1], coordinates[2]); break; case 2: SpecificMsg = L"%s has been teleported to %s"; player_object->m_World[2] += 1;//does float support ++? break; case 3: SpecificMsg = L"%s has been teleported to \"%s\""; break; } } else SpecificMsg = FailPlyrNtSpwn; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0, teleport_to); } } } return succeded; } BOOL __fastcall Player::Jump_Teleport(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL, *SpecificMsg = NULL; short Player_Indexes[16]; int pi_found = 0; float coordinates[3]; int arg_len; if ((arg_len = ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found))) { cmd_args += arg_len; if (!*cmd_args) { for (int i = 0; i < pi_found; i++) { SpecificMsg = NULL; HaloCE_lib::SPARTAN *player_object = GetPlayerObj(Player_Indexes[i]); if (player_object) { //if player is in a vehicle, use vehicle's coords_or_vectors HaloCE_lib::SPARTAN *vehicle_object = (HaloCE_lib::SPARTAN*)GetPlayerVehObj(player_object); if (vehicle_object) player_object = vehicle_object; for (int i = 0; i < 3; i++) coordinates[i] = player_object->m_World[i]; succeded = TRUE; SpecificMsg = L"%s's current coordinates is %.2fx %.2fy %.2fz"; } else SpecificMsg = FailPlyrNtSpwn; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0, coordinates[0], coordinates[1], coordinates[2]); } } } else if ((arg_len = CMDsLib::ParseStrFloat(++cmd_args, &coordinates[0])) && (arg_len = CMDsLib::ParseStrFloat((++cmd_args += arg_len), &coordinates[1])) && CMDsLib::ParseStrFloat((++cmd_args += arg_len), &coordinates[2])) { for (int i = 0; i < pi_found; i++) { SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { HaloCE_lib::SPARTAN *player_object = GetPlayerObj(Player_Indexes[i]); if (player_object) { //if player is in a vehicle, use vehicle's coords_or_vectors HaloCE_lib::SPARTAN *vehicle_object = (HaloCE_lib::SPARTAN*)GetPlayerVehObj(player_object); if (vehicle_object) player_object = vehicle_object; for (int i = 0; i < 3; i++) player_object->m_World[i] += coordinates[i]; succeded = TRUE; SpecificMsg = L"%s's coordinates has been adjusted by %.2fx %.2fy %.2fz"; } else SpecificMsg = FailPlyrNtSpwn; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0, coordinates[0], coordinates[1], coordinates[2]); } } } else GenericMsg = FailInvalNum; } else GenericMsg = FailPlyrNtFnd; if (GenericMsg) HaloSay(GenericMsg, exec_player_index); return succeded; } BOOL __fastcall Player::Velocity(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL, *SpecificMsg = NULL; short Player_Indexes[16]; int pi_found = 0; float vectors[3]; int arg_len; if ((arg_len = ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found))) { cmd_args += arg_len; if (!*cmd_args) { for (int i = 0; i < pi_found; i++) { SpecificMsg = NULL; HaloCE_lib::SPARTAN *player_object = GetPlayerObj(Player_Indexes[i]); if (player_object) { //if player is in a vehicle, use vehicle's coords_or_vectors HaloCE_lib::SPARTAN *vehicle_object = (HaloCE_lib::SPARTAN*)GetPlayerVehObj(player_object); if (vehicle_object) player_object = vehicle_object; for (int i = 0; i < 3; i++) vectors[i] = player_object->m_Velocity[i]; succeded = TRUE; SpecificMsg = L"%s's current vector is %.2fx %.2fy %.2fz"; } else SpecificMsg = FailPlyrNtSpwn; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0, vectors[0], vectors[1], vectors[2]); } } } else if ((arg_len = CMDsLib::ParseStrFloat(++cmd_args, &vectors[0])) && (arg_len = CMDsLib::ParseStrFloat((++cmd_args += arg_len), &vectors[1])) && CMDsLib::ParseStrFloat((++cmd_args += arg_len), &vectors[2])) { for (int i = 0; i < pi_found; i++) { SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { HaloCE_lib::SPARTAN *player_object = GetPlayerObj(Player_Indexes[i]); if (player_object) { //if player is in a vehicle, use vehicle's coords_or_vectors HaloCE_lib::SPARTAN *vehicle_object = (HaloCE_lib::SPARTAN*)GetPlayerVehObj(player_object); if (vehicle_object) player_object = vehicle_object; for (int i = 0; i < 3; i++) player_object->m_Velocity[i] = vectors[i]; succeded = TRUE; SpecificMsg = L"%s's vector has been changed to %.2fx %.2fy %.2fz"; } else SpecificMsg = FailPlyrNtSpwn; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0, vectors[0], vectors[1], vectors[2]); } } } else GenericMsg = FailInvalNum; } else GenericMsg = FailPlyrNtFnd; if (GenericMsg) HaloSay(GenericMsg, exec_player_index); return succeded; } BOOL __fastcall Player::Ammo(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL, *SpecificMsg = NULL; short Player_Indexes[16]; int pi_found = 0; int arg_len; if ((arg_len = ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found))) { cmd_args += arg_len; int number; //displayer info if (!*cmd_args) { for (int i = 0; i < pi_found; i++) { SpecificMsg = NULL; HaloCE_lib::SPARTAN* player_object = GetPlayerObj(Player_Indexes[i]); if(player_object) { HaloCE_lib::WEAPON_OBJECT *weapon_object = (HaloCE_lib::WEAPON_OBJECT*)GetObj(player_object->WeaponTag.Index); if (weapon_object) { number = weapon_object->rounds_total; succeded = TRUE; SpecificMsg = L"%s's weapon's ammo is at %i"; } else SpecificMsg = FailPlyrNoWep; } else SpecificMsg = FailPlyrNtSpwn; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0, number); } } } else if (CMDsLib::ParseStrInt(++cmd_args, &number)) { for (int i = 0; i < pi_found; i++) { SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { HaloCE_lib::SPARTAN* player_object = GetPlayerObj(Player_Indexes[i]); if(player_object) { HaloCE_lib::WEAPON_OBJECT *weapon_object = (HaloCE_lib::WEAPON_OBJECT*)GetObj(player_object->WeaponTag.Index); if (weapon_object) { weapon_object->rounds_total = (short)number; succeded = TRUE; SpecificMsg = L"%s's weapon's ammo has been changed to %i"; } else SpecificMsg = FailPlyrNoWep; } else SpecificMsg = FailPlyrNtSpwn; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0, number); } } } else GenericMsg = FailInvalNum; } else GenericMsg = FailPlyrNtFnd; if (GenericMsg) HaloSay(GenericMsg, exec_player_index); return succeded; } BOOL __fastcall Player::Battery(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL, *SpecificMsg = NULL; short Player_Indexes[16]; int pi_found = 0; int arg_len; if ((arg_len = ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found))) { cmd_args += arg_len; float fnumber; //displayer info if (!*cmd_args) { for (int i = 0; i < pi_found; i++) { SpecificMsg = NULL; HaloCE_lib::SPARTAN* player_object = GetPlayerObj(Player_Indexes[i]); if(player_object) { HaloCE_lib::WEAPON_OBJECT *weapon_object = (HaloCE_lib::WEAPON_OBJECT*)GetObj(player_object->WeaponTag.Index); if (weapon_object) { fnumber = 100.0f - (weapon_object->battery_used * 100.0f); succeded = TRUE; SpecificMsg = L"%s's weapon's battery is at %.2f%%"; } else SpecificMsg = FailPlyrNoWep; } else SpecificMsg = FailPlyrNtSpwn; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0, fnumber); } } } else if (CMDsLib::ParseStrFloat(++cmd_args, &fnumber)) { for (int i = 0; i < pi_found; i++) { SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { HaloCE_lib::SPARTAN* player_object = GetPlayerObj(Player_Indexes[i]); if(player_object) { HaloCE_lib::WEAPON_OBJECT *weapon_object = (HaloCE_lib::WEAPON_OBJECT*)GetObj(player_object->WeaponTag.Index); if (weapon_object) { weapon_object->battery_used = (100.0f - fnumber)/ 100.0f; succeded = TRUE; SpecificMsg = L"%s's weapon's battery has been changed to %.2f%%"; } else SpecificMsg = FailPlyrNoWep; } else SpecificMsg = FailPlyrNtSpwn; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0, fnumber); } } } else GenericMsg = FailInvalNum; } else GenericMsg = FailPlyrNtFnd; if (GenericMsg) HaloSay(GenericMsg, exec_player_index); return succeded; } BOOL __fastcall Player::Health(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL, *SpecificMsg = NULL; short Player_Indexes[16]; int pi_found = 0; int arg_len; if ((arg_len = ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found))) { cmd_args += arg_len; float fnumber; //displayer info if (!*cmd_args) { for (int i = 0; i < pi_found; i++) { SpecificMsg = NULL; HaloCE_lib::SPARTAN* player_object = GetPlayerObj(Player_Indexes[i]); if(player_object) { fnumber = player_object->Health * 100.0f; succeded = TRUE; SpecificMsg = L"%s's health is at %.2f%%"; } else SpecificMsg = FailPlyrNtSpwn; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0, fnumber); } } } else if (CMDsLib::ParseStrFloat(++cmd_args, &fnumber)) { for (int i = 0; i < pi_found; i++) { SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { HaloCE_lib::SPARTAN* player_object = GetPlayerObj(Player_Indexes[i]); if(player_object) { player_object->Health = fnumber / 100.0f; succeded = TRUE; SpecificMsg = L"%s's health has been set to %.2f%%"; } else SpecificMsg = FailPlyrNtSpwn; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0, fnumber); } } } else GenericMsg = FailInvalNum; } else GenericMsg = FailPlyrNtFnd; if (GenericMsg) HaloSay(GenericMsg, exec_player_index); return succeded; } BOOL __fastcall Player::Shield(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL, *SpecificMsg = NULL; short Player_Indexes[16]; int pi_found = 0; int arg_len; if ((arg_len = ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found))) { cmd_args += arg_len; float fnumber; //displayer info if (!*cmd_args) { for (int i = 0; i < pi_found; i++) { SpecificMsg = NULL; HaloCE_lib::SPARTAN* player_object = GetPlayerObj(Player_Indexes[i]); if(player_object) { fnumber = player_object->Shield_00 * 100.0f; succeded = TRUE; SpecificMsg = L"%s's shield is at %.2f%%"; } else SpecificMsg = FailPlyrNtSpwn; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0, fnumber); } } } else if (CMDsLib::ParseStrFloat(++cmd_args, &fnumber)) { for (int i = 0; i < pi_found; i++) { SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { HaloCE_lib::SPARTAN* player_object = GetPlayerObj(Player_Indexes[i]); if(player_object) { player_object->Shield_00 = fnumber / 100.0f; succeded = TRUE; SpecificMsg = L"%s's shield has been set to %.2f%%"; } else SpecificMsg = FailPlyrNtSpwn; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0, fnumber); } } } else GenericMsg = FailInvalNum; } else GenericMsg = FailPlyrNtFnd; if (GenericMsg) HaloSay(GenericMsg, exec_player_index); return succeded; } BOOL __fastcall Player::AFK(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; short Player_Indexes[16]; int pi_found = 0; if (ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found)) { for (int i = 0; i < pi_found; i++) { wchar_t *SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { HaloCE_lib::OBJECT_TAG ObjTag = players[Player_Indexes[i]].PlayerObjTag; if (ObjTag.Tag != -1) { DWORD playertag = players[Player_Indexes[i]].PlayerID; playertag <<= 16; playertag |= Player_Indexes[i]; __asm { PUSH 0x7FFFFFF ;//respawn time after death MOV EBX,playertag CALL DWORD PTR [PlayerDeath_func_address] ADD ESP,4 } SpecificMsg = L"%s is now afk."; } else { players[Player_Indexes[i]].RespawnTimer = 30;//1 sec SpecificMsg = L"%s is no longer afk."; } succeded = TRUE; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, -1, players[Player_Indexes[i]].PlayerName0); } } } else HaloSay(FailPlyrNtFnd, exec_player_index); return succeded; } BOOL __fastcall Player::Team_Change(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; DWORD Team = 0; short Player_Indexes[16]; int pi_found = 0; if (ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found)) { for (int i = 0; i < pi_found; i++) { wchar_t *SpecificMsg = NULL, *team_str; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { KillPlayer(Player_Indexes[i]); Team = players[Player_Indexes[i]].Team; if (Team) { Team = 0; team_str = L"Red"; } else { Team = 1; team_str = L"Blue"; } players[Player_Indexes[i]].Team = Team; succeded = TRUE; SpecificMsg = L"%s has been switched to %s team."; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, -1, players[Player_Indexes[i]].PlayerName0, team_str); } } } else HaloSay(FailPlyrNtFnd, exec_player_index); return succeded; } BOOL __fastcall Player::Kick(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; short Player_Indexes[16]; int pi_found = 0; if (ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found)) { for (int i = 0; i < pi_found; i++) { wchar_t *SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { if (Player_Indexes[i]) { char _pi_char[3] = {'\0','\0','\0'}; if (Player_Indexes[i] > 8) { _pi_char[0] = '1'; _pi_char[1] = (Player_Indexes[i] - 10) + '1'; } else { _pi_char[0] = Player_Indexes[i] + '1'; _pi_char[1] = '\0'; } __asm { LEA EAX,[_pi_char] CALL DWORD PTR [sv_kick_func_address] MOV succeded,TRUE } SpecificMsg = L"%s has been kicked."; } else SpecificMsg = L"Failed: Cannot kick host (%s)!"; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, -1, players[Player_Indexes[i]].PlayerName0); } } } else HaloSay(FailPlyrNtFnd, exec_player_index); return succeded; } BOOL __fastcall Player::Ban(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; short Player_Indexes[16]; int pi_found = 0; if (ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found)) { for (int i = 0; i < pi_found; i++) { wchar_t *SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { if (Player_Indexes[i]) { char *ban_params[2]; char player_index_char[3] = {'\0','\0','\0'}; if (Player_Indexes[i] > 8) { player_index_char[0] = '1'; player_index_char[1] = (Player_Indexes[i] - 10) + '1'; } else player_index_char[0] = Player_Indexes[i] + '1'; char dhms_chars = '\0'; ban_params[0] = player_index_char; ban_params[1] = &dhms_chars; __asm { LEA ECX,[ban_params] MOV EAX,1 CALL DWORD PTR [sv_ban_func_address] MOV succeded,TRUE } SpecificMsg = L"%s has been banned."; } else SpecificMsg = L"Failed: Cannot ban host (%s)!"; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, -1, players[Player_Indexes[i]].PlayerName0); } } } else HaloSay(FailPlyrNtFnd, exec_player_index); return succeded; } BOOL __fastcall Player::Kill(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; short Player_Indexes[16]; int pi_found = 0; if (ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found)) { for (int i = 0; i < pi_found; i++) { wchar_t *SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { if (KillPlayer(Player_Indexes[i])) { succeded = TRUE; //get random kill msg SYSTEMTIME systime; GetLocalTime(&systime); int rand = (systime.wMilliseconds >> 2) + Player_Indexes[i]; rand &= 7;//only 0 to 7 indexs' are valid SpecificMsg = SuccededKillMsgs[rand]; } else SpecificMsg = FailPlyrNtSpwn; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, -1, players[Player_Indexes[i]].PlayerName0); } } } else HaloSay(FailPlyrNtFnd, exec_player_index); return succeded; } BOOL __fastcall Player::Eject(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; short Player_Indexes[16]; int pi_found = 0; if (ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found)) { for (int i = 0; i < pi_found; i++) { wchar_t *SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { HaloCE_lib::SPARTAN *player_object = GetPlayerObj(Player_Indexes[i]); if (player_object) { HaloCE_lib::VEHICLE_OBJECT *vehicle_object = GetPlayerVehObj(player_object); if (vehicle_object) { HaloCE_lib::OBJECT_TAG PlayerObjTag = players[Player_Indexes[i]].PlayerObjTag; __asm { MOV EAX,PlayerObjTag CALL UnitExitVehicle_func_address } succeded = TRUE; SpecificMsg = L"%s has been ejected from a vehicle."; } else SpecificMsg = FailPlyrNtInVeh; } else SpecificMsg = FailPlyrNtSpwn; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0); } } } else HaloSay(FailPlyrNtFnd, exec_player_index); return succeded; } BOOL __fastcall Player::Flip_Vehicle(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; short Player_Indexes[16]; int pi_found = 0; if (ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found)) { for (int i = 0; i < pi_found; i++) { wchar_t *SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { HaloCE_lib::SPARTAN *player_object = GetPlayerObj(Player_Indexes[i]); if (player_object) { //if player is in a vehicle, use vehicle's coords_or_vectors HaloCE_lib::SPARTAN *vehicle_object = (HaloCE_lib::SPARTAN*)GetPlayerVehObj(player_object); if (vehicle_object) { player_object = vehicle_object; //player_object->m_LowerRot[0] = 0; //player_object->m_LowerRot[1] = 0; //player_object->m_LowerRot[2] = 1; //wierd but its really "m_LowerRot" player_object->m_Scale[0] = 0; player_object->m_Scale[1] = 0; float z_axis = player_object->m_Scale[2]; //flip 180 if (z_axis < 0) z_axis = 1; else z_axis = -1; player_object->m_Scale[2] = z_axis; succeded = TRUE; SpecificMsg = L"%s's vehicle has been fliped 180°."; } else SpecificMsg = FailPlyrNtInVeh; } else SpecificMsg = FailPlyrNtSpwn; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0); } } } else HaloSay(FailPlyrNtFnd, exec_player_index); return succeded; } BOOL __fastcall Player::Admin(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL; short Player_Indexes[16]; int buffer_num = 0, pi_found = 0; int arg_len; if ((arg_len = ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found))) { cmd_args += arg_len; if (!*cmd_args) { succeded = TRUE; for (int i = 0; i < pi_found; i++) { HaloSay( L"%s's current admin level is %u.", -1, players[Player_Indexes[i]].PlayerName0, TempAdmin[Player_Indexes[i]]); } } else if (CMDsLib::ParseStrInt(++cmd_args, &buffer_num)) { DWORD admin_level = (DWORD)buffer_num; if (TempAdmin[exec_player_index] >= admin_level) { for (int i = 0; i < pi_found; i++) { wchar_t *SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { if (Player_Indexes[i])//same as != 0 { TempAdmin[Player_Indexes[i]] = admin_level; succeded = TRUE; SpecificMsg = L"%s has been changed to admin level %u."; } else SpecificMsg = L"Failed: Cannot change host (%s)'s admin level"; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, -1, players[Player_Indexes[i]].PlayerName0, admin_level); } } } else GenericMsg = L"Failed: You can't promote an admin higher yous."; } else GenericMsg = FailInvalNum; } else GenericMsg = FailPlyrNtFnd; if (GenericMsg) HaloSay(GenericMsg, exec_player_index); return succeded; } BOOL __fastcall Player::Set_Teleport_Loc(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; TELEPORT_LOCATION tele_site; wchar_t *GenericMsg = NULL; short Player_Index; int pi_found = 1; int arg_len; if ((arg_len = ParseCMDStrPlayers(cmd_args, &Player_Index, pi_found))) { cmd_args += arg_len; if (*++cmd_args) { //count the number of spaces bool space_found = false; wchar_t *cmd_w_ptr = cmd_args; while (*cmd_w_ptr++) if (*cmd_w_ptr == ' ') space_found = true; if (!space_found) { int i = 0; wchar_t wchar; do { wchar = cmd_args[i]; tele_site.teleport_loc_name[i] = wchar; } while (wchar && i++ < TELE_LOC_NAME_SIZE); //add null at end if too long tele_site.teleport_loc_name[TELE_LOC_NAME_SIZE - 1] = '\0'; wchar_t *SpecificMsg = NULL; HaloCE_lib::SPARTAN *player_object = GetPlayerObj(Player_Index); if (player_object) { //if player is in a vehicle, use vehicle's coords_or_vectors HaloCE_lib::SPARTAN *vehicle_object = (HaloCE_lib::SPARTAN*)GetPlayerVehObj(player_object); if (vehicle_object) player_object = vehicle_object; for (int i = 0; i < 3; i++) tele_site.coordinates[i] = player_object->m_World[i]; unsigned int map_i = 0, tele_loc_i = 0; if (!FindMapIndex(&maps_tele_sites, Current_Map_Str, map_i)) { MAPS map_loc; for (int i = 0; i < MAP_STR_SIZE; i++) map_loc.map_name[i] = Current_Map_Str[i]; maps_tele_sites.push_back(map_loc); map_i = maps_tele_sites.size() - 1; } //if the tele site exists, overwrite it if (FindTeleLocNameIndex(&maps_tele_sites[map_i].teleport_locations, tele_site.teleport_loc_name, tele_loc_i)) maps_tele_sites[map_i].teleport_locations[tele_loc_i] = tele_site; else maps_tele_sites[map_i].teleport_locations.push_back(tele_site); WriteLocationsToFile(LocationsFilePath, &maps_tele_sites); succeded = TRUE; //unfortunatly the location name comes first, but in the error messages, player comes first HaloSay( L"New location \"%s\", has been set for %s's current position.", -1, cmd_args, players[Player_Index].PlayerName0); } else SpecificMsg = FailPlyrNtSpwn; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Index].PlayerName0); } } else GenericMsg = FailNoSpaces; } else GenericMsg = FailMissingLoc; } else GenericMsg = FailPlyrNtFnd; if (GenericMsg) HaloSay(GenericMsg, exec_player_index); return succeded; } BOOL __fastcall Player::Spawn_Biped(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL; short Player_Indexes[16]; int pi_found = 0; if ((cmd_args += ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found))) { int how_many_to_spawn; if (CMDsLib::ParseStrInt(++cmd_args, &how_many_to_spawn)) { for (int i = 0; i < pi_found; i++) { wchar_t *SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { HaloCE_lib::SPARTAN *player_object = GetPlayerObj(Player_Indexes[i]); if (player_object) { HaloCE_lib::SPARTAN *vehicle_object = (HaloCE_lib::SPARTAN*)GetPlayerVehObj(player_object); if (vehicle_object) player_object = vehicle_object; float coords[3]; coords[0] = player_object->m_World[0] + 1; coords[1] = player_object->m_World[1] + 1; coords[2] = player_object->m_World[2] + 0.5f; __asm { MOV ECX,DWORD PTR [ObjTagList_ptr_address] MOV ECX, DWORD PTR [ECX] MOV EDX,DWORD PTR [ECX+174h] MOV EDX,DWORD PTR [EDX+0Ch] CMP EDX,0xFF JE SHORT biped_inval ;//6E2280->addr+168h]->addr+1Ch]-> player obj type tag MOV ECX,DWORD PTR [ECX+168h] ;//__fastcall params MOV EDX,DWORD PTR [ECX+1Ch] LEA ECX,[coords] XOR ESI,ESI continue_biped_create_loop: CMP ESI,how_many_to_spawn JGE SHORT bipeds_spawned//exit_biped_create_loop CALL CreateObject INC ESI JMP SHORT continue_biped_create_loop //exit_biped_create_loop: biped_inval: MOV ECX,DWORD PTR [FailBadSpawn] MOV SpecificMsg,ECX JMP SHORT biped_failed bipeds_spawned: MOV succeded,TRUE } SpecificMsg = L"Biped(s) spawned next to %s"; __asm biped_failed: } else SpecificMsg = FailPlyrNtSpwn; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0); } } } else GenericMsg = FailInvalNum; } else GenericMsg = FailPlyrNtFnd; if (GenericMsg) HaloSay(GenericMsg, exec_player_index); return succeded; } BOOL __fastcall Player::Spawn_Hog(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; short Player_Indexes[16]; int pi_found = 0; if (ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found)) { DWORD dwOldProtect; if (VirtualProtect( (LPVOID)Player0_index, sizeof(WORD), PAGE_EXECUTE_READWRITE, &dwOldProtect)) { for (int i = 0; i < pi_found; i++) { wchar_t *SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { *Player0_index = Player_Indexes[i]; //doesnt spawn on some custom maps //__asm CALL SpawnHog_func_address __asm { //DWORD objlist = *(DWORD*)ObjTagList_ptr_address; MOV ECX,DWORD PTR [ObjTagList_ptr_address] MOV ECX, DWORD PTR [ECX] //DWORD num_of_objs = *(DWORD*)(objlist+0x164); //if (num_of_objs) CMP DWORD PTR [ECX+164h],0 JE SHORT hog_bad_list //DWORD vehicle_list_header = *(DWORD*)(objlist+0x168); MOV ECX,DWORD PTR [ECX+168h] //DWORD num_of_veh = *(WORD*)(vehicle_list_header+0x20); MOVZX EAX,WORD PTR [ECX+20h] //DWORD vehicle_list = *(DWORD*)(vehicle_list_header+0x24); MOV ECX,DWORD PTR [ECX+24h] //if (num_of_veh) TEST EAX,EAX JE SHORT hog_bad_list PUSH 1// num_of_veh PUSH ECX//vehicle_list CALL DWORD PTR [SpawnObjAtPlayer0_func_address] ADD ESP,8 CMP EAX,-1 JNZ SHORT hog_val_player MOV ECX,DWORD PTR [FailPlyrNtSpwn] MOV SpecificMsg,ECX JMP SHORT hog_failed hog_val_player: TEST AX,AX JNZ SHORT hog_spawned hog_bad_list: MOV ECX,DWORD PTR [FailBadSpawn] MOV SpecificMsg,ECX JMP SHORT hog_failed hog_spawned: MOV succeded,TRUE } SpecificMsg = L"Warthog spawned next to %s"; __asm hog_failed: } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0); } } *Player0_index = 0;//change back to 0 when finished VirtualProtect( (LPVOID)Player0_index, sizeof(WORD), dwOldProtect, &dwOldProtect); } } else HaloSay(FailPlyrNtFnd, exec_player_index); return succeded; } BOOL __fastcall Player::Spawn_All_Vehicles(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; short Player_Indexes[16]; int pi_found = 0; if (ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found)) { DWORD dwOldProtect; if (VirtualProtect( (LPVOID)Player0_index, sizeof(WORD), PAGE_EXECUTE_READWRITE, &dwOldProtect)) { for (int i = 0; i < pi_found; i++) { wchar_t *SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { //[40848BF0+i*10]= vehicle tag //[40848BE4+0C]->E3D40260 (1st one?) //[40848B44+24]->40848BE4 //[40848198+168]->40848B44 //[6E2280]->40848198 //[ObjTagList_ptr_address]->6E2280 *Player0_index = Player_Indexes[i]; __asm { //DWORD objlist = *(DWORD*)ObjTagList_ptr_address; MOV ECX,DWORD PTR [ObjTagList_ptr_address] MOV ECX, DWORD PTR [ECX] //DWORD num_of_objs = *(DWORD*)(objlist+0x164); //if (num_of_objs) CMP DWORD PTR [ECX+164h],0 JE SHORT vehs_bad_list //DWORD vehicle_list_header = *(DWORD*)(objlist+0x168); MOV ECX,DWORD PTR [ECX+168h] //DWORD num_of_veh = *(WORD*)(vehicle_list_header+0x20); MOVZX EAX,WORD PTR [ECX+20h] //DWORD vehicle_list = *(DWORD*)(vehicle_list_header+0x24); MOV ECX,DWORD PTR [ECX+24h] //if (num_of_veh) TEST EAX,EAX JE SHORT vehs_bad_list PUSH EAX PUSH ECX CALL DWORD PTR SpawnObjAtPlayer0_func_address ADD ESP,8 CMP EAX,-1 JNZ SHORT vehs_val_player MOV ECX,DWORD PTR [FailPlyrNtSpwn] MOV SpecificMsg,ECX JMP SHORT vehs_failed vehs_val_player: TEST AX,AX JNZ SHORT vehs_spawned vehs_bad_list: MOV ECX,DWORD PTR [FailBadSpawn] MOV SpecificMsg,ECX JMP SHORT vehs_failed vehs_spawned: MOV succeded,TRUE } SpecificMsg = L"Vehicles spawned next to %s"; __asm vehs_failed: } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0); } } *Player0_index = 0;//change back to 0 when finished VirtualProtect( (LPVOID)Player0_index, sizeof(WORD), dwOldProtect, &dwOldProtect); } } else HaloSay(FailPlyrNtFnd, exec_player_index); return succeded; } BOOL __fastcall Player::Spawn_All_Weapons(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; short Player_Indexes[16]; int pi_found = 0; if (ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found)) { DWORD dwOldProtect; if (VirtualProtect( (LPVOID)Player0_index, sizeof(WORD), PAGE_EXECUTE_READWRITE, &dwOldProtect)) { for (int i = 0; i < pi_found; i++) { wchar_t *SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { *Player0_index = Player_Indexes[i]; __asm { //DWORD objlist = *(DWORD*)ObjTagList_ptr_address; MOV ECX,DWORD PTR [ObjTagList_ptr_address] MOV ECX, DWORD PTR [ECX] //DWORD num_of_objs = *(DWORD*)(objlist+0x14C); //if (num_of_objs) MOV EAX,DWORD PTR [ECX+14Ch] TEST EAX,EAX JE SHORT weps_bad_list //DWORD weapon_list = *(DWORD*)(objlist+0x150); MOV ECX,DWORD PTR [ECX+150h] //if (weapon_list) TEST ECX,ECX JE SHORT weps_bad_list PUSH EAX PUSH ECX CALL DWORD PTR [SpawnObjAtPlayer0_func_address] ADD ESP,8 CMP EAX,-1 JNZ SHORT weps_val_player MOV ECX,DWORD PTR [FailPlyrNtSpwn] MOV SpecificMsg,ECX JMP SHORT weps_failed weps_val_player: TEST AX,AX JNZ SHORT weps_spawned weps_bad_list: MOV ECX,DWORD PTR [FailBadSpawn] MOV SpecificMsg,ECX JMP SHORT weps_failed weps_spawned: MOV succeded,1 } SpecificMsg = L"Weapons spawned next to %s"; __asm weps_failed: } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0); } } *Player0_index = 0;//change back to 0 when finished VirtualProtect( (LPVOID)Player0_index, sizeof(WORD), dwOldProtect, &dwOldProtect); } } else HaloSay(FailPlyrNtFnd, exec_player_index); return succeded; } BOOL __fastcall Player::Spawn_All_Powerups(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; short Player_Indexes[16]; int pi_found = 0; if (ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found)) { DWORD dwOldProtect; if (VirtualProtect( (LPVOID)Player0_index, sizeof(WORD), PAGE_EXECUTE_READWRITE, &dwOldProtect)) { for (int i = 0; i < pi_found; i++) { wchar_t *SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { *Player0_index = Player_Indexes[i]; __asm { //DWORD objlist = *(DWORD*)ObjTagList_ptr_address; MOV ECX,DWORD PTR [ObjTagList_ptr_address] MOV ECX, DWORD PTR [ECX] //DWORD num_of_objs = *(DWORD*)(objlist+0x158); //if (num_of_objs) MOV EAX,DWORD PTR [ECX+158h] TEST EAX,EAX JE SHORT pwrups_bad_list //DWORD powerup_list = *(DWORD*)(objlist+0x15C); MOV ECX,DWORD PTR [ECX+15Ch] //if (powerup_list) TEST ECX,ECX JE SHORT pwrups_bad_list PUSH EAX PUSH ECX CALL DWORD PTR [SpawnObjAtPlayer0_func_address] ADD ESP,8 CMP EAX,-1 JNZ SHORT pwrups_val_player MOV ECX,DWORD PTR [FailPlyrNtSpwn] MOV SpecificMsg,ECX JMP SHORT pwrups_failed pwrups_val_player: TEST AX,AX JNZ SHORT pwrups_spawned pwrups_bad_list: MOV ECX,DWORD PTR [FailBadSpawn] MOV SpecificMsg,ECX JMP SHORT pwrups_failed pwrups_spawned: MOV succeded,TRUE } SpecificMsg = L"Powerups spawned next to %s"; __asm pwrups_failed: } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0); } } *Player0_index = 0;//change back to 0 when finished VirtualProtect( (LPVOID)Player0_index, sizeof(WORD), dwOldProtect, &dwOldProtect); } } else HaloSay(FailPlyrNtFnd, exec_player_index); return succeded; } BOOL __fastcall Player::Copy_Vehicle(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; short Player_Indexes[16]; int pi_found = 0; wchar_t *GenericMsg = NULL; int pi2_to_find = 1; short player2_index; if ((cmd_args += ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found)) && ParseCMDStrPlayers(++cmd_args, &player2_index, pi2_to_find)) { if (TempAdmin[exec_player_index] >= TempAdmin[player2_index]) { HaloCE_lib::SPARTAN *player2_object = GetPlayerObj(player2_index); if (player2_object) { //if player is in a vehicle, use vehicle's coords_or_vectors HaloCE_lib::SPARTAN *vehicle_object = (HaloCE_lib::SPARTAN*)GetPlayerVehObj(player2_object); if (vehicle_object) player2_object = vehicle_object; float coords[3]; coords[0] = player2_object->m_World[0] + 1; coords[1] = player2_object->m_World[1] + 1; coords[2] = player2_object->m_World[2] + 0.5f; for (int i = 0; i < pi_found; i++) { wchar_t *SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { HaloCE_lib::SPARTAN *player_object = GetPlayerObj(Player_Indexes[i]); if (player_object) { //if player is in a vehicle, use vehicle's coords_or_vectors HaloCE_lib::SPARTAN *vehicle_object = (HaloCE_lib::SPARTAN*)GetPlayerVehObj(player_object); if (vehicle_object) { __asm { ;//__fastcall params MOV EDX,DWORD PTR [vehicle_object] MOV EDX,DWORD PTR [EDX] LEA ECX,[coords] CALL CreateObject MOV succeded,TRUE } HaloSay( L"%s's vehicle has been spawned next to %s", exec_player_index, players[player2_index].PlayerName0, players[Player_Indexes[i]].PlayerName0); } else SpecificMsg = FailPlyrNtInVeh; } else SpecificMsg = FailPlyrNtSpwn; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0); } } } else GenericMsg = FailPlyrNtSpwn; } else GenericMsg = FailLowAdminLvl; } else GenericMsg = FailPlyrNtFnd; if (GenericMsg) HaloSay(GenericMsg, exec_player_index, players[player2_index].PlayerName0); return succeded; } BOOL __fastcall Player::Copy_Weapon(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; short Player_Indexes[16]; int pi_found = 0; wchar_t *GenericMsg = NULL; int pi2_to_find = 1; short player2_index; if ((cmd_args += ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found)) && ParseCMDStrPlayers(++cmd_args, &player2_index, pi2_to_find)) { if (TempAdmin[exec_player_index] >= TempAdmin[player2_index]) { HaloCE_lib::SPARTAN *player2_object = GetPlayerObj(player2_index); if (player2_object) { //if player is in a vehicle, use vehicle's coords_or_vectors HaloCE_lib::SPARTAN *vehicle_object = (HaloCE_lib::SPARTAN*)GetPlayerVehObj(player2_object); if (vehicle_object) player2_object = vehicle_object; float coords[3]; coords[0] = player2_object->m_World[0] + 1; coords[1] = player2_object->m_World[1] + 1; coords[2] = player2_object->m_World[2] + 0.5f; for (int i = 0; i < pi_found; i++) { wchar_t *SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { HaloCE_lib::SPARTAN *player_object = GetPlayerObj(Player_Indexes[i]); if (player_object) { short weapon_index = player_object->WeaponTag.Index; //if player is in a vehicle, use vehicle's weapon //doesn't work on vehicle weapons //short veh_wep_index = player_object->VehicleWeaponTag.Index; //if (veh_wep_index != -1) weapon_index = veh_wep_index; DWORD weapon_obj = GetObj(weapon_index); if (weapon_obj) { __asm { ;//__fastcall params MOV EDX,DWORD PTR [weapon_obj] MOV EDX,DWORD PTR [EDX] LEA ECX,[coords] CALL CreateObject MOV succeded,TRUE } HaloSay( L"%s's weapon has been spawned next to %s", exec_player_index, players[player2_index].PlayerName0, players[Player_Indexes[i]].PlayerName0); } else SpecificMsg = FailPlyrNoWep; } else SpecificMsg = FailPlyrNtSpwn; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0); } } } else GenericMsg = FailPlyrNtSpwn; } else GenericMsg = FailLowAdminLvl; } else GenericMsg = FailPlyrNtFnd; if (GenericMsg) HaloSay(GenericMsg, exec_player_index, players[player2_index].PlayerName0); return succeded; } BOOL __fastcall Player::Destroy_Objects_Mode(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL; int enable; if (!*cmd_args) { enable = DestroyObjsEnabled; GenericMsg = L"Destroy objects mode is set at %u"; succeded = TRUE; } else if (CMDsLib::ParseStrInt(cmd_args, &enable)) { DestroyObjsEnabled = enable; GenericMsg = L"Destroy objects mode has been set to %u"; succeded = TRUE; } else GenericMsg = FailInvalNum; HaloSay(GenericMsg, exec_player_index, enable); return succeded; } BOOL __fastcall Player::Destroy_Weapon(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; short Player_Indexes[16]; int pi_found = 0; if (ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found)) { for (int i = 0; i < pi_found; i++) { wchar_t *SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { HaloCE_lib::SPARTAN *player_object = GetPlayerObj(Player_Indexes[i]); if (player_object) { HaloCE_lib::OBJECT_TAG WepObjTag = player_object->WeaponTag; //use vehicle turret if valid tag HaloCE_lib::OBJECT_TAG VehWepObjTag = player_object->VehicleWeaponTag; if (VehWepObjTag.Tag != -1) WepObjTag = VehWepObjTag; if (WepObjTag.Tag != -1) { __asm { MOV EAX,WepObjTag CALL DWORD PTR [DestroyObj_func_address] MOV succeded,TRUE } SpecificMsg = L"%s's weapon has been destroyed"; } else SpecificMsg = FailPlyrNoWep; } else SpecificMsg = FailPlyrNtSpwn; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0); } } } else HaloSay(FailPlyrNtFnd, exec_player_index); return succeded; } BOOL __fastcall Player::Say(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; short Player_Indexes[16]; int pi_found = 0; wchar_t *msg_to = cmd_args, *GenericMsg = NULL;; if (*ServerType == HOST) { int arg_len; if ((arg_len = ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found))) { cmd_args += arg_len; if (pi_found == (*Players_ptr)->NumOfItems) { HaloSay(++cmd_args, -1); } else { msg_to[cmd_args - msg_to] = 0;//add null terminator wchar_t *sv_buffer = &HaloSay_server_buffer[SV_NAME_SIZE]; swprintf_s( sv_buffer, SV_BUFFER_SIZE, L"[Private Message][from %s][to %s]: %s", players[exec_player_index].PlayerName0, msg_to, ++cmd_args); CHAT_INFO chat_info; chat_info.ChatType = Server; chat_info.From_PlayerIndex = 0; chat_info.msg_str = sv_buffer; for (int i = 0; i < pi_found; i++) { ServerSay(chat_info, players[Player_Indexes[i]].PlayerChatIndex); HaloSay( L"Message sent to %s", exec_player_index, players[Player_Indexes[i]].PlayerName0); } } succeded = TRUE; } else GenericMsg = FailPlyrNtFnd; } else GenericMsg = FailSvCmd; if (GenericMsg) HaloSay(GenericMsg, exec_player_index); return succeded | DO_NOT_SEND_MSG; } BOOL __fastcall Player::ObjectScale(wchar_t *cmd_args, short exec_player_index) { BOOL succeded = FALSE; wchar_t *GenericMsg = NULL, *SpecificMsg = NULL; short Player_Indexes[16]; int pi_found = 0; float scale; int arg_len; if ((arg_len = ParseCMDStrPlayers(cmd_args, Player_Indexes, pi_found))) { cmd_args += arg_len; if (!*cmd_args) { for (int i = 0; i < pi_found; i++) { SpecificMsg = NULL; HaloCE_lib::SPARTAN *player_object = GetPlayerObj(Player_Indexes[i]); if (player_object) { //if player is in a vehicle, use vehicle's coords_or_vectors HaloCE_lib::SPARTAN *vehicle_object = (HaloCE_lib::SPARTAN*)GetPlayerVehObj(player_object); if (vehicle_object) player_object = vehicle_object; succeded = TRUE; SpecificMsg = L"%s's current object scale is %.2f%%"; } else SpecificMsg = FailPlyrNtSpwn; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0, player_object->obj_scale * 100.0f); } } } else if (CMDsLib::ParseStrFloat(++cmd_args, &scale)) { for (int i = 0; i < pi_found; i++) { SpecificMsg = NULL; if (TempAdmin[exec_player_index] >= TempAdmin[Player_Indexes[i]]) { HaloCE_lib::SPARTAN *player_object = GetPlayerObj(Player_Indexes[i]); if (player_object) { //if player is in a vehicle, use vehicle's coords_or_vectors HaloCE_lib::SPARTAN *vehicle_object = (HaloCE_lib::SPARTAN*)GetPlayerVehObj(player_object); if (vehicle_object) player_object = vehicle_object; player_object->obj_scale = scale; succeded = TRUE; SpecificMsg = L"%s's object scale has been changed to %.2f%%"; } else SpecificMsg = FailPlyrNtSpwn; } else SpecificMsg = FailLowAdminLvl; if (SpecificMsg) { HaloSay( SpecificMsg, exec_player_index, players[Player_Indexes[i]].PlayerName0, scale * 100.0f); } } } else GenericMsg = FailInvalNum; } else GenericMsg = FailPlyrNtFnd; if (GenericMsg) HaloSay(GenericMsg, exec_player_index); return succeded; }
RadWolfie/Halo-Dev-Controls
HDC/CMDParser.cpp
C++
gpl-3.0
105,714
package eu.fbk.fcw.utils.corpus; import java.io.Serializable; /** * Created by alessio on 12/11/15. */ public class Word implements Serializable { private int id; private String form; private String lemma; private String pos; private int depParent; private String depLabel; private int begin; private int end; public static Word readFromArray(String[] parts) { //todo: better management of possibilities if (parts.length >= 12) { return new Word( Integer.parseInt(parts[0]), parts[1], parts[2], parts[4], Integer.parseInt(parts[8]), parts[10] ); } return new Word( Integer.parseInt(parts[0]), parts[1], parts[2], parts[4] ); } public Word(int id, String form, String lemma, String pos) { this.id = id; this.form = form; this.lemma = lemma; this.pos = pos; } public Word(int id, String form, String lemma, String pos, int depParent, String depLabel) { this.id = id; this.form = form; this.lemma = lemma; this.pos = pos; this.depParent = depParent; this.depLabel = depLabel; } public String getForm() { return form; } public void setForm(String form) { this.form = form; } public String getLemma() { return lemma; } public void setLemma(String lemma) { this.lemma = lemma; } public String getPos() { return pos; } public void setPos(String pos) { this.pos = pos; } public int getDepParent() { return depParent; } public void setDepParent(int depParent) { this.depParent = depParent; } public String getDepLabel() { return depLabel; } public void setDepLabel(String depLabel) { this.depLabel = depLabel; } public int getId() { return id; } public int getBegin() { return begin; } public void setBegin(int begin) { this.begin = begin; } public int getEnd() { return end; } public void setEnd(int end) { this.end = end; } @Override public String toString() { return "Word{" + "id=" + id + ", form='" + form + '\'' + ", lemma='" + lemma + '\'' + ", pos='" + pos + '\'' + ", depParent=" + depParent + ", depLabel='" + depLabel + '\'' + '}'; } @Override public boolean equals(Object obj) { if (obj instanceof Word) { return ((Word) obj).getId() == id; } return super.equals(obj); } }
fbk/fcw
fcw-utils/src/main/java/eu/fbk/fcw/utils/corpus/Word.java
Java
gpl-3.0
2,901
<?php namespace Bk\MeteoBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class MeteoController extends Controller { public function indexAction() { $param = $this->container->getParameter('OpenWeatherMap'); /* $fake = '../src/Bk/MeteoBundle/cache/fake/france.json'; $json = json_decode(file_get_contents($fake)); $jsonCities = $json->list; $cities = array(); foreach ($jsonCities as $jsonCity) { var_dump($jsonCity); $weather = new \Bk\MeteoBundle\Entity\Weather(); $weather ->setDate($jsonCity->dt) ->setSunrise($jsonCity->sys->sunrise) ->setSunset($jsonCity->sys->sunset) ->setTemperature($jsonCity->main->temp) ->setTemperatureMin($jsonCity->main->temp_min) ->setTemperatureMax($jsonCity->main->temp_max) ->setPressure($jsonCity->main->pressure) ->setHumidity($jsonCity->main->humidity) ->setWindSpeed($jsonCity->wind->speed) ->setWindDirectionValue($jsonCity->wind->deg) ->setCloudsCover($jsonCity->clouds->all) ->setCloudsDescription($jsonCity->weather[0]->description) ; $city = new \Bk\MeteoBundle\Entity\City(); $city ->setName($jsonCity->name) ->setLongitude($jsonCity->coord->lon) ->setLatitude($jsonCity->coord->lat) ->addWeather($weather) ; var_dump($city->getWeathers()); var_dump($city); } * */ return $this->render('BkMeteoBundle:Meteo:index.html.twig', array('cities' => $param['city'])); } }
LemoineSimon/meteo
src/Bk/MeteoBundle/Controller/MeteoController.php
PHP
gpl-3.0
1,869
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AppRequestGenerator { public class TabSettings { public TabSettings(string name) { this.Name = name; this.Settings = new Dictionary<string, object>(); } public string Name { get; set; } public Dictionary<string, object> Settings; } }
tsauter/AppRequestGenerator
AppRequestGenerator/TabSettings.cs
C#
gpl-3.0
441
package com.github.epd.sprout.levels; import com.github.epd.sprout.Assets; import com.github.epd.sprout.messages.Messages; import java.util.Arrays; public class DeadEndLevel extends Level { private static final int SIZE = 5; { color1 = 0x534f3e; color2 = 0xb9d661; } @Override public String tilesTex() { return Assets.TILES_CAVES; } @Override public String waterTex() { return Assets.WATER_HALLS; } @Override protected boolean build() { setSize(7, 7); Arrays.fill(map, Terrain.WALL); for (int i = 2; i < SIZE; i++) { for (int j = 2; j < SIZE; j++) { map[i * getWidth() + j] = Terrain.EMPTY; } } for (int i = 1; i <= SIZE; i++) { map[getWidth() + i] = map[getWidth() * SIZE + i] = map[getWidth() * i + 1] = map[getWidth() * i + SIZE] = Terrain.WATER; } entrance = SIZE * getWidth() + SIZE / 2 + 1; map[entrance] = Terrain.ENTRANCE; exit = 0; return true; } @Override public String tileName(int tile) { switch (tile) { case Terrain.WATER: return Messages.get(CityLevel.class, "water_name"); case Terrain.HIGH_GRASS: return Messages.get(CityLevel.class, "high_grass_name"); default: return super.tileName(tile); } } @Override protected void createMobs() { } @Override protected void createItems() { } @Override public int randomRespawnCell() { return entrance - getWidth(); } }
G2159687/espd
app/src/main/java/com/github/epd/sprout/levels/DeadEndLevel.java
Java
gpl-3.0
1,393
import sys,os class Solution(): def reverse(self, x): sign=1 if x<0: sign=-1 x=x*-1 token=str(x) str_rev="" str_len=len(token) for i in range(str_len): str_rev+=token[str_len-i-1] num_rev=int(str_rev) if sign==1 and num_rev>2**31-1: return 0 if sign==-1 and num_rev>2**31: return 0 return num_rev*sign my_sol=Solution() print my_sol.reverse(123)
urashima9616/Leetcode_Python
leet7.py
Python
gpl-3.0
491
/** * Sky profile implementation * * ICRAR - International Centre for Radio Astronomy Research * (c) UWA - The University of Western Australia, 2016 * Copyright by UWA (in the framework of the ICRAR) * All rights reserved * * Contributed by Aaron Robotham, Rodrigo Tobar * * This file is part of libprofit. * * libprofit 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 3 of the License, or * (at your option) any later version. * * libprofit is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with libprofit. If not, see <http://www.gnu.org/licenses/>. */ #include <vector> #include "profit/common.h" #include "profit/model.h" #include "profit/sky.h" namespace profit { void SkyProfile::validate() { /* no-op for the time being, probably check value in range, etc */ } void SkyProfile::adjust_for_finesampling(unsigned int finesampling) { bg = requested_bg / (finesampling * finesampling); } void SkyProfile::evaluate(Image &image, const Mask &mask, const PixelScale & /*scale*/, const Point &/*offset*/, double /*magzero*/) { /* In case we need to mask some pixels out */ auto mask_it = mask.begin(); /* Fill the image with the background value */ for(auto &pixel: image) { /* Check the calculation mask and avoid pixel if necessary */ if( mask && !*mask_it++ ) { continue; } pixel += this->bg; } } SkyProfile::SkyProfile(const Model &model, const std::string &name) : Profile(model, name), bg(0.), requested_bg(0.) { register_parameter("bg", requested_bg); } } /* namespace profit */
ICRAR/libprofit
src/sky.cpp
C++
gpl-3.0
1,932
package com.creativecub.iotarduino; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.Switch; import android.widget.TextView; import java.util.List; public class DataAdapter extends RecyclerView.Adapter<DataAdapter.MyViewHolder> { private List<Data> moviesList; public class MyViewHolder extends RecyclerView.ViewHolder { public TextView title, year, genre; public ImageView ivIcon; public Switch aSwitch; public MyViewHolder(View view) { super(view); title = (TextView) view.findViewById(R.id.title); genre = (TextView) view.findViewById(R.id.genre); year = (TextView) view.findViewById(R.id.year); ivIcon = (ImageView) view.findViewById(R.id.ivIcon); aSwitch = (Switch) view.findViewById(R.id.switch1); } } public DataAdapter(List<Data> moviesList) { this.moviesList = moviesList; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.my_row, parent, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { Data data = moviesList.get(position); holder.title.setText(data.getTitle()); holder.genre.setText(data.getGenre()); holder.year.setText(data.getYear()); holder.ivIcon.setImageBitmap(data.getIvIcon()); holder.aSwitch.setChecked(data.gettoggle()); } @Override public int getItemCount() { return moviesList.size(); } }
nigelcog/mini-IoT
android/mini-IoT/app/src/main/java/com/creativecub/iotarduino/DataAdapter.java
Java
gpl-3.0
1,899
var classglobal = [ [ "Buffer", "df/d84/classglobal.html#a77b5ab3a88955255ac7abc7251919fbc", null ], [ "run", "df/d84/classglobal.html#a917c15ea7d2eafaa6df0aea5868a86e7", null ], [ "require", "df/d84/classglobal.html#a9b11defd1000737a5b70b50edfcc8156", null ], [ "GC", "df/d84/classglobal.html#a02a28758a633a7b1493471415c8949ba", null ], [ "console", "df/d84/classglobal.html#a69cd8fa430cb4536156e8052a37c9303", null ] ];
xushiwei/fibjs
docs/df/d84/classglobal.js
JavaScript
gpl-3.0
441
using UnityEngine; using UnityEngine.UI; using System.Collections.Generic; public class NPCController : MonoBehaviour { public new string name; //public GameObject uiCanvas; public Text uiName; void Awake() { uiName.text = name; } //void Update() { // if(Camera.main != null && Camera.main.transform.hasChanged) { // When in cutscenes, the main camera is disabled // gameObject.transform.forward = Camera.main.transform.forward; // Keeps the text facing the player // Quaternion rotation = Quaternion.Euler(0, Camera.main.transform.localRotation.y, 0); // gameObject.transform.localRotation = rotation; // } //} }
SandroHc/AB-Operation-Shadowy-Situation
Assets/Scripts/NPC/NPCController.cs
C#
gpl-3.0
638
# -*- coding: utf-8 -*- __author__ = 'LIWEI240' """ Constants definition """ class Const(object): class RetCode(object): OK = 0 InvalidParam = -1 NotExist = -2 ParseError = -3
lwldcr/keyboardman
common/const.py
Python
gpl-3.0
214
//Settings actype = ['image/png','image/jpeg','image/jpg','image/gif']; /* Accepted mime type */ maxweight = 819200; /* Max file size in octets */ maxwidth = 150; /* Max width of the image */ maxheight = 150; /* Max height*/ //Caching variable selector ish = $('.ish'); /* On attach element hide or show */ msgUp = $('.msgUp'); /* container message, infos, error... */ filezone = $('.filezone'); /* Selector filezone label */ fileprev = $('.filezone').children('img'); /* Selector img element */ filesend = $('#filesend'); /* Selector input file (children label) */ fileup = $('#fileup'); /* Selector button submit */ reset = $('#reset'); /* Selector button reset */ ish.hide(); /* Initial hide */ $(':file').change(function(e) { //Cancel the default execution e.preventDefault(); //Full file file = this.files[0]; var filer = new FileReader; filer.onload = function() { //Get size and type var aType = file.type; var aSize = file.size; //Check the file size if(aSize > maxweight) { msgUp.text('To large, maximum'+ maxweight +' bytes'); return; } //Check the file type if($.inArray(aType, actype) === -1) { msgUp.text('File type not allowed'); return; } //Set src / preview fileprev.attr('src', filer.result); //Make new Image for get the width / height var image = new Image(); image.src = filer.result; image.onload = function() { //Set width / height aWidth = image.width; aHeight = image.height; //Check width if(aWidth > maxwidth) { msgUp.text('Maximum' + maxwidth +' width allowed'); return; } //Check height if(aHeight > maxheight) { msgUp.text('Maximum' + maxheight +' height allowed'); return; } //Success of every check, display infos about the image and show up the <img> tag msgUp.html('Size :'+ aSize +' bytes<br>Filetype : '+ aType +'<br>Width :'+ aWidth +' px<br>Height: '+ aHeight +' px'); ish.show(); filesend.addClass('lock').css('height','0%'); //End image }; //End filer }; //File is up filer.readAsDataURL(file); }); //input file prevent on lock $(document).off('click', '#filesend'); $(document).on('click', '#filesend', function(e) { //Cancel the default execution if img ready to be send to php if($(this).hasClass('lock')) e.preventDefault(); }); //On reset $(document).off('click', '#reset'); $(document).on('click', '#reset', function(e) { //Cancel the default execution e.preventDefault(); //Remove the href link fileprev.attr('src', ''); //Set default message msgUp.text('Drop your avatar !'); //Remove the lock of the input file if(filesend.hasClass('lock')) filesend.css('height','100%').removeClass(); //Set default reset value $(this).val('Clear'); //Back to hide ish.hide(); }); //On fileup $(document).off('click', '#fileup'); $(document).on('click', '#fileup', function(e) { //Cancel the default execution e.preventDefault(); //Set variable which contain the entiere form / field var filesfm = new FormData(document.querySelector("form")); $.ajax({ url: 'upload.php', //Server side script (php...) type: 'POST', data:filesfm, processData: false, //Avoid jquery process contentType: false //Avoid set content type (done by var filesfm) }).done(function(msg) { //Hide the button upload fileup.hide(); //Change the text reset button (make as reinitialize the form) reset.val('Upload again !'); //On success upload if(msg === 'err') msgUp.text('Something went wrong, try again.'); //That should not happen ! else msgUp.text('Success, your file is available '+ msg); //Add the url of your file except the filename generated }); });
Anyon3/simplehtml5upload
upload.js
JavaScript
gpl-3.0
3,860
<?php /** * Piwik - free/libre analytics platform * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * */ namespace Piwik\Plugins\CoreUpdater; use Piwik\Config; use Piwik\Mail; use Piwik\Option; use Piwik\Piwik; use Piwik\Plugins\UsersManager\API as UsersManagerApi; use Piwik\SettingsPiwik; use Piwik\UpdateCheck; use Piwik\Version; /** * Class to check and notify users via email if there is a core update available. */ class UpdateCommunication { /** * Checks whether update communication in general is enabled or not. * * @return bool */ public function isEnabled() { $isEnabled = (bool) Config::getInstance()->General['enable_update_communication']; if($isEnabled === true && SettingsPiwik::isInternetEnabled() === true){ return true; } return false; } /** * Sends a notification email to all super users if there is a core update available but only if we haven't notfied * them about a specific new version yet. * * @return bool */ public function sendNotificationIfUpdateAvailable() { if (!$this->isNewVersionAvailable()) { return; } if ($this->hasNotificationAlreadyReceived()) { return; } $this->setHasLatestUpdateNotificationReceived(); $this->sendNotifications(); } protected function sendNotifications() { $latestVersion = $this->getLatestVersion(); $host = SettingsPiwik::getPiwikUrl(); $subject = Piwik::translate('CoreUpdater_NotificationSubjectAvailableCoreUpdate', $latestVersion); $message = Piwik::translate('ScheduledReports_EmailHello'); $message .= "\n\n"; $message .= Piwik::translate('CoreUpdater_ThereIsNewVersionAvailableForUpdate'); $message .= "\n\n"; $message .= Piwik::translate('CoreUpdater_YouCanUpgradeAutomaticallyOrDownloadPackage', $latestVersion); $message .= "\n"; $message .= $host . 'index.php?module=CoreUpdater&action=newVersionAvailable'; $message .= "\n\n"; $version = new Version(); if ($version->isStableVersion($latestVersion)) { $message .= Piwik::translate('CoreUpdater_ViewVersionChangelog'); $message .= "\n"; $message .= $this->getLinkToChangeLog($latestVersion); $message .= "\n\n"; } $message .= Piwik::translate('CoreUpdater_ReceiveEmailBecauseIsSuperUser', $host); $message .= "\n\n"; $message .= Piwik::translate('CoreUpdater_FeedbackRequest'); $message .= "\n"; $message .= 'https://matomo.org/contact/'; $this->sendEmailNotification($subject, $message); } private function getLinkToChangeLog($version) { $version = str_replace('.', '-', $version); $link = sprintf('https://matomo.org/changelog/piwik-%s/', $version); return $link; } /** * Send an email notification to all super users. * * @param $subject * @param $message */ protected function sendEmailNotification($subject, $message) { $superUsers = UsersManagerApi::getInstance()->getUsersHavingSuperUserAccess(); foreach ($superUsers as $superUser) { $mail = new Mail(); $mail->setDefaultFromPiwik(); $mail->addTo($superUser['email']); $mail->setSubject($subject); $mail->setBodyText($message); $mail->send(); } } protected function isNewVersionAvailable() { UpdateCheck::check(); $hasUpdate = UpdateCheck::isNewestVersionAvailable(); if (!$hasUpdate) { return false; } $latestVersion = self::getLatestVersion(); $version = new Version(); if (!$version->isVersionNumber($latestVersion)) { return false; } return $hasUpdate; } protected function hasNotificationAlreadyReceived() { $latestVersion = $this->getLatestVersion(); $lastVersionSent = $this->getLatestVersionSent(); if (!empty($lastVersionSent) && ($latestVersion == $lastVersionSent || version_compare($latestVersion, $lastVersionSent) == -1)) { return true; } return false; } private function getLatestVersion() { $version = UpdateCheck::getLatestVersion(); if (!empty($version)) { $version = trim($version); } return $version; } private function getLatestVersionSent() { return Option::get($this->getNotificationSentOptionName()); } private function setHasLatestUpdateNotificationReceived() { $latestVersion = $this->getLatestVersion(); Option::set($this->getNotificationSentOptionName(), $latestVersion); } private function getNotificationSentOptionName() { return 'last_update_communication_sent_core'; } }
mneudert/piwik
plugins/CoreUpdater/UpdateCommunication.php
PHP
gpl-3.0
5,094
#include "Registry.hpp" Registry::ExtrinsicRegistry::ExtrinsicRegistry() : window{}, splitter{}, GUI{new GuiSettings{}} {}
GenaBitu/NIMP
src/Registry/ExtrinsicRegistry.cpp
C++
gpl-3.0
124
const {ipcFuncMain, ipcFuncMainCb, getIpcNameFunc, sendToBackgroundPage} = require('./util-main') const {ipcMain} = require('electron') const getIpcName = getIpcNameFunc('ContextMenus') const extInfos = require('../../extensionInfos') const sharedState = require('../../sharedStateMain') ipcMain.on('get-extension-menu',(e) => ipcMain.emit('get-extension-menu-reply', null, sharedState.extensionMenu)) ipcMain.on('chrome-context-menus-clicked', async (e, extensionId, tabId, info)=>{ sendToBackgroundPage(extensionId, getIpcName('onClicked'), info, tabId) }) ipcFuncMainCb('contextMenus', 'create', (e, extensionId, createProperties, cb)=> { console.log('contextMenu', 'create', extensionId, createProperties) const manifest = extInfos[extensionId].manifest const icon = Object.values(manifest.icons)[0] const menuItemId = createProperties.id if(!sharedState.extensionMenu[extensionId]) sharedState.extensionMenu[extensionId] = [] sharedState.extensionMenu[extensionId].push({properties: createProperties, menuItemId, icon}) sharedState.extensionMenu[extensionId].sort((a,b) => (a.properties.count || 99) - (b.properties.count || 99)) //TODO onClick cb() }) ipcFuncMain('contextMenus', 'update', (e, extensionId, id, updateProperties) => { const menu = sharedState.extensionMenu[extensionId] if(menu){ const item = menu.find(propeties=>propeties.id === id || propeties.menuItemId === id) if(item) Object.assign(item.properties,updateProperties) } }) ipcFuncMain('contextMenus', 'remove', (e, extensionId, menuItemId) => { const menu = sharedState.extensionMenu[extensionId] if(menu){ const i = menu.findIndex(propeties=>propeties.menuItemId === menuItemId || propeties.id === menuItemId) if(i != -1) menu.splice(i,1) } }) ipcFuncMain('contextMenus', 'removeAll', (e, extensionId) => { console.log('contextMenu', 'removeAll', extensionId) delete sharedState.extensionMenu[extensionId] })
kura52/sushi-browser
src/remoted-chrome/browser/context-menus-main.js
JavaScript
gpl-3.0
1,947
var Card = require("./Card"); var CARDS = require("./cards"); var CARDNUM = require("./cardnum"); var api = require("../rpcapi"); var util = require("../util"); var state = require("../state"); var imgUtil = require("../img"); // INDEX ----------------------------------------------------------------------- function IndexCard() { Card.call(this, CARDNUM.INDEX, "#card-index"); } IndexCard.prototype = Object.create(Card.prototype); IndexCard.prototype.show = function() { Card.prototype.show.call(this); state.toCard(this); util.setHeader("Foxi"); util.setSubheader(); util.showBackButton(function() { CARDS.CONNECTION.activate(); }); }; IndexCard.prototype.load = function() { var card = this; card.render('index'); $("a[data-card-link]").on('click', function() { util.freezeUI(this); var linked = CARDS[$(this).attr('data-card-link')]; linked.activate(); }); api.VideoLibrary.GetRecentlyAddedMovies({ properties: [ 'art' ], limits: { end: 4 } }).then(function(data) { card.render('index_recent_movies', data.result, '#index-recent-movies'); imgUtil.loadImages($("#index-recent-movies img[data-cache-url]"), imgUtil.dimensions.movie); }); api.VideoLibrary.GetRecentlyAddedEpisodes({ properties: [ 'art' ], limits: { end: 4 } }).then(function(data) { card.render('index_recent_episodes', data.result, '#index-recent-episodes'); imgUtil.loadImages($("#index-recent-episodes img[data-cache-url]"), imgUtil.dimensions.tv_thumb); }); this.loaded = true; this.show(); }; module.exports = new IndexCard();
soupytwist/Foxi
src/cards/IndexCard.js
JavaScript
gpl-3.0
1,623
package com.supermap.desktop.framemenus; import com.supermap.desktop.Application; import com.supermap.desktop.Interface.IBaseItem; import com.supermap.desktop.Interface.IForm; import com.supermap.desktop.implement.CtrlAction; import com.supermap.desktop.ui.controls.JDialogWorkspaceSaveAs; import javax.swing.*; public class CtrlActionWorkspaceSaveAsOracle extends CtrlAction { public CtrlActionWorkspaceSaveAsOracle(IBaseItem caller, IForm formClass) { super(caller, formClass); } public void run(){ JFrame parent = (JFrame) Application.getActiveApplication().getMainFrame(); JDialogWorkspaceSaveAs dialog = new JDialogWorkspaceSaveAs(parent, true,JDialogWorkspaceSaveAs.saveAsOracle); dialog.showDialog(); } @Override public boolean enable() { return true; } }
SuperMap-iDesktop/SuperMap-iDesktop-Cross
DataView/src/main/java/com/supermap/desktop/framemenus/CtrlActionWorkspaceSaveAsOracle.java
Java
gpl-3.0
785
<?php /** * Base renderer for rendering HTML based diffs for PHP DiffLib. * * PHP version 5 * * Copyright (c) 2009 Chris Boulton <chris.boulton@interspire.com> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the Chris Boulton nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package DiffLib * @author Chris Boulton <chris.boulton@interspire.com> * @copyright (c) 2009 Chris Boulton * @license New BSD License http://www.opensource.org/licenses/bsd-license.php * @version 1.1 * @link http://github.com/chrisboulton/php-diff */ namespace Helper\Diff\Renderer\Html; class Base extends \Helper\Diff\Renderer\Base { /** * @var array Array of the default options that apply to this renderer. */ protected $defaultOptions = array( 'tabSize' => 4 ); /** * Render and return an array structure suitable for generating HTML * based differences. Generally called by subclasses that generate a * HTML based diff and return an array of the changes to show in the diff. * * @return array An array of the generated chances, suitable for presentation in HTML. */ public function render() { // As we'll be modifying a & b to include our change markers, // we need to get the contents and store them here. That way // we're not going to destroy the original data $a = $this->diff->getA(); $b = $this->diff->getB(); $changes = array(); $opCodes = $this->diff->getGroupedOpcodes(); foreach($opCodes as $group) { $blocks = array(); $lastTag = null; $lastBlock = 0; foreach($group as $code) { list($tag, $i1, $i2, $j1, $j2) = $code; if($tag == 'replace' && $i2 - $i1 == $j2 - $j1) { for($i = 0; $i < ($i2 - $i1); ++$i) { $fromLine = $a[$i1 + $i]; $toLine = $b[$j1 + $i]; list($start, $end) = $this->getChangeExtent($fromLine, $toLine); if($start != 0 || $end != 0) { $last = $end + strlen($fromLine); $fromLine = substr_replace($fromLine, "\0", $start, 0); $fromLine = substr_replace($fromLine, "\1", $last + 1, 0); $last = $end + strlen($toLine); $toLine = substr_replace($toLine, "\0", $start, 0); $toLine = substr_replace($toLine, "\1", $last + 1, 0); $a[$i1 + $i] = $fromLine; $b[$j1 + $i] = $toLine; } } } if($tag != $lastTag) { $blocks[] = array( 'tag' => $tag, 'base' => array( 'offset' => $i1, 'lines' => array() ), 'changed' => array( 'offset' => $j1, 'lines' => array() ) ); $lastBlock = count($blocks)-1; } $lastTag = $tag; if($tag == 'equal') { $lines = array_slice($a, $i1, ($i2 - $i1)); $blocks[$lastBlock]['base']['lines'] += $this->formatLines($lines); $lines = array_slice($b, $j1, ($j2 - $j1)); $blocks[$lastBlock]['changed']['lines'] += $this->formatLines($lines); } else { if($tag == 'replace' || $tag == 'delete') { $lines = array_slice($a, $i1, ($i2 - $i1)); $lines = $this->formatLines($lines); $lines = str_replace(array("\0", "\1"), array('<del>', '</del>'), $lines); $blocks[$lastBlock]['base']['lines'] += $lines; } if($tag == 'replace' || $tag == 'insert') { $lines = array_slice($b, $j1, ($j2 - $j1)); $lines = $this->formatLines($lines); $lines = str_replace(array("\0", "\1"), array('<ins>', '</ins>'), $lines); $blocks[$lastBlock]['changed']['lines'] += $lines; } } } $changes[] = $blocks; } return $changes; } /** * Given two strings, determine where the changes in the two strings * begin, and where the changes in the two strings end. * * @param string $fromLine The first string. * @param string $toLine The second string. * @return array Array containing the starting position (0 by default) and the ending position (-1 by default) */ private function getChangeExtent($fromLine, $toLine) { $start = 0; $limit = min(strlen($fromLine), strlen($toLine)); while($start < $limit && $fromLine{$start} == $toLine{$start}) { ++$start; } $end = -1; $limit = $limit - $start; while(-$end <= $limit && substr($fromLine, $end, 1) == substr($toLine, $end, 1)) { --$end; } return array( $start, $end + 1 ); } /** * Format a series of lines suitable for output in a HTML rendered diff. * This involves replacing tab characters with spaces, making the HTML safe * for output, ensuring that double spaces are replaced with &nbsp; etc. * * @param array $lines Array of lines to format. * @return array Array of the formatted lines. */ private function formatLines($lines) { $lines = array_map(array($this, 'ExpandTabs'), $lines); $lines = array_map(array($this, 'HtmlSafe'), $lines); foreach($lines as &$line) { $line = preg_replace('# ( +)|^ #e', "\$this->fixSpaces('\\1')", $line); } return $lines; } /** * Replace a string containing spaces with a HTML representation using &nbsp;. * * @param string $spaces The string of spaces. * @return string The HTML representation of the string. */ function fixSpaces($spaces='') { $count = strlen($spaces); if($count == 0) { return ''; } $div = floor($count / 2); $mod = $count % 2; return str_repeat('&nbsp; ', $div).str_repeat('&nbsp;', $mod); } /** * Replace tabs in a single line with a number of spaces as defined by the tabSize option. * * @param string $line The containing tabs to convert. * @return string The line with the tabs converted to spaces. */ private function expandTabs($line) { return str_replace("\t", str_repeat(' ', $this->options['tabSize']), $line); } /** * Make a string containing HTML safe for output on a page. * * @param string $string The string. * @return string The string with the HTML characters replaced by entities. */ private function htmlSafe($string) { if(function_exists('mb_convert_encoding')) { $string = mb_convert_encoding($string, 'UTF-8'); } return htmlspecialchars($string, ENT_NOQUOTES, 'UTF-8'); } }
simontaosim/phpprojekt_simon
app/helper/Diff/Renderer/html/base.php
PHP
gpl-3.0
7,456
package com.ebrightmoon.doraemonkit.ui.widget.tableview.listener; import java.util.ArrayList; import java.util.List; public abstract class Observable<T> { public final ArrayList<T> observables = new ArrayList<>(); /**AttachObserver(通过实例注册观察者) **/ public void register(T observer){ if(observer==null) throw new NullPointerException(); synchronized(observables){ if(!observables.contains(observer)){ observables.add(observer); } } } /**UnattachObserver(注销观察者) **/ public void unRegister(T observer){ if(observer==null) throw new NullPointerException(); if(observables.contains(observer)){ observables.remove(observer); } } public void unRegisterAll(){ synchronized(observables){ observables.clear(); } } /**Ruturnthesizeofobservers*/ public int countObservers(){ synchronized(observables){ return observables.size(); } } /** *notify all observer(通知所有观察者,在子类中实现) */ public abstract void notifyObservers(List<T> observers); }
jinsedeyuzhou/NewsClient
doraemonkit/src/main/java/com/ebrightmoon/doraemonkit/ui/widget/tableview/listener/Observable.java
Java
gpl-3.0
1,237
/* * Beautiful Capi generates beautiful C API wrappers for your C++ classes * Copyright (C) 2015 Petr Petrovich Petrov * * This file is part of Beautiful Capi. * * Beautiful Capi 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 3 of the License, or * (at your option) any later version. * * Beautiful Capi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Beautiful Capi. If not, see <http://www.gnu.org/licenses/>. * */ #include <iostream> #include "CircleImpl.h" Example::CircleImpl::CircleImpl() : m_radius(10.0) { std::cout << "Circle ctor" << std::endl; } Example::CircleImpl::CircleImpl(const CircleImpl& other) : m_radius(other.m_radius) { std::cout << "Circle copy ctor" << std::endl; } Example::CircleImpl::~CircleImpl() { std::cout << "Circle dtor" << std::endl; } void Example::CircleImpl::Show() const { std::cout << "CircleImpl::Show(), radius = " << m_radius << std::endl; } void Example::CircleImpl::SetRadius(double radius) { m_radius = radius; }
PetrPPetrov/beautiful-capi
examples/down_cast/library/source/CircleImpl.cpp
C++
gpl-3.0
1,394
<?php /** * Created by JetBrains PhpStorm. * Project: Amphibian * User: Carl "Tex" Morgan * Date: 7/10/13 * Time: 1:15 PM * All rights reserved by Inselberge Inc. unless otherwise stated. */ require_once AMPHIBIAN_GENERATORS_ABSTRACT_INTERFACES."BasicGeneratorInterface.php"; interface FormGeneratorInterface extends BasicGeneratorInterface { /** setFormType * @param $formType * @return mixed */ public function setFormType( $formType ); public function execute(); }
inselberge/Amphibian
generators/abstract/interfaces/FormGeneratorInterface.php
PHP
gpl-3.0
506
package com.fr.plugin.chart.custom.component; import com.fr.chart.chartattr.Plot; import com.fr.chart.web.ChartHyperPoplink; import com.fr.chart.web.ChartHyperRelateCellLink; import com.fr.chart.web.ChartHyperRelateFloatLink; import com.fr.design.ExtraDesignClassManager; import com.fr.design.beans.BasicBeanPane; import com.fr.design.chart.javascript.ChartEmailPane; import com.fr.design.chart.series.SeriesCondition.impl.ChartHyperPoplinkPane; import com.fr.design.chart.series.SeriesCondition.impl.ChartHyperRelateCellLinkPane; import com.fr.design.chart.series.SeriesCondition.impl.ChartHyperRelateFloatLinkPane; import com.fr.design.chart.series.SeriesCondition.impl.FormHyperlinkPane; import com.fr.design.designer.TargetComponent; import com.fr.design.fun.HyperlinkProvider; import com.fr.design.gui.HyperlinkFilterHelper; import com.fr.design.gui.controlpane.NameObjectCreator; import com.fr.design.gui.controlpane.NameableCreator; import com.fr.design.gui.imenutable.UIMenuNameableCreator; import com.fr.design.hyperlink.ReportletHyperlinkPane; import com.fr.design.hyperlink.WebHyperlinkPane; import com.fr.design.javascript.JavaScriptImplPane; import com.fr.design.javascript.ParameterJavaScriptPane; import com.fr.design.module.DesignModuleFactory; import com.fr.general.FRLogger; import com.fr.general.Inter; import com.fr.general.NameObject; import com.fr.js.EmailJavaScript; import com.fr.js.FormHyperlinkProvider; import com.fr.js.JavaScript; import com.fr.js.JavaScriptImpl; import com.fr.js.NameJavaScript; import com.fr.js.NameJavaScriptGroup; import com.fr.js.ParameterJavaScript; import com.fr.js.ReportletHyperlink; import com.fr.js.WebHyperlink; import com.fr.plugin.chart.designer.component.VanChartUIListControlPane; import com.fr.stable.ListMap; import com.fr.stable.Nameable; import com.fr.stable.bridge.StableFactory; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Created by Fangjie on 2016/4/28. */ public class VanChartHyperLinkPane extends VanChartUIListControlPane { public VanChartHyperLinkPane() { super(); } @Override public NameableCreator[] createNameableCreators() { //面板初始化,需要在populate的时候更新 Map<String, NameableCreator> nameCreators = new ListMap<>(); NameableCreator[] creators = DesignModuleFactory.getHyperlinkGroupType().getHyperlinkCreators(); for (NameableCreator creator : creators) { nameCreators.put(creator.menuName(), creator); } Set<HyperlinkProvider> providers = ExtraDesignClassManager.getInstance().getArray(HyperlinkProvider.XML_TAG); for (HyperlinkProvider provider : providers) { NameableCreator nc = provider.createHyperlinkCreator(); nameCreators.put(nc.menuName(), nc); } return nameCreators.values().toArray(new NameableCreator[nameCreators.size()]); } protected BasicBeanPane createPaneByCreators(NameableCreator creator) { Constructor<? extends BasicBeanPane> constructor = null; try { constructor = creator.getUpdatePane().getConstructor(HashMap.class, boolean.class); return constructor.newInstance(plot.getHyperLinkEditorMap(), false); } catch (InstantiationException e) { FRLogger.getLogger().error(e.getMessage(), e); } catch (IllegalAccessException e) { FRLogger.getLogger().error(e.getMessage(), e); } catch (NoSuchMethodException e) { return super.createPaneByCreators(creator); } catch (InvocationTargetException e) { FRLogger.getLogger().error(e.getMessage(), e); } return null; } /** * 弹出列表的标题. * * @return 返回标题字符串. */ public String title4PopupWindow() { return Inter.getLocText("FR-Designer_Hyperlink"); } @Override protected String getAddItemText() { return Inter.getLocText("FR-Designer_Add_Hyperlink"); } @Override protected AddItemMenuDef getAddItemMenuDef (NameableCreator[] creators) { return new AddVanChartItemMenuDef(creators); } public void populate(NameJavaScriptGroup nameHyperlink_array) { java.util.List<NameObject> list = new ArrayList<NameObject>(); if (nameHyperlink_array != null) { for (int i = 0; i < nameHyperlink_array.size(); i++) { list.add(new NameObject(nameHyperlink_array.getNameHyperlink(i).getName(), nameHyperlink_array.getNameHyperlink(i).getJavaScript())); } } this.populate(list.toArray(new NameObject[list.size()])); } public void populate(TargetComponent elementCasePane) { //populate } /** * updateJs的Group * * @return 返回NameJavaScriptGroup */ public NameJavaScriptGroup updateJSGroup() { Nameable[] res = this.update(); NameJavaScript[] res_array = new NameJavaScript[res.length]; for (int i = 0; i < res.length; i++) { NameObject no = (NameObject) res[i]; res_array[i] = new NameJavaScript(no.getName(), (JavaScript) no.getObject()); } return new NameJavaScriptGroup(res_array); } public void populate(Plot plot) { this.plot = plot; HashMap paneMap = getHyperlinkMap(plot); //安装平台内打开插件时,添加相应按钮 Set<HyperlinkProvider> providers = ExtraDesignClassManager.getInstance().getArray(HyperlinkProvider.XML_TAG); for (HyperlinkProvider provider : providers) { NameableCreator nc = provider.createHyperlinkCreator(); paneMap.put(nc.getHyperlink(), nc.getUpdatePane()); } java.util.List<UIMenuNameableCreator> list = refreshList(paneMap); NameObjectCreator[] creators = new NameObjectCreator[list.size()]; for (int i = 0; list != null && i < list.size(); i++) { UIMenuNameableCreator uiMenuNameableCreator = list.get(i); creators[i] = new NameObjectCreator(uiMenuNameableCreator.getName(), uiMenuNameableCreator.getObj().getClass(), uiMenuNameableCreator.getPaneClazz()); } refreshNameableCreator(creators); java.util.List<NameObject> nameObjects = new ArrayList<NameObject>(); NameJavaScriptGroup nameGroup = populateHotHyperLink(plot); for (int i = 0; nameGroup != null && i < nameGroup.size(); i++) { NameJavaScript javaScript = nameGroup.getNameHyperlink(i); if (javaScript != null && javaScript.getJavaScript() != null) { JavaScript script = javaScript.getJavaScript(); UIMenuNameableCreator uiMenuNameableCreator = new UIMenuNameableCreator(javaScript.getName(), script, getUseMap(paneMap, script.getClass())); nameObjects.add(new NameObject(uiMenuNameableCreator.getName(), uiMenuNameableCreator.getObj())); } } this.populate(nameObjects.toArray(new NameObject[nameObjects.size()])); doLayout(); } protected NameJavaScriptGroup populateHotHyperLink(Plot plot) { return plot.getHotHyperLink(); } protected HashMap getHyperlinkMap(Plot plot) { HashMap<Class, Class> map = new HashMap<Class, Class>(); map.put(ReportletHyperlink.class, ReportletHyperlinkPane.class); map.put(EmailJavaScript.class, ChartEmailPane.class); map.put(WebHyperlink.class, WebHyperlinkPane.class); map.put(ParameterJavaScript.class, ParameterJavaScriptPane.class); map.put(JavaScriptImpl.class, JavaScriptImplPane.class); map.put(ChartHyperPoplink.class, ChartHyperPoplinkPane.class); map.put(ChartHyperRelateCellLink.class, ChartHyperRelateCellLinkPane.class); map.put(ChartHyperRelateFloatLink.class, ChartHyperRelateFloatLinkPane.class); map.put(FormHyperlinkProvider.class, FormHyperlinkPane.class); return map; } public void update(Plot plot) { NameJavaScriptGroup nameGroup = updateNameGroup(); updateHotHyperLink(plot, nameGroup); } protected void updateHotHyperLink(Plot plot, NameJavaScriptGroup nameGroup) { plot.setHotHyperLink(nameGroup); } private NameJavaScriptGroup updateNameGroup() { Nameable[] nameables = update(); NameJavaScriptGroup nameGroup = new NameJavaScriptGroup(); nameGroup.clear(); for (int i = 0; i < nameables.length; i++) { JavaScript javaScript = (JavaScript) ((NameObject) nameables[i]).getObject(); String name = nameables[i].getName(); NameJavaScript nameJava = new NameJavaScript(name, javaScript); nameGroup.addNameHyperlink(nameJava); } return nameGroup; } protected java.util.List<UIMenuNameableCreator> refreshList(HashMap map) { java.util.List<UIMenuNameableCreator> list = new ArrayList<UIMenuNameableCreator>(); list.add(new UIMenuNameableCreator(Inter.getLocText("Chart-Link_Reportlet"), new ReportletHyperlink(), getUseMap(map, ReportletHyperlink.class))); list.add(new UIMenuNameableCreator(Inter.getLocText("Chart-Link_Mail"), new EmailJavaScript(), VanChartEmailPane.class)); list.add(new UIMenuNameableCreator(Inter.getLocText("Chart-Link_Web"), new WebHyperlink(), getUseMap(map, WebHyperlink.class))); list.add(new UIMenuNameableCreator(Inter.getLocText("Chart-Link_Dynamic_Parameters"), new ParameterJavaScript(), getUseMap(map, ParameterJavaScript.class))); list.add(new UIMenuNameableCreator("JavaScript", new JavaScriptImpl(), getUseMap(map, JavaScriptImpl.class))); list.add(new UIMenuNameableCreator(Inter.getLocText("Chart-Float_Chart"), new ChartHyperPoplink(), getUseMap(map, ChartHyperPoplink.class))); list.add(new UIMenuNameableCreator(Inter.getLocText("Chart-Link_Cell"), new ChartHyperRelateCellLink(), getUseMap(map, ChartHyperRelateCellLink.class))); list.add(new UIMenuNameableCreator(Inter.getLocText("Chart-Link_Float"), new ChartHyperRelateFloatLink(), getUseMap(map, ChartHyperRelateFloatLink.class))); FormHyperlinkProvider hyperlink = StableFactory.getMarkedInstanceObjectFromClass(FormHyperlinkProvider.XML_TAG, FormHyperlinkProvider.class); list.add(new UIMenuNameableCreator(Inter.getLocText("Chart-Link_Form"), hyperlink, getUseMap(map, FormHyperlinkProvider.class))); return list; } protected Class<? extends BasicBeanPane> getUseMap(HashMap map, Object key) { if (map.get(key) != null) { return (Class<? extends BasicBeanPane>) map.get(key); } //引擎在这边放了个provider,当前表单对象 for (Object tempKey : map.keySet()) { if (((Class) tempKey).isAssignableFrom((Class) key)) { return (Class<? extends BasicBeanPane>) map.get(tempKey); } } return null; } protected class AddVanChartItemMenuDef extends AddItemMenuDef { public AddVanChartItemMenuDef(NameableCreator[] creators) { super(creators); } @Override protected boolean whetherAdd(String itemName) { return HyperlinkFilterHelper.whetherAddHyperlink4Chart(itemName); } } //邮箱 public static class VanChartEmailPane extends ChartEmailPane { @Override protected boolean needRenamePane() { return false; } } }
fanruan/finereport-design
designer_chart/src/com/fr/plugin/chart/custom/component/VanChartHyperLinkPane.java
Java
gpl-3.0
11,772
package test.janus.data; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.apache.log4j.Logger; import org.janus.data.DataContext; import org.janus.data.DataContextImpl; import org.janus.data.DataDescription; import org.janus.data.DataDescriptionImpl; import org.junit.Test; public class DataDescriptionTest { private static final String THIS_EXCEPTION_IS_OK = "This Exception is ok"; private static final String THIS_EXCEPTION_IS_NOT_OK = "This Exception is not ok"; public static final Logger LOG = Logger.getLogger(DataDescriptionTest.class .getSimpleName()); private DataDescription createTestDescription() { DataDescription description = new DataDescriptionImpl(); description.getHandle("first"); description.getHandle("second"); return description; } @Test public void testGetHandle() { DataDescription description = new DataDescriptionImpl(); int h0 = description.getHandle("first"); int h1 = description.getHandle("second"); assertEquals(0, h0); assertEquals(1, h1); assertEquals(0, description.getHandle("first")); assertEquals(1, description.getHandle("second")); } @Test public void testExistsHandleName() { DataDescription description = createTestDescription(); assertEquals(true, description.existsHandleName("first")); assertEquals(false, description.existsHandleName("name")); } @Test public void testGetHandleName() { DataDescription description = createTestDescription(); assertEquals("first", description.getHandleName(description.getHandle("first"))); assertEquals("second", description.getHandleName(description.getHandle("second"))); } @Test public void testCreateAnonymousHandle() { DataDescription description = createTestDescription(); assertNotEquals(description.getHandle("first"), description.createAnonymousHandle()); assertNotEquals(description.getHandle("second"), description.createAnonymousHandle()); } @Test public void testFix() { try { DataDescription description = createTestDescription(); DataContext ctx = description.newContext(); description.getHandle("gehtNichtMehr"); fail("not fixed"); } catch (Exception rx) { LOG.error(THIS_EXCEPTION_IS_OK,rx); } } @Test public void testFixAnonymous() { try { DataDescription description = createTestDescription(); DataContext ctx = description.newContext(); description.createAnonymousHandle(); fail("not fixed"); } catch (Exception rx) { LOG.error(THIS_EXCEPTION_IS_OK,rx); } } @Test public void testFixErlaubt() { try { DataDescription description = createTestDescription(); DataContext ctx = description.newContext(); description.getHandle("second"); } catch (Exception rx) { LOG.error(THIS_EXCEPTION_IS_NOT_OK,rx); fail("not fixed"); } } @Test public void testGetSize() { DataDescription description = createTestDescription(); assertEquals(2, description.getSize()); } @Test public void testNewContext() { DataDescription description = createTestDescription(); DataContext ctx = description.newContext(); assertTrue(ctx instanceof DataContextImpl); } }
ThoNill/JanusData
JanusData/test/test/janus/data/DataDescriptionTest.java
Java
gpl-3.0
3,870
package com.minecolonies.coremod.client.gui; import com.ldtteam.blockout.Pane; import com.ldtteam.blockout.controls.Button; import com.ldtteam.blockout.controls.ButtonHandler; import com.ldtteam.blockout.controls.Text; import com.ldtteam.blockout.views.ScrollingList; import com.ldtteam.blockout.views.Window; import com.ldtteam.structurize.util.LanguageHandler; import com.minecolonies.api.colony.ICitizenDataView; import com.minecolonies.api.colony.IColonyView; import com.minecolonies.api.colony.buildings.views.IBuildingView; import com.minecolonies.api.util.BlockPosUtil; import com.minecolonies.api.util.constant.Constants; import com.minecolonies.coremod.Network; import com.minecolonies.coremod.colony.buildings.AbstractBuildingGuards; import com.minecolonies.coremod.colony.buildings.views.LivingBuildingView; import com.minecolonies.coremod.network.messages.server.colony.building.home.AssignUnassignMessage; import net.minecraft.util.math.BlockPos; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import static com.minecolonies.api.util.constant.WindowConstants.*; import static com.minecolonies.coremod.client.gui.huts.WindowHutBuilderModule.DARKGREEN; import static com.minecolonies.coremod.client.gui.huts.WindowHutBuilderModule.RED; /** * Window for the hiring or firing of a worker. */ public class WindowAssignCitizen extends Window implements ButtonHandler { /** * Threshold that defines when the living quarters are too far away. */ private static final double FAR_DISTANCE_THRESHOLD = 250; /** * The view of the current building. */ private final IBuildingView building; /** * List of citizens which can be assigned. */ private final ScrollingList citizenList; /** * The colony. */ private final IColonyView colony; /** * Contains all the citizens. */ private List<ICitizenDataView> citizens = new ArrayList<>(); /** * Constructor for the window when the player wants to assign a worker for a certain home building. * * @param c the colony view. * @param buildingId the building position. */ public WindowAssignCitizen(final IColonyView c, final BlockPos buildingId) { super(Constants.MOD_ID + ASSIGN_CITIZEN_RESOURCE_SUFFIX); this.colony = c; building = colony.getBuilding(buildingId); citizenList = findPaneOfTypeByID(CITIZEN_LIST, ScrollingList.class); updateCitizens(); } /** * Clears and resets/updates all citizens. */ private void updateCitizens() { citizens.clear(); citizens.addAll(colony.getCitizens().values()); //Removes all citizens which already have a job. citizens = colony.getCitizens().values().stream() .filter(cit -> cit.getHomeBuilding() == null || !(colony.getBuilding(cit.getHomeBuilding()) instanceof AbstractBuildingGuards.View) && !cit.getHomeBuilding().equals(building.getID())) .sorted(Comparator.comparing(cit -> ((ICitizenDataView) cit).getHomeBuilding() == null ? 0 : 1) .thenComparingLong(cit -> { if (((ICitizenDataView) cit).getWorkBuilding() == null) { return 0; } return BlockPosUtil.getDistance2D(((ICitizenDataView) cit).getWorkBuilding(), building.getPosition()); })).collect(Collectors.toList()); } /** * Called when the GUI has been opened. Will fill the fields and lists. */ @Override public void onOpened() { updateCitizens(); citizenList.enable(); citizenList.show(); //Creates a dataProvider for the homeless citizenList. citizenList.setDataProvider(new ScrollingList.DataProvider() { /** * The number of rows of the list. * @return the number. */ @Override public int getElementCount() { return citizens.size(); } /** * Inserts the elements into each row. * @param index the index of the row/list element. * @param rowPane the parent Pane for the row, containing the elements to update. */ @Override public void updateElement(final int index, @NotNull final Pane rowPane) { @NotNull final ICitizenDataView citizen = citizens.get(index); if (building instanceof LivingBuildingView) { rowPane.findPaneOfTypeByID(CITIZEN_LABEL, Text.class).setText(citizen.getName()); final BlockPos work = citizen.getWorkBuilding(); String workString = ""; double newDistance = 0; if (work != null) { newDistance = BlockPosUtil.getDistance2D(work, building.getPosition());; workString = " " + newDistance + " blocks"; } final BlockPos home = citizen.getHomeBuilding(); String homeString = ""; boolean better = false; boolean badCurrentLiving = false; if (home != null) { if (work != null) { final double oldDistance = BlockPosUtil.getDistance2D(work, home); homeString = LanguageHandler.format("com.minecolonies.coremod.gui.homeHut.currently", oldDistance); better = newDistance < oldDistance; if (oldDistance >= FAR_DISTANCE_THRESHOLD) { badCurrentLiving = true; } } else { homeString = LanguageHandler.format("com.minecolonies.coremod.gui.homeHut.current", home.getX(), home.getY(), home.getZ()); } } final Text newLivingLabel = rowPane.findPaneOfTypeByID(CITIZEN_JOB, Text.class); newLivingLabel.setText(LanguageHandler.format(citizen.getJob()) + workString); if (better) { newLivingLabel.setColors(DARKGREEN); } final Text currentLivingLabel = rowPane.findPaneOfTypeByID(CITIZEN_LIVING, Text.class); currentLivingLabel.setText(homeString); if (badCurrentLiving) { currentLivingLabel.setColors(RED); } final Button done = rowPane.findPaneOfTypeByID(CITIZEN_DONE, Button.class); if (colony.isManualHousing()) { done.enable(); } else { done.disable(); } } } }); } @Override public void onUpdate() { updateCitizens(); window.findPaneOfTypeByID(CITIZEN_LIST, ScrollingList.class).refreshElementPanes(); } /** * Called when any button has been clicked. * * @param button the clicked button. */ @Override public void onButtonClicked(@NotNull final Button button) { if (button.getID().equals(BUTTON_DONE)) { final int row = citizenList.getListElementIndexByPane(button); final ICitizenDataView data = citizens.get(row); if (building instanceof LivingBuildingView) { ((LivingBuildingView) building).addResident(data.getId()); } Network.getNetwork().sendToServer(new AssignUnassignMessage(this.building, true, data.getId())); } else if (!button.getID().equals(BUTTON_CANCEL)) { return; } if (colony.getTownHall() != null) { building.openGui(false); } } }
Minecolonies/minecolonies
src/main/java/com/minecolonies/coremod/client/gui/WindowAssignCitizen.java
Java
gpl-3.0
8,602
<?php class Default_Model_DbTable_Marketing extends Zend_Db_Table_Abstract { protected $_name = 'marketing'; protected $_primary = 'id'; } class Default_Model_Marketing { protected $_id; protected $_type; protected $_code; protected $_status; protected $_created; protected $_modified; protected $_mapper; public function __construct(array $options = null) { if(is_array($options)) { $this->setOptions($options); } } public function __set($name, $value) { $method = 'set' . $name; if(('mapper' == $name) || !method_exists($this, $method)) { throw new Exception('Invalid '.$name.' property '.$method); } $this->$method($value); } public function __get($name) { $method = 'get' . $name; if(('mapper' == $name) || !method_exists($this, $method)) { throw new Exception('Invalid '.$name.' property '.$method); } return $this->$method(); } public function setOptions(array $options) { $methods = get_class_methods($this); foreach($options as $key => $value) { $method = 'set' . ucfirst($key); if(in_array($method, $methods)) { $this->$method($value); } } return $this; } public function setId($id) { $this->_id = (int) $id; return $this; } public function getId() { return $this->_id; } public function setType($value) { $this->_type = (string) $value; return $this; } public function getType() { return $this->_type; } public function setCode($value) { $this->_code = (string) $value; return $this; } public function getCode() { return $this->_code; } public function setStatus($value) { $this->_status = (!empty($value))?true:false; return $this; } public function getStatus() { return $this->_status; } public function setCreated($value) { $this->_created = (!empty($value) && strtotime($value)>0)?strtotime($value):null; return $this; } public function getCreated() { return $this->_created; } public function setModified($value) { $this->_modified = (!empty($value) && strtotime($value)>0)?strtotime($value):null; return $this; } public function getModified() { return $this->_modified; } public function setMapper($mapper) { $this->_mapper = $mapper; return $this; } public function getMapper() { if(null === $this->_mapper) { $this->setMapper(new Default_Model_MarketingMapper()); } return $this->_mapper; } public function save() { return $this->getMapper()->save($this); } public function find($id) { return $this->getMapper()->find($id, $this); } public function fetchAll($select = null) { return $this->getMapper()->fetchAll($select); } public function delete() { if(null === ($id = $this->getId())) { throw new Exception('Invalid record selected!'); } return $this->getMapper()->delete($id); } } class Default_Model_MarketingMapper { protected $_dbTable; public function setDbTable($dbTable) { if(is_string($dbTable)) { $dbTable = new $dbTable(); } if(!$dbTable instanceof Zend_Db_Table_Abstract) { throw new Exception('Invalid table data gateway provided'); } $this->_dbTable = $dbTable; return $this; } public function getDbTable() { if(null === $this->_dbTable) { $this->setDbTable('Default_Model_DbTable_Marketing'); } return $this->_dbTable; } public function save(Default_Model_Marketing $model) { $data = array( 'type' => $model->getType(), 'code' => $model->getCode(), 'status' => $model->getStatus()?'1':'0', ); if(null === ($id = $model->getId())) { $data['created'] = new Zend_Db_Expr('NOW()'); $data['modified'] = new Zend_Db_Expr('NOW()'); $id = $this->getDbTable()->insert($data); } else { $data['modified'] = new Zend_Db_Expr('NOW()'); $this->getDbTable()->update($data, array('id = ?' => $id)); } return $id; } public function find($id, Default_Model_Marketing $model) { $result = $this->getDbTable()->find($id); if(0 == count($result)) { return; } $row = $result->current(); $model->setOptions($row->toArray()); return $model; } public function fetchAll($select) { $resultSet = $this->getDbTable()->fetchAll($select); $entries = array(); foreach($resultSet as $row) { $model = new Default_Model_Marketing(); $model->setOptions($row->toArray()) ->setMapper($this); $entries[] = $model; } return $entries; } public function delete($id) { $where = $this->getDbTable()->getAdapter()->quoteInto('id = ?', $id); return $this->getDbTable()->delete($where); } }
tsergium/funcake.org
application/models/Marketing.php
PHP
gpl-3.0
4,540
/* * Katana - a powerful, open-source screenshot utility * * Copyright (C) 2018, Gage Alexander <gage@washedout.co> * * Katana 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 3 of the License, or * any later version. * * Katana is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Katana. If not, see <http://www.gnu.org/licenses/>. */ const packager = require('electron-packager') const options = { platform: ['darwin'], arch: 'x64', icon: './app/static/images/icon', dir: '.', ignore: ['build'], out: './build/Release', overwrite: true, prune: true } packager(options, (error, path) => { if (error) { return ( console.log(`Error: ${error}`) ) } console.log(`Package created, path: ${path}`) })
bluegill/katana
build/index.js
JavaScript
gpl-3.0
1,149
package eu.clarin.weblicht.bindings.cmd.ws; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; /** * * @author akislev */ @XmlAccessorType(value = XmlAccessType.FIELD) public class OutputValues extends AbstractValues<OutputValue> { @XmlElement(name = "ParameterValue", required = true) private List<OutputValue> values; OutputValues() { } @Override protected List<OutputValue> getValues() { return values; } public boolean add(OutputValue value) { if (values == null) { values = new ArrayList<OutputValue>(); } return values.add(value); } @Override public OutputValues copy() { OutputValues v = (OutputValues) super.copy(); v.values = copy(values); return v; } }
weblicht/oaipmh-cmdi-bindings
src/main/java/eu/clarin/weblicht/bindings/cmd/ws/OutputValues.java
Java
gpl-3.0
932
import * as gulp from 'gulp'; import * as runSequence from 'run-sequence'; import {loadTasks} from './tools/utils'; import {SEED_TASKS_DIR, PROJECT_TASKS_DIR} from './tools/config'; loadTasks(SEED_TASKS_DIR); loadTasks(PROJECT_TASKS_DIR); // -------------- // Build dev. gulp.task('build.dev', (done: any) => runSequence('clean.dev', 'tslint', // 'css-lint', // the old css task we no longer need 'scss-lint', // the task we created 'build.assets.dev', // 'build.html_css', // the old css task we no longer need 'build.html_scss', // the task we created 'build.js.dev', 'build.index.dev', done)); // -------------- // Build dev watch. gulp.task('build.dev.watch', (done: any) => runSequence('build.dev', 'watch.dev', done)); // -------------- // Build e2e. gulp.task('build.e2e', (done: any) => runSequence('clean.dev', 'tslint', 'build.assets.dev', 'build.js.e2e', 'build.index.dev', done)); // -------------- // Build prod. gulp.task('build.prod', (done: any) => runSequence('clean.prod', 'tslint', // 'css-lint', // the old css task we no longer need 'scss-lint', // the task we created 'build.assets.prod', // 'build.html_css', // the old css task we no longer need 'build.html_scss', // the task we created 'copy.js.prod', 'build.js.prod', 'build.bundles', 'build.bundles.app', 'build.index.prod', done)); // -------------- // Build test. gulp.task('build.test', (done: any) => runSequence('clean.dev', 'tslint', 'build.assets.dev', 'build.js.test', 'build.index.dev', done)); // -------------- // Build test watch. gulp.task('build.test.watch', (done: any) => runSequence('build.test', 'watch.test', done)); // -------------- // Build tools. gulp.task('build.tools', (done: any) => runSequence('clean.tools', 'build.js.tools', done)); // -------------- // Docs gulp.task('docs', (done: any) => runSequence('build.docs', 'serve.docs', done)); // -------------- // Serve dev gulp.task('serve.dev', (done: any) => runSequence('build.dev', 'server.start', 'watch.dev', done)); // -------------- // Serve e2e gulp.task('serve.e2e', (done: any) => runSequence('build.e2e', 'server.start', 'watch.e2e', done)); // -------------- // Serve prod gulp.task('serve.prod', (done: any) => runSequence('build.prod', 'server.prod', done)); // -------------- // Test. gulp.task('test', (done: any) => runSequence('build.test', 'karma.start', done));
smartbiz/angular2-dashboard
gulpfile.ts
TypeScript
gpl-3.0
2,854
package l2s.gameserver.instancemanager; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import l2s.commons.util.Rnd; import l2s.gameserver.model.Player; import l2s.gameserver.model.quest.Quest; import l2s.gameserver.model.quest.QuestState; public class DailyQuestsManager { private static final Logger _log = LoggerFactory.getLogger(DailyQuestsManager.class); private static List<Integer> _disabledQuests = new ArrayList<Integer>(); public static void EngageSystem() { switch(Rnd.get(1, 3)) //60-64 1 quest per day { case 1: _disabledQuests.add(470); break; case 2: _disabledQuests.add(474); break; } switch(Rnd.get(1, 2)) //75-79 2 quest per day { case 1: _disabledQuests.add(488); break; case 2: _disabledQuests.add(489); break; } _log.info("Daily Quests Disable Managed: Loaded " + _disabledQuests.size() + " quests in total (4)."); } //dunno if this is retail but as I understand if quest gone from the list it will be removed from the player as well. public static void checkAndRemoveDisabledQuests(Player player) { if(player == null) return; for(int qId : _disabledQuests) { Quest q = QuestManager.getQuest(qId); QuestState qs = player.getQuestState(q.getName()); if(qs == null) continue; if(q.checkMaxLevelCondition(player)) continue; qs.exitCurrentQuest(true); } } public static boolean isQuestDisabled(int questId) { if(_disabledQuests.contains(questId)) return true; return false; } }
pantelis60/L2Scripts_Underground
gameserver/src/main/java/l2s/gameserver/instancemanager/DailyQuestsManager.java
Java
gpl-3.0
1,579
package com.bioxx.tfc.Render.Blocks; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.world.IBlockAccess; import org.lwjgl.opengl.GL11; import com.bioxx.tfc.TileEntities.TELoom; import com.bioxx.tfc.api.TFCBlocks; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; public class RenderLoom implements ISimpleBlockRenderingHandler { static float minX = 0F; static float maxX = 1F; static float minY = 0F; static float maxY = 1F; static float minZ = 0F; static float maxZ = 1F; @Override public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { TELoom te = (TELoom) world.getTileEntity(x, y, z); Block materialBlock; if(te.loomType < 16) { materialBlock = TFCBlocks.WoodSupportH; } else { materialBlock = TFCBlocks.WoodSupportH2; } renderer.renderAllFaces = true; GL11.glPushMatrix(); //Arms this.setRotatedRenderBounds(renderer, te.rotation, minX+0.1F, minY, minZ+0.75F, maxX-0.8F, maxY, maxZ-0.15F); renderer.renderStandardBlock(materialBlock, x, y, z); this.setRotatedRenderBounds(renderer, te.rotation, minX+0.8F, minY, minZ+0.75F, maxX-0.1F, maxY, maxZ-0.15F); renderer.renderStandardBlock(materialBlock, x, y, z); //Arm holding sections //L this.setRotatedRenderBounds(renderer, te.rotation, minX+0.1F, minY+0.25F, minZ+0.5F, maxX-0.8F, maxY-0.7F, maxZ-0.25F); renderer.renderStandardBlock(materialBlock, x, y, z); this.setRotatedRenderBounds(renderer, te.rotation, minX+0.1F, minY+0.05F, minZ+0.5F, maxX-0.8F, maxY-0.9F, maxZ-0.25F); renderer.renderStandardBlock(materialBlock, x, y, z); //R this.setRotatedRenderBounds(renderer, te.rotation, minX+0.8F, minY+0.25F, minZ+0.5F, maxX-0.1F, maxY-0.7F, maxZ-0.25F); renderer.renderStandardBlock(materialBlock, x, y, z); this.setRotatedRenderBounds(renderer, te.rotation, minX+0.8F, minY+0.05F, minZ+0.5F, maxX-0.1F, maxY-0.9F, maxZ-0.25F); renderer.renderStandardBlock(materialBlock, x, y, z); //cross this.setRotatedRenderBounds(renderer, te.rotation, maxX-0.8F, minY+0.8F, minZ+0.75F, minX+0.8F, maxY-0.1F, maxZ-0.15F); renderer.renderStandardBlock(materialBlock, x, y, z); this.setRotatedRenderBounds(renderer, te.rotation, maxX-0.8F, 0F, minZ+0.75F, minX+0.8F, minY+0.1F, maxZ-0.15F); renderer.renderStandardBlock(materialBlock, x, y, z); rotate(renderer, 0); renderer.renderAllFaces = false; GL11.glPopMatrix(); return true; } public void rotate(RenderBlocks renderer, int i) { renderer.uvRotateEast = i; renderer.uvRotateWest = i; renderer.uvRotateNorth = i; renderer.uvRotateSouth = i; } private void setRotatedRenderBounds(RenderBlocks renderer, byte rotation , float x, float y, float z, float X, float Y, float Z){ switch(rotation){ case 0: renderer.setRenderBounds(x,y,z,X,Y,Z); break; case 1: renderer.setRenderBounds(maxZ-Z,y,x,maxZ-z,Y,X); break; case 2: renderer.setRenderBounds(x,y,maxZ-Z,X,Y,maxZ-z); break; case 3: renderer.setRenderBounds(z,y,x,Z,Y,X); break; default: break; } } @Override public void renderInventoryBlock(Block block, int meta, int modelID, RenderBlocks renderer) { Block materialBlock; if(meta < 16) { materialBlock = TFCBlocks.WoodSupportH; } else { materialBlock = TFCBlocks.WoodSupportH2; } GL11.glPushMatrix(); GL11.glRotatef(180, 0, 1, 0); //Arms renderer.setRenderBounds(minX+0.1F, minY, minZ+0.75F, maxX-0.8F, maxY, maxZ-0.15F); rotate(renderer, 1); renderInvBlock(materialBlock, meta, renderer); renderer.setRenderBounds(minX+0.8F, minY, minZ+0.75F, maxX-0.1F, maxY, maxZ-0.15F); rotate(renderer, 1); renderInvBlock(materialBlock, meta, renderer); //Arm holding sections //L renderer.setRenderBounds(minX+0.1F, minY+0.35F, minZ+0.6F, maxX-0.8F, maxY-0.6F, maxZ-0.25F); rotate(renderer, 1); renderInvBlock(materialBlock, meta, renderer); renderer.setRenderBounds(minX+0.1F, minY+0.15F, minZ+0.6F, maxX-0.8F, maxY-0.8F, maxZ-0.25F); rotate(renderer, 1); renderInvBlock(materialBlock, meta, renderer); //R renderer.setRenderBounds(minX+0.8F, minY+0.35F, minZ+0.6F, maxX-0.1F, maxY-0.6F, maxZ-0.25F); rotate(renderer, 1); renderInvBlock(materialBlock, meta, renderer); renderer.setRenderBounds(minX+0.8F, minY+0.15F, minZ+0.6F, maxX-0.1F, maxY-0.8F, maxZ-0.25F); rotate(renderer, 1); renderInvBlock(materialBlock, meta, renderer); //cross renderer.setRenderBounds(maxX-0.8F, minY+0.8F, minZ+0.75F, minX+0.8F, maxY-0.1F, maxZ-0.15F); rotate(renderer, 1); renderInvBlock(materialBlock, meta, renderer); renderer.setRenderBounds(maxX-0.8F, 0F, minZ+0.75F, minX+0.8F, minY+0.1F, maxZ-0.15F); rotate(renderer, 1); renderInvBlock(materialBlock, meta, renderer); rotate(renderer, 0); GL11.glPopMatrix(); } @Override public boolean shouldRender3DInInventory(int modelId) { return true; } @Override public int getRenderId() { return 0; } public static void renderInvBlock(Block block, int m, RenderBlocks renderer) { Tessellator var14 = Tessellator.instance; GL11.glTranslatef(-0.5F, -0.5F, -0.5F); var14.startDrawingQuads(); var14.setNormal(0.0F, -1.0F, 0.0F); renderer.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, block.getIcon(0, m)); var14.draw(); var14.startDrawingQuads(); var14.setNormal(0.0F, 1.0F, 0.0F); renderer.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, block.getIcon(1, m)); var14.draw(); var14.startDrawingQuads(); var14.setNormal(0.0F, 0.0F, -1.0F); renderer.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, block.getIcon(2, m)); var14.draw(); var14.startDrawingQuads(); var14.setNormal(0.0F, 0.0F, 1.0F); renderer.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, block.getIcon(3, m)); var14.draw(); var14.startDrawingQuads(); var14.setNormal(-1.0F, 0.0F, 0.0F); renderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, block.getIcon(4, m)); var14.draw(); var14.startDrawingQuads(); var14.setNormal(1.0F, 0.0F, 0.0F); renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, block.getIcon(5, m)); var14.draw(); GL11.glTranslatef(0.5F, 0.5F, 0.5F); } public static void renderInvBlockHoop(Block block, int m, RenderBlocks renderer) { Tessellator var14 = Tessellator.instance; GL11.glTranslatef(-0.5F, -0.5F, -0.5F); var14.startDrawingQuads(); var14.setNormal(0.0F, -1.0F, 0.0F); renderer.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, block.getIcon(10, m)); var14.draw(); var14.startDrawingQuads(); var14.setNormal(0.0F, 1.0F, 0.0F); renderer.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, block.getIcon(11, m)); var14.draw(); var14.startDrawingQuads(); var14.setNormal(0.0F, 0.0F, -1.0F); renderer.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, block.getIcon(12, m)); var14.draw(); var14.startDrawingQuads(); var14.setNormal(0.0F, 0.0F, 1.0F); renderer.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, block.getIcon(13, m)); var14.draw(); var14.startDrawingQuads(); var14.setNormal(-1.0F, 0.0F, 0.0F); renderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, block.getIcon(14, m)); var14.draw(); var14.startDrawingQuads(); var14.setNormal(1.0F, 0.0F, 0.0F); renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, block.getIcon(15, m)); var14.draw(); GL11.glTranslatef(0.5F, 0.5F, 0.5F); } }
raymondbh/TFCraft
src/Common/com/bioxx/tfc/Render/Blocks/RenderLoom.java
Java
gpl-3.0
7,580
# -*- coding: utf-8 -*- #---------------------------------------------------------------------------- # Menu for quickly adding waypoints when on move #---------------------------------------------------------------------------- # Copyright 2007-2008, Oliver White # # 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 3 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 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 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, see <http://www.gnu.org/licenses/>. #--------------------------------------------------------------------------- from modules.base_module import RanaModule import cairo from time import time from math import pi def getModule(*args, **kwargs): return ClickMenu(*args, **kwargs) class ClickMenu(RanaModule): """Overlay info on the map""" def __init__(self, *args, **kwargs): RanaModule.__init__(self, *args, **kwargs) self.lastWaypoint = "(none)" self.lastWaypointAddTime = 0 self.messageLingerTime = 2 def handleMessage(self, message, messageType, args): if message == "addWaypoint": m = self.m.get("waypoints", None) if m is not None: self.lastWaypoint = m.newWaypoint() self.lastWaypointAddTime = time() def drawMapOverlay(self, cr): """Draw an overlay on top of the map, showing various information about position etc.""" # waypoins will be done in another way, so this is disabled for the time being # (x,y,w,h) = self.get('viewport') # # dt = time() - self.lastWaypointAddTime # if(dt > 0 and dt < self.messageLingerTime): # self.drawNewWaypoint(cr, x+0.5*w, y+0.5*h, w*0.3) # else: # m = self.m.get('clickHandler', None) # if(m != None): # m.registerXYWH(x+0.25*w,y+0.25*h,w*0.5,h*0.5, "clickMenu:addWaypoint") def drawNewWaypoint(self, cr, x, y, size): text = self.lastWaypoint cr.set_font_size(200) extents = cr.text_extents(text) (w, h) = (extents[2], extents[3]) cr.set_source_rgb(0, 0, 0.5) cr.arc(x, y, size, 0, 2 * pi) cr.fill() x1 = x - 0.5 * w y1 = y + 0.5 * h border = 20 cr.set_source_rgb(1, 1, 1) cr.move_to(x1, y1) cr.show_text(text) cr.fill()
ryfx/modrana
modules/_mod_clickMenu.py
Python
gpl-3.0
2,761
package org.dongchao.model.entity; import org.hibernate.validator.constraints.NotEmpty; import javax.persistence.*; import java.io.Serializable; import java.util.List; import java.util.Objects; import java.util.Set; /** * Created by zhaodongchao on 2017/5/3. */ @Table(name = "dc_user") @Entity public class User implements Serializable { @GeneratedValue(strategy = GenerationType.AUTO) @Id private Integer userId; @NotEmpty private String username; private String password; private String salt; /* 存放用户拥有的角色的对象的集合 多对多关联fetch不能设置为懒加载 */ @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinTable(name = "dc_user_role", joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "userId")}, inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "roleId")}) private Set<Role> role; @Transient private List<String> roles; @Transient private Set<String> permissions; public User() { } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public List<String> getRoles() { return roles; } public void setRoles(List<String> roles) { this.roles = roles; } public Set<Role> getRole() { return role; } public void setRole(Set<Role> role) { this.role = role; } public Set<String> getPermissions() { return permissions; } public void setPermissions(Set<String> permissions) { this.permissions = permissions; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return Objects.equals(userId, user.userId) && Objects.equals(username, user.username) && Objects.equals(password, user.password) && Objects.equals(roles, user.roles); } @Override public int hashCode() { return Objects.hash(userId, username, password, roles); } @Override public String toString() { final StringBuilder sb = new StringBuilder("User{"); sb.append("userId=").append(userId); sb.append(", username='").append(username).append('\''); sb.append(", password='").append(password).append('\''); sb.append(", salt='").append(salt).append('\''); sb.append(", roles=").append(roles); sb.append(", permissions=").append(permissions); sb.append('}'); return sb.toString(); } }
zhaodongchao/dcproj
dcproj-model/src/main/java/org/dongchao/model/entity/User.java
Java
gpl-3.0
3,180
package com.github.kuros.random.jpa.testUtil.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "employee_department") public class EmployeeDepartment { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "employee_id") private Long employeeId; @Column(name = "shift_id") private Integer shiftId; @Column(name = "department_id") private Integer departmentId; public Long getId() { return id; } public void setId(final Long id) { this.id = id; } public Long getEmployeeId() { return employeeId; } public void setEmployeeId(final Long employeeId) { this.employeeId = employeeId; } public Integer getShiftId() { return shiftId; } public void setShiftId(final Integer shiftId) { this.shiftId = shiftId; } public Integer getDepartmentId() { return departmentId; } public void setDepartmentId(final Integer departmentId) { this.departmentId = departmentId; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final EmployeeDepartment that = (EmployeeDepartment) o; return !(id != null ? !id.equals(that.id) : that.id != null); } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } }
kuros/random-jpa
src/test/java/com/github/kuros/random/jpa/testUtil/entity/EmployeeDepartment.java
Java
gpl-3.0
1,656
/* * This file is part of muCommander, http://www.mucommander.com * Copyright (C) 2002-2012 Maxence Bernard * * muCommander 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 3 of the License, or * (at your option) any later version. * * muCommander is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mucommander.ui.main; import java.awt.*; import java.awt.event.ActionEvent; import java.net.MalformedURLException; import java.util.*; import java.util.List; import java.util.regex.PatternSyntaxException; import javax.swing.*; import javax.swing.filechooser.FileSystemView; import com.mucommander.adb.AndroidMenu; import com.mucommander.adb.AdbUtils; import com.mucommander.bonjour.BonjourDirectory; import com.mucommander.utils.FileIconsCache; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.mucommander.bonjour.BonjourMenu; import com.mucommander.bonjour.BonjourService; import com.mucommander.bookmark.Bookmark; import com.mucommander.bookmark.BookmarkListener; import com.mucommander.bookmark.BookmarkManager; import com.mucommander.commons.conf.ConfigurationEvent; import com.mucommander.commons.conf.ConfigurationListener; import com.mucommander.commons.file.AbstractFile; import com.mucommander.commons.file.FileFactory; import com.mucommander.commons.file.FileProtocols; import com.mucommander.commons.file.FileURL; import com.mucommander.commons.file.filter.PathFilter; import com.mucommander.commons.file.filter.RegexpPathFilter; import com.mucommander.commons.file.impl.local.LocalFile; import com.mucommander.commons.runtime.OsFamily; import com.mucommander.conf.TcConfigurations; import com.mucommander.conf.TcPreference; import com.mucommander.conf.TcPreferences; import com.mucommander.utils.text.Translator; import com.mucommander.ui.action.TcAction; import com.mucommander.ui.action.impl.OpenLocationAction; import com.mucommander.ui.button.PopupButton; import com.mucommander.ui.dialog.server.FTPPanel; import com.mucommander.ui.dialog.server.HTTPPanel; import com.mucommander.ui.dialog.server.NFSPanel; import com.mucommander.ui.dialog.server.SFTPPanel; import com.mucommander.ui.dialog.server.SMBPanel; import com.mucommander.ui.dialog.server.ServerConnectDialog; import com.mucommander.ui.dialog.server.ServerPanel; import com.mucommander.ui.event.LocationEvent; import com.mucommander.ui.event.LocationListener; import com.mucommander.ui.helper.MnemonicHelper; import com.mucommander.ui.icon.CustomFileIconProvider; import com.mucommander.ui.icon.FileIcons; import com.mucommander.ui.icon.IconManager; import ru.trolsoft.ui.TMenuSeparator; /** * <code>DrivePopupButton</code> is a button which, when clicked, pops up a menu with a list of volumes items that be used * to change the current folder. * * @author Maxence Bernard */ public class DrivePopupButton extends PopupButton implements BookmarkListener, ConfigurationListener, LocationListener { private static Logger logger; /** FolderPanel instance that contains this button */ private FolderPanel folderPanel; /** Current volumes */ private static AbstractFile volumes[]; /** static FileSystemView instance, has a (non-null) value only under Windows */ private static FileSystemView fileSystemView; /** Caches extended drive names, has a (non-null) value only under Windows */ private static Map<AbstractFile, String> extendedNameCache; /** Caches drive icons */ private static Map<AbstractFile, Icon> iconCache = new HashMap<>(); /** Filters out volumes from the list based on the exclude regexp defined in the configuration, null if the regexp * is not defined. */ private static PathFilter volumeFilter; static { if (OsFamily.WINDOWS.isCurrent()) { fileSystemView = FileSystemView.getFileSystemView(); extendedNameCache = new HashMap<>(); } try { String excludeRegexp = TcConfigurations.getPreferences().getVariable(TcPreference.VOLUME_EXCLUDE_REGEXP); if (excludeRegexp != null) { volumeFilter = new RegexpPathFilter(excludeRegexp, true); volumeFilter.setInverted(true); } } catch(PatternSyntaxException e) { getLogger().info("Invalid regexp for conf variable " + TcPreferences.VOLUME_EXCLUDE_REGEXP, e); } // Initialize the volumes list volumes = getDisplayableVolumes(); } /** * Creates a new <code>DrivePopupButton</code> which is to be added to the given FolderPanel. * * @param folderPanel the FolderPanel instance this button will be added to */ DrivePopupButton(FolderPanel folderPanel) { this.folderPanel = folderPanel; // Listen to location events to update the button when the current folder changes folderPanel.getLocationManager().addLocationListener(this); // Listen to bookmark changes to update the button if a bookmark corresponding to the current folder // has been added/edited/removed BookmarkManager.addBookmarkListener(this); // Listen to configuration changes to update the button if the system file icons policy has changed TcConfigurations.addPreferencesListener(this); // Use new JButton decorations introduced in Mac OS X 10.5 (Leopard) //if (OsFamily.MAC_OS_X.isCurrent() && OsVersion.MAC_OS_X_10_5.isCurrentOrHigher()) { //setMargin(new Insets(6,8,6,8)); //putClientProperty("JComponent.sizeVariant", "small"); //putClientProperty("JComponent.sizeVariant", "large"); //putClientProperty("JButton.buttonType", "textured"); //} } /** * Updates the button's label and icon to reflect the current folder and match one of the current volumes: * <<ul> * <li>If the specified folder corresponds to a bookmark, the bookmark's name will be displayed * <li>If the specified folder corresponds to a local file, the enclosing volume's name will be displayed * <li>If the specified folder corresponds to a remote file, the protocol's name will be displayed * </ul> * The button's icon will be the current folder's one. */ private void updateButton() { AbstractFile currentFolder = folderPanel.getCurrentFolder(); setText(buildLabel(currentFolder)); // setToolTipText(newToolTip); // Set the folder icon based on the current system icons policy setIcon(FileIcons.getFileIcon(currentFolder)); } private String buildLabel(AbstractFile currentFolder) { String currentPath = currentFolder != null ? currentFolder.getAbsolutePath() : null; FileURL currentURL = currentFolder != null ? currentFolder.getURL() : null; // String newToolTip = null; // First tries to find a bookmark matching the specified folder List<Bookmark> bookmarks = BookmarkManager.getBookmarks(); String newLabel = null; for (Bookmark b : bookmarks) { if (currentPath != null && currentPath.equals(b.getLocation())) { // Note: if several bookmarks match current folder, the first one will be used newLabel = b.getName(); break; } } if (newLabel != null) { return newLabel; } // If no bookmark matched current folder String protocol = currentURL != null ? currentURL.getScheme() : null; if (!FileProtocols.FILE.equals(protocol)) { // Remote file, use the protocol's name return protocol != null ? protocol.toUpperCase() : ""; } else { // Local file, use volume's name // Patch for Windows UNC network paths (weakly characterized by having a host different from 'localhost'): // display 'SMB' which is the underlying protocol if (OsFamily.WINDOWS.isCurrent() && !FileURL.LOCALHOST.equals(currentURL.getHost())) { return "SMB"; } else { // getCanonicalPath() must be avoided under Windows for the following reasons: // a) it is not necessary, Windows doesn't have symlinks // b) it triggers the dreaded 'No disk in drive' error popup dialog. // c) when network drives are present but not mounted (e.g. X:\ mapped onto an SMB share), // getCanonicalPath which is I/O bound will take a looooong time to execute int bestIndex = getBestIndex(getVolumePath(currentFolder)); return volumes[bestIndex].getName(); // Not used because the call to FileSystemView is slow // if(fileSystemView!=null) // newToolTip = getWindowsExtendedDriveName(volumes[bestIndex]); } } } private int getBestIndex(String currentPath) { int bestLength = -1; int bestIndex = 0; for (int i = 0; i < volumes.length; i++) { String volumePath = getVolumePath(volumes[i]).toLowerCase(); int len = volumePath.length(); if (currentPath.startsWith(volumePath) && len > bestLength) { bestIndex = i; bestLength = len; } } return bestIndex; } @NotNull private String getVolumePath(AbstractFile file) { if (OsFamily.WINDOWS.isCurrent()) { return file.getAbsolutePath(false); } else { return file.getCanonicalPath(false); } } /** * Returns the extended name of the given local file, e.g. "Local Disk (C:)" for C:\. The returned value is * interesting only under Windows. This method is I/O bound and very slow so it should not be called from the main * event thread. * * @param localFile the file for which to return the extended name * @return the extended name of the given local file */ private static String getExtendedDriveName(AbstractFile localFile) { // Note: fileSystemView.getSystemDisplayName(java.io.File) is unfortunately very very slow String name = fileSystemView.getSystemDisplayName((java.io.File)localFile.getUnderlyingFileObject()); if (name == null || name.isEmpty()) { // This happens for CD/DVD drives when they don't contain any disc return localFile.getName(); } return name; } /** * Returns the list of volumes to be displayed in the popup menu. * * <p>The raw list of volumes is fetched using {@link LocalFile#getVolumes()} and then * filtered using the regexp defined in the {@link TcPreferences#VOLUME_EXCLUDE_REGEXP} configuration variable * (if defined). * * @return the list of volumes to be displayed in the popup menu */ private static AbstractFile[] getDisplayableVolumes() { AbstractFile[] volumes = LocalFile.getVolumes(); if (volumeFilter != null) { return volumeFilter.filter(volumes); } return volumes; } //////////////////////////////// // PopupButton implementation // //////////////////////////////// @Override public JPopupMenu getPopupMenu() { JPopupMenu popupMenu = new JPopupMenu(); // Update the list of volumes in case new ones were mounted volumes = getDisplayableVolumes(); // Add volumes final MainFrame mainFrame = folderPanel.getMainFrame(); MnemonicHelper mnemonicHelper = new MnemonicHelper(); // Provides mnemonics and ensures uniqueness addVolumes(popupMenu, mainFrame, mnemonicHelper); popupMenu.add(new TMenuSeparator()); addBookmarks(popupMenu, mainFrame, mnemonicHelper); popupMenu.add(new TMenuSeparator()); // Add 'Network shares' shortcut if (FileFactory.isRegisteredProtocol(FileProtocols.SMB)) { TcAction action = new CustomOpenLocationAction(mainFrame, new Bookmark(Translator.get("drive_popup.network_shares"), "smb:///", null)); action.setIcon(IconManager.getIcon(IconManager.IconSet.FILE, CustomFileIconProvider.NETWORK_ICON_NAME)); setMnemonic(popupMenu.add(action), mnemonicHelper); } if (BonjourDirectory.isActive()) { // Add Bonjour services menu setMnemonic(popupMenu.add(new BonjourMenu() { @Override public TcAction getMenuItemAction(BonjourService bs) { return new CustomOpenLocationAction(mainFrame, bs); } }), mnemonicHelper); } addAdbDevices(popupMenu, mainFrame, mnemonicHelper); popupMenu.add(new TMenuSeparator()); // Add 'connect to server' shortcuts setMnemonic(popupMenu.add(new ServerConnectAction("SMB...", SMBPanel.class)), mnemonicHelper); setMnemonic(popupMenu.add(new ServerConnectAction("FTP...", FTPPanel.class)), mnemonicHelper); setMnemonic(popupMenu.add(new ServerConnectAction("SFTP...", SFTPPanel.class)), mnemonicHelper); setMnemonic(popupMenu.add(new ServerConnectAction("HTTP...", HTTPPanel.class)), mnemonicHelper); setMnemonic(popupMenu.add(new ServerConnectAction("NFS...", NFSPanel.class)), mnemonicHelper); return popupMenu; } private void addVolumes(JPopupMenu popupMenu, MainFrame mainFrame, MnemonicHelper mnemonicHelper) { boolean useExtendedDriveNames = fileSystemView != null; List<JMenuItem> itemsV = new ArrayList<>(); int nbVolumes = volumes.length; for (int i = 0; i < nbVolumes; i++) { TcAction action = new CustomOpenLocationAction(mainFrame, volumes[i]); String volumeName = volumes[i].getName(); // If several volumes have the same filename, use the volume's path for the action's label instead of the // volume's path, to disambiguate for (int j = 0; j < nbVolumes; j++) { if (j != i && volumes[j].getName().equalsIgnoreCase(volumeName)) { action.setLabel(volumes[i].getAbsolutePath()); break; } } JMenuItem item = popupMenu.add(action); setMnemonic(item, mnemonicHelper); // Set icon from cache Icon icon = iconCache.get(volumes[i]); if (icon != null) { item.setIcon(icon); } if (useExtendedDriveNames) { // Use the last known value (if any) while we update it in a separate thread String previousExtendedName = extendedNameCache.get(volumes[i]); if (previousExtendedName != null) { item.setText(previousExtendedName); } } itemsV.add(item); // JMenu offers no way to retrieve a particular JMenuItem, so we have to keep them } new RefreshDriveNamesAndIcons(popupMenu, itemsV).start(); } private void addBookmarks(JPopupMenu popupMenu, MainFrame mainFrame, MnemonicHelper mnemonicHelper) { // Add bookmarks List<Bookmark> bookmarks = BookmarkManager.getBookmarks(); if (!bookmarks.isEmpty()) { addBookmarksGroup(popupMenu, mainFrame, mnemonicHelper, bookmarks, null); } else { // No bookmark : add a disabled menu item saying there is no bookmark popupMenu.add(Translator.get("bookmarks_menu.no_bookmark")).setEnabled(false); } } private void addBookmarksGroup(JComponent parentMenu, MainFrame mainFrame, MnemonicHelper mnemonicHelper, List<Bookmark> bookmarks, String parent) { for (Bookmark b : bookmarks) { if ((b.getParent() == null && parent == null) || (parent != null && parent.equals(b.getParent()))) { if (b.getName().equals(BookmarkManager.BOOKMARKS_SEPARATOR) && b.getLocation().isEmpty()) { parentMenu.add(new TMenuSeparator()); continue; } if (b.getLocation().isEmpty()) { JMenu groupMenu = new JMenu(b.getName()); parentMenu.add(groupMenu); addBookmarksGroup(groupMenu, mainFrame, mnemonicHelper, bookmarks, b.getName()); setMnemonic(groupMenu, mnemonicHelper); } else { JMenuItem item = createBookmarkMenuItem(parentMenu, mainFrame, b); setMnemonic(item, mnemonicHelper); } } } } private JMenuItem createBookmarkMenuItem(JComponent parentMenu, MainFrame mainFrame, Bookmark b) { JMenuItem item; if (parentMenu instanceof JPopupMenu) { item = ((JPopupMenu)parentMenu).add(new CustomOpenLocationAction(mainFrame, b)); } else { item = ((JMenu)parentMenu).add(new CustomOpenLocationAction(mainFrame, b)); } //JMenuItem item = popupMenu.add(new CustomOpenLocationAction(mainFrame, b)); String location = b.getLocation(); if (!location.contains("://")) { AbstractFile file = FileFactory.getFile(location); if (file != null) { Icon icon = FileIconsCache.getInstance().getIcon(file); if (icon != null) { item.setIcon(icon); } // Image image = FileIconsCache.getInstance().getImageIcon(file); // if (image != null) { // item.setIcon(new ImageIcon(image)); // } } } else if (location.startsWith("ftp://") || location.startsWith("sftp://") || location.startsWith("http://")) { item.setIcon(IconManager.getIcon(IconManager.IconSet.FILE, CustomFileIconProvider.NETWORK_ICON_NAME)); } else if (location.startsWith("adb://")) { item.setIcon(IconManager.getIcon(IconManager.IconSet.FILE, CustomFileIconProvider.ANDROID_ICON_NAME)); } return item; } private void addAdbDevices(JPopupMenu popupMenu, MainFrame mainFrame, MnemonicHelper mnemonicHelper) { if (AdbUtils.checkAdb()) { setMnemonic(popupMenu.add(new AndroidMenu() { @Override public TcAction getMenuItemAction(String deviceSerial) { FileURL url = getDeviceURL(deviceSerial); return new CustomOpenLocationAction(mainFrame, url); } @Nullable private FileURL getDeviceURL(String deviceSerial) { try { return FileURL.getFileURL("adb://" + deviceSerial); } catch (MalformedURLException e) { e.printStackTrace(); return null; } } }), mnemonicHelper); } } /** * Calls to getExtendedDriveName(String) are very slow, so they are performed in a separate thread so as * to not lock the main even thread. The popup menu gets first displayed with the short drive names, and * then refreshed with the extended names as they are retrieved. */ private class RefreshDriveNamesAndIcons extends Thread { private JPopupMenu popupMenu; private List<JMenuItem> items; RefreshDriveNamesAndIcons(JPopupMenu popupMenu, List<JMenuItem> items) { super("RefreshDriveNamesAndIcons"); this.popupMenu = popupMenu; this.items = items; } @Override public void run() { final boolean useExtendedDriveNames = fileSystemView != null; for (int i = 0; i < items.size(); i++) { final JMenuItem item = items.get(i); final String extendedName = getExtendedDriverName(useExtendedDriveNames, volumes[i]); final Icon icon = getIcon(volumes[i]); SwingUtilities.invokeLater(() -> { if (useExtendedDriveNames) { item.setText(extendedName); } if (icon != null) { item.setIcon(icon); } }); } // Re-calculate the popup menu's dimensions SwingUtilities.invokeLater(() -> { popupMenu.invalidate(); popupMenu.pack(); }); } @Nullable private Icon getIcon(AbstractFile file) { // Set system icon for volumes, only if system icons are available on the current platform final Icon icon = FileIcons.hasProperSystemIcons() ? FileIcons.getSystemFileIcon(file) : null; if (icon != null) { iconCache.put(file, icon); } return icon; } @Nullable private String getExtendedDriverName(boolean useExtendedDriveNames, AbstractFile file) { if (useExtendedDriveNames) { // Under Windows, show the extended drive name (e.g. "Local Disk (C:)" instead of just "C:") but use // the simple drive name for the mnemonic (i.e. 'C' instead of 'L'). String extendedName = getExtendedDriveName(file); // Keep the extended name for later (see above) extendedNameCache.put(file, extendedName); return extendedName; } return null; } } /** * Convenience method that sets a mnemonic to the given JMenuItem, using the specified MnemonicHelper. * * @param menuItem the menu item for which to set a mnemonic * @param mnemonicHelper the MnemonicHelper instance to be used to determine the mnemonic's character. */ private void setMnemonic(JMenuItem menuItem, MnemonicHelper mnemonicHelper) { menuItem.setMnemonic(mnemonicHelper.getMnemonic(menuItem.getText())); } ////////////////////////////// // BookmarkListener methods // ////////////////////////////// public void bookmarksChanged() { // Refresh label in case a bookmark with the current location was changed updateButton(); } /////////////////////////////////// // ConfigurationListener methods // /////////////////////////////////// /** * Listens to certain configuration variables. */ public void configurationChanged(ConfigurationEvent event) { String var = event.getVariable(); // Update the button's icon if the system file icons policy has changed if (var.equals(TcPreferences.USE_SYSTEM_FILE_ICONS)) { updateButton(); } } //////////////////////// // Overridden methods // //////////////////////// @Override public Dimension getPreferredSize() { // Limit button's maximum width to something reasonable and leave enough space for location field, // as bookmarks name can be as long as users want them to be. // Note: would be better to use JButton.setMaximumSize() but it doesn't seem to work Dimension d = super.getPreferredSize(); if (d.width > 160) { d.width = 160; } return d; } /////////////////// // Inner classes // /////////////////// /** * This action pops up {@link com.mucommander.ui.dialog.server.ServerConnectDialog} for a specified * protocol. */ private class ServerConnectAction extends AbstractAction { private Class<? extends ServerPanel> serverPanelClass; private ServerConnectAction(String label, Class<? extends ServerPanel> serverPanelClass) { super(label); this.serverPanelClass = serverPanelClass; } public void actionPerformed(ActionEvent actionEvent) { new ServerConnectDialog(folderPanel, serverPanelClass).showDialog(); } } /** * This modified {@link OpenLocationAction} changes the current folder on the {@link FolderPanel} that contains * this button, instead of the currently active {@link FolderPanel}. */ private class CustomOpenLocationAction extends OpenLocationAction { CustomOpenLocationAction(MainFrame mainFrame, Bookmark bookmark) { super(mainFrame, new HashMap<>(), bookmark); } CustomOpenLocationAction(MainFrame mainFrame, AbstractFile file) { super(mainFrame, new HashMap<>(), file); } CustomOpenLocationAction(MainFrame mainFrame, BonjourService bs) { super(mainFrame, new HashMap<>(), bs); } CustomOpenLocationAction(MainFrame mainFrame, FileURL url) { super(mainFrame, new HashMap<>(), url); } //////////////////////// // Overridden methods // //////////////////////// @Override protected FolderPanel getFolderPanel() { return folderPanel; } } /********************************** * LocationListener Implementation **********************************/ public void locationChanged(LocationEvent e) { // Update the button's label to reflect the new current folder updateButton(); } public void locationChanging(LocationEvent locationEvent) { } public void locationCancelled(LocationEvent locationEvent) { } public void locationFailed(LocationEvent locationEvent) {} private static Logger getLogger() { if (logger == null) { logger = LoggerFactory.getLogger(DrivePopupButton.class); } return logger; } }
trol73/mucommander
src/main/com/mucommander/ui/main/DrivePopupButton.java
Java
gpl-3.0
26,393
<?php /** * @package mod_digisem * @copyright 2011-2013 Patrick Meyer, Tobias Niedl * @license GNU General Public License (GPL) 3.0 (http://www.gnu.org/licenses/gpl.html) */ /** * FTPs file transfer handler * * @author Patrick Meyer * @since d#9 */ class FTPsHandler extends FTPHandler { /** * Connects to the server via using $host. * * @return TRUE, if connection to host can be established. */ function connect() { $this->conn_id = ftp_ssl_connect($this->host); if ($this->conn_id) { return true; } else { return false; } } } ?>
digisem/digisem
filetransfer/ftps.php
PHP
gpl-3.0
677
/* Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments Copyright (C) ITsysCOM GmbH 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 3 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 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 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, see <http://www.gnu.org/licenses/> */ package dispatchers import ( "testing" "time" "github.com/cgrates/cgrates/config" "github.com/cgrates/cgrates/utils" "github.com/cgrates/ltcache" ) func TestDspCacheSv1PingError(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) CGREvent := &utils.CGREvent{ Tenant: "tenant", ID: "", Time: &time.Time{}, Event: nil, APIOpts: nil, } var reply *string result := dspSrv.CacheSv1Ping(CGREvent, reply) expected := "DISPATCHER_ERROR:NO_DATABASE_CONNECTION" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1PingErrorArgs(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) var reply *string result := dspSrv.CacheSv1Ping(nil, reply) expected := "DISPATCHER_ERROR:NO_DATABASE_CONNECTION" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1PingErrorAttributeSConns(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) cgrCfg.DispatcherSCfg().AttributeSConns = []string{"test"} CGREvent := &utils.CGREvent{ Tenant: "tenant", ID: "", Time: &time.Time{}, Event: nil, APIOpts: nil, } var reply *string result := dspSrv.CacheSv1Ping(CGREvent, reply) expected := "MANDATORY_IE_MISSING: [ApiKey]" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1GetItemIDsError(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) cgrCfg.DispatcherSCfg().AttributeSConns = []string{"test"} CGREvent := &utils.ArgsGetCacheItemIDsWithAPIOpts{} var reply *[]string result := dspSrv.CacheSv1GetItemIDs(CGREvent, reply) expected := "MANDATORY_IE_MISSING: [ApiKey]" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1GetItemIDsErrorArgsNil(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) CGREvent := &utils.ArgsGetCacheItemIDsWithAPIOpts{ Tenant: "tenant", } var reply *[]string result := dspSrv.CacheSv1GetItemIDs(CGREvent, reply) expected := "DISPATCHER_ERROR:NO_DATABASE_CONNECTION" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1HasItemError(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) cgrCfg.DispatcherSCfg().AttributeSConns = []string{"test"} CGREvent := &utils.ArgsGetCacheItemWithAPIOpts{} var reply *bool result := dspSrv.CacheSv1HasItem(CGREvent, reply) expected := "MANDATORY_IE_MISSING: [ApiKey]" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1HasItemErrorArgsNil(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) CGREvent := &utils.ArgsGetCacheItemWithAPIOpts{ Tenant: "tenant", } var reply *bool result := dspSrv.CacheSv1HasItem(CGREvent, reply) expected := "DISPATCHER_ERROR:NO_DATABASE_CONNECTION" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1GetItemExpiryTimeCacheSv1GetItemExpiryTimeError(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) cgrCfg.DispatcherSCfg().AttributeSConns = []string{"test"} CGREvent := &utils.ArgsGetCacheItemWithAPIOpts{} var reply *time.Time result := dspSrv.CacheSv1GetItemExpiryTime(CGREvent, reply) expected := "MANDATORY_IE_MISSING: [ApiKey]" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1GetItemExpiryTimeCacheSv1GetItemExpiryTimeErrorArgsNil(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) CGREvent := &utils.ArgsGetCacheItemWithAPIOpts{ Tenant: "tenant", } var reply *time.Time result := dspSrv.CacheSv1GetItemExpiryTime(CGREvent, reply) expected := "DISPATCHER_ERROR:NO_DATABASE_CONNECTION" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1RemoveItemError(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) cgrCfg.DispatcherSCfg().AttributeSConns = []string{"test"} CGREvent := &utils.ArgsGetCacheItemWithAPIOpts{} var reply *string result := dspSrv.CacheSv1RemoveItem(CGREvent, reply) expected := "MANDATORY_IE_MISSING: [ApiKey]" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1RemoveItemArgsNil(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) CGREvent := &utils.ArgsGetCacheItemWithAPIOpts{ Tenant: "tenant", } var reply *string result := dspSrv.CacheSv1RemoveItem(CGREvent, reply) expected := "DISPATCHER_ERROR:NO_DATABASE_CONNECTION" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1RemoveItemsError(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) cgrCfg.DispatcherSCfg().AttributeSConns = []string{"test"} CGREvent := &utils.AttrReloadCacheWithAPIOpts{} var reply *string result := dspSrv.CacheSv1RemoveItems(CGREvent, reply) expected := "MANDATORY_IE_MISSING: [ApiKey]" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1RemoveItemsArgsNil(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) CGREvent := &utils.AttrReloadCacheWithAPIOpts{ Tenant: "tenant", } var reply *string result := dspSrv.CacheSv1RemoveItems(CGREvent, reply) expected := "DISPATCHER_ERROR:NO_DATABASE_CONNECTION" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1ClearError(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) cgrCfg.DispatcherSCfg().AttributeSConns = []string{"test"} CGREvent := &utils.AttrCacheIDsWithAPIOpts{} var reply *string result := dspSrv.CacheSv1Clear(CGREvent, reply) expected := "MANDATORY_IE_MISSING: [ApiKey]" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1ClearArgsNil(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) CGREvent := &utils.AttrCacheIDsWithAPIOpts{ Tenant: "tenant", } var reply *string result := dspSrv.CacheSv1Clear(CGREvent, reply) expected := "DISPATCHER_ERROR:NO_DATABASE_CONNECTION" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1GetCacheStatsError(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) cgrCfg.DispatcherSCfg().AttributeSConns = []string{"test"} CGREvent := &utils.AttrCacheIDsWithAPIOpts{} var reply *map[string]*ltcache.CacheStats result := dspSrv.CacheSv1GetCacheStats(CGREvent, reply) expected := "MANDATORY_IE_MISSING: [ApiKey]" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1GetCacheStatsArgsNil(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) CGREvent := &utils.AttrCacheIDsWithAPIOpts{ Tenant: "tenant", } var reply *map[string]*ltcache.CacheStats result := dspSrv.CacheSv1GetCacheStats(CGREvent, reply) expected := "DISPATCHER_ERROR:NO_DATABASE_CONNECTION" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1PrecacheStatusError(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) cgrCfg.DispatcherSCfg().AttributeSConns = []string{"test"} CGREvent := &utils.AttrCacheIDsWithAPIOpts{} var reply *map[string]string result := dspSrv.CacheSv1PrecacheStatus(CGREvent, reply) expected := "MANDATORY_IE_MISSING: [ApiKey]" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1PrecacheStatusArgsNil(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) CGREvent := &utils.AttrCacheIDsWithAPIOpts{ Tenant: "tenant", } var reply *map[string]string result := dspSrv.CacheSv1PrecacheStatus(CGREvent, reply) expected := "DISPATCHER_ERROR:NO_DATABASE_CONNECTION" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1HasGroupError(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) cgrCfg.DispatcherSCfg().AttributeSConns = []string{"test"} CGREvent := &utils.ArgsGetGroupWithAPIOpts{} var reply *bool result := dspSrv.CacheSv1HasGroup(CGREvent, reply) expected := "MANDATORY_IE_MISSING: [ApiKey]" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1HasGroupArgsNil(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) CGREvent := &utils.ArgsGetGroupWithAPIOpts{ Tenant: "tenant", } var reply *bool result := dspSrv.CacheSv1HasGroup(CGREvent, reply) expected := "DISPATCHER_ERROR:NO_DATABASE_CONNECTION" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1GetGroupItemIDsError(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) cgrCfg.DispatcherSCfg().AttributeSConns = []string{"test"} CGREvent := &utils.ArgsGetGroupWithAPIOpts{} var reply *[]string result := dspSrv.CacheSv1GetGroupItemIDs(CGREvent, reply) expected := "MANDATORY_IE_MISSING: [ApiKey]" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1GetGroupItemIDsArgsNil(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) CGREvent := &utils.ArgsGetGroupWithAPIOpts{ Tenant: "tenant", } var reply *[]string result := dspSrv.CacheSv1GetGroupItemIDs(CGREvent, reply) expected := "DISPATCHER_ERROR:NO_DATABASE_CONNECTION" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1RemoveGroupError(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) cgrCfg.DispatcherSCfg().AttributeSConns = []string{"test"} CGREvent := &utils.ArgsGetGroupWithAPIOpts{} var reply *string result := dspSrv.CacheSv1RemoveGroup(CGREvent, reply) expected := "MANDATORY_IE_MISSING: [ApiKey]" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1RemoveGroupArgsNil(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) CGREvent := &utils.ArgsGetGroupWithAPIOpts{ Tenant: "tenant", } var reply *string result := dspSrv.CacheSv1RemoveGroup(CGREvent, reply) expected := "DISPATCHER_ERROR:NO_DATABASE_CONNECTION" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1ReloadCacheError(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) cgrCfg.DispatcherSCfg().AttributeSConns = []string{"test"} CGREvent := &utils.AttrReloadCacheWithAPIOpts{} var reply *string result := dspSrv.CacheSv1ReloadCache(CGREvent, reply) expected := "MANDATORY_IE_MISSING: [ApiKey]" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1ReloadCacheNil(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) CGREvent := &utils.AttrReloadCacheWithAPIOpts{ Tenant: "tenant", } var reply *string result := dspSrv.CacheSv1ReloadCache(CGREvent, reply) expected := "DISPATCHER_ERROR:NO_DATABASE_CONNECTION" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1LoadCacheError(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) cgrCfg.DispatcherSCfg().AttributeSConns = []string{"test"} CGREvent := &utils.AttrReloadCacheWithAPIOpts{} var reply *string result := dspSrv.CacheSv1LoadCache(CGREvent, reply) expected := "MANDATORY_IE_MISSING: [ApiKey]" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1LoadCacheNil(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) CGREvent := &utils.AttrReloadCacheWithAPIOpts{ Tenant: "tenant", } var reply *string result := dspSrv.CacheSv1LoadCache(CGREvent, reply) expected := "DISPATCHER_ERROR:NO_DATABASE_CONNECTION" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1ReplicateRemoveError(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) cgrCfg.DispatcherSCfg().AttributeSConns = []string{"test"} CGREvent := &utils.ArgCacheReplicateRemove{} var reply *string result := dspSrv.CacheSv1ReplicateRemove(CGREvent, reply) expected := "MANDATORY_IE_MISSING: [ApiKey]" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1ReplicateRemoveNil(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) CGREvent := &utils.ArgCacheReplicateRemove{ Tenant: "tenant", } var reply *string result := dspSrv.CacheSv1ReplicateRemove(CGREvent, reply) expected := "DISPATCHER_ERROR:NO_DATABASE_CONNECTION" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1ReplicateSetError(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) cgrCfg.DispatcherSCfg().AttributeSConns = []string{"test"} CGREvent := &utils.ArgCacheReplicateSet{} var reply *string result := dspSrv.CacheSv1ReplicateSet(CGREvent, reply) expected := "MANDATORY_IE_MISSING: [ApiKey]" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } } func TestDspCacheSv1ReplicateSetNil(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() dspSrv := NewDispatcherService(nil, cgrCfg, nil, nil) CGREvent := &utils.ArgCacheReplicateSet{ Tenant: "tenant", } var reply *string result := dspSrv.CacheSv1ReplicateSet(CGREvent, reply) expected := "DISPATCHER_ERROR:NO_DATABASE_CONNECTION" if result == nil || result.Error() != expected { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", expected, result) } }
cgrates/cgrates
dispatchers/caches_test.go
GO
gpl-3.0
17,047
/************************************ * AUTHOR: Divyansh Gaba * * INSTITUTION: ASET, BIJWASAN * ************************************/ #include<bits/stdc++.h> #define fast ios_base::sync_with_stdio(0); cin.tie(0); #define F first #define S second #define PB push_back #define MP make_pair #define REP(i,a,b) for (int i = a; i <= b; i++) using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int,int> pi; int main() { fast; ll n,k; cin>>n>>k; ll a[n]; for(int i = 0;i<n;i++) cin>>a[i]; sort(a,a+n); int cov = 0; int ans = 0; for(int i = 0;i<n-1;i++) { if(a[i] <= cov) continue; for(int j = i+1;j<n;j++) { if(a[j]-a[i] > k) { cov = a[j-1]+k; ans+=1; break; } } } if(cov < a[n-1]) ans+=1; cout<<ans<<endl; return 0; }
divyanshgaba/Competitive-Coding
Hackerland Radio Transmitters/main.cpp
C++
gpl-3.0
919
package org.shikimori.library.adapters; import android.content.Context; import android.view.View; import android.view.ViewGroup; import com.nostra13.universalimageloader.core.ImageLoader; import org.shikimori.library.R; import org.shikimori.library.adapters.base.BaseListAdapter; import org.shikimori.library.adapters.holder.SettingsHolder; import org.shikimori.library.objects.ActionQuote; import org.shikimori.library.objects.one.ItemCommentsShiki; import org.shikimori.library.tool.ProjectTool; import org.shikimori.library.tool.hs; import java.util.Date; import java.util.List; /** * Created by LeshiyGS on 1.04.2015. */ public class CommentsAdapter extends BaseListAdapter<ItemCommentsShiki, SettingsHolder> implements View.OnClickListener { private View.OnClickListener clickListener; public CommentsAdapter(Context context, List<ItemCommentsShiki> list) { super(context, list, R.layout.item_shiki_comments_list, SettingsHolder.class); } String formatDate(long date, String format) { return hs.getStringDate(format, new Date(date)); } @Override public void setListeners(SettingsHolder holder) { super.setListeners(holder); if (clickListener != null) holder.ivSettings.setOnClickListener(clickListener); holder.ivPoster.setOnClickListener(this); } @Override public SettingsHolder getViewHolder(View v) { SettingsHolder hol = super.getViewHolder(v); hol.ivSettings = find(v, R.id.icSettings); return hol; } public void setOnSettingsListener(View.OnClickListener clickListener) { this.clickListener = clickListener; } @Override public void setValues(SettingsHolder holder, ItemCommentsShiki item, int position) { holder.tvName.setText(item.nickname); Date date = hs.getDateFromString("yyyy-MM-dd'T'HH:mm:ss.SSSZ", item.created_at); String sdate = formatDate(date.getTime(), "dd MMMM yyyy HH:mm"); holder.tvDate.setText(sdate); // HtmlText text = new HtmlText(getContext(), false); // text.setText(item.html_body, holder.tvText); holder.llBodyHtml.removeAllViews(); holder.llBodyHtml.setTag(R.id.icQuote, new ActionQuote(item.user_id, item.nickname, item.id)); // initDescription(item, holder.llBodyHtml); if (item.parsedContent.getParent() != null) ((ViewGroup) item.parsedContent.getParent()).removeAllViews(); holder.llBodyHtml.addView(item.parsedContent); holder.ivSettings.setTag(position); // очищаем картинку перед загрузкой чтобы она при прокрутке не мигала holder.ivPoster.setImageDrawable(null); holder.ivPoster.setTag(position); ImageLoader.getInstance().displayImage(item.image_x160, holder.ivPoster); } @Override public void onClick(View v) { // this is user if (v.getId() == R.id.ivPoster) { ItemCommentsShiki item = getItem((int) v.getTag()); ProjectTool.goToUser(getContext(), item.user_id); } } public ItemCommentsShiki getItemById(String id){ for (int i = 0; i < getCount(); i++) { ItemCommentsShiki item = getItem(i); if(item.id.equals(id)) return item; } return null; } }
LeshiyGS/shikimori
library/src/main/java/org/shikimori/library/adapters/CommentsAdapter.java
Java
gpl-3.0
3,387
#include <XBeeAtCmd.hpp> #include <iostream> #include <stdlib.h> #include <XBeeDebug.hpp> XBeeAtCmd::XBeeAtCmd(){ _frameId = XBEE_DEFAULT_FRAME_ID; _atCmd = XBEE_DEFAULT_AT_CMD; _paramValue = new vector<uint8_t>(); } vector<uint8_t> XBeeAtCmd::getParamValue(){ return *(_paramValue); } unsigned short XBeeAtCmd::length(){ //TODO: VERIFIER, C'EST PAS BIEN //On soustrait parce que le champ "length" de ce type de frame //ne prend en compte que la trame AT return (3+_paramValue->size());//-XBEE_MIN_FRAME_LENGTH); } vector<uint8_t> XBeeAtCmd::toBytes(){ vector<uint8_t> res; res.push_back(_frameId); int8_t i; for(i=1;i>=0;i--) res.push_back((_atCmd & (0xFF << i*8)) >> i*8); res.insert(res.end(),_paramValue->begin(),_paramValue->end()); return res; } bool XBeeAtCmd::setFrameId(uint8_t frameId){ _frameId = frameId; return true; } uint8_t XBeeAtCmd::getFrameID(){ return _frameId; } bool XBeeAtCmd::setAtCmd(uint16_t atCmd){ _atCmd = atCmd; return true; } bool XBeeAtCmd::setParamValue(const vector<uint8_t>& paramValue){ //TODO: verifier si paramValue respect la taille définite dans la doc de zigbee //por ahi en vez de un define, hacer una estructura que ya tenga el rango valido junto con el comando? //if(paramValue.size() <= ){ if(_paramValue){ _paramValue->clear(); } else{ _paramValue = new vector<uint8_t>(); } (*_paramValue) = paramValue; return true; } bool XBeeAtCmd::setParamValue(const string& paramValue, bool set0){ //TODO: verifier si paramValue respect la taille définite dans la doc de zigbee //por ahi en vez de un define, hacer una estructura que ya tenga el rango valido junto con el comando? if(_paramValue){ _paramValue->clear(); } else{ _paramValue = new vector<uint8_t>(); } unsigned int i; for(i=0; i<paramValue.length(); i++) _paramValue->push_back(paramValue[i]); if(set0) _paramValue->push_back(0); return true; } bool XBeeAtCmd::loadFrame(const vector<uint8_t>& frame){ _frameId = frame[4]; _atCmd = 0; unsigned short i; for(i=0;i<2;i++) _atCmd += (frame[i+5] << (1-i)*8); if(_paramValue->size() != 0) _paramValue->clear(); _paramValue->insert(_paramValue->begin(),frame.begin()+7,frame.end()-1); return true; } void XBeeAtCmd::debug(){ XBeeDebug::debugHex("Frame ID : ",_frameId,1); XBeeDebug::debugMap(XBeeDebug::XBeeAtCmd,_atCmd,false); XBeeDebug::debugHex("Parameter Value : ",_paramValue); cout << endl; }
andresmanelli/XBeeAPI
src/XBeeAtCmd.cpp
C++
gpl-3.0
2,472
#pragma once #include "imgui.h" namespace bengine { inline void setup_imgui_style_green() { ImGuiStyle& style = ImGui::GetStyle(); // light style from Pacôme Danhiez (user itamago) https://github.com/ocornut/imgui/pull/511#issuecomment-175719267 style.Alpha = 1.0f; style.FrameRounding = 3.0f; style.Colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); style.Colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f); style.Colors[ImGuiCol_WindowBg] = ImVec4(0.01f, 0.10f, 0.01f, 0.94f); style.Colors[ImGuiCol_ChildWindowBg] = ImVec4(0.00f, 0.05f, 0.00f, 0.00f); style.Colors[ImGuiCol_PopupBg] = ImVec4(0.01f, 0.10f, 0.01f, 0.94f); style.Colors[ImGuiCol_Border] = ImVec4(0.00f, 0.00f, 0.00f, 0.39f); style.Colors[ImGuiCol_BorderShadow] = ImVec4(1.00f, 1.00f, 1.00f, 0.10f); style.Colors[ImGuiCol_FrameBg] = ImVec4(0.00f, 0.40f, 0.00f, 0.94f); style.Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.49f, 0.98f, 0.40f); style.Colors[ImGuiCol_FrameBgActive] = ImVec4(0.00f, 0.49f, 0.00f, 0.67f); style.Colors[ImGuiCol_TitleBg] = ImVec4(0.01f, 0.5f, 0.01f, 1.00f); style.Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.00f, 1.00f, 1.00f, 0.51f); style.Colors[ImGuiCol_TitleBgActive] = ImVec4(0.01f, 0.6f, 0.01f, 1.00f); style.Colors[ImGuiCol_MenuBarBg] = ImVec4(0.1f, 0.4f, 0.1f, 1.00f); style.Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.98f, 0.98f, 0.98f, 0.53f); style.Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.69f, 0.69f, 0.69f, 1.00f); style.Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.59f, 0.59f, 0.59f, 1.00f); style.Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.49f, 0.49f, 0.49f, 1.00f); //style.Colors[ImGuiCol_ComboBg] = ImVec4(0.86f, 0.86f, 0.86f, 0.99f); style.Colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); style.Colors[ImGuiCol_SliderGrab] = ImVec4(0.24f, 0.52f, 0.88f, 1.00f); style.Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); style.Colors[ImGuiCol_Button] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); style.Colors[ImGuiCol_ButtonHovered] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); style.Colors[ImGuiCol_ButtonActive] = ImVec4(0.06f, 0.53f, 0.98f, 1.00f); style.Colors[ImGuiCol_Header] = ImVec4(0.26f, 0.59f, 0.98f, 0.31f); style.Colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f); style.Colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); style.Colors[ImGuiCol_Column] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f); style.Colors[ImGuiCol_ColumnHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.78f); style.Colors[ImGuiCol_ColumnActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); style.Colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.50f); style.Colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); style.Colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); style.Colors[ImGuiCol_CloseButton] = ImVec4(0.59f, 0.59f, 0.59f, 0.50f); style.Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.98f, 0.39f, 0.36f, 1.00f); style.Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.98f, 0.39f, 0.36f, 1.00f); style.Colors[ImGuiCol_PlotLines] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f); style.Colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); style.Colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); style.Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); style.Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); style.Colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); } inline void setup_imgui_style_light() { ImGuiStyle& style = ImGui::GetStyle(); style.Colors[ImGuiCol_Text] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); style.Colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f); //style.Colors[ImGuiCol_TextHovered] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); //style.Colors[ImGuiCol_TextActive] = ImVec4(1.00f, 1.00f, 0.00f, 1.00f); style.Colors[ImGuiCol_WindowBg] = ImVec4(0.94f, 0.94f, 0.94f, 1.00f); style.Colors[ImGuiCol_ChildWindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); style.Colors[ImGuiCol_Border] = ImVec4(0.00f, 0.00f, 0.00f, 0.39f); style.Colors[ImGuiCol_BorderShadow] = ImVec4(1.00f, 1.00f, 1.00f, 0.10f); style.Colors[ImGuiCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); style.Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); style.Colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); style.Colors[ImGuiCol_TitleBg] = ImVec4(0.96f, 0.96f, 0.96f, 1.00f); style.Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.00f, 1.00f, 1.00f, 0.51f); style.Colors[ImGuiCol_TitleBgActive] = ImVec4(0.82f, 0.82f, 0.82f, 1.00f); style.Colors[ImGuiCol_MenuBarBg] = ImVec4(0.86f, 0.86f, 0.86f, 1.00f); style.Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.98f, 0.98f, 0.98f, 0.53f); style.Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.69f, 0.69f, 0.69f, 0.80f); style.Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.49f, 0.49f, 0.49f, 0.80f); style.Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.49f, 0.49f, 0.49f, 1.00f); //style.Colors[ImGuiCol_ComboBg] = ImVec4(0.86f, 0.86f, 0.86f, 0.99f); style.Colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); style.Colors[ImGuiCol_SliderGrab] = ImVec4(0.26f, 0.59f, 0.98f, 0.78f); style.Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); style.Colors[ImGuiCol_Button] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); style.Colors[ImGuiCol_ButtonHovered] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); style.Colors[ImGuiCol_ButtonActive] = ImVec4(0.06f, 0.53f, 0.98f, 1.00f); style.Colors[ImGuiCol_Header] = ImVec4(0.26f, 0.59f, 0.98f, 0.31f); style.Colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f); style.Colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); style.Colors[ImGuiCol_Column] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f); style.Colors[ImGuiCol_ColumnHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.78f); style.Colors[ImGuiCol_ColumnActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); style.Colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.00f); style.Colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); style.Colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); style.Colors[ImGuiCol_CloseButton] = ImVec4(0.59f, 0.59f, 0.59f, 0.50f); style.Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.98f, 0.39f, 0.36f, 1.00f); style.Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.98f, 0.39f, 0.36f, 1.00f); style.Colors[ImGuiCol_PlotLines] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f); style.Colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); style.Colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); style.Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); style.Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); //style.Colors[ImGuiCol_TooltipBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.94f); style.Colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); } inline void setup_imgui_style() { //setup_imgui_style_green(); ImGui::StyleColorsDark(); } }
thebracket/bgame
src/bengine/imgui_style.hpp
C++
gpl-3.0
7,197
<?php namespace botwebapi\resources\api\workspaces\directoryBasedWorkspaces; use botwebapi\resources as resources; use botwebapi as botwebapi; class DirectoryBasedWorkspaces extends resources\BotWebApiResource { public function __construct($resource_uri, $parent_resource) { parent::__construct($resource_uri, '1.0', 'https://github.com/kipr/botwebapi', $parent_resource); } public function get() { $links = new botwebapi\LinksObject(); $links->addLink($this->getResourceUri()); if($this->getParentUri()) { $links->addLink($this->getParentUri(), array('rel' => 'parent')); } // we need a DB for this... return new botwebapi\JsonHttpResponse(200, array('about' => new botwebapi\AboutObject($this), 'links' => $links)); } public function post($content) { $json_data = json_decode($content, true); if(!$json_data) { return new botwebapi\JsonHttpResponse(400, 'Could not parse the content ('.json_last_error().')'); } if(!array_key_exists('path', $json_data)) { return new botwebapi\JsonHttpResponse(422, 'Parameter "path" required'); } $path = $json_data["path"]; if(!file_exists($path)) { return new botwebapi\JsonHttpResponse(404, $path.' does not exist'); } $enc_path = base64_encode($path); $location = botwebapi\LinksObject::buildUri($this->getResourceUri().'/'.urlencode($enc_path)); return new botwebapi\HttpResponse(201, '', array('Location' => $location)); } public function put($content) { return new botwebapi\JsonHttpResponse(405, $_SERVER['REQUEST_METHOD'].' is not supported'); } public function delete($content) { return new botwebapi\JsonHttpResponse(405, $_SERVER['REQUEST_METHOD'].' is not supported'); } protected function getChild($resource_name) { try { $workspace_path = base64_decode(urldecode($resource_name)); $resource_class_name = __NAMESPACE__.'\\Workspace'; return new $resource_class_name($workspace_path, $this->getResourceUri().'/'.$resource_name, $this); } catch(\Exception $e) { return NULL; } } } ?>
kipr/botwebapi
botwebapi/classes/botwebapi/resources/api/workspaces/directoryBasedWorkspaces/DirectoryBasedWorkspaces.php
PHP
gpl-3.0
2,461
# -*- coding: utf-8 -*- """ Created on Sun Sep 17 22:06:52 2017 Based on: print_MODFLOW_inputs_res_NWT.m @author: gcng """ # print_MODFLOW_inputs import numpy as np import MODFLOW_NWT_lib as mf # functions to write individual MODFLOW files import os # os functions from ConfigParser import SafeConfigParser parser = SafeConfigParser() parser.read('settings.ini') LOCAL_DIR = parser.get('settings', 'local_dir') GSFLOW_DIR = LOCAL_DIR + "/GSFLOW" # - directories sw_2005_NWT = 2 # 1 for MODFLOW-2005; 2 for MODFLOW-NWT algorithm (both can be # carried out with MODFLOW-NWT code) fl_BoundConstH = 0 # 1 for const head at high elev boundary, needed for numerical # convergence for AGU2016 poster. Maybe resolved with MODFLOW-NWT? if sw_2005_NWT == 1: # MODFLOW input files GSFLOW_indir = GSFLOW_DIR + '/inputs/MODFLOW_2005/' # MODFLOW output files GSFLOW_outdir = GSFLOW_DIR + '/outputs/MODFLOW_2005/' elif sw_2005_NWT == 2: # MODFLOW input files GSFLOW_indir = GSFLOW_DIR + '/inputs/MODFLOW_NWT/' # MODFLOW output files GSFLOW_outdir = GSFLOW_DIR + '/outputs/MODFLOW_NWT/' infile_pre = 'test2lay_py'; NLAY = 2; DZ = [100, 50] # [NLAYx1] [m] ***testing # DZ = [350, 100] # [NLAYx1] [m] ***testing # length of transient stress period (follows 1-day steady-state period) [d] # perlen_tr = 365; # [d], ok if too long # perlen_tr = 365*5 + ceil(365*5/4); # [d], includes leap years; ok if too long (I think, but maybe run time is longer?) perlen_tr = 365*30 + np.ceil(365*30/4) # [d], includes leap years; ok if too long (I think, but maybe run time is longer?) GIS_indir = GSFLOW_DIR + '/DataToReadIn/GIS/'; # use restart file as initial cond (empty string to not use restart file) fil_res_in = '' # empty string to not use restart file #fil_res_in = '/home/gcng/workspace/Pfil_res_inrojectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/test2lay_melt_30yr.out' % empty string to not use restart file # for various files: ba6, dis, uzf, lpf surfz_fil = GIS_indir + 'topo.asc' # surfz_fil = GIS_indir + 'SRTM_new_20161208.asc' # for various files: ba6, uzf mask_fil = GIS_indir + 'basinmask_dischargept.asc' # for sfr reach_fil = GIS_indir + 'reach_data.txt' segment_fil_all = [GIS_indir + 'segment_data_4A_INFORMATION_Man.csv', GIS_indir + 'segment_data_4B_UPSTREAM_Man.csv', GIS_indir + 'segment_data_4C_DOWNSTREAM_Man.csv'] # create MODFLOW input directory if it does not exist: if not os.path.isdir(GSFLOW_indir): os.makedirs(GSFLOW_indir) # while we're at it, create MODFLOW output file if it does not exist: if not os.path.isdir(GSFLOW_outdir): os.makedirs(GSFLOW_outdir) ## mf.write_dis_MOD2_f(GSFLOW_indir, infile_pre, surfz_fil, NLAY, DZ, perlen_tr); mf.write_ba6_MOD3_2(GSFLOW_indir, infile_pre, mask_fil, fl_BoundConstH); # list this below write_dis_MOD2_f # flow algorithm if sw_2005_NWT == 1: mf.write_lpf_MOD2_f2_2(GSFLOW_indir, infile_pre, surfz_fil, NLAY); elif sw_2005_NWT == 2: # MODFLOW-NWT files mf.write_upw_MOD2_f2_2(GSFLOW_indir, infile_pre, surfz_fil, NLAY); mf.NWT_write_file(GSFLOW_indir, infile_pre); # unsat zone and streamflow input files mf.make_uzf3_f_2(GSFLOW_indir, infile_pre, surfz_fil, mask_fil); mf.make_sfr2_f_Mannings(GSFLOW_indir, infile_pre, reach_fil, segment_fil_all); # list this below write_dis_MOD2_f # Write PCG file (only used for MODFLOW-2005, but this function also creates OC file) mf.write_OC_PCG_MOD_f(GSFLOW_indir, infile_pre, perlen_tr); # Write namefile mf.write_nam_MOD_f2_NWT(GSFLOW_indir, GSFLOW_outdir, infile_pre, fil_res_in, sw_2005_NWT);
UMN-Hydro/GSFLOW_pre-processor
python_scripts/MODFLOW_scripts/print_MODFLOW_inputs_res_NWT.py
Python
gpl-3.0
3,667
package dualcraft.org.server.classic.cmd.impl; /*License ==================== Copyright (c) 2010-2012 Daniel Vidmar We use a modified GNU gpl v 3 license for this. GNU gpl v 3 is included in License.txt The modified part of the license is some additions which state the following: "Redistributions of this project in source or binary must give credit to UnXoft Interactive and DualCraft" "Redistributions of this project in source or binary must modify at least 300 lines of code in order to release an initial version. This will require documentation or proof of the 300 modified lines of code." "Our developers reserve the right to add any additions made to a redistribution of DualCraft into the main project" "Our developers reserver the right if they suspect a closed source software using any code from our project to request to overview the source code of the suspected software. If the owner of the suspected software refuses to allow a devloper to overview the code then we shall/are granted the right to persue legal action against him/her"*/ import dualcraft.org.server.classic.cmd.Command; import dualcraft.org.server.classic.cmd.CommandParameters; import dualcraft.org.server.classic.model.Player; /** * Official /summon command * */ public class SummonCommand extends Command { /** * The instance of this command. */ private static final SummonCommand INSTANCE = new SummonCommand(); /** * Gets the singleton instance of this command. * @return The singleton instance of this command. */ public static SummonCommand getCommand() { return INSTANCE; } public String name() { return "summon"; } /** * Default private constructor. */ private SummonCommand() { /* empty */ } public void execute(Player player, CommandParameters params) { // Player using command is OP? if (params.getArgumentCount() == 1) { for (Player other : player.getWorld().getPlayerList().getPlayers()) { if (other.getName().toLowerCase().equals(params.getStringArgument(0).toLowerCase())) { //TODO: Make the player face each other? other.teleport(player.getPosition(), player.getRotation()); return; } } // Player not found player.getActionSender().sendChatMessage(params.getStringArgument(0) + " was not found"); return; } else { player.getActionSender().sendChatMessage("Wrong number of arguments"); } player.getActionSender().sendChatMessage("/summon <name>"); } }
MinedroidFTW/DualCraft
org/server/classic/cmd/impl/SummonCommand.java
Java
gpl-3.0
2,455
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DemoHubManager.cs" company="Exit Games GmbH"> // Part of: Photon Unity Demos // </copyright> // <summary> // Used as starting point to let developer choose amongst all demos available. // </summary> // <author>developer@exitgames.com</author> // -------------------------------------------------------------------------------------------------------------------- using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine.EventSystems; using UnityEngine.SceneManagement; namespace ExitGames.Demos { public class DemoHubManager : MonoBehaviour { public Text TitleText; public Text DescriptionText; public GameObject OpenSceneButton; public GameObject OpenWebLinkButton; string MainDemoWebLink = "http://bit.ly/2f8OFu8"; struct DemoData { public string Title; public string Description; public string Scene; public string WebLink; } Dictionary<string,DemoData> _data = new Dictionary<string, DemoData>(); string currentSelection; // Use this for initialization void Awake () { OpenSceneButton.SetActive(false); OpenWebLinkButton.SetActive(false); // Setup data _data.Add( "DemoBoxes", new DemoData() { Title = "Demo Boxes", Description = "Uses ConnectAndJoinRandom script.\n" + "(joins a random room or creates one)\n" + "\n" + "Instantiates simple prefabs.\n" + "Synchronizes positions without smoothing.\n" + "Shows that RPCs target a specific object.", Scene = "DemoBoxes-Scene" } ); _data.Add( "DemoWorker", new DemoData() { Title = "Demo Worker", Description = "Joins the default lobby and shows existing rooms.\n" + "Lets you create or join a room.\n" + "Instantiates an animated character.\n" + "Synchronizes position and animation state of character with smoothing.\n" + "Implements simple in-room Chat via RPC calls.", Scene = "DemoWorker-Scene" } ); _data.Add( "MovementSmoothing", new DemoData() { Title = "Movement Smoothing", Description = "Uses ConnectAndJoinRandom script.\n" + "Shows several basic ways to synchronize positions between controlling client and remote ones.\n" + "The TransformView is a good default to use.", Scene = "DemoSynchronization-Scene" } ); _data.Add( "BasicTutorial", new DemoData() { Title = "Basic Tutorial", Description = "All custom code for connection, player and scene management.\n" + "Auto synchronization of room levels.\n" + "Uses PhotonAnimatoView for Animator synch.\n" + "New Unity UI all around, for Menus and player health HUD.\n" + "Full step by step tutorial available online.", Scene = "PunBasics-Launcher" , WebLink = "http://j.mp/2dibZIM" } ); _data.Add( "OwnershipTransfer", new DemoData() { Title = "Ownership Transfer", Description = "Shows how to transfer the ownership of a PhotonView.\n" + "The owner will send position updates of the GameObject.\n" + "Transfer can be edited per PhotonView and set to Fixed (no transfer), Request (owner has to agree) or Takeover (owner can't object).", Scene = "DemoChangeOwner-Scene" } ); _data.Add( "PickupTeamsScores", new DemoData() { Title = "Pickup, Teams, Scores", Description = "Uses ConnectAndJoinRandom script.\n" + "Implements item pickup with RPCs.\n" + "Uses Custom Properties for Teams.\n" + "Counts score per player and team.\n" + "Uses PhotonPlayer extension methods for easy Custom Property access.", Scene = "DemoPickup-Scene" } ); _data.Add( "Chat", new DemoData() { Title = "Chat", Description = "Uses the Chat API (now part of PUN).\n" + "Simple UI.\n" + "You can enter any User ID.\n" + "Automatically subscribes some channels.\n" + "Allows simple commands via text.\n" + "\n" + "Requires configuration of Chat App ID in scene.", Scene = "DemoChat-Scene" } ); _data.Add( "RPGMovement", new DemoData() { Title = "RPG Movement", Description = "Demonstrates how to use the PhotonTransformView component to synchronize position updates smoothly using inter- and extrapolation.\n" + "\n" + "This demo also shows how to setup a Mecanim Animator to update animations automatically based on received position updates (without sending explicit animation updates).", Scene = "DemoRPGMovement-Scene" } ); _data.Add( "MecanimAnimations", new DemoData() { Title = "Mecanim Animations", Description = "This demo shows how to use the PhotonAnimatorView component to easily synchronize Mecanim animations.\n" + "\n" + "It also demonstrates another feature of the PhotonTransformView component which gives you more control how position updates are inter-/extrapolated by telling the component how fast the object moves and turns using SetSynchronizedValues().", Scene = "DemoMecanim-Scene" } ); _data.Add( "2DGame", new DemoData() { Title = "2D Game Demo", Description = "Synchronizes animations, positions and physics in a 2D scene.", Scene = "Demo2DJumpAndRunWithPhysics-Scene" } ); _data.Add( "FriendsAndAuth", new DemoData() { Title = "Friends & Authentication", Description = "Shows connect with or without (server-side) authentication.\n" + "\n" + "Authentication requires minor server-side setup (in Dashboard).\n" + "\n" + "Once connected, you can find (made up) friends.\nJoin a room just to see how that gets visible in friends list.", Scene = "DemoFriends-Scene" } ); _data.Add( "TurnBasedGame", new DemoData() { Title = "'Rock Paper Scissor' Turn Based Game", Description = "Demonstrate TurnBased Game Mechanics using PUN.\n" + "\n" + "It makes use of the TurnBasedManager Utility Script", Scene = "DemoRPS-Scene" } ); _data.Add( "MarcoPoloTutorial", new DemoData() { Title = "Marco Polo Tutorial", Description = "Final result you could get when you do the Marco Polo Tutorial.\n" + "Slightly modified to be more compatible with this package.", Scene = "MarcoPolo-Scene", WebLink = "http://tinyurl.com/nmylf44" } ); } public void SelectDemo(string Reference) { currentSelection = Reference; TitleText.text = _data[currentSelection].Title; DescriptionText.text = _data[currentSelection].Description; OpenSceneButton.SetActive(!string.IsNullOrEmpty(_data[currentSelection].Scene)); OpenWebLinkButton.SetActive(!string.IsNullOrEmpty(_data[currentSelection].WebLink)); } public void OpenScene() { if (string.IsNullOrEmpty(currentSelection)) { Debug.LogError("Bad setup, a CurrentSelection is expected at this point"); return; } SceneManager.LoadScene(_data[currentSelection].Scene); } public void OpenWebLink() { if (string.IsNullOrEmpty(currentSelection)) { Debug.LogError("Bad setup, a CurrentSelection is expected at this point"); return; } Application.OpenURL(_data[currentSelection].WebLink); } public void OpenMainWebLink() { Application.OpenURL(MainDemoWebLink); } } }
KonovalovAnton/CoOpMaze
Assets/Tools/Photon Unity Networking/Demos/DemoHub/Scripts/DemoHubManager.cs
C#
gpl-3.0
7,549
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2008 Doug Hellmann All rights reserved. # """ """ __version__ = "$Id$" #end_pymotw_header import EasyDialogs valid_responses = { 1:'yes', 0:'no', -1:'cancel', } response = EasyDialogs.AskYesNoCancel('Select an option') print 'You selected:', valid_responses[response]
qilicun/python
python2/PyMOTW-1.132/PyMOTW/EasyDialogs/EasyDialogs_AskYesNoCancel.py
Python
gpl-3.0
390
/* * Copyright (C) 2011 Carl Green * * 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 3 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 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * 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, see <http://www.gnu.org/licenses/>. */ package info.carlwithak.mpxg2.printing; import info.carlwithak.mpxg2.model.Program; import info.carlwithak.mpxg2.model.RoutingData; import info.carlwithak.mpxg2.model.effects.algorithms.Ambience; import info.carlwithak.mpxg2.model.effects.algorithms.AutoPan; import info.carlwithak.mpxg2.model.effects.algorithms.Chamber; import info.carlwithak.mpxg2.model.effects.algorithms.ChorusAlgorithm; import info.carlwithak.mpxg2.model.effects.algorithms.ChorusPedalVol; import info.carlwithak.mpxg2.model.effects.algorithms.DelayDual; import info.carlwithak.mpxg2.model.effects.algorithms.DetuneDual; import info.carlwithak.mpxg2.model.effects.algorithms.EchoDual; import info.carlwithak.mpxg2.model.effects.algorithms.EqPedalVol; import info.carlwithak.mpxg2.model.effects.algorithms.Overdrive; import info.carlwithak.mpxg2.model.effects.algorithms.Panner; import info.carlwithak.mpxg2.model.effects.algorithms.PedalWah1; import info.carlwithak.mpxg2.model.effects.algorithms.Plate; import info.carlwithak.mpxg2.model.effects.algorithms.Screamer; import info.carlwithak.mpxg2.model.effects.algorithms.ShiftDual; import info.carlwithak.mpxg2.model.effects.algorithms.Tone; import info.carlwithak.mpxg2.model.effects.algorithms.UniVybe; import info.carlwithak.mpxg2.model.effects.algorithms.VolumeDual; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Tests for RoutingPrinter. * * @author Carl Green */ public class RoutingPrinterTest { /** * Test printing a textual representation of the routing. * * G2 Blue is a simple all along the upper route routing. * * @throws PrintException if an error is encountered while printing */ @Test public void testPrintG2Blue() throws PrintException { Program program = new Program(); RoutingData routing = new RoutingData(); routing.setEffectId(8); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting0(routing); routing = new RoutingData(); routing.setEffectId(0); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting1(routing); routing = new RoutingData(); routing.setEffectId(1); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting2(routing); routing = new RoutingData(); routing.setEffectId(6); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting3(routing); routing = new RoutingData(); routing.setEffectId(2); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting4(routing); routing = new RoutingData(); routing.setEffectId(3); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting5(routing); routing = new RoutingData(); routing.setEffectId(4); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting6(routing); routing = new RoutingData(); routing.setEffectId(5); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting7(routing); routing = new RoutingData(); routing.setEffectId(7); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting8(routing); program.setEffect1(new UniVybe()); program.setEffect2(new PedalWah1()); program.setChorus(new ChorusPedalVol()); program.setDelay(new EchoDual()); program.setReverb(new Ambience()); program.setGain(new Screamer()); String expected = "I=1=2=G=C=D=R=e=O"; assertEquals(expected, RoutingPrinter.print(program)); } /** * Test printing a textual representation of the routing. * * Guitar Solo splits into the lower route. * * @throws PrintException if an error is encountered while printing */ @Test public void testPrintGuitarSolo() throws PrintException { Program program = new Program(); RoutingData routing = new RoutingData(); routing.setEffectId(8); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting0(routing); routing = new RoutingData(); routing.setEffectId(5); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting1(routing); routing = new RoutingData(); routing.setEffectId(2); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting2(routing); routing = new RoutingData(); routing.setEffectId(6); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting3(routing); routing = new RoutingData(); routing.setEffectId(0); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(3); routing.setPathType(0); program.setRouting4(routing); routing = new RoutingData(); routing.setEffectId(3); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(1); routing.setPathType(1); program.setRouting5(routing); routing = new RoutingData(); routing.setEffectId(4); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(1); program.setRouting6(routing); routing = new RoutingData(); routing.setEffectId(1); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(2); routing.setPathType(1); program.setRouting7(routing); routing = new RoutingData(); routing.setEffectId(7); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting8(routing); program.setEffect1(new DetuneDual()); program.setEffect2(new Panner()); program.setDelay(new EchoDual()); program.setReverb(new Plate()); program.setGain(new Screamer()); String expected = "I=e=c=G=1===R=2=O\n" + " |=D===|"; String actual = RoutingPrinter.print(program); assertEquals(expected, actual); } /** * Test printing a textual representation of the routing. * * Cordovox splits and has mono and stereo paths. * * @throws PrintException if an error is encountered while printing */ @Test public void testPrintCordovox() throws PrintException { Program program = new Program(); RoutingData routing = new RoutingData(); routing.setEffectId(8); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting0(routing); routing = new RoutingData(); routing.setEffectId(5); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting1(routing); routing = new RoutingData(); routing.setEffectId(6); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting2(routing); routing = new RoutingData(); routing.setEffectId(2); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(3); routing.setPathType(0); program.setRouting3(routing); routing = new RoutingData(); routing.setEffectId(0); routing.setUpperInputConnection(0); routing.setLowerInputConnection(4); routing.setRouting(1); routing.setPathType(1); program.setRouting4(routing); routing = new RoutingData(); routing.setEffectId(1); routing.setUpperInputConnection(3); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(1); program.setRouting5(routing); routing = new RoutingData(); routing.setEffectId(3); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(1); program.setRouting6(routing); routing = new RoutingData(); routing.setEffectId(4); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(1); program.setRouting7(routing); routing = new RoutingData(); routing.setEffectId(7); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(2); routing.setPathType(1); program.setRouting8(routing); program.setEffect1(new AutoPan()); program.setEffect2(new AutoPan()); program.setChorus(new ChorusAlgorithm()); program.setDelay(new EchoDual()); program.setReverb(new Chamber()); program.setEq(new EqPedalVol()); program.setGain(new Tone()); String expected = "I=E=G=C--\\2=D=R=O\n" + " |/1=======|"; String actual = RoutingPrinter.print(program); assertEquals(expected, actual); } /** * Test printing a textual representation of the routing. * * PowerChords has "lower case numbers". * * @throws PrintException if an error is encountered while printing */ @Test public void testPrintPowerChords() throws PrintException { Program program = new Program(); RoutingData routing = new RoutingData(); routing.setEffectId(8); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting0(routing); routing = new RoutingData(); routing.setEffectId(1); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting1(routing); routing = new RoutingData(); routing.setEffectId(6); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting2(routing); routing = new RoutingData(); routing.setEffectId(5); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting3(routing); routing = new RoutingData(); routing.setEffectId(0); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting4(routing); routing = new RoutingData(); routing.setEffectId(2); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting5(routing); routing = new RoutingData(); routing.setEffectId(3); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting6(routing); routing = new RoutingData(); routing.setEffectId(4); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting7(routing); routing = new RoutingData(); routing.setEffectId(7); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting8(routing); program.setEffect1(new ShiftDual()); program.setDelay(new DelayDual()); program.setReverb(new Chamber()); program.setGain(new Overdrive()); String expected = "I=₂=G=e=1=c=D=R=O"; assertEquals(expected, RoutingPrinter.print(program)); } /** * Test printing a textual representation of the routing. * * Pitch Cascade has inactive effects on the lower routing. * * @throws PrintException if an error is encountered while printing */ @Test public void testPrintPitchCascase() throws PrintException { Program program = new Program(); RoutingData routing = new RoutingData(); routing.setEffectId(8); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting0(routing); routing = new RoutingData(); routing.setEffectId(6); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting1(routing); routing = new RoutingData(); routing.setEffectId(1); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(3); routing.setPathType(0); program.setRouting2(routing); routing = new RoutingData(); routing.setEffectId(5); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(1); routing.setPathType(1); program.setRouting3(routing); routing = new RoutingData(); routing.setEffectId(3); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(1); routing.setPathType(1); program.setRouting4(routing); routing = new RoutingData(); routing.setEffectId(0); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(1); routing.setPathType(1); program.setRouting5(routing); routing = new RoutingData(); routing.setEffectId(2); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(1); routing.setPathType(1); program.setRouting6(routing); routing = new RoutingData(); routing.setEffectId(4); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(2); routing.setPathType(1); program.setRouting7(routing); routing = new RoutingData(); routing.setEffectId(7); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting8(routing); program.setEffect1(new ShiftDual()); program.setEffect2(new VolumeDual()); program.setDelay(new DelayDual()); program.setReverb(new Ambience()); program.setEq(new EqPedalVol()); program.setGain(new Overdrive()); String expected = "I=G=2=========R=O\n" + " |=E=D=1=c=|"; assertEquals(expected, RoutingPrinter.print(program)); } /** * Test printing an invalid routing where it splits into two routes but * never combines again. * * @throws PrintException if an error is encountered while printing */ @Test(expected = PrintException.class) public void testInvalidRouting() throws PrintException { Program program = new Program(); RoutingData routing = new RoutingData(); routing.setEffectId(8); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting0(routing); routing = new RoutingData(); routing.setEffectId(5); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting1(routing); routing = new RoutingData(); routing.setEffectId(2); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting2(routing); routing = new RoutingData(); routing.setEffectId(6); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(0); routing.setPathType(0); program.setRouting3(routing); routing = new RoutingData(); routing.setEffectId(0); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(3); routing.setPathType(0); program.setRouting4(routing); routing = new RoutingData(); routing.setEffectId(3); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(1); routing.setPathType(1); program.setRouting5(routing); routing = new RoutingData(); routing.setEffectId(4); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(1); routing.setPathType(1); program.setRouting6(routing); routing = new RoutingData(); routing.setEffectId(1); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(1); routing.setPathType(1); program.setRouting7(routing); routing = new RoutingData(); routing.setEffectId(7); routing.setUpperInputConnection(0); routing.setLowerInputConnection(0); routing.setRouting(1); routing.setPathType(1); program.setRouting8(routing); RoutingPrinter.print(program); } }
carlgreen/Lexicon-MPX-G2-Editor
mpxg2-cli/src/test/java/info/carlwithak/mpxg2/printing/RoutingPrinterTest.java
Java
gpl-3.0
20,290
package com.oitsjustjose.vtweaks.common.config; import net.minecraftforge.common.ForgeConfigSpec; public class ItemTweakConfig { private static final String CATEGORY_ITEM_TWEAKS = "item tweaks"; public static ForgeConfigSpec.BooleanValue ENABLE_EGG_HATCHING; public static ForgeConfigSpec.IntValue EGG_HATCING_CHANCE; public static ForgeConfigSpec.BooleanValue ENABLE_SAPLING_SELF_PLANTING; public static ForgeConfigSpec.BooleanValue ENABLE_DESPAWN_TIME_OVERRIDE; public static ForgeConfigSpec.IntValue DESPAWN_TIME_OVERRIDE; public static ForgeConfigSpec.BooleanValue ENABLE_CONCRETE_TWEAKS; public static void init(ForgeConfigSpec.Builder COMMON_BUILDER) { COMMON_BUILDER.comment("Item Tweaks").push(CATEGORY_ITEM_TWEAKS); ENABLE_EGG_HATCHING = COMMON_BUILDER.comment("Allows egg items in the world to hatch instead of despawn") .define("eggHatchingEnabled", true); EGG_HATCING_CHANCE = COMMON_BUILDER .comment("The chance (out of 100 - higher means more frequent) that the egg will turn into a chick\n" + "**DO NOT SET THIS TOO HIGH OR ELSE CHICKENS MAY INFINITELY LAG YOUR WORLD**") .defineInRange("eggHatchingChance", 1, 1, 100); ENABLE_SAPLING_SELF_PLANTING = COMMON_BUILDER .comment("Instead of de-spawning, saplings will attempt to plant themselves") .define("enableSaplingPlanting", true); ENABLE_DESPAWN_TIME_OVERRIDE = COMMON_BUILDER.comment("Allow for modifications to item despawn timers") .define("enableDespawnTimeAdjustments", false); DESPAWN_TIME_OVERRIDE = COMMON_BUILDER.comment( "Adjust Item Despawn Time (in ticks: 20 ticks in a second - default despawn delay is 6000 ticks)\n" + "-1 prevents items from despawning at all.\n" + "If other \"do x on despawn\" configs are enabled, then those items **will still despawn**") .defineInRange("despawnTimeAdjustments", 6000, -1, Integer.MAX_VALUE); ENABLE_CONCRETE_TWEAKS = COMMON_BUILDER .comment("Convert Concrete Powder to Concrete when the item is thrown into water") .define("enableConreteTweaks", true); COMMON_BUILDER.pop(); } }
oitsjustjose/V-Tweaks
src/main/java/com/oitsjustjose/vtweaks/common/config/ItemTweakConfig.java
Java
gpl-3.0
2,337
using System; using System.Globalization; using System.Threading.Tasks; using Microsoft.AspNet.Mvc.ModelBinding; namespace Yavsc { public class MyDecimalModelBinder : IModelBinder { public async Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext) { ValueProviderResult valueResult = bindingContext.ValueProvider .GetValue(bindingContext.ModelName); decimal actualValue ; try { actualValue = Decimal.Parse(valueResult.FirstValue, System.Globalization.NumberStyles.AllowDecimalPoint); return await ModelBindingResult.SuccessAsync(bindingContext.ModelName,actualValue); } catch (Exception ) { } return await ModelBindingResult.FailedAsync(bindingContext.ModelName); } } public class MyDateTimeModelBinder : IModelBinder { public async Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext) { ValueProviderResult valueResult = bindingContext.ValueProvider .GetValue(bindingContext.ModelName); DateTime actualValue ; ModelStateEntry modelState = new ModelStateEntry(); // DateTime are sent in the french format if (DateTime.TryParse(valueResult.FirstValue,new CultureInfo("fr-FR"), DateTimeStyles.AllowInnerWhite, out actualValue)) { return await ModelBindingResult.SuccessAsync(bindingContext.ModelName,actualValue); } return await ModelBindingResult.FailedAsync(bindingContext.ModelName); } } }
pazof/yavsc
src/Yavsc/CustomModelBinder.cs
C#
gpl-3.0
1,696
require_relative 'blockchain' class EcononyNode def req_main mailbox = ZMQ::Socket.new ZMQ::PULL mailbox.bind 'inproc://requests' requesters = [] while true task, *args = mailbox.recv_array end end end # vim:tabstop=2 shiftwidth=2 noexpandtab:
benzrf/econony
node.rb
Ruby
gpl-3.0
262
int ObservableBlockedComForce::actual_calculate(PartCfg & partCfg) { double* A = last_value; unsigned int i; unsigned int block; unsigned int n_blocks; unsigned int blocksize; unsigned int id; IntList* ids; if (!sortPartCfg()) { runtimeErrorMsg() <<"could not sort partCfg"; return -1; } ids=(IntList*) container; n_blocks=n/3; blocksize=ids->n/n_blocks; for ( block = 0; block < n_blocks; block++ ) { for ( i = 0; i < blocksize; i++ ) { id = ids->e[block*blocksize+i]; if (ids->e[i] >= n_part) return 1; A[3*block+0] += partCfg[id].f.f[0]/time_step/time_step*2; A[3*block+1] += partCfg[id].f.f[1]/time_step/time_step*2; A[3*block+2] += partCfg[id].f.f[2]/time_step/time_step*2; } } return 0; }
KonradBreitsprecher/espresso
src/core/observables/not_yet_implemented/BlockedComForce.hpp
C++
gpl-3.0
785
// Qt #include <QDateTime> // Application #include "CRemoteControlData.h" //------------------------------------------------------------------------------------------------- quint32 CFileTransferData::m_ulNextTransferID = 1; CFileTransferData::CFileTransferData(QTcpSocket* pSocket, const QString& sSourceName, const QString& sTargetName, quint32 ulFileSize, bool bOut) : m_pSocket(pSocket) , m_pFile(nullptr) , m_tLastIncomingMessageTime(QDateTime::currentDateTime()) , m_sSourceName(sSourceName) , m_sTargetName(sTargetName) , m_ulOffsetInFile(0) , m_ulFileSize(ulFileSize) , m_bOut(bOut) , m_bDone(false) , m_bCompCRC(false) , m_bSameCRC(false) , m_bFileInfoSent(false) , m_bGotFileInfo(false) , m_bEchoFileCRC(false) { m_ulTransferID = getNewTransferID(); } CFileTransferData::CFileTransferData(QTcpSocket* pSocket, const QString& sSourceName, const QString& sTargetName, quint32 ulFileSize, quint32 ulTransferID, bool bOut) : m_pSocket(pSocket) , m_pFile(nullptr) , m_tLastIncomingMessageTime(QDateTime::currentDateTime()) , m_sSourceName(sSourceName) , m_sTargetName(sTargetName) , m_ulOffsetInFile(0) , m_ulFileSize(ulFileSize) , m_bOut(bOut) , m_bDone(false) , m_bCompCRC(false) , m_bSameCRC(false) , m_bFileInfoSent(false) , m_bGotFileInfo(false) , m_bEchoFileCRC(false) { m_ulTransferID = ulTransferID; m_ulNextTransferID = ulTransferID + 1; } CFileTransferData::~CFileTransferData() { if (m_pFile != nullptr) { if (m_pFile->isOpen()) m_pFile->close(); delete m_pFile; } } // Generates a file transfer ID using current time and an auto-incremented integer quint32 CFileTransferData::getNewTransferID() { m_ulNextTransferID++; return QDateTime::currentDateTime().time().second() + QDateTime::currentDateTime().time().msec() + m_ulNextTransferID; }
Jango73/qt-plus
source/cpp/RemoteControl/CRemoteControlData.cpp
C++
gpl-3.0
1,927
package org.optimizationBenchmarking.evaluator.data.spec; import java.lang.ref.SoftReference; /** * The storage type of * {@link org.optimizationBenchmarking.evaluator.data.spec.Attribute * attribute}. Attributes can be {@link #PERMANENTLY_STORED permanently} * stored, {@link #TEMPORARILY_STORED temporarily} stored as long as there * is enough memory, or {@link #NEVER_STORED not stored} at all in internal * caches. Whenever a attribute which may be stored in a cache is accessed, * first it is checked whether the attribute resides in the cache. If so, * the cached value is returned. Otherwise, it is computed. */ public enum EAttributeType { /** * This type is for attributes which must be permanently stored in the * data set. */ PERMANENTLY_STORED(true), /** * Attributes of this type my be stored in the data sets but may also be * purged in low-memory situations. Once purged, they will simply be * re-computed. This is realized by internally referencing them with * {@link java.lang.ref.SoftReference soft references} which will be * garbage collected when the memory situation warrants it. */ TEMPORARILY_STORED(true) { /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") final <T> T unpack(final Object o) { return ((o != null) ? (((SoftReference<T>) (o)).get()) : null); } /** {@inheritDoc} */ @Override final Object pack(final Object o) { return new SoftReference<>(o); } }, /** * Attributes of this type will never be stored. We would use this * attribute type for attributes that either consume a lot of memory or * are known to be rarely accessed twice. Storing them is either not * feasible or makes no sense. Attributes of this type will always be * re-computed when accessed. */ NEVER_STORED(false); /** store the data */ final boolean m_store; /** * Create the attribute type * * @param store * should the attribute data */ private EAttributeType(final boolean store) { this.m_store = store; } /** * Unpack an object: the method is internally used to unwrap objects by * the cache in a data object. * * @param o * the packed object * @return the unpacked object * @param <T> * the goal type */ @SuppressWarnings("unchecked") <T> T unpack(final Object o) { return ((T) o); } /** * pack an object: the method is internally used to wrap objects by the * cache in a data object. * * @param o * the unpacked object * @return the packed object */ Object pack(final Object o) { return o; } }
optimizationBenchmarking/evaluator-base
src/main/java/org/optimizationBenchmarking/evaluator/data/spec/EAttributeType.java
Java
gpl-3.0
2,775
package model.beans; import java.util.Date; /** * * @author Gepardas */ public class Invoice { private String buyerName; private String buyerCode; private String buyerAdress; private String buyerCity; private String buyerCountry; private String buyerPhone; private String buyerEmail; private String buyerGetAlldata; private Long id; private Date date; private double totalExcVat; private int vat; private int total; public Long getId() { return id; } public void setId(Long id) { this.id = id; } }
GiGsolutions/Invoice_generator
src/model/beans/Invoice.java
Java
gpl-3.0
655
<?PHP require_once('inc/ircplugin.php'); require_once('inc/ircformat.php'); require_once('mpd/mpd.class.php'); if(!class_exists('MbotMpd')) { class MbotMpd extends IrcPlugin { private $host = 'localhost'; private $port = 6600; private $password = ''; private $max_list = 10; private $last_search = array(); public function OnMpd(&$channel, IrcPrivMsg $priv_msg, array $argv) { $this->Connect(); switch(strtolower($argv[0])) { case 'np': return $this->HandleNp($channel); case 'pause': return $this->HandlePause(); case 'search': return $this->HandleSearch($channel, $argv[1], $argv[2]); case 'play': return $this->HandlePlay($channel, $argv[1], $argv[2]); } } //a few shorthands public function OnSearch(&$channel, IrcPrivMsg $priv_msg, array $argv) { $this->Connect(); return $this->HandleSearch($channel, 'title', $argv[0]); } public function OnPlay(&$channel, IrcPrivMsg $priv_msg, array $argv) { $this->Connect(); return $this->HandlePlay($channel, 'title', $argv[0]); } public function OnList(&$channel, IrcPrivMsg $priv_msg, array $argv) { $this->Connect(); return $this->PlayLastSearch($argv[0]); } private function HandleNp(&$channel) { $this->mpd->RefreshInfo(); $current_track = $this->mpd->playlist[$this->mpd->current_track_id]; $channel->Send($current_track['Artist'].' - '.$current_track['Title']); } private function HandlePause() { $this->mpd->Pause(); } private function HandleSearch(&$channel, $type, $str) { $return = $this->SearchDB($type, $str); if(count($return) == 0) { $channel->Send("Nothing found"); } elseif(count($return) <= $this->max_list) { $this->SearchResults(&$channel, $return); } else { $channel->Send('I\'m not going to list '.count($return).' songs'); } } private function HandlePlay(&$channel, $type, $str) { if(strtolower($type) === 'list') return $this->PlayLastSearch($type); $return = $this->SearchDB($type, $str); if(count($return) == 1) { $this->Play($return[0]['file']); $channel->Send('Playing: '.$return[0]['Artist'].' - '.$return[0]['Title']); } elseif(count($return) == 0) { $channel->Send("Nothing found"); } else { $channel->Send('More than one song matches...'); if(count($return) <= $this->max_list) { $this->SearchResults(&$channel, $return); } else $channel->Send('Actually there are too many matching songs that match even to list'); } } private function Connect() { $this->mpd = empty($this->password) ? new mpd($this->host, $this->port) : new mpd($this->host, $this->port, $this->password); } private function SearchDB($type, $str) { $allowed_types = array('artist' => MPD_SEARCH_ARTIST, 'title' => MPD_SEARCH_TITLE, 'album' => MPD_SEARCH_ALBUM); if(!isset($allowed_types[strtolower($type)])) return; return $this->mpd->Search($allowed_types[strtolower($type)], $str); } private function Play($file) { //if song is already on the playlist, do not add it again $found = false; foreach($this->mpd->playlist as $idx => $song) { if($song['file'] == $file) { echo 'Song is already in the playlist'."\n"; $this->mpd->SkipTo($idx); $found = true; break; } } if(!$found) { $this->mpd->PLAdd($file); $this->mpd->RefreshInfo(); $this->mpd->SkipTo(count($this->mpd->playlist)-1); } } private function PlayLastSearch($idx) { if(isset($this->last_search[$idx])) $this->Play($this->last_search[$idx]['file']); } private function SearchResults(&$channel, $songs) { $this->last_search = $songs; foreach($songs as $idx => $song) { $channel->Send(IrcFormat::Bold($idx).'. '.$song['Artist'].' - '.$song['Title']); } $channel->Send('To play: '.IrcFormat::Green('!list #')); } } } return new MbotMpd; ?>
mylssi/mbot-php
plugins/mbot_mpd.php
PHP
gpl-3.0
3,883
/* Copyright_License { G-Meter INU. Copyright (C) 2013-2015 Peter F Bradshaw A detailed list of copyright holders can be found in the file "AUTHORS". 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 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #ifndef GPSSENSORS_HPP #define GPSSENSORS_HPP #include <jni.h> #include "Utility/DeviceInputBuffer.hpp" /** * This class is a singleton. Its purpose is to handle communication to and * from the Android GPS systems. * * This class buffers that data in order to ensure consistancy. */ class GPSSensor : public DeviceInputBuffer { public: /** * Get a reference to the singleton GPSSensor object. If the object does not * yet it exist then it is created. This is the only way that the object * of this class may be created. * @return The reference the object. This reference is always valid at the * time theis function is called. */ static GPSSensor& Instance() { static GPSSensor instance; return instance; } /** * GPS status. These definitions originate in the Android LocationProvider * API documentation. */ enum GPSStatus { OUT_OF_SERVICE = 0, // GPS disabled TEMPORARILY_UNAVAILABLE = 1, // Waiting for fix AVAILABLE = 2 // Position available }; /** * Set the GPS status. * @param env The JNI enviroment. * @param obj The JNI object. * @param connected The connected status: true or false. */ void Connected(JNIEnv *env, jobject obj, jint connected); /** * Give the GPS connection state. * @return The state: OUT_OF_SERVICE - not connected, TEMPORARILY_UNAVAILABLE - waiting for fix, AVAILABLE - fix available. */ GPSStatus Connected() const; /** * Set the GPS state. * @param env The JNI enviroment. * @param obj The JNI object. * @param time GPS time. * @param n_birds Number of birds in view. * @param lambda GPS lambda. * @param phi GPS phi. * @param hasAlt Valid GPS altitude: true or false. * @param alt GPS altitude in meters. * @param hasBearing Valid GPS bearing: true or false. * @param bearing GPS bearing. * @param hasSpeed Valid speed: true or false. * @param speed GPS speed. * @param hasError Valid GPS error: true or false. * @param error GPS error. * @param hasAcc Valid GPS acceleration: true or false. * @param acc GPS acceleration. */ void State(JNIEnv *env, jobject obj, jlong time, jint n_birds, jdouble lambda, jdouble phi, jboolean hasAlt, jdouble alt, jboolean hasBearing, jdouble bearing, jboolean hasSpeed, jdouble speed, jboolean hasError, jdouble error, jboolean hasAcc, jdouble acc); /** * Give the time of the fix. * @return The time of the fix from the GPS unit. */ long Time() const; /** * Give the number of birds. * @return The number of birds used to develope the fix. */ int Birds() const; /** * Give the latitude of the fix. * @return The latitude in radians. */ double Phi() const; /** * Give the longitude of the fix. * @return The longitude in radians. */ double Lambda() const; /** * Give the status of the altitude. * @return If the value of Z() is good then true. */ bool ZStatus() const; /** * Give the altitude above the Geod. * @return The altitude in meters. */ double Z() const; /** * Give the status of the argument of the track. * @return If the value of Omega() is good then true. */ bool OmegaStatus() const; /** * Give the argument of the track. * @return The argument in radians. */ double Omega() const; /** * Give the status of the magnitude of the track. * @return If the value of S() is good then true. */ bool SStatus() const; /** * Give the magnitude of the track. * @return The magnitude in meters per second. */ double S() const; /** * Give the status of the error. * @return If the value of Epsilon() is good then true. */ bool EpsilonStatus() const; /** * Give the value of the fix error. * @return The representative error of the fix in meters. */ double Epsilon() const; /** * Give the status of the acceleration value. * @return If the value A() is good then true. */ bool AStatus() const; /** * Give the value of the acceleration. * @return The acceleration in meters per second per second. */ double A() const; private: /** * Ctor. Called from GPSSensor::Instance() only. */ GPSSensor(); /** * Do not allow copying by any method! */ GPSSensor(const GPSSensor&); GPSSensor& operator=(const GPSSensor&); /** * State. */ GPSStatus status; // GPS status from Java. int n[2]; // Number of birds. long t[2]; // Time of observation. double phi[2]; // Lat. double lambda[2]; // Lon. double z[2]; // Alt. bool z_good[2]; // Z value are valid. double omega[2]; // Argument to track vector. bool omega_good[2]; // Omega value is valid. double s[2]; // Magnitude of the track vector. bool s_good[2]; // S value is valid. double epsilon[2]; // Error estimate. bool epsilon_good[2]; // Epsilon value is valid. double a[2]; // Magnitude of acceleration. bool a_good[2]; // A value is valid. }; #endif /* GPSSENSORS_HPP */
Exadios/g-meter
jni/Executive/Android/GPSSensor.hpp
C++
gpl-3.0
6,361
/*========================================================================= == == == Rong 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 3 of the License, or == == (at your option) any later version. == == == == Rong is distributed in the hope that it will be useful, == == but WITHOUT ANY WARRANTY; without even the implied warranty of == == MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the == == GNU General Public License for more details. == == == == You should have received a copy of the GNU General Public License == == along with this program. If not, see <http://www.gnu.org/licenses/>.== == == =========================================================================*/ /*Авторы/Authors: zlv(Евгений Лежнин) <z_lezhnin@mail2000.ru>, 2011 -- Томск->Сибирь pavertomato(Егор Лежнин) <pavertomato@gmail.com>, 2011 -- Томск->Сибирь*/ #include "aboutdialog.h" #include "ui_aboutdialog.h" AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); connect(ui->closeButton,SIGNAL(clicked()),this,SLOT(close())); } AboutDialog::~AboutDialog() { delete ui; } //да тут тоже всё как-то слишком уж просто...
zlv/Rong
src/aboutdialog.cpp
C++
gpl-3.0
1,807
<?xml version="1.0" ?><!DOCTYPE TS><TS language="cs" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="14"/> <source>About Emercoin</source> <translation>O Emercoinu</translation> </message> <message> <location filename="../forms/aboutdialog.ui" line="53"/> <source>&lt;b&gt;Emercoin&lt;/b&gt; version</source> <translation>&lt;b&gt;Emercoin&lt;/b&gt; verze</translation> </message> <message> <location filename="../forms/aboutdialog.ui" line="85"/> <source>Copyright © 2009-2012 Bitcoin Developers This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file license.txt 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>Copyright © 2009-2012 Vývojáři Emercoinu Tohle je experimentální program. Šířen pod licencí MIT/X11, viz přiložený soubor license.txt nebo http://www.opensource.org/licenses/mit-license.php. Tento produkt zahrnuje programy vyvinuté OpenSSL Projektem pro použití v OpenSSL Toolkitu (http://www.openssl.org/) a kryptografický program od Erika Younga (eay@cryptsoft.com) a program UPnP od Thomase Bernarda.</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="14"/> <source>Address Book</source> <translation>Adresář</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="20"/> <source>These are your Emercoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Tohle jsou tvé Emercoinové adresy pro příjem plateb. Můžeš pokaždé dát každému odesílateli jinou adresu, abys věděl, kdo ti kdy kolik platil.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="33"/> <source>Double-click to edit address or label</source> <translation>Dvojklikem myši začneš upravovat označení adresy</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="57"/> <source>Create a new address</source> <translation>Vytvoř novou adresu</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="60"/> <source>&amp;New Address...</source> <translation>Nová &amp;adresa...</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="71"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Zkopíruj aktuálně vybranou adresu do systémové schránky</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="74"/> <source>&amp;Copy to Clipboard</source> <translation>&amp;Zkopíruj do schránky</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="85"/> <source>Show &amp;QR Code</source> <translation>Zobraz &amp;QR kód</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="96"/> <source>Sign a message to prove you own this address</source> <translation>Podepiš zprávu, čímž prokážeš, že jsi vlastníkem této adresy</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="99"/> <source>&amp;Sign Message</source> <translation>Po&amp;depiš zprávu</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="110"/> <source>Delete the currently selected address from the list. Only sending addresses can be deleted.</source> <translation>Smaž aktuálně vybranou adresu ze seznamu. Smazány mohou být pouze adresy příjemců.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="113"/> <source>&amp;Delete</source> <translation>S&amp;maž</translation> </message> <message> <location filename="../addressbookpage.cpp" line="61"/> <source>Copy address</source> <translation>Kopíruj adresu</translation> </message> <message> <location filename="../addressbookpage.cpp" line="62"/> <source>Copy label</source> <translation>Kopíruj označení</translation> </message> <message> <location filename="../addressbookpage.cpp" line="63"/> <source>Edit</source> <translation>Uprav</translation> </message> <message> <location filename="../addressbookpage.cpp" line="64"/> <source>Delete</source> <translation>Smaž</translation> </message> <message> <location filename="../addressbookpage.cpp" line="281"/> <source>Export Address Book Data</source> <translation>Exportuj data adresáře</translation> </message> <message> <location filename="../addressbookpage.cpp" line="282"/> <source>Comma separated file (*.csv)</source> <translation>CSV formát (*.csv)</translation> </message> <message> <location filename="../addressbookpage.cpp" line="295"/> <source>Error exporting</source> <translation>Chyba při exportu</translation> </message> <message> <location filename="../addressbookpage.cpp" line="295"/> <source>Could not write to file %1.</source> <translation>Nemohu zapisovat do souboru %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="77"/> <source>Label</source> <translation>Označení</translation> </message> <message> <location filename="../addresstablemodel.cpp" line="77"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location filename="../addresstablemodel.cpp" line="113"/> <source>(no label)</source> <translation>(bez označení)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="26"/> <source>Dialog</source> <translation>Dialog</translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="32"/> <location filename="../forms/askpassphrasedialog.ui" line="97"/> <source>TextLabel</source> <translation>Textový popisek</translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="50"/> <source>Enter passphrase</source> <translation>Zadej platné heslo</translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="64"/> <source>New passphrase</source> <translation>Zadej nové heslo</translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="78"/> <source>Repeat new passphrase</source> <translation>Totéž heslo ještě jednou</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="34"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Zadej nové heslo k peněžence.&lt;br/&gt;Použij &lt;b&gt;alespoň 10 náhodných znaků&lt;/b&gt; nebo &lt;b&gt;alespoň osm slov&lt;/b&gt;.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="35"/> <source>Encrypt wallet</source> <translation>Zašifruj peněženku</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="38"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>K provedení této operace musíš zadat heslo k peněžence, aby se mohla odemknout.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="43"/> <source>Unlock wallet</source> <translation>Odemkni peněženku</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="46"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>K provedení této operace musíš zadat heslo k peněžence, aby se mohla dešifrovat.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="51"/> <source>Decrypt wallet</source> <translation>Dešifruj peněženku</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="54"/> <source>Change passphrase</source> <translation>Změň heslo</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="55"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Zadej staré a nové heslo k peněžence.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="101"/> <source>Confirm wallet encryption</source> <translation>Potvrď zašifrování peněženky</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="102"/> <source>WARNING: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR EMERCOINS&lt;/b&gt;! Are you sure you wish to encrypt your wallet?</source> <translation>VAROVÁNÍ: Pokud zašifruješ peněženku a ztratíš či zapomeneš heslo, &lt;b&gt;PŘIJDEŠ O VŠECHNY EMERCOINY&lt;/b&gt;! Jsi si jistý, že chceš peněženku zašifrovat?</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="111"/> <location filename="../askpassphrasedialog.cpp" line="160"/> <source>Wallet encrypted</source> <translation>Peněženka je zašifrována</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="112"/> <source>Emercoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your emercoins from being stolen by malware infecting your computer.</source> <translation>Emercoin se teď ukončí, aby dokončil zašifrování. Pamatuj však, že pouhé zašifrování peněženky úplně nezabraňuje krádeži tvých emercoinů malwarem, kterým se může počítač nakazit.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="208"/> <location filename="../askpassphrasedialog.cpp" line="232"/> <source>Warning: The Caps Lock key is on.</source> <translation>Upozornění: Caps Lock je zapnutý.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="117"/> <location filename="../askpassphrasedialog.cpp" line="124"/> <location filename="../askpassphrasedialog.cpp" line="166"/> <location filename="../askpassphrasedialog.cpp" line="172"/> <source>Wallet encryption failed</source> <translation>Zašifrování peněženky selhalo</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="118"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Zašifrování peněženky selhalo kvůli vnitřní chybě. Tvá peněženka tedy nebyla zašifrována.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="125"/> <location filename="../askpassphrasedialog.cpp" line="173"/> <source>The supplied passphrases do not match.</source> <translation>Zadaná hesla nejsou shodná.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="136"/> <source>Wallet unlock failed</source> <translation>Odemčení peněženky selhalo</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="137"/> <location filename="../askpassphrasedialog.cpp" line="148"/> <location filename="../askpassphrasedialog.cpp" line="167"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Nezadal jsi správné heslo pro dešifrování peněženky.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="147"/> <source>Wallet decryption failed</source> <translation>Dešifrování peněženky selhalo</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="161"/> <source>Wallet passphrase was succesfully changed.</source> <translation>Heslo k peněžence bylo v pořádku změněno.</translation> </message> </context> <context> <name>EmercoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="69"/> <source>Emercoin Wallet</source> <translation>Emercoinová peněženka</translation> </message> <message> <location filename="../bitcoingui.cpp" line="142"/> <location filename="../bitcoingui.cpp" line="464"/> <source>Synchronizing with network...</source> <translation>Synchronizuji se sítí...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="145"/> <source>Block chain synchronization in progress</source> <translation>Provádí se synchronizace řetězce bloků</translation> </message> <message> <location filename="../bitcoingui.cpp" line="176"/> <source>&amp;Overview</source> <translation>&amp;Přehled</translation> </message> <message> <location filename="../bitcoingui.cpp" line="177"/> <source>Show general overview of wallet</source> <translation>Zobraz celkový přehled peněženky</translation> </message> <message> <location filename="../bitcoingui.cpp" line="182"/> <source>&amp;Transactions</source> <translation>&amp;Transakce</translation> </message> <message> <location filename="../bitcoingui.cpp" line="183"/> <source>Browse transaction history</source> <translation>Procházet historii transakcí</translation> </message> <message> <location filename="../bitcoingui.cpp" line="188"/> <source>&amp;Address Book</source> <translation>&amp;Adresář</translation> </message> <message> <location filename="../bitcoingui.cpp" line="189"/> <source>Edit the list of stored addresses and labels</source> <translation>Uprav seznam uložených adres a jejich označení</translation> </message> <message> <location filename="../bitcoingui.cpp" line="194"/> <source>&amp;Receive coins</source> <translation>Pří&amp;jem mincí</translation> </message> <message> <location filename="../bitcoingui.cpp" line="195"/> <source>Show the list of addresses for receiving payments</source> <translation>Zobraz seznam adres pro příjem plateb</translation> </message> <message> <location filename="../bitcoingui.cpp" line="200"/> <source>&amp;Send coins</source> <translation>P&amp;oslání mincí</translation> </message> <message> <location filename="../bitcoingui.cpp" line="201"/> <source>Send coins to a emercoin address</source> <translation>Pošli mince na Emercoinovou adresu</translation> </message> <message> <location filename="../bitcoingui.cpp" line="206"/> <source>Sign &amp;message</source> <translation>Po&amp;depiš zprávu</translation> </message> <message> <location filename="../bitcoingui.cpp" line="207"/> <source>Prove you control an address</source> <translation>Prokaž vlastnictví adresy</translation> </message> <message> <location filename="../bitcoingui.cpp" line="226"/> <source>E&amp;xit</source> <translation>&amp;Konec</translation> </message> <message> <location filename="../bitcoingui.cpp" line="227"/> <source>Quit application</source> <translation>Ukončit aplikaci</translation> </message> <message> <location filename="../bitcoingui.cpp" line="230"/> <source>&amp;About %1</source> <translation>&amp;O %1</translation> </message> <message> <location filename="../bitcoingui.cpp" line="231"/> <source>Show information about Emercoin</source> <translation>Zobraz informace o Emercoinu</translation> </message> <message> <location filename="../bitcoingui.cpp" line="233"/> <source>About &amp;Qt</source> <translation>O &amp;Qt</translation> </message> <message> <location filename="../bitcoingui.cpp" line="234"/> <source>Show information about Qt</source> <translation>Zobraz informace o Qt</translation> </message> <message> <location filename="../bitcoingui.cpp" line="236"/> <source>&amp;Options...</source> <translation>&amp;Možnosti...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="237"/> <source>Modify configuration options for emercoin</source> <translation>Uprav nastavení Emercoinu</translation> </message> <message> <location filename="../bitcoingui.cpp" line="239"/> <source>Open &amp;Emercoin</source> <translation>Otevři &amp;Emercoin</translation> </message> <message> <location filename="../bitcoingui.cpp" line="240"/> <source>Show the Emercoin window</source> <translation>Zobraz okno Emercoinu</translation> </message> <message> <location filename="../bitcoingui.cpp" line="241"/> <source>&amp;Export...</source> <translation>&amp;Export...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="242"/> <source>Export the data in the current tab to a file</source> <translation>Exportovat data z tohoto panelu do souboru</translation> </message> <message> <location filename="../bitcoingui.cpp" line="243"/> <source>&amp;Encrypt Wallet</source> <translation>Zaši&amp;fruj peněženku</translation> </message> <message> <location filename="../bitcoingui.cpp" line="244"/> <source>Encrypt or decrypt wallet</source> <translation>Zašifruj nebo dešifruj peněženku</translation> </message> <message> <location filename="../bitcoingui.cpp" line="246"/> <source>&amp;Backup Wallet</source> <translation>&amp;Zazálohovat peněženku</translation> </message> <message> <location filename="../bitcoingui.cpp" line="247"/> <source>Backup wallet to another location</source> <translation>Zazálohuj peněženku na jiné místo</translation> </message> <message> <location filename="../bitcoingui.cpp" line="248"/> <source>&amp;Change Passphrase</source> <translation>Změň &amp;heslo</translation> </message> <message> <location filename="../bitcoingui.cpp" line="249"/> <source>Change the passphrase used for wallet encryption</source> <translation>Změň heslo k šifrování peněženky</translation> </message> <message> <location filename="../bitcoingui.cpp" line="272"/> <source>&amp;File</source> <translation>&amp;Soubor</translation> </message> <message> <location filename="../bitcoingui.cpp" line="281"/> <source>&amp;Settings</source> <translation>&amp;Nastavení</translation> </message> <message> <location filename="../bitcoingui.cpp" line="287"/> <source>&amp;Help</source> <translation>Ná&amp;pověda</translation> </message> <message> <location filename="../bitcoingui.cpp" line="294"/> <source>Tabs toolbar</source> <translation>Panel s listy</translation> </message> <message> <location filename="../bitcoingui.cpp" line="305"/> <source>Actions toolbar</source> <translation>Panel akcí</translation> </message> <message> <location filename="../bitcoingui.cpp" line="317"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location filename="../bitcoingui.cpp" line="407"/> <source>emercoin-qt</source> <translation>emercoin-qt</translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="449"/> <source>%n active connection(s) to Emercoin network</source> <translation><numerusform>%n aktivní spojení do Emercoinové sítě</numerusform><numerusform>%n aktivní spojení do Emercoinové sítě</numerusform><numerusform>%n aktivních spojení do Emercoinové sítě</numerusform></translation> </message> <message> <location filename="../bitcoingui.cpp" line="475"/> <source>Downloaded %1 of %2 blocks of transaction history.</source> <translation>Staženo %1 z %2 bloků transakční historie.</translation> </message> <message> <location filename="../bitcoingui.cpp" line="487"/> <source>Downloaded %1 blocks of transaction history.</source> <translation>Staženo %1 bloků transakční historie.</translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="502"/> <source>%n second(s) ago</source> <translation><numerusform>před vteřinou</numerusform><numerusform>před %n vteřinami</numerusform><numerusform>před %n vteřinami</numerusform></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="506"/> <source>%n minute(s) ago</source> <translation><numerusform>před minutou</numerusform><numerusform>před %n minutami</numerusform><numerusform>před %n minutami</numerusform></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="510"/> <source>%n hour(s) ago</source> <translation><numerusform>před hodinou</numerusform><numerusform>před %n hodinami</numerusform><numerusform>před %n hodinami</numerusform></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="514"/> <source>%n day(s) ago</source> <translation><numerusform>včera</numerusform><numerusform>před %n dny</numerusform><numerusform>před %n dny</numerusform></translation> </message> <message> <location filename="../bitcoingui.cpp" line="520"/> <source>Up to date</source> <translation>aktuální</translation> </message> <message> <location filename="../bitcoingui.cpp" line="525"/> <source>Catching up...</source> <translation>Stahuji...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="533"/> <source>Last received block was generated %1.</source> <translation>Poslední stažený blok byl vygenerován %1.</translation> </message> <message> <location filename="../bitcoingui.cpp" line="597"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>Tahle transakce přesahuje velikostní limit. I tak ji ale můžeš poslat, pokud za ni zaplatíš poplatek %1, který půjde uzlům, které tvou transakci zpracují, a navíc tak podpoříš síť. Chceš zaplatit poplatek?</translation> </message> <message> <location filename="../bitcoingui.cpp" line="602"/> <source>Sending...</source> <translation>Posílám...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="629"/> <source>Sent transaction</source> <translation>Odeslané transakce</translation> </message> <message> <location filename="../bitcoingui.cpp" line="630"/> <source>Incoming transaction</source> <translation>Příchozí transakce</translation> </message> <message> <location filename="../bitcoingui.cpp" line="631"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Datum: %1 Částka: %2 Typ: %3 Adresa: %4 </translation> </message> <message> <location filename="../bitcoingui.cpp" line="751"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Peněženka je &lt;b&gt;zašifrovaná&lt;/b&gt; a momentálně &lt;b&gt;odemčená&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoingui.cpp" line="759"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Peněženka je &lt;b&gt;zašifrovaná&lt;/b&gt; a momentálně &lt;b&gt;zamčená&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoingui.cpp" line="782"/> <source>Backup Wallet</source> <translation>Záloha peněženky</translation> </message> <message> <location filename="../bitcoingui.cpp" line="782"/> <source>Wallet Data (*.dat)</source> <translation>Data peněženky (*.dat)</translation> </message> <message> <location filename="../bitcoingui.cpp" line="785"/> <source>Backup Failed</source> <translation>Zálohování selhalo</translation> </message> <message> <location filename="../bitcoingui.cpp" line="785"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Při ukládání peněženky na nové místo se přihodila nějaká chyba.</translation> </message> </context> <context> <name>DisplayOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="270"/> <source>&amp;Unit to show amounts in: </source> <translation>&amp;Jednotka pro částky: </translation> </message> <message> <location filename="../optionsdialog.cpp" line="274"/> <source>Choose the default subdivision unit to show in the interface, and when sending coins</source> <translation>Zvol výchozí podjednotku, která se bude zobrazovat v programu a při posílání mincí</translation> </message> <message> <location filename="../optionsdialog.cpp" line="281"/> <source>Display addresses in transaction list</source> <translation>Ukazovat adresy ve výpisu transakcí</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="14"/> <source>Edit Address</source> <translation>Uprav adresu</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="25"/> <source>&amp;Label</source> <translation>&amp;Označení</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="35"/> <source>The label associated with this address book entry</source> <translation>Označení spojené s tímto záznamem v adresáři</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="42"/> <source>&amp;Address</source> <translation>&amp;Adresa</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="52"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Adresa spojená s tímto záznamem v adresáři. Lze upravovat jen pro odesílací adresy.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="20"/> <source>New receiving address</source> <translation>Nová přijímací adresa</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="24"/> <source>New sending address</source> <translation>Nová odesílací adresa</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="27"/> <source>Edit receiving address</source> <translation>Uprav přijímací adresu</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="31"/> <source>Edit sending address</source> <translation>Uprav odesílací adresu</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="91"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Zadaná adresa &quot;%1&quot; už v adresáři je.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="96"/> <source>The entered address &quot;%1&quot; is not a valid emercoin address.</source> <translation>Zadaná adresa &quot;%1&quot; není platná Emercoinová adresa.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="101"/> <source>Could not unlock wallet.</source> <translation>Nemohu odemknout peněženku.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="106"/> <source>New key generation failed.</source> <translation>Nepodařilo se mi vygenerovat nový klíč.</translation> </message> </context> <context> <name>MainOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="170"/> <source>&amp;Start Emercoin on window system startup</source> <translation>&amp;Spustit Emercoin při startu systému</translation> </message> <message> <location filename="../optionsdialog.cpp" line="171"/> <source>Automatically start Emercoin after the computer is turned on</source> <translation>Automaticky spustí Emercoin po zapnutí počítače</translation> </message> <message> <location filename="../optionsdialog.cpp" line="175"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimalizovávat do ikony v panelu</translation> </message> <message> <location filename="../optionsdialog.cpp" line="176"/> <source>Show only a tray icon after minimizing the window</source> <translation>Po minimalizaci okna zobrazí pouze ikonu v panelu</translation> </message> <message> <location filename="../optionsdialog.cpp" line="180"/> <source>Map port using &amp;UPnP</source> <translation>Namapovat port přes &amp;UPnP</translation> </message> <message> <location filename="../optionsdialog.cpp" line="181"/> <source>Automatically open the Emercoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Automaticky otevře potřebný port na routeru. Tohle funguje jen za předpokladu, že tvůj router podporuje UPnP a že je UPnP povolené.</translation> </message> <message> <location filename="../optionsdialog.cpp" line="185"/> <source>M&amp;inimize on close</source> <translation>&amp;Zavřením minimalizovat</translation> </message> <message> <location filename="../optionsdialog.cpp" line="186"/> <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>Zavřením se aplikace minimalizuje. Pokud je tato volba zaškrtnuta, tak se aplikace ukončí pouze zvolením Konec v menu.</translation> </message> <message> <location filename="../optionsdialog.cpp" line="190"/> <source>&amp;Connect through SOCKS4 proxy:</source> <translation>&amp;Připojit přes SOCKS4 proxy:</translation> </message> <message> <location filename="../optionsdialog.cpp" line="191"/> <source>Connect to the Bitcon network through a SOCKS4 proxy (e.g. when connecting through Tor)</source> <translation>Připojí se do Emercoinové sítě přes SOCKS4 proxy (např. když se připojuje přes Tor)</translation> </message> <message> <location filename="../optionsdialog.cpp" line="196"/> <source>Proxy &amp;IP: </source> <translation>&amp;IP adresa proxy:</translation> </message> <message> <location filename="../optionsdialog.cpp" line="202"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>IP adresa proxy (např. 127.0.0.1)</translation> </message> <message> <location filename="../optionsdialog.cpp" line="205"/> <source>&amp;Port: </source> <translation>P&amp;ort: </translation> </message> <message> <location filename="../optionsdialog.cpp" line="211"/> <source>Port of the proxy (e.g. 1234)</source> <translation>Port proxy (např. 1234)</translation> </message> <message> <location filename="../optionsdialog.cpp" line="217"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation>Dobrovolný transakční poplatek za každý započatý kB dopomáhá k rychlému zpracování tvých transakcí. Většina transakcí má do 1 kB. Doporučená výše poplatku je 0.01.</translation> </message> <message> <location filename="../optionsdialog.cpp" line="223"/> <source>Pay transaction &amp;fee</source> <translation>Platit &amp;transakční poplatek</translation> </message> <message> <location filename="../optionsdialog.cpp" line="226"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation>Dobrovolný transakční poplatek za každý započatý kB dopomáhá k rychlému zpracování tvých transakcí. Většina transakcí má do 1 kB. Doporučená výše poplatku je 0.01.</translation> </message> </context> <context> <name>MessagePage</name> <message> <location filename="../forms/messagepage.ui" line="14"/> <source>Message</source> <translation>Zpráva</translation> </message> <message> <location filename="../forms/messagepage.ui" line="20"/> <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>Podepsáním zprávy svými adresami můžeš prokázat, že je skutečně vlastníš. Buď opatrný a nepodepisuj nic vágního; například při phishingových útocích můžeš být lákán, abys něco takového podepsal. Podepisuj pouze zcela úplná a detailní prohlášení, se kterými souhlasíš.</translation> </message> <message> <location filename="../forms/messagepage.ui" line="38"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Tvá adresa (např. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location filename="../forms/messagepage.ui" line="48"/> <source>Choose adress from address book</source> <translation>Vyber adresu z adresáře</translation> </message> <message> <location filename="../forms/messagepage.ui" line="58"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location filename="../forms/messagepage.ui" line="71"/> <source>Paste address from clipboard</source> <translation>Vlož adresu ze schránky</translation> </message> <message> <location filename="../forms/messagepage.ui" line="81"/> <source>Alt+P</source> <translation>Alt+V</translation> </message> <message> <location filename="../forms/messagepage.ui" line="93"/> <source>Enter the message you want to sign here</source> <translation>Sem vepiš zprávu, kterou chceš podepsat</translation> </message> <message> <location filename="../forms/messagepage.ui" line="105"/> <source>Click &quot;Sign Message&quot; to get signature</source> <translation>Kliknutím na &quot;Podepiš zprávu&quot; získáš podpis</translation> </message> <message> <location filename="../forms/messagepage.ui" line="117"/> <source>Sign a message to prove you own this address</source> <translation>Podepiš zprávu, čímž prokážeš, že jsi vlastníkem této adresy</translation> </message> <message> <location filename="../forms/messagepage.ui" line="120"/> <source>&amp;Sign Message</source> <translation>&amp;Podepiš zprávu</translation> </message> <message> <location filename="../forms/messagepage.ui" line="131"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Zkopíruj podpis do systémové schránky</translation> </message> <message> <location filename="../forms/messagepage.ui" line="134"/> <source>&amp;Copy to Clipboard</source> <translation>&amp;Zkopíruj do schránky</translation> </message> <message> <location filename="../messagepage.cpp" line="74"/> <location filename="../messagepage.cpp" line="89"/> <location filename="../messagepage.cpp" line="101"/> <source>Error signing</source> <translation>Chyba při podepisování</translation> </message> <message> <location filename="../messagepage.cpp" line="74"/> <source>%1 is not a valid address.</source> <translation>%1 není platná adresa.</translation> </message> <message> <location filename="../messagepage.cpp" line="89"/> <source>Private key for %1 is not available.</source> <translation>Soukromý klíč pro %1 není dostupný.</translation> </message> <message> <location filename="../messagepage.cpp" line="101"/> <source>Sign failed</source> <translation>Podepisování selhalo</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../optionsdialog.cpp" line="79"/> <source>Main</source> <translation>Hlavní</translation> </message> <message> <location filename="../optionsdialog.cpp" line="84"/> <source>Display</source> <translation>Zobrazení</translation> </message> <message> <location filename="../optionsdialog.cpp" line="104"/> <source>Options</source> <translation>Možnosti</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="14"/> <source>Form</source> <translation>Formulář</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="40"/> <source>Balance:</source> <translation>Stav účtu:</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="47"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="54"/> <source>Number of transactions:</source> <translation>Počet transakcí:</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="61"/> <source>0</source> <translation>0</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="68"/> <source>Unconfirmed:</source> <translation>Nepotvrzeno:</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="75"/> <source>0 BTC</source> <translation>0 BTC</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="82"/> <source>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt; p, li { white-space: pre-wrap; } &lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Ubuntu'; font-size:11pt; font-weight:400; font-style:normal;&quot;&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Wallet&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt; p, li { white-space: pre-wrap; } &lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:&apos;Ubuntu&apos;; font-size:11pt; font-weight:400; font-style:normal;&quot;&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Peněženka&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="122"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Poslední transakce&lt;/b&gt;</translation> </message> <message> <location filename="../overviewpage.cpp" line="103"/> <source>Your current balance</source> <translation>Aktuální stav tvého účtu</translation> </message> <message> <location filename="../overviewpage.cpp" line="108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Celkem z transakcí, které ještě nejsou potvrzené a které se ještě nezapočítávají do celkového stavu účtu</translation> </message> <message> <location filename="../overviewpage.cpp" line="111"/> <source>Total number of transactions in wallet</source> <translation>Celkový počet transakcí v peněžence</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="14"/> <source>Dialog</source> <translation>Dialog</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="32"/> <source>QR Code</source> <translation>QR kód</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="52"/> <source>Request Payment</source> <translation>Požadovat platbu</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="67"/> <source>Amount:</source> <translation>Částka:</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="102"/> <source>BTC</source> <translation>BTC</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="118"/> <source>Label:</source> <translation>Označení:</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="141"/> <source>Message:</source> <translation>Zpráva:</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="183"/> <source>&amp;Save As...</source> <translation>&amp;Ulož jako...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="101"/> <source>Save Image...</source> <translation>Ulož obrázek...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="101"/> <source>PNG Images (*.png)</source> <translation>PNG obrázky (*.png)</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="14"/> <location filename="../sendcoinsdialog.cpp" line="122"/> <location filename="../sendcoinsdialog.cpp" line="127"/> <location filename="../sendcoinsdialog.cpp" line="132"/> <location filename="../sendcoinsdialog.cpp" line="137"/> <location filename="../sendcoinsdialog.cpp" line="143"/> <location filename="../sendcoinsdialog.cpp" line="148"/> <location filename="../sendcoinsdialog.cpp" line="153"/> <source>Send Coins</source> <translation>Pošli mince</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="64"/> <source>Send to multiple recipients at once</source> <translation>Pošli více příjemcům naráz</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="67"/> <source>&amp;Add recipient...</source> <translation>Při&amp;dej příjemce...</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="84"/> <source>Remove all transaction fields</source> <translation>Smaž všechny transakční formuláře</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="87"/> <source>Clear all</source> <translation>Všechno smaž</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="106"/> <source>Balance:</source> <translation>Stav účtu:</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="113"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="144"/> <source>Confirm the send action</source> <translation>Potvrď odeslání</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="147"/> <source>&amp;Send</source> <translation>&amp;Pošli</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="94"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; pro %2 (%3)</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="99"/> <source>Confirm send coins</source> <translation>Potvrď odeslání mincí</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="100"/> <source>Are you sure you want to send %1?</source> <translation>Jsi si jistý, že chceš poslat %1?</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="100"/> <source> and </source> <translation> a </translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="123"/> <source>The recepient address is not valid, please recheck.</source> <translation>Adresa příjemce je neplatná, překontroluj ji prosím.</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="128"/> <source>The amount to pay must be larger than 0.</source> <translation>Odesílaná částka musí být větší než 0.</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="133"/> <source>Amount exceeds your balance</source> <translation>Částka překračuje stav účtu</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="138"/> <source>Total exceeds your balance when the %1 transaction fee is included</source> <translation>Celková částka při připočítání poplatku %1 překročí stav účtu</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="144"/> <source>Duplicate address found, can only send to each address once in one send operation</source> <translation>Zaznamenána duplikovaná adresa; každá adresa může být v odesílané platbě pouze jednou</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="149"/> <source>Error: Transaction creation failed </source> <translation>Chyba: Vytvoření transakce selhalo </translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="154"/> <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>Chyba Transakce byla odmítnuta. Tohle může nastat, pokud nějaké mince z tvé peněženky už jednou byly utraceny, například pokud používáš kopii souboru wallet.dat a mince byly utraceny v druhé kopii, ale nebyly označeny jako utracené v této.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="14"/> <source>Form</source> <translation>Formulář</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="29"/> <source>A&amp;mount:</source> <translation>Čá&amp;stka:</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="42"/> <source>Pay &amp;To:</source> <translation>&amp;Komu:</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="66"/> <location filename="../sendcoinsentry.cpp" line="26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Zadej označení této adresy; obojí se ti pak uloží do adresáře</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="75"/> <source>&amp;Label:</source> <translation>&amp;Označení:</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="93"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Adresa příjemce (např. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="103"/> <source>Choose address from address book</source> <translation>Vyber adresu z adresáře</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="113"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="120"/> <source>Paste address from clipboard</source> <translation>Vlož adresu ze schránky</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="130"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="137"/> <source>Remove this recipient</source> <translation>Smaž tohoto příjemce</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="25"/> <source>Enter a Emercoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Zadej Emercoinovou adresu (např. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="18"/> <source>Open for %1 blocks</source> <translation>Otevřeno pro %1 bloků</translation> </message> <message> <location filename="../transactiondesc.cpp" line="20"/> <source>Open until %1</source> <translation>Otřevřeno dokud %1</translation> </message> <message> <location filename="../transactiondesc.cpp" line="26"/> <source>%1/offline?</source> <translation>%1/offline?</translation> </message> <message> <location filename="../transactiondesc.cpp" line="28"/> <source>%1/unconfirmed</source> <translation>%1/nepotvrzeno</translation> </message> <message> <location filename="../transactiondesc.cpp" line="30"/> <source>%1 confirmations</source> <translation>%1 potvrzení</translation> </message> <message> <location filename="../transactiondesc.cpp" line="47"/> <source>&lt;b&gt;Status:&lt;/b&gt; </source> <translation>&lt;b&gt;Stav:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="52"/> <source>, has not been successfully broadcast yet</source> <translation>, ještě nebylo rozesláno</translation> </message> <message> <location filename="../transactiondesc.cpp" line="54"/> <source>, broadcast through %1 node</source> <translation>, rozesláno přes %1 uzel</translation> </message> <message> <location filename="../transactiondesc.cpp" line="56"/> <source>, broadcast through %1 nodes</source> <translation>, rozesláno přes %1 uzlů</translation> </message> <message> <location filename="../transactiondesc.cpp" line="60"/> <source>&lt;b&gt;Date:&lt;/b&gt; </source> <translation>&lt;b&gt;Datum:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="67"/> <source>&lt;b&gt;Source:&lt;/b&gt; Generated&lt;br&gt;</source> <translation>&lt;b&gt;Zdroj:&lt;/b&gt; Vygenerováno&lt;br&gt;</translation> </message> <message> <location filename="../transactiondesc.cpp" line="73"/> <location filename="../transactiondesc.cpp" line="90"/> <source>&lt;b&gt;From:&lt;/b&gt; </source> <translation>&lt;b&gt;Od:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="90"/> <source>unknown</source> <translation>neznámo</translation> </message> <message> <location filename="../transactiondesc.cpp" line="91"/> <location filename="../transactiondesc.cpp" line="114"/> <location filename="../transactiondesc.cpp" line="173"/> <source>&lt;b&gt;To:&lt;/b&gt; </source> <translation>&lt;b&gt;Pro:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="94"/> <source> (yours, label: </source> <translation> (tvoje, označení: </translation> </message> <message> <location filename="../transactiondesc.cpp" line="96"/> <source> (yours)</source> <translation> (tvoje)</translation> </message> <message> <location filename="../transactiondesc.cpp" line="131"/> <location filename="../transactiondesc.cpp" line="145"/> <location filename="../transactiondesc.cpp" line="190"/> <location filename="../transactiondesc.cpp" line="207"/> <source>&lt;b&gt;Credit:&lt;/b&gt; </source> <translation>&lt;b&gt;Příjem:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="133"/> <source>(%1 matures in %2 more blocks)</source> <translation>(%1 dozraje po %2 blocích)</translation> </message> <message> <location filename="../transactiondesc.cpp" line="137"/> <source>(not accepted)</source> <translation>(neakceptováno)</translation> </message> <message> <location filename="../transactiondesc.cpp" line="181"/> <location filename="../transactiondesc.cpp" line="189"/> <location filename="../transactiondesc.cpp" line="204"/> <source>&lt;b&gt;Debit:&lt;/b&gt; </source> <translation>&lt;b&gt;Výdaj:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="195"/> <source>&lt;b&gt;Transaction fee:&lt;/b&gt; </source> <translation>&lt;b&gt;Transakční poplatek:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="211"/> <source>&lt;b&gt;Net amount:&lt;/b&gt; </source> <translation>&lt;b&gt;Čistá částka:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="217"/> <source>Message:</source> <translation>Zpráva:</translation> </message> <message> <location filename="../transactiondesc.cpp" line="219"/> <source>Comment:</source> <translation>Komentář:</translation> </message> <message> <location filename="../transactiondesc.cpp" line="221"/> <source>Transaction ID:</source> <translation>ID transakce:</translation> </message> <message> <location filename="../transactiondesc.cpp" line="224"/> <source>Generated coins must wait 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, it will change to &quot;not accepted&quot; and not be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Vygenerované mince musí čekat 120 bloků, než mohou být utraceny. Když jsi vygeneroval tenhle blok, tak byl rozposlán do sítě, aby byl přidán do řetězce bloků. Pokud se mu nepodaří dostat se do řetězce, změní se na &quot;neakceptovaný&quot; a nepůjde utratit. Občas se to může stát, když jiný uzel vygeneruje blok zhruba ve stejném okamžiku jako ty.</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="14"/> <source>Transaction details</source> <translation>Detaily transakce</translation> </message> <message> <location filename="../forms/transactiondescdialog.ui" line="20"/> <source>This pane shows a detailed description of the transaction</source> <translation>Toto okno zobrazuje detailní popis transakce</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="213"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="213"/> <source>Type</source> <translation>Typ</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="213"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="213"/> <source>Amount</source> <translation>Částka</translation> </message> <message numerus="yes"> <location filename="../transactiontablemodel.cpp" line="274"/> <source>Open for %n block(s)</source> <translation><numerusform>Otevřeno pro 1 blok</numerusform><numerusform>Otevřeno pro %n bloky</numerusform><numerusform>Otevřeno pro %n bloků</numerusform></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="277"/> <source>Open until %1</source> <translation>Otřevřeno dokud %1</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="280"/> <source>Offline (%1 confirmations)</source> <translation>Offline (%1 potvrzení)</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="283"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Nepotvrzeno (%1 z %2 potvrzení)</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="286"/> <source>Confirmed (%1 confirmations)</source> <translation>Potvrzeno (%1 potvrzení)</translation> </message> <message numerus="yes"> <location filename="../transactiontablemodel.cpp" line="295"/> <source>Mined balance will be available in %n more blocks</source> <translation><numerusform>Vytěžené mince budou použitelné po jednom bloku</numerusform><numerusform>Vytěžené mince budou použitelné po %n blocích</numerusform><numerusform>Vytěžené mince budou použitelné po %n blocích</numerusform></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="301"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Tento blok nedostal žádný jiný uzel a pravděpodobně nebude akceptován!</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="304"/> <source>Generated but not accepted</source> <translation>Vygenerováno, ale neakceptováno</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="347"/> <source>Received with</source> <translation>Přijato do</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="349"/> <source>Received from</source> <translation>Přijato od</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="352"/> <source>Sent to</source> <translation>Posláno na</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="354"/> <source>Payment to yourself</source> <translation>Platba sama sobě</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="356"/> <source>Mined</source> <translation>Vytěženo</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="394"/> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="593"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Stav transakce. Najetím myši na toto políčko si zobrazíš počet potvrzení.</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="595"/> <source>Date and time that the transaction was received.</source> <translation>Datum a čas přijetí transakce.</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="597"/> <source>Type of transaction.</source> <translation>Druh transakce.</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="599"/> <source>Destination address of transaction.</source> <translation>Cílová adresa transakce.</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="601"/> <source>Amount removed from or added to balance.</source> <translation>Částka odečtená z nebo přičtená k účtu.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="55"/> <location filename="../transactionview.cpp" line="71"/> <source>All</source> <translation>Vše</translation> </message> <message> <location filename="../transactionview.cpp" line="56"/> <source>Today</source> <translation>Dnes</translation> </message> <message> <location filename="../transactionview.cpp" line="57"/> <source>This week</source> <translation>Tento týden</translation> </message> <message> <location filename="../transactionview.cpp" line="58"/> <source>This month</source> <translation>Tento měsíc</translation> </message> <message> <location filename="../transactionview.cpp" line="59"/> <source>Last month</source> <translation>Minulý měsíc</translation> </message> <message> <location filename="../transactionview.cpp" line="60"/> <source>This year</source> <translation>Letos</translation> </message> <message> <location filename="../transactionview.cpp" line="61"/> <source>Range...</source> <translation>Rozsah...</translation> </message> <message> <location filename="../transactionview.cpp" line="72"/> <source>Received with</source> <translation>Přijato</translation> </message> <message> <location filename="../transactionview.cpp" line="74"/> <source>Sent to</source> <translation>Posláno</translation> </message> <message> <location filename="../transactionview.cpp" line="76"/> <source>To yourself</source> <translation>Sám sobě</translation> </message> <message> <location filename="../transactionview.cpp" line="77"/> <source>Mined</source> <translation>Vytěženo</translation> </message> <message> <location filename="../transactionview.cpp" line="78"/> <source>Other</source> <translation>Ostatní</translation> </message> <message> <location filename="../transactionview.cpp" line="84"/> <source>Enter address or label to search</source> <translation>Zadej adresu nebo označení pro její vyhledání</translation> </message> <message> <location filename="../transactionview.cpp" line="90"/> <source>Min amount</source> <translation>Minimální částka</translation> </message> <message> <location filename="../transactionview.cpp" line="124"/> <source>Copy address</source> <translation>Kopíruj adresu</translation> </message> <message> <location filename="../transactionview.cpp" line="125"/> <source>Copy label</source> <translation>Kopíruj její označení</translation> </message> <message> <location filename="../transactionview.cpp" line="126"/> <source>Copy amount</source> <translation>Kopíruj částku</translation> </message> <message> <location filename="../transactionview.cpp" line="127"/> <source>Edit label</source> <translation>Uprav označení</translation> </message> <message> <location filename="../transactionview.cpp" line="128"/> <source>Show details...</source> <translation>Zobraz detaily....</translation> </message> <message> <location filename="../transactionview.cpp" line="268"/> <source>Export Transaction Data</source> <translation>Exportuj transakční data</translation> </message> <message> <location filename="../transactionview.cpp" line="269"/> <source>Comma separated file (*.csv)</source> <translation>CSV formát (*.csv)</translation> </message> <message> <location filename="../transactionview.cpp" line="277"/> <source>Confirmed</source> <translation>Potvrzeno</translation> </message> <message> <location filename="../transactionview.cpp" line="278"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location filename="../transactionview.cpp" line="279"/> <source>Type</source> <translation>Typ</translation> </message> <message> <location filename="../transactionview.cpp" line="280"/> <source>Label</source> <translation>Označení</translation> </message> <message> <location filename="../transactionview.cpp" line="281"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location filename="../transactionview.cpp" line="282"/> <source>Amount</source> <translation>Částka</translation> </message> <message> <location filename="../transactionview.cpp" line="283"/> <source>ID</source> <translation>ID</translation> </message> <message> <location filename="../transactionview.cpp" line="287"/> <source>Error exporting</source> <translation>Chyba při exportu</translation> </message> <message> <location filename="../transactionview.cpp" line="287"/> <source>Could not write to file %1.</source> <translation>Nemohu zapisovat do souboru %1.</translation> </message> <message> <location filename="../transactionview.cpp" line="382"/> <source>Range:</source> <translation>Rozsah:</translation> </message> <message> <location filename="../transactionview.cpp" line="390"/> <source>to</source> <translation>až</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="145"/> <source>Sending...</source> <translation>Posílám...</translation> </message> </context> <context> <name>emercoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="3"/> <source>Emercoin version</source> <translation>Verze Emercoinu</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="4"/> <source>Usage:</source> <translation>Užití:</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="5"/> <source>Send command to -server or emercoind</source> <translation>Poslat příkaz pro -server nebo emercoind</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="6"/> <source>List commands</source> <translation>Výpis příkazů</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="7"/> <source>Get help for a command</source> <translation>Získat nápovědu pro příkaz</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="8"/> <source>Options:</source> <translation>Možnosti:</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="9"/> <source>Specify configuration file (default: emercoin.conf)</source> <translation>Konfigurační soubor (výchozí: emercoin.conf)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="10"/> <source>Specify pid file (default: emercoind.pid)</source> <translation>PID soubor (výchozí: emercoind.pid)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="11"/> <source>Generate coins</source> <translation>Generovat mince</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="12"/> <source>Don&apos;t generate coins</source> <translation>Negenerovat mince</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="13"/> <source>Start minimized</source> <translation>Startovat minimalizovaně</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="14"/> <source>Specify data directory</source> <translation>Adresář pro data</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="15"/> <source>Specify connection timeout (in milliseconds)</source> <translation>Zadej časový limit spojení (v milisekundách)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="16"/> <source>Connect through socks4 proxy</source> <translation>Připojovat se přes socks4 proxy</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="17"/> <source>Allow DNS lookups for addnode and connect</source> <translation>Povolit DNS dotazy pro addnode (přidání uzlu) a connect (připojení)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="18"/> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation>Čekat na spojení na &lt;portu&gt; (výchozí: 8333 nebo testnet: 18333)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="19"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Povol nejvýše &lt;n&gt; připojení k uzlům (výchozí: 125)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="20"/> <source>Add a node to connect to</source> <translation>Přidat uzel, ke kterému se připojit</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="21"/> <source>Connect only to the specified node</source> <translation>Připojovat se pouze k udanému uzlu</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="22"/> <source>Don&apos;t accept connections from outside</source> <translation>Nepřijímat připojení zvenčí</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="23"/> <source>Don&apos;t bootstrap list of peers using DNS</source> <translation>Nenačítat seznam uzlů z DNS</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="24"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Práh pro odpojování nesprávně se chovajících uzlů (výchozí: 100)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="25"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Doba ve vteřinách, po kterou se nebudou moci nesprávně se chovající uzly znovu připojit (výchozí: 86400)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="28"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 10000)</source> <translation>Maximální velikost přijímacího bufferu pro každé spojení, &lt;n&gt;*1000 bytů (výchozí: 10000)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="29"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 10000)</source> <translation>Maximální velikost odesílacího bufferu pro každé spojení, &lt;n&gt;*1000 bytů (výchozí: 10000)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="30"/> <source>Don&apos;t attempt to use UPnP to map the listening port</source> <translation>Nesnažit se použít UPnP k namapování naslouchacího portu</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="31"/> <source>Attempt to use UPnP to map the listening port</source> <translation>Snažit se použít UPnP k namapování naslouchacího portu</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="32"/> <source>Fee per kB to add to transactions you send</source> <translation>Poplatek za kB, který se přidá ke každé odeslané transakci</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="33"/> <source>Accept command line and JSON-RPC commands</source> <translation>Akceptovat příkazy z příkazové řádky a přes JSON-RPC</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="34"/> <source>Run in the background as a daemon and accept commands</source> <translation>Běžet na pozadí jako démon a akceptovat příkazy</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="35"/> <source>Use the test network</source> <translation>Použít testovací síť (testnet)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="36"/> <source>Output extra debugging information</source> <translation>Tisknout speciální ladící informace</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="37"/> <source>Prepend debug output with timestamp</source> <translation>Připojit před ladící výstup časové razítko</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="38"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Posílat stopovací/ladící informace do konzole místo do souboru debug.log</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="39"/> <source>Send trace/debug info to debugger</source> <translation>Posílat stopovací/ladící informace do debuggeru</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="40"/> <source>Username for JSON-RPC connections</source> <translation>Uživatelské jméno pro JSON-RPC spojení</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="41"/> <source>Password for JSON-RPC connections</source> <translation>Heslo pro JSON-RPC spojení</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="42"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332)</source> <translation>Čekat na JSON-RPC spojení na &lt;portu&gt; (výchozí: 8332)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="43"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Povolit JSON-RPC spojení ze specifikované IP adresy</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="44"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Posílat příkazy uzlu běžícím na &lt;ip&gt; (výchozí: 127.0.0.1)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="45"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Nastavit zásobník klíčů na velikost &lt;n&gt; (výchozí: 100)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="46"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Přeskenovat řetězec bloků na chybějící transakce tvé pěněženky</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="47"/> <source> SSL options: (see the Emercoin Wiki for SSL setup instructions)</source> <translation> Možnosti SSL: (viz instrukce nastavení SSL v Emercoin Wiki)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="50"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Použít OpenSSL (https) pro JSON-RPC spojení</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="51"/> <source>Server certificate file (default: server.cert)</source> <translation>Soubor se serverovým certifikátem (výchozí: server.cert)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="52"/> <source>Server private key (default: server.pem)</source> <translation>Soubor se serverovým soukromým klíčem (výchozí: server.pem)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="53"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Akceptovatelné šifry (výchozí: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="56"/> <source>This help message</source> <translation>Tato nápověda</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="57"/> <source>Cannot obtain a lock on data directory %s. Emercoin is probably already running.</source> <translation>Nedaří se mi získat zámek na datový adresář %s. Emercoin pravděpodobně už jednou běží.</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="60"/> <source>Loading addresses...</source> <translation>Načítám adresy...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="61"/> <source>Error loading addr.dat</source> <translation>Chyba při načítání addr.dat</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="63"/> <source>Error loading blkindex.dat</source> <translation>Chyba při načítání blkindex.dat</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="65"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Chyba při načítání wallet.dat: peněženka je poškozená</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="66"/> <source>Error loading wallet.dat: Wallet requires newer version of Emercoin</source> <translation>Chyba při načítání wallet.dat: peněženka vyžaduje novější verzi Emercoinu</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="67"/> <source>Wallet needed to be rewritten: restart Emercoin to complete</source> <translation>Soubor s peněženkou potřeboval přepsat: restartuj Emercoin, aby se operace dokončila</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="68"/> <source>Error loading wallet.dat</source> <translation>Chyba při načítání wallet.dat</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="62"/> <source>Loading block index...</source> <translation>Načítám index bloků...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="64"/> <source>Loading wallet...</source> <translation>Načítám peněženku...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="69"/> <source>Rescanning...</source> <translation>Přeskenovávám...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="70"/> <source>Done loading</source> <translation>Načítání dokončeno</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="71"/> <source>Invalid -proxy address</source> <translation>Neplatná -proxy adresa</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="72"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;</source> <translation>Neplatná částka pro -paytxfee=&lt;částka&gt;</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="73"/> <source>Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction.</source> <translation>Upozornění: -paytxfee je nastaveno velmi vysoko. Toto je transakční poplatek, který zaplatíš za každou poslanou transakci.</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="76"/> <source>Error: CreateThread(StartNode) failed</source> <translation>Chyba: Selhalo CreateThread(StartNode)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="77"/> <source>Warning: Disk space is low </source> <translation>Upozornění: Na disku je málo místa </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="78"/> <source>Unable to bind to port %d on this computer. Emercoin is probably already running.</source> <translation>Nedaří se mi připojit na port %d na tomhle počítači. Emercoin už pravděpodobně jednou běží.</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="81"/> <source>Warning: Please check that your computer&apos;s date and time are correct. If your clock is wrong Emercoin will not work properly.</source> <translation>Upozornění: Zkontroluj, že máš v počítači správně nastavený datum a čas. Pokud jsou nastaveny špatně, Emercoin nebude fungovat správně.</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="84"/> <source>beta</source> <translation>beta</translation> </message> </context> </TS>
coinkeeper/2015-06-22_18-38_emercoin
src/qt/locale/bitcoin_cs.ts
TypeScript
gpl-3.0
89,836
class CreateHapReportClients < ActiveRecord::Migration[5.2] def change create_table :hap_report_clients do |t| t.references :client t.integer :age t.boolean :emancipated t.boolean :head_of_household t.string :household_ids, array: true t.integer :project_types, array: true t.boolean :veteran t.boolean :mental_health t.boolean :substance_abuse t.boolean :domestic_violence t.integer :income_at_start t.integer :income_at_exit t.boolean :homeless t.integer :nights_in_shelter t.datetime :deleted_at t.timestamps end end end
greenriver/hmis-warehouse
db/warehouse/migrate/20210510182341_create_hap_report_clients.rb
Ruby
gpl-3.0
633
/** * This file\code is part of InTouch project. * * InTouch - is a .NET wrapper for the vk.com API. * https://github.com/virtyaluk/InTouch * * Copyright (c) 2016 Bohdan Shtepan * http://modern-dev.com/ * * Licensed under the GPLv3 license. */ namespace ModernDev.InTouch { /// <summary> /// A <see cref="VideoReorderVideosParams"/> class describes a <see cref="VideoMethods.ReorderVideos"/> method params. /// </summary> public class VideoReorderVideosParams : MethodParamsGroup { /// <summary> /// ID of the user or community that owns the album with videos. /// </summary> [MethodParam(Name = "target_id")] public int TargetId { get; set; } /// <summary> /// ID of the video album. /// </summary> [MethodParam(Name = "album_id")] public int AlbumId { get; set; } /// <summary> /// ID of the user or community that owns the video. /// </summary> [MethodParam(Name = "owner_id", IsRequired = true)] public int OwnerId { get; set; } /// <summary> /// ID of the video. /// </summary> [MethodParam(Name = "video_id", IsRequired = true)] public int VideoId { get; set; } /// <summary> /// ID of the user or community that owns the video before which the video in question shall be placed. /// </summary> [MethodParam(Name = "before_owner_id")] public int BeforeOwnerId { get; set; } /// <summary> /// ID of the video before which the video in question shall be placed. /// </summary> [MethodParam(Name = "before_video_id")] public int BeforeVideoId { get; set; } /// <summary> /// ID of the user or community that owns the video after which the photo in question shall be placed. /// </summary> [MethodParam(Name = "after_owner_id")] public int AfterOwnerId { get; set; } /// <summary> /// ID of the video after which the photo in question shall be placed. /// </summary> [MethodParam(Name = "after_video_id")] public int AfterVideoId { get; set; } } }
virtyaluk/InTouch
ModernDev.InTouch.Shared/API/MethodsParams/VideoReorderVideosParams.cs
C#
gpl-3.0
2,215
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Drawing; using Gabriel.Cat.Extension; using System.Collections; namespace Gabriel.Cat.Binaris { public class StringBinario : ElementoIListBinario<char> { public StringBinario() : base(ElementoBinario.ElementosTipoAceptado(Serializar.TiposAceptados.Char), LongitudBinaria.ULong) { } public StringBinario(byte[] marcaFin) : base(ElementoBinario.ElementosTipoAceptado(Serializar.TiposAceptados.Char), marcaFin) { } public override object GetObject(MemoryStream bytes) { return new string((char[])base.GetObject(bytes)); } public override byte[] GetBytes(object obj) { string str = obj as string; if(str==null) throw new ArgumentException(String.Format("Se tiene que serializar {0}","".GetType().FullName)); return base.GetBytes(str.ToCharArray()); } public override string ToString() { return "TipoDatos=String"; } } }
tetradog/Gabriel.Cat.Binaris
StringBinario.cs
C#
gpl-3.0
973
# ----------------------------------------------------------------------------- # Getting Things GNOME! - a personal organizer for the GNOME desktop # Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau # # 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 3 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 MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the 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, see <http://www.gnu.org/licenses/>. # ----------------------------------------------------------------------------- from gi.repository import Gtk from gi.repository import GdkPixbuf from GTG.core.tag import ALLTASKS_TAG from GTG.gtk.colors import get_colored_tags_markup, rgba_to_hex from GTG.backends.backend_signals import BackendSignals class BackendsTree(Gtk.TreeView): """ Gtk.TreeView that shows the currently loaded backends. """ COLUMN_BACKEND_ID = 0 # never shown, used for internal lookup. COLUMN_ICON = 1 COLUMN_TEXT = 2 # holds the backend "human-readable" name COLUMN_TAGS = 3 def __init__(self, backendsdialog): """ Constructor, just initializes the gtk widgets @param backends: a reference to the dialog in which this is loaded """ super().__init__() self.dialog = backendsdialog self.req = backendsdialog.get_requester() self._init_liststore() self._init_renderers() self._init_signals() self.refresh() def refresh(self): """refreshes the Gtk.Liststore""" self.backendid_to_iter = {} self.liststore.clear() # Sort backends # 1, put default backend on top # 2, sort backends by human name backends = list(self.req.get_all_backends(disabled=True)) backends = sorted(backends, key=lambda backend: (not backend.is_default(), backend.get_human_name())) for backend in backends: self.add_backend(backend) self.on_backend_state_changed(None, backend.get_id()) def on_backend_added(self, sender, backend_id): """ Signal callback executed when a new backend is loaded @param sender: not used, only here to let this function be used as a callback @param backend_id: the id of the backend to add """ # Add backend = self.req.get_backend(backend_id) if not backend: return self.add_backend(backend) self.refresh() # Select self.select_backend(backend_id) # Update it's enabled state self.on_backend_state_changed(None, backend.get_id()) def add_backend(self, backend): """ Adds a new backend to the list @param backend_id: the id of the backend to add """ if backend: backend_iter = self.liststore.append([ backend.get_id(), self.dialog.get_pixbuf_from_icon_name(backend.get_icon(), 16), backend.get_human_name(), self._get_markup_for_tags(backend.get_attached_tags()), ]) self.backendid_to_iter[backend.get_id()] = backend_iter def on_backend_state_changed(self, sender, backend_id): """ Signal callback executed when a backend is enabled/disabled. @param sender: not used, only here to let this function be used as a callback @param backend_id: the id of the backend to add """ if backend_id in self.backendid_to_iter: b_iter = self.backendid_to_iter[backend_id] b_path = self.liststore.get_path(b_iter) backend = self.req.get_backend(backend_id) backend_name = backend.get_human_name() if backend.is_enabled(): text = backend_name else: # FIXME This snippet is on more than 2 places!!! # FIXME create a function which takes a widget and # flag and returns color as #RRGGBB style_context = self.get_style_context() color = style_context.get_color(Gtk.StateFlags.INSENSITIVE) color = rgba_to_hex(color) text = f"<span color='{color}'>{backend_name}</span>" self.liststore[b_path][self.COLUMN_TEXT] = text # Also refresh the tags new_tags = self._get_markup_for_tags(backend.get_attached_tags()) self.liststore[b_path][self.COLUMN_TAGS] = new_tags def _get_markup_for_tags(self, tag_names): """Given a list of tags names, generates the pango markup to render that list with the tag colors used in GTG @param tag_names: the list of the tags (strings) @return str: the pango markup string """ if ALLTASKS_TAG in tag_names: tags_txt = "" else: tags_txt = get_colored_tags_markup(self.req, tag_names) return "<small>" + tags_txt + "</small>" def remove_backend(self, backend_id): """ Removes a backend from the treeview, and selects the first (to show something in the configuration panel @param backend_id: the id of the backend to remove """ if backend_id in self.backendid_to_iter: self.liststore.remove(self.backendid_to_iter[backend_id]) del self.backendid_to_iter[backend_id] self.select_backend() def _init_liststore(self): """Creates the liststore""" self.liststore = Gtk.ListStore(object, GdkPixbuf.Pixbuf, str, str) self.set_model(self.liststore) def _init_renderers(self): """Initializes the cell renderers""" # We hide the columns headers self.set_headers_visible(False) # For the backend icon pixbuf_cell = Gtk.CellRendererPixbuf() tvcolumn_pixbuf = Gtk.TreeViewColumn('Icon', pixbuf_cell) tvcolumn_pixbuf.add_attribute(pixbuf_cell, 'pixbuf', self.COLUMN_ICON) self.append_column(tvcolumn_pixbuf) # For the backend name text_cell = Gtk.CellRendererText() tvcolumn_text = Gtk.TreeViewColumn('Name', text_cell) tvcolumn_text.add_attribute(text_cell, 'markup', self.COLUMN_TEXT) self.append_column(tvcolumn_text) text_cell.connect('edited', self.cell_edited_callback) text_cell.set_property('editable', True) # For the backend tags tags_cell = Gtk.CellRendererText() tvcolumn_tags = Gtk.TreeViewColumn('Tags', tags_cell) tvcolumn_tags.add_attribute(tags_cell, 'markup', self.COLUMN_TAGS) self.append_column(tvcolumn_tags) def cell_edited_callback(self, text_cell, path, new_text): """If a backend name is changed, it saves the changes in the Backend @param text_cell: not used. The Gtk.CellRendererText that emitted the signal. Only here because it's passed by the signal @param path: the Gtk.TreePath of the edited cell @param new_text: the new name of the backend """ # we strip everything not permitted in backend names new_text = ''.join(c for c in new_text if (c.isalnum() or c in [" ", "-", "_"])) selected_iter = self.liststore.get_iter(path) # update the backend name backend_id = self.liststore.get_value(selected_iter, self.COLUMN_BACKEND_ID) backend = self.dialog.get_requester().get_backend(backend_id) if backend: backend.set_human_name(new_text) # update the text in the liststore self.liststore.set(selected_iter, self.COLUMN_TEXT, new_text) def _init_signals(self): """Initializes the backends and gtk signals """ self.connect("cursor-changed", self.on_select_row) _signals = BackendSignals() _signals.connect(_signals.BACKEND_ADDED, self.on_backend_added) _signals.connect(_signals.BACKEND_STATE_TOGGLED, self.on_backend_state_changed) def on_select_row(self, treeview=None): """When a row is selected, displays the corresponding editing panel @var treeview: not used """ self.dialog.on_backend_selected(self.get_selected_backend_id()) def _get_selected_path(self): """ Helper function to get the selected path @return Gtk.TreePath : returns exactly one path for the selected object or None """ selection = self.get_selection() if selection: model, selected_paths = self.get_selection().get_selected_rows() if selected_paths: return selected_paths[0] return None def select_backend(self, backend_id=None): """ Selects the backend corresponding to backend_id. If backend_id is none, refreshes the current configuration panel. @param backend_id: the id of the backend to select """ selection = self.get_selection() if backend_id in self.backendid_to_iter: backend_iter = self.backendid_to_iter[backend_id] if selection: selection.select_iter(backend_iter) else: if self._get_selected_path(): # We just reselect the currently selected entry self.on_select_row() else: # If nothing is selected, we select the first entry if selection: selection.select_path("0") self.dialog.on_backend_selected(self.get_selected_backend_id()) def get_selected_backend_id(self): """ returns the selected backend id, or none @return string: the selected backend id (or None) """ selected_path = self._get_selected_path() if not selected_path: return None selected_iter = self.liststore.get_iter(selected_path) return self.liststore.get_value(selected_iter, self.COLUMN_BACKEND_ID)
getting-things-gnome/gtg
GTG/gtk/backends/backendstree.py
Python
gpl-3.0
10,617
package org.usfirst.frc.team5940.states; import edu.wpi.first.wpilibj.RobotBase; public abstract class State implements Runnable { @SuppressWarnings("unused") protected RobotBase robot; //Update recall delay private int delay = 25; /** * Constructor * @param robot Saved in this class, allows states to determine information about the robot. This should be passed the subclass of RobotBase of your code. */ public State (RobotBase robot){ //Set the robot this.robot = robot; } /** * Overriden run method for Runnable superclass. Started with STATE_RUNNABLE_NAME.run(); or STATE_THREAD_NAME.start(); */ @Override public void run() { //Initilize this.init(); //Continue until interupdete while (!Thread.interrupted()) { //Update update(); //try to sleep try { Thread.sleep(delay); } catch (InterruptedException e) { /*Print the error*/e.printStackTrace(); } } } /** * Called once right after run() is called, even if the Thread is interrupted. */ protected abstract void init(); /** * Called forever with a delay of delay (the var) while the Thread is not interrupted. */ protected abstract void update(); }
BREAD5940/FRC-2016-BREAD-Codebase
FRC-2016-BREAD-Codebase/src/org/usfirst/frc/team5940/states/State.java
Java
gpl-3.0
1,232
#include "Sub.h" void Sub::delay(uint32_t ms) { hal.scheduler->delay(ms); }
SDRC-AUV/ardusub
ArduSub/compat.cpp
C++
gpl-3.0
81
OpenCart 2.1.0.2 = 1cd91582d238b93e00ffbb4d4b166161 OpenCart 2.0.1.1 = e8968a84ed474fa687574f6b2af3d04b
gohdan/DFC
known_files/hashes/upload/admin/language/english/openbay/amazonus_bulk_listing.php
PHP
gpl-3.0
104
import Component from '@glimmer/component'; import { action } from '@ember/object'; import { inject as service } from '@ember/service'; import type WindowService from 'emberclear/services/window'; export default class Install extends Component { @service window!: WindowService; @action install() { return this.window.promptInstall(); } }
NullVoxPopuli/emberclear
client/web/emberclear/app/components/app/top-nav/install/index.ts
TypeScript
gpl-3.0
354
package com.pms.bean; import java.io.Serializable; import java.util.Date; import java.util.List; //合约实体类 public class Contract implements Serializable{ private int contractId;//合约ID private String contractNo;//合约编号 private String contractPicture;//合约图片地址 private int contractType;//是否解约状态 private int contractDirection;//(合约类型<出租合约、租赁合约>) private Date contractStart;//合约开始时间 private Date contractEnd;//合约结束时间 private Company company;//多对一关系,一个合约对应一个企业用户 private List<CBDParking> cbdparking;//多对多关系, public List<CBDParking> getCbdParking() { return cbdparking; } public void setCbdParking(List<CBDParking> cbdParking) { this.cbdparking = cbdParking; } public int getContractId() { return contractId; } public void setContractId(int contractId) { this.contractId = contractId; } public String getContractNo() { return contractNo; } public void setContractNo(String contractNo) { this.contractNo = contractNo; } public String getContractPicture() { return contractPicture; } public void setContractPicture(String contractPicture) { this.contractPicture = contractPicture; } public int getContractType() { return contractType; } public void setContractType(int contractType) { this.contractType = contractType; } public int getContractDirection() { return contractDirection; } public void setContractDirection(int contractDirection) { this.contractDirection = contractDirection; } public Date getContractStart() { return contractStart; } public void setContractStart(Date contractStart) { this.contractStart = contractStart; } public Date getContractEnd() { return contractEnd; } public void setContractEnd(Date contractEnd) { this.contractEnd = contractEnd; } public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company; } @Override public String toString() { return "Contract [contractId=" + contractId + ", contractNo=" + contractNo + ", contractPicture=" + contractPicture + ", contractType=" + contractType + ", contractDirection=" + contractDirection + ", contractStart=" + contractStart + ", contractEnd=" + contractEnd + ", company=" + company + ", cbdparking=" + cbdparking + ", getCbdParking()=" + getCbdParking() + ", getContractId()=" + getContractId() + ", getContractNo()=" + getContractNo() + ", getContractPicture()=" + getContractPicture() + ", getContractType()=" + getContractType() + ", getContractDirection()=" + getContractDirection() + ", getContractStart()=" + getContractStart() + ", getContractEnd()=" + getContractEnd() + ", getCompany()=" + getCompany() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]"; } }
yeSlin1/CBdParking
src/com/pms/bean/Contract.java
Java
gpl-3.0
2,916
import { Component } from '@angular/core' import template from './modal-portfolio.component.html' @Component({ selector: 'modal-portfolio', template }) export class ModalPortfolioComponent { constructor() {} }
szorfein/Meteor-App
client/imports/app/modal/modal-portfolio.component.ts
TypeScript
gpl-3.0
224
// DlgMSMeer.cpp : implementation file // #include "stdafx.h" #include "Risa.h" #include "DlgMSMeer.h" #include "afxdialogex.h" #include "msImageProcessor.h" // CDlgMSMeer dialog IMPLEMENT_DYNAMIC(CDlgMSMeer, CDialogEx) CDlgMSMeer::CDlgMSMeer(cv::Mat* pmImg, bool bColor, CWnd* pParent /*=NULL*/) : CDialogEx(CDlgMSMeer::IDD, pParent) , m_nOP(0) , m_sigmaS(6) , m_sigmaR(2) , m_nMinRegion(100) { m_pmSource = pmImg; m_bColor = bColor; hasFilter_ = 0; hasSegment_ = 0; cbgImage_ = NULL; filtImage_ = NULL; segmImage_ = NULL; } CDlgMSMeer::~CDlgMSMeer() { if(cbgImage_ != NULL) delete cbgImage_; if(filtImage_ != NULL) delete filtImage_; if(segmImage_ != NULL) delete segmImage_; } void CDlgMSMeer::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Radio(pDX, IDC_RADIO_OP, m_nOP); DDX_Text(pDX, IDC_EDIT_BW_SPATIAL, m_sigmaS); DDX_Text(pDX, IDC_EDIT_BW_COLOR, m_sigmaR); DDX_Text(pDX, IDC_EDIT_MIN_REGION, m_nMinRegion); } BEGIN_MESSAGE_MAP(CDlgMSMeer, CDialogEx) ON_BN_CLICKED(IDC_RUN, &CDlgMSMeer::OnBnClickedRun) ON_BN_CLICKED(IDOK, &CDlgMSMeer::OnBnClickedOk) END_MESSAGE_MAP() // CDlgMSMeer message handlers void CDlgMSMeer::OnBnClickedRun() { // TODO: Add your control notification handler code here UpdateData(TRUE); // ==> variable BeginWaitCursor(); // parameters // sigma_s // sigma_r // a // epsilon // minRegion // kernel radius // filter // speedup level sigmaS = m_sigmaS; sigmaR = m_sigmaR; minRegion = m_nMinRegion; //, kernelSize //obtain image dimensions float speedUpThreshold_ = (float) 0.1; SpeedUpLevel speedUpLevel_ = MED_SPEEDUP;; int width, height; width = cbgImage_->x_; height = cbgImage_->y_; //obtain image type (color or grayscale) imageType gtype; if(cbgImage_->colorIm_) gtype = COLOR; else gtype = GRAYSCALE; gpMsgbar->ShowMessage("Input parameters:\n"); gpMsgbar->ShowMessage("\tSpatial Bandwidth\t= %4d\n\tColor Bandwidth\t= %4.1f\n", sigmaS, sigmaR); gpMsgbar->ShowMessage("\tMinimum Region\t= %4d\n", minRegion); //determine operation (filtering or segmentation) int operation = m_nOP; //create instance of image processor class msImageProcessor *iProc = new msImageProcessor(); //define an input image using the image under consideration //(if filtering or segmentation has taken place, then use this // result upon performing fusing...) if((operation == 2)&&(hasFilter_)) iProc->DefineImage(filtImage_->im_, gtype, height, width); else iProc->DefineImage(cbgImage_->im_, gtype, height, width); int dim; if(cbgImage_->colorIm_) { dim = 3; m_mResult.create(height, width, CV_8UC3); }else{ dim = 1; m_mResult.create(height, width, CV_8UC1); } iProc->SetSpeedThreshold(speedUpThreshold_); switch(operation) { //filter case 1: iProc->Filter(sigmaS, sigmaR, speedUpLevel_); if (iProc->ErrorStatus == EL_ERROR) { gpMsgbar->ShowMessage("%s\n", iProc->ErrorMessage); return; } else if (iProc->ErrorStatus == EL_HALT) { break; } //obtain the filtered image.... filtImage_->Resize(width, height, cbgImage_->colorIm_); iProc->GetResults(filtImage_->im_); if (iProc->ErrorStatus == EL_ERROR) { gpMsgbar->ShowMessage("%s\n", iProc->ErrorMessage); return; } //indicate that only the filtered image has been computed... hasFilter_ = 1; hasSegment_ = 0; memcpy(m_mResult.data, filtImage_->im_, dim*height*width*sizeof(unsigned char)); if(m_bColor) { cv::Mat bgr(height, width, CV_8UC3 ); int from_to[] = { 0,2, 1,1, 2,0}; cv::mixChannels( &m_mResult, 1, &bgr, 1, from_to, 3 ); bgr.copyTo(m_mResult); } cv::namedWindow("filter", CV_WINDOW_AUTOSIZE ); cv::imshow( "filter", m_mResult); break; //fuse case 2: iProc->FuseRegions(sigmaR, minRegion); if (iProc->ErrorStatus == EL_ERROR) { gpMsgbar->ShowMessage("%s\n", iProc->ErrorMessage); return; } else if (iProc->ErrorStatus == EL_HALT) { break; } //obtain the segmented image... segmImage_->Resize(width, height, cbgImage_->colorIm_); iProc->GetResults(segmImage_->im_); if (iProc->ErrorStatus == EL_ERROR) { gpMsgbar->ShowMessage("%s\n", iProc->ErrorMessage); return; } //indicate that the segmented image has been computed... hasSegment_ = 1; memcpy(m_mResult.data, segmImage_->im_, dim*height*width*sizeof(unsigned char)); if(m_bColor) { cv::Mat bgr(height, width, CV_8UC3 ); int from_to[] = { 0,2, 1,1, 2,0}; cv::mixChannels( &m_mResult, 1, &bgr, 1, from_to, 3 ); bgr.copyTo(m_mResult); } cv::namedWindow("fuse", CV_WINDOW_AUTOSIZE ); cv::imshow( "fuse", m_mResult); break; //segment default: //filter the image... iProc->Filter(sigmaS, sigmaR, speedUpLevel_); if (iProc->ErrorStatus == EL_ERROR) { gpMsgbar->ShowMessage("%s\n", iProc->ErrorMessage); return; } else if (iProc->ErrorStatus == EL_HALT) { break; } //filter the image.... unsigned char *tempImage = new unsigned char [dim*height*width]; iProc->GetResults(tempImage); if (iProc->ErrorStatus == EL_ERROR) { gpMsgbar->ShowMessage("%s\n", iProc->ErrorMessage); delete [] tempImage; return; } //fuse regions... iProc->FuseRegions(sigmaR, minRegion); if (iProc->ErrorStatus == EL_ERROR) { gpMsgbar->ShowMessage("%s\n", iProc->ErrorMessage); delete [] tempImage; return; } else if (iProc->ErrorStatus == EL_HALT) { delete [] tempImage; break; } //obtain the segmented and filtered image... filtImage_->Resize(width, height, cbgImage_->colorIm_); memcpy(filtImage_->im_, tempImage, dim*height*width*sizeof(unsigned char)); delete [] tempImage; segmImage_->Resize(width, height, cbgImage_->colorIm_); iProc->GetResults(segmImage_->im_); if (iProc->ErrorStatus) { gpMsgbar->ShowMessage("%s\n", iProc->ErrorMessage); return; } //indicate that both the filtered and segmented image have been computed... hasFilter_ = 1; hasSegment_ = 1; memcpy(m_mResult.data, segmImage_->im_, dim*height*width*sizeof(unsigned char)); if(m_bColor) { cv::Mat bgr(height, width, CV_8UC3 ); int from_to[] = { 0,2, 1,1, 2,0}; cv::mixChannels( &m_mResult, 1, &bgr, 1, from_to, 3 ); bgr.copyTo(m_mResult); } cv::namedWindow("segment", CV_WINDOW_AUTOSIZE ); cv::imshow( "segment", m_mResult); } //delete the image processing object delete iProc; EndWaitCursor(); } BOOL CDlgMSMeer::OnInitDialog() { CDialogEx::OnInitDialog(); // TODO: Add extra initialization here cbgImage_ = new BgImage(); filtImage_ = new BgImage(); segmImage_ = new BgImage(); if(m_bColor) { cv::Mat rgb(m_pmSource->rows, m_pmSource->cols, CV_8UC3 ); int from_to[] = { 0,2, 1,1, 2,0}; cv::mixChannels( m_pmSource, 1, &rgb, 1, from_to, 3 ); cbgImage_->SetImageFromRGB(rgb.data, rgb.cols, rgb.rows, true); //rgb.copyTo(pNew->m_cvMat); }else cbgImage_->SetImageFromRGB(m_pmSource->data, m_pmSource->cols, m_pmSource->rows, true); hasFilter_ = 0; hasSegment_ = 0; return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CDlgMSMeer::OnBnClickedOk() { // TODO: Add your control notification handler code here CDialogEx::OnOK(); if(m_mResult.data != NULL) { m_mResult.copyTo(*m_pmSource); } }
HedgehogTW/Risa
DlgMSMeer.cpp
C++
gpl-3.0
7,364