code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php namespace Drupal\effective_activism\AccessControlHandler; use Drupal; use Drupal\Core\Access\AccessResult; use Drupal\Core\Entity\EntityAccessControlHandler; use Drupal\Core\Entity\EntityInterface; use Drupal\Core\Session\AccountInterface; /** * Access controller for the Event entity. * * @see \Drupal\effective_activism\Entity\Event. */ class EventAccessControlHandler extends EntityAccessControlHandler { /** * {@inheritdoc} */ protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) { switch ($operation) { case 'view': if (!$entity->isPublished()) { return AccessControl::isManager($entity->get('parent')->entity->get('organization')->entity, $account); } else { return AccessControl::isStaff($entity->get('parent')->entity->get('organization')->entity, $account); } case 'update': return AccessControl::isGroupStaff([$entity->get('parent')->entity], $account); case 'delete': return AccessControl::isManager($entity->get('parent')->entity->get('organization')->entity, $account); } // Unknown operation, no opinion. return AccessResult::neutral(); } /** * {@inheritdoc} */ protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) { return AccessControl::isGroupStaff([Drupal::request()->get('group')], $account); } }
EffectiveActivism/effective_activism
src/AccessControlHandler/EventAccessControlHandler.php
PHP
agpl-3.0
1,456
/** * Copyright (C) 2001-2017 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero 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 * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui.actions; import com.rapidminer.RapidMiner; import com.rapidminer.core.license.ProductConstraintManager; import com.rapidminer.gui.MainFrame; import com.rapidminer.gui.tools.ResourceAction; import com.rapidminer.gui.tools.dialogs.AboutBox; import java.awt.event.ActionEvent; /** * The type About action. * * @author Simon Fischer */ public class AboutAction extends ResourceAction { private static final long serialVersionUID = 1L; private MainFrame mainFrame; /** * Instantiates a new About action. * * @param mainFrame the main frame */ public AboutAction(MainFrame mainFrame) { super("about"); this.mainFrame = mainFrame; setCondition(EDIT_IN_PROGRESS, DONT_CARE); } @Override public void actionPerformed(ActionEvent e) { new AboutBox(mainFrame, RapidMiner.getLongVersion(), ProductConstraintManager.INSTANCE.getActiveLicense()) .setVisible(true); } }
cm-is-dog/rapidminer-studio-core
src/main/java/com/rapidminer/gui/actions/AboutAction.java
Java
agpl-3.0
1,819
class CreateVersions < ActiveRecord::Migration def self.up create_table :versions do |t| t.string :item_type, :null => false t.integer :item_id, :null => false t.string :event, :null => false t.string :whodunnit t.text :object t.datetime :created_at end add_index :versions, [:item_type, :item_id] create_table :blog_post_versions do |t| t.string :item_type, :null => false t.integer :item_id, :null => false t.string :event, :null => false t.string :whodunnit t.text :object t.datetime :created_at end add_index :blog_post_versions, [:item_type, :item_id] end def self.down drop_table :blog_post_versions drop_table :versions end end
xdite/Airesis
db/migrate/20131202101922_create_versions.rb
Ruby
agpl-3.0
783
title: Event History toc: [Documentation, Programming Guide, WAMP Features, PubSub, Event History] # Event History Event history allows a WAMP client to retrieve a set of past events for a subscription. Retrieval is by subscription ID, and for a set number of events. ## Configuration in Crossbar.io Crossbar.io does not normally store PubSub events. To enable event history for a topic, you need to configure an event store as part of the Crossbar.io config. An example for this is ```json { "name": "realm1", "roles": [ ], "store": { "type": "memory", "event-history": [ { "uri": "com.example.oncounter", "limit": 10000 } ] } } ``` The above configures a store on the realm `realm1` which resides in memory, and which stores the last 1000 events for the topic `com.example.oncounter`. For the time being, `memory` is the only valid argument for where the store is kept, so there is no event history across restarts of Crossbar.io. We are going to implement an LMDB database which will allow persistence across program restarts. For the time being, event history can only be stored for a specific topic URI. Use of pattern-based subscriptions is not supported. ## Required Client Permissions To be able to retrieve event history, a client needs to have two permissions: * It must be allowed to call the retrieval procedure ('wamp.subscription.get_events'). * It must be allowed to subscribe to the subscription (as identified by the subscription ID given in the call). This requirement is necessary to prevent clients for circumeventing the subscription permissions by simply periodically retrieving events for a subscription. For the time being, the only way to get that subscription ID locally is to actually subscribe to to the topic. (We are thinking about implementing a call to retrieve the subscription ID without subscribing, or an extra argument for the subscribe request to allow this.) ## Calling to Get the Events The actual call to retrieve events is ```javascript session.call('wamp.subscription.get_events', [subcriptionID, 20]).then( function (history) { console.log("got history for " + history.length + " events"); for (var i = 0; i < history.length; ++i) { console.log(history[i].timestamp, history[i].publication, history[i].args[0]); } }, function (err) { console.log("could not retrieve event history", err); } ); ``` where the arguments are the subscription ID to retrieve events for and the number of past events to be retrieved. The event history is returned as an array of event objects.
w1z2g3/crossbar
docs/pages/programming-guide/pubsub/Event-History.md
Markdown
agpl-3.0
2,653
(function() { 'use strict'; angular.module('columbyApp') .controller('SearchCtrl', function($log,$rootScope, $scope, SearchSrv) { /* ---------- SETUP ----------------------------------------------------------------------------- */ $scope.contentLoading = true; $scope.search = {}; $rootScope.title = 'columby.com | search'; $scope.pagination = { itemsPerPage: 20, datasets:{ currentPage: 1 }, accounts:{ currentPage: 1 }, tags:{ currentPage: 1 } }; /* ---------- SCOPE FUNCTIONS ------------------------------------------------------------------- */ $scope.doSearch = function(){ $scope.search.hits = null; if ($scope.search.searchTerm.length>2){ $scope.search.message = 'Searching for: ' + $scope.search.searchTerm; SearchSrv.query({ text: $scope.search.searchTerm, limit: $scope.pagination.itemsPerPage }).then(function (response) { $scope.search.hits = response; $scope.search.message = null; $scope.pagination.datasets.numPages = response.datasets.count / $scope.pagination.itemsPerPage; $scope.pagination.accounts.numPages = response.accounts.count / $scope.pagination.itemsPerPage; $scope.pagination.tags.numPages = response.tags.count / $scope.pagination.itemsPerPage; }, function(err){ $scope.search.message = 'Error: ' + err.data.message; }); } else { $scope.search.message = 'Type at least 3 characters.'; } }; /* ---------- INIT ---------------------------------------------------------------------------- */ if ($rootScope.searchTerm){ $scope.search.searchTerm = $rootScope.searchTerm; $log.debug($scope.search.searchTerm); delete $rootScope.searchTerm; $log.debug($scope.search.searchTerm); $scope.doSearch(); } }); })();
columby/www.columby.com
src/www/app/controllers/search/search.controller.js
JavaScript
agpl-3.0
1,953
QuestionCuePoint cuePoint = new QuestionCuePoint(); cuePoint.EntryId = "0_mej0it92"; cuePoint.Question = "hello world"; OnCompletedHandler<CuePoint> handler = new OnCompletedHandler<CuePoint>( (CuePoint result, Exception e) => { CodeExample.PrintObject(result); done = true; }); CuePointService.Add(cuePoint) .SetCompletion(handler) .Execute(client);
kaltura/developer-platform
test/golden/add_question_cuepoint/csharp.cs
C#
agpl-3.0
391
from . import models from . import lroe
factorlibre/l10n-spain
l10n_es_ticketbai_api_batuz/__init__.py
Python
agpl-3.0
40
/** * Copyright (c) 2011-2018 libgroestlcoin developers (see AUTHORS) * * This file is part of libgroestlcoin. * * libgroestlcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <groestlcoin/groestlcoin/network/protocol.hpp> #include <cstddef> #include <cstdint> #include <functional> #include <memory> #include <system_error> #include <boost/date_time.hpp> #include <boost/filesystem.hpp> #include <boost/format.hpp> #include <groestlcoin/groestlcoin/error.hpp> #include <groestlcoin/groestlcoin/network/authority.hpp> #include <groestlcoin/groestlcoin/network/hosts.hpp> #include <groestlcoin/groestlcoin/network/handshake.hpp> #include <groestlcoin/groestlcoin/network/seeder.hpp> #include <groestlcoin/groestlcoin/utility/logger.hpp> #include <groestlcoin/groestlcoin/utility/threadpool.hpp> namespace libgroestlcoin { namespace network { using std::placeholders::_1; using std::placeholders::_2; using boost::filesystem::path; using boost::format; using boost::posix_time::time_duration; using boost::posix_time::seconds; // Based on http://bitcoinstats.com/network/dns-servers #ifdef ENABLE_TESTNET const hosts::authority_list protocol::default_seeds = { { "testnet-seed.alexykot.me", 18333 }, { "testnet-seed.bitcoin.petertodd.org", 18333 }, { "testnet-seed.bluematt.me", 18333 }, { "testnet-seed.bitcoin.schildbach.de", 18333 } }; #else const hosts::authority_list protocol::default_seeds = { { "seed.bitnodes.io", 8333 }, { "seed.bitcoinstats.com", 8333 }, { "seed.bitcoin.sipa.be", 8333 }, { "dnsseed.bluematt.me", 8333 }, { "seed.bitcoin.jonasschnelli.ch", 8333 }, { "dnsseed.bitcoin.dashjr.org", 8333 } // Previously also included: // bitseed.xf2.org:8333 // archivum.info:8333 // progressbar.sk:8333 // faucet.bitcoin.st:8333 // bitcoin.securepayment.cc:8333 }; #endif const size_t protocol::default_max_outbound = 8; // TODO: parameterize for config access. const size_t watermark_connection_limit = 10; const time_duration watermark_reset_interval = seconds(1); protocol::protocol(threadpool& pool, hosts& peers, handshake& shake, network& net, const hosts::authority_list& seeds, uint16_t port, size_t max_outbound) : strand_(pool), host_pool_(peers), handshake_(shake), network_(net), max_outbound_(max_outbound), watermark_timer_(pool.service()), watermark_count_(0), listen_port_(port), channel_subscribe_(std::make_shared<channel_subscriber_type>(pool)), seeds_(seeds) { } void protocol::start(completion_handler handle_complete) { // handshake.start doesn't accept an error code so we prevent its // execution in case of start failure, using this lambda wrapper. const auto start_handshake = [this, handle_complete] (const std::error_code& ec) { if (ec) { handle_complete(ec); return; } strand_.wrap(&handshake::start, &handshake_, handle_complete)(); }; const auto run_protocol = strand_.wrap(&protocol::handle_start, this, _1, start_handshake); host_pool_.load( strand_.wrap(&protocol::fetch_count, this, _1, run_protocol)); } void protocol::handle_start(const std::error_code& ec, completion_handler handle_complete) { if (ec) { log_error(LOG_PROTOCOL) << "Failure fetching height: " << ec.message(); handle_complete(ec); return; } // TODO: handle run startup failure. handle_complete(ec); run(); } void protocol::stop(completion_handler handle_complete) { host_pool_.save( strand_.wrap(&protocol::handle_stop, this, _1, handle_complete)); } void protocol::handle_stop(const std::error_code& ec, completion_handler handle_complete) { if (ec) { log_error(LOG_PROTOCOL) << "Failure saving hosts file: " << ec.message(); handle_complete(ec); return; } channel_subscribe_->relay(error::service_stopped, nullptr); handle_complete(error::success); } void protocol::fetch_count(const std::error_code& ec, completion_handler handle_complete) { if (ec) { log_error(LOG_PROTOCOL) << "Failure loading hosts file: " << ec.message(); handle_complete(ec); return; } host_pool_.fetch_count( strand_.wrap(&protocol::start_seeder, this, _1, _2, handle_complete)); } void protocol::start_seeder(const std::error_code& ec, size_t hosts_count, completion_handler handle_complete) { if (ec) { log_error(LOG_PROTOCOL) << "Failure checking existing hosts file: " << ec.message(); handle_complete(ec); return; } if (hosts_count == 0) { seeder_ = std::make_shared<seeder>(this, seeds_, handle_complete); seeder_->start(); return; } handle_complete(error::success); } std::string protocol::state_to_string(connect_state state) const { switch (state) { case connect_state::finding_peer: return "finding peer"; case connect_state::connecting: return "connecting to peer"; case connect_state::established: return "established connection"; case connect_state::stopped: return "stopped"; } // Unhandled state! BITCOIN_ASSERT(false); return ""; } void protocol::modify_slot(slot_index slot, connect_state state) { connect_states_[slot] = state; log_debug(LOG_PROTOCOL) << "Outbound connection on slot [" << slot << "] " << state_to_string(state) << "."; } void protocol::run() { strand_.queue( std::bind(&protocol::start_connecting, this)); if (listen_port_ == 0) return; // Unhandled startup failure condition. network_.listen(listen_port_, strand_.wrap(&protocol::handle_listen, this, _1, _2)); } void protocol::start_connecting() { // Initialize the connection slots. BITCOIN_ASSERT(connections_.empty()); BITCOIN_ASSERT(connect_states_.empty()); connect_states_.resize(max_outbound_); for (size_t slot = 0; slot < connect_states_.size(); ++slot) modify_slot(slot, connect_state::stopped); // Start the main outbound connect loop. start_stopped_connects(); start_watermark_reset_timer(); } void protocol::start_stopped_connects() { for (size_t slot = 0; slot < connect_states_.size(); ++slot) if (connect_states_[slot] == connect_state::stopped) try_connect_once(slot); } void protocol::try_connect_once(slot_index slot) { ++watermark_count_; if (watermark_count_ > watermark_connection_limit) return; BITCOIN_ASSERT(slot <= connect_states_.size()); BITCOIN_ASSERT(connect_states_[slot] == connect_state::stopped); // Begin connection flow: finding_peer -> connecting -> established. // Failures end with connect_state::stopped and loop back here again. modify_slot(slot, connect_state::finding_peer); host_pool_.fetch_address( strand_.wrap(&protocol::attempt_connect, this, _1, _2, slot)); } void protocol::start_watermark_reset_timer() { // This timer just loops continuously at fixed intervals // resetting the watermark_count_ variable and starting stopped slots. const auto reset_watermark = [this](const boost::system::error_code& ec) { if (ec) { if (ec != boost::asio::error::operation_aborted) log_error(LOG_PROTOCOL) << "Failure resetting watermark timer: " << ec.message(); BITCOIN_ASSERT(ec == boost::asio::error::operation_aborted); return; } if (watermark_count_ > watermark_connection_limit) log_debug(LOG_PROTOCOL) << "Resuming connection attempts."; // Perform the reset, reallowing connection attempts. watermark_count_ = 0; start_stopped_connects(); // Looping timer... start_watermark_reset_timer(); }; watermark_timer_.expires_from_now(watermark_reset_interval); watermark_timer_.async_wait(strand_.wrap(reset_watermark, _1)); } template <typename ConnectionList> bool already_connected(const network_address_type& address, const ConnectionList& connections) { for (const auto& connection: connections) if (connection.address.ip == address.ip && connection.address.port == address.port) return true; return false; } void protocol::attempt_connect(const std::error_code& ec, const network_address_type& address, slot_index slot) { BITCOIN_ASSERT(connect_states_[slot] == connect_state::finding_peer); modify_slot(slot, connect_state::connecting); if (ec) { log_error(LOG_PROTOCOL) << "Failure randomly selecting a peer address for slot [" << slot << "] " << ec.message(); return; } if (already_connected(address, connections_)) { log_debug(LOG_PROTOCOL) << "Already connected to selected peer [" << authority(address).to_string() << "]"; // Retry another connection, still in same strand. modify_slot(slot, connect_state::stopped); try_connect_once(slot); return; } log_debug(LOG_PROTOCOL) << "Connecting to peer [" << authority(address).to_string() << "] on slot [" << slot << "]"; const authority peer(address); connect(handshake_, network_, peer.host, peer.port, strand_.wrap(&protocol::handle_connect, this, _1, _2, address, slot)); } void protocol::handle_connect(const std::error_code& ec, channel_ptr node, const network_address_type& address, slot_index slot) { BITCOIN_ASSERT(connect_states_[slot] == connect_state::connecting); if (ec || !node) { log_debug(LOG_PROTOCOL) << "Failure connecting to peer [" << authority(address).to_string() << "] on slot [" << slot << "] " << ec.message(); // Retry another connection, still in same strand. modify_slot(slot, connect_state::stopped); try_connect_once(slot); return; } modify_slot(slot, connect_state::established); BITCOIN_ASSERT(connections_.size() <= max_outbound_); connections_.push_back({address, node}); log_info(LOG_PROTOCOL) << "Connected to peer [" << authority(address).to_string() << "] on slot [" << slot << "] (" << connections_.size() << " total)"; // Remove channel from list of connections node->subscribe_stop( strand_.wrap(&protocol::outbound_channel_stopped, this, _1, node, slot)); setup_new_channel(node); } void protocol::maintain_connection(const std::string& hostname, uint16_t port) { connect(handshake_, network_, hostname, port, strand_.wrap(&protocol::handle_manual_connect, this, _1, _2, hostname, port)); } void protocol::handle_manual_connect(const std::error_code& ec, channel_ptr node, const std::string& hostname, uint16_t port) { if (ec || !node) { log_debug(LOG_PROTOCOL) << "Failure connecting manually to peer [" << authority(hostname, port).to_string() << "] " << ec.message(); // Retry connect. maintain_connection(hostname, port); return; } manual_connections_.push_back(node); // Connected! log_info(LOG_PROTOCOL) << "Connection to peer established manually [" << authority(hostname, port).to_string() << "]"; // Subscript to channel stop notifications. node->subscribe_stop( strand_.wrap(&protocol::manual_channel_stopped, this, _1, node, hostname, port)); setup_new_channel(node); } void protocol::handle_listen(const std::error_code& ec, acceptor_ptr accept) { if (!accept) return; if (ec) { log_error(LOG_PROTOCOL) << "Error while starting listener: " << ec.message(); return; } // Listen for connections. accept->accept( strand_.wrap(&protocol::handle_accept, this, _1, _2, accept)); } void protocol::handle_accept(const std::error_code& ec, channel_ptr node, acceptor_ptr accept) { if (!accept) return; // Relisten for connections. accept->accept( strand_.wrap(&protocol::handle_accept, this, _1, _2, accept)); if (ec) { if (node) log_debug(LOG_PROTOCOL) << "Failure accepting connection from [" << node->address().to_string() << "] " << ec.message(); else log_debug(LOG_PROTOCOL) << "Failure accepting connection: " << ec.message(); return; } accepted_channels_.push_back(node); log_info(LOG_PROTOCOL) << "Accepted connection from [" << node->address().to_string() << "] (" << accepted_channels_.size() << " total)"; const auto handshake_complete = [this, node](const std::error_code& ec) { if (!node) return; if (ec) { log_debug(LOG_PROTOCOL) << "Failure in handshake from [" << node->address().to_string() << "] " << ec.message(); return; } // Remove channel from list of connections node->subscribe_stop( strand_.wrap(&protocol::inbound_channel_stopped, this, _1, node)); setup_new_channel(node); }; handshake_.ready(node, handshake_complete); } void protocol::setup_new_channel(channel_ptr node) { if (!node) return; const auto handle_send = [node](const std::error_code& ec) { if (!node) return; if (ec) { log_debug(LOG_PROTOCOL) << "Send error [" << node->address().to_string() << "] " << ec.message(); } }; // Subscribe to address messages. node->subscribe_address( strand_.wrap(&protocol::handle_address_message, this, _1, _2, node)); node->send(get_address_type(), handle_send); // Notify subscribers channel_subscribe_->relay(error::success, node); } template <typename ConnectionsList> void remove_connection(ConnectionsList& connections, channel_ptr node) { auto it = connections.begin(); for (; it != connections.end(); ++it) if (it->node == node) break; BITCOIN_ASSERT(it != connections.end()); connections.erase(it); } void protocol::outbound_channel_stopped(const std::error_code& ec, channel_ptr node, slot_index slot) { // We must always attempt a reconnection. if (ec) { if (node) log_debug(LOG_PROTOCOL) << "Channel stopped (outbound) [" << node->address().to_string() << "] " << ec.message(); else log_debug(LOG_PROTOCOL) << "Channel stopped (outbound): " << ec.message(); } // Erase this channel from our list and then attempt a reconnection. remove_connection(connections_, node); BITCOIN_ASSERT(connect_states_[slot] == connect_state::established); modify_slot(slot, connect_state::stopped); // Attempt reconnection. try_connect_once(slot); } template <typename ChannelsList> void remove_channel(ChannelsList& channels, channel_ptr node) { const auto it = std::find(channels.begin(), channels.end(), node); BITCOIN_ASSERT(it != channels.end()); channels.erase(it); } void protocol::manual_channel_stopped(const std::error_code& ec, channel_ptr node, const std::string& hostname, uint16_t port) { // We must always attempt a reconnection. if (ec) { if (node) log_debug(LOG_PROTOCOL) << "Channel stopped (manual) [" << authority(hostname, port).to_string() << "] " << ec.message(); else log_debug(LOG_PROTOCOL) << "Channel stopped (manual): " << ec.message(); } // Remove from accepted connections. // Timeout logic would go here if we ever need it. remove_channel(manual_connections_, node); // Attempt reconnection. maintain_connection(hostname, port); } void protocol::inbound_channel_stopped(const std::error_code& ec, channel_ptr node) { // We do not attempt to reconnect inbound connections. if (ec) { if (node) log_debug(LOG_PROTOCOL) << "Channel stopped (inbound) [" << node->address().to_string() << "] " << ec.message(); else log_debug(LOG_PROTOCOL) << "Channel stopped (inbound): " << ec.message(); } // Remove from accepted connections (no reconnect). remove_channel(accepted_channels_, node); } void protocol::handle_address_message(const std::error_code& ec, const address_type& packet, channel_ptr node) { if (!node) return; if (ec) { // TODO: reset the connection. log_debug(LOG_PROTOCOL) << "Failure getting addresses from [" << node->address().to_string() << "] " << ec.message(); return; } log_debug(LOG_PROTOCOL) << "Storing addresses from [" << node->address().to_string() << "]"; for (const auto& net_address: packet.addresses) host_pool_.store(net_address, strand_.wrap(&protocol::handle_store_address, this, _1)); // Subscribe to address messages. node->subscribe_address( strand_.wrap(&protocol::handle_address_message, this, _1, _2, node)); } void protocol::handle_store_address(const std::error_code& ec) { if (ec) log_error(LOG_PROTOCOL) << "Failed to store address: " << ec.message(); } void protocol::fetch_connection_count( fetch_connection_count_handler handle_fetch) { strand_.queue( std::bind(&protocol::do_fetch_connection_count, this, handle_fetch)); } void protocol::do_fetch_connection_count( fetch_connection_count_handler handle_fetch) { handle_fetch(error::success, connections_.size()); } void protocol::subscribe_channel(channel_handler handle_channel) { channel_subscribe_->subscribe(handle_channel); } size_t protocol::total_connections() const { return connections_.size() + manual_connections_.size() + accepted_channels_.size(); } void protocol::set_max_outbound(size_t max_outbound) { max_outbound_ = max_outbound; } void protocol::set_hosts_filename(const std::string& hosts_path) { host_pool_.file_path_ = hosts_path; } // Deprecated, this is problematic because there is no enabler. void protocol::disable_listener() { listen_port_ = 0; } // Deprecated, should be private. void protocol::bootstrap(completion_handler handle_complete) { } } // namespace network } // namespace libgroestlcoin
GroestlCoin/libgroestlcoin
src/network/protocol.cpp
C++
agpl-3.0
19,757
/* * PHEX - The pure-java Gnutella-servent. * Copyright (C) 2001 - 2006 Arne Babenhauserheide ( arne_bab <at> web <dot> de ) * * 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 * * Created on 08.02.2005 * --- CVS Information --- * $Id: RSSParser.java 3682 2007-01-09 15:32:14Z gregork $ */ package phex.util; import java.io.IOException; import java.io.PushbackReader; import java.io.Reader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class RSSParser { /** This Class reads out RSS-files passed to it and * collects them in the array "magnets[]". * Check the usage in phex.gui.dialogs.NewDowloadDialog */ /** * List of possible EOL characters, not exactly according to YAML 4.1.4 */ private static final String EOL_CHARACTERS = "\r\n"; private static final char[] AMPERSAND_AMP = new char[] {'a', 'm', 'p', ';'}; private static final String START_OF_ELEMENT_CHAR = "<"; private static final String END_OF_ELEMENT_CHAR = ">"; private static final String END_OF_ELEMENT_CHARN = "/"; private static final char[] XML_LINE = new char[] {'<', '?', 'x', 'm', 'l'}; private static final char[] MAGNET_PREFIX = new char[] {'m', 'a', 'g', 'n', 'e', 't'}; private static final char[] HTTP_PREFIX = new char[] {'h', 't', 't', 'p', ':', '/'}; private static final char[] MAGNET_TAG = new char[] {'<', 'm', 'a', 'g', 'n', 'e', 't', '>'}; private static final char[] ENCLOSURE_TAG_START = new char[] {'<', 'e', 'n', 'c', 'l', 'o', 's', 'u'}; private static final char[] ENCLOSURE_TAG_MID = new char[] {'r', 'e'}; private static final char[] URL_IDENTIFIER = new char[] {'u', 'r', 'l', '=', '"'}; //" private static final char[] ITEM_ELEMENT = new char[] {'<', 'i', 't', 'e', 'm', '>',}; private static final char[] END_OF_ITEM_ELEMENT = new char[] {'<', '/', 'i', 't', 'e', 'm', '>',}; private static final char[] RSS_TAG = new char[] {'<', 'r', 's', 's', '>',}; private static final char[] END_OF_RSS_TAG = new char[] {'<', '/', 'r', 's', 's', '>',}; private final PushbackReader reader; private final List<String> magnets; public RSSParser(Reader reader) { magnets = new ArrayList<String>(); this.reader = new PushbackReader(reader, 6); } public void start() throws IOException { try { /* The FileReader checks, if the File begins with "#MAGMA" * and sends the characters following the "#MAGMA" to the * listFinder. */ char buff[] = new char[5]; int readBytes = 0; while (readBytes != 5) { int count = reader.read(buff, readBytes, 5); if (count == -1) { throw new IOException("Input file is no XML-File (" + String.valueOf(buff) + ")."); } readBytes += count; } if (Arrays.equals(buff, XML_LINE)) { parseXml(); } } finally { reader.close(); } } public List getMagnets() { // Can be called to get the included magnets return magnets; } private void parseXml() throws IOException { int pos = 0; int c; while (true) { c = reader.read(); if (c == RSS_TAG[pos]) { pos++; if (pos == RSS_TAG.length) { // found rss-tag.. find the first item. parseList(); pos = 0; } } else if (c == -1) { // reached the end... return; } else {// next char of rss tag not found... skip line... pos = 0; //skipToEndOfObject(); parseList(); // ignore that this is careless } } } private void parseList() throws IOException { int pos = 0; int c; while (true) { c = reader.read(); if (c == ITEM_ELEMENT[pos]) { pos++; if (pos == ITEM_ELEMENT.length) { // found list: element.. skip line and continue to parse body. parseItemBody(); pos = 0; } } else if (c == END_OF_RSS_TAG[pos]) { pos++; if (pos == END_OF_RSS_TAG.length) { // RSS_TAG ended. pos = 0; return; } } else if (c == -1) { // reached the end... return; } else {// next char of list element not found... skip line... pos = 0; } } } public void parseItemBody() throws IOException { int c; int pos = 0; while (true) { c = reader.read(); if (c == MAGNET_TAG[pos]) { pos++; if (pos == MAGNET_TAG.length) { // we found a magnet-element // pre check if this really is a magnet.. char buff[] = new char[6]; int readBytes = 0; while (readBytes != 6) { int count = reader.read(buff, readBytes, 6); if (count == -1) { return; } readBytes += count; } reader.unread(buff); if (Arrays.equals(buff, MAGNET_PREFIX)) { // reached quoted magnet pos = 0; parseMagnet(); } else if (Arrays.equals(buff, HTTP_PREFIX)) { // reached quoted magnet pos = 0; parseMagnet(); } else { // skip to the end of this magnet-tag, // it doesn't contain a magnet nor a http-uri. } pos = 0; } } /** * Code to read out enclosures with * http- or magnet-uris doesn't work yet. */ else if (c == ENCLOSURE_TAG_START[pos]) { pos++; if (pos == ENCLOSURE_TAG_START.length) { // we found an enclosure-tag // pre check if this contains a magnet or http-url.. pos = 0; while (true) { c = reader.read(); //go forward up to the end of the URL-identifier. if (c == URL_IDENTIFIER[pos]) { pos++; if (pos == URL_IDENTIFIER.length) { //this containis an url-identifier. // check for magnet or http-start. char buff[] = new char[6]; int readBytes = 0; while (readBytes != 6) { int count = reader.read(buff, readBytes, 6); if (count == -1) { return; } readBytes += count; } reader.unread(buff); if (Arrays.equals(buff, MAGNET_PREFIX)) { // reached quoted magnet pos = 0; parseMagnet(); break; } else if (Arrays.equals(buff, HTTP_PREFIX)) { // reached quoted http-url pos = 0; parseMagnet(); break; } } } else if (END_OF_ELEMENT_CHAR.indexOf(c) != -1) { //return if we reached the end of the enclosure. pos = 0; break; } else if (c == -1) { pos = 0; return; } else { pos = 0; } } // end of inner while (true) } else // pos != ENCLOSURE_TAG_START.length { // next letter } } else if (c == -1) { // reached the EOF pos = 0; return; } /** * Commented it out, because it creaded an Array Out of Bounds error * ToDo: Catch the Error and read out the titles of the items to use them along the magnets. * ToDo: Read out the content of the rss-items, so they can be shown alongside the magnet in the list (best in a tooltip). */ else if (pos <= 6 && c == END_OF_ITEM_ELEMENT[pos]) { pos++; if (pos == END_OF_ITEM_ELEMENT.length) { // the item ended. pos = 0; return; } } /* **/ else { pos = 0; // didn't continue as magnet or enclosure tag, reset pos. } } //end of of while-loop } public void parseMagnet() throws IOException { StringBuffer magnetBuf = new StringBuffer(); int c; while (true) { c = reader.read(); if (c == ' ' || EOL_CHARACTERS.indexOf(c) != -1) {// skip all line folding characters.. and all spaces continue; } else if (c == '<') {// found the end of the magnet. break; } /** * only necessary when we are able to read out enclosures. */ else if (c == '"') //" { // found the end of the magnet. break; } else if (c == -1) { // unexpected end... return; } else if (c == '&') { char buff[] = new char[4]; int readBytes = 0; while (readBytes != 4) { int count = reader.read(buff, readBytes, 4); if (count == -1) { return; } readBytes += count; } if (Arrays.equals(buff, AMPERSAND_AMP)) { // reached quoted magnet magnetBuf.append('&'); } else { reader.unread(buff); magnetBuf.append((char) c); } } else { magnetBuf.append((char) c); } } magnets.add(magnetBuf.toString()); } /** * Skips all content till end of line. */ private void skipToEndOfObject() throws IOException { // Only gets the next ending of any object. Could be improved to get // the end of a specific object supplied by the calling funktion. // At the moment ends either with "/>" or with "</" int c; while (true) { c = reader.read(); if (c < 0) {// stream ended... a valid line could not be read... return return; } else if (START_OF_ELEMENT_CHAR.indexOf(c) != -1) {// we found a possble end o the object... check if there are followups c = reader.read(); if (END_OF_ELEMENT_CHARN.indexOf(c) != -1) { return; } else { // the last character was no End of Element char... push it back reader.unread(c); } } else if (END_OF_ELEMENT_CHARN.indexOf(c) != -1) {// we found a possble end o the object... check if there are followups c = reader.read(); if (END_OF_ELEMENT_CHAR.indexOf(c) != -1) { return; } else { // the last character was no End of Element char... push it back reader.unread(c); } } } } }
deepstupid/phex
src/main/java/phex/util/RSSParser.java
Java
agpl-3.0
13,551
<?php /* Smarty version 2.6.11, created on 2012-09-04 14:40:06 compiled from cache/modules/Accounts/EditView.tpl */ ?> <?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php'); smarty_core_load_plugins(array('plugins' => array(array('function', 'sugar_include', 'cache/modules/Accounts/EditView.tpl', 39, false),array('function', 'counter', 'cache/modules/Accounts/EditView.tpl', 45, false),array('function', 'sugar_translate', 'cache/modules/Accounts/EditView.tpl', 49, false),array('function', 'sugar_getjspath', 'cache/modules/Accounts/EditView.tpl', 150, false),array('function', 'html_options', 'cache/modules/Accounts/EditView.tpl', 389, false),array('function', 'sugar_getimagepath', 'cache/modules/Accounts/EditView.tpl', 417, false),array('modifier', 'default', 'cache/modules/Accounts/EditView.tpl', 46, false),array('modifier', 'strip_semicolon', 'cache/modules/Accounts/EditView.tpl', 57, false),array('modifier', 'lookup', 'cache/modules/Accounts/EditView.tpl', 414, false),array('modifier', 'count', 'cache/modules/Accounts/EditView.tpl', 494, false),)), $this); ?> <div class="clear"></div> <form action="index.php" method="POST" name="<?php echo $this->_tpl_vars['form_name']; ?> " id="<?php echo $this->_tpl_vars['form_id']; ?> " <?php echo $this->_tpl_vars['enctype']; ?> > <table width="100%" cellpadding="0" cellspacing="0" border="0" class="dcQuickEdit"> <tr> <td class="buttons"> <input type="hidden" name="module" value="<?php echo $this->_tpl_vars['module']; ?> "> <?php if (isset ( $_REQUEST['isDuplicate'] ) && $_REQUEST['isDuplicate'] == 'true'): ?> <input type="hidden" name="record" value=""> <input type="hidden" name="duplicateSave" value="true"> <input type="hidden" name="duplicateId" value="<?php echo $this->_tpl_vars['fields']['id']['value']; ?> "> <?php else: ?> <input type="hidden" name="record" value="<?php echo $this->_tpl_vars['fields']['id']['value']; ?> "> <?php endif; ?> <input type="hidden" name="isDuplicate" value="false"> <input type="hidden" name="action"> <input type="hidden" name="return_module" value="<?php echo $_REQUEST['return_module']; ?> "> <input type="hidden" name="return_action" value="<?php echo $_REQUEST['return_action']; ?> "> <input type="hidden" name="return_id" value="<?php echo $_REQUEST['return_id']; ?> "> <input type="hidden" name="module_tab"> <input type="hidden" name="contact_role"> <?php if (! empty ( $_REQUEST['return_module'] ) || ! empty ( $_REQUEST['relate_to'] )): ?> <input type="hidden" name="relate_to" value="<?php if ($_REQUEST['return_relationship']): echo $_REQUEST['return_relationship']; elseif ($_REQUEST['relate_to'] && empty ( $_REQUEST['from_dcmenu'] )): echo $_REQUEST['relate_to']; elseif (empty ( $this->_tpl_vars['isDCForm'] ) && empty ( $_REQUEST['from_dcmenu'] )): echo $_REQUEST['return_module']; endif; ?>"> <input type="hidden" name="relate_id" value="<?php echo $_REQUEST['return_id']; ?> "> <?php endif; ?> <input type="hidden" name="offset" value="<?php echo $this->_tpl_vars['offset']; ?> "> <input type="submit" id="SAVE" value="Save" name="button" title="Save" accessKey="a" class="button primary" onclick="this.form.action.value='Save'; saveClickCheckPrimary(); if(check_form('EditView'))SUGAR.ajaxUI.submitForm(this.form);return false; " value="Save" > <?php if (! empty ( $_REQUEST['return_action'] ) && ( $_REQUEST['return_action'] == 'DetailView' && ! empty ( $_REQUEST['return_id'] ) )): ?><input title="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_TITLE']; ?> " accessKey="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_KEY']; ?> " class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=DetailView&module=<?php echo $_REQUEST['return_module']; ?> &record=<?php echo $_REQUEST['return_id']; ?> '); return false;" name="button" value="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_LABEL']; ?> " type="button" id="CANCEL"> <?php elseif (! empty ( $_REQUEST['return_action'] ) && ( $_REQUEST['return_action'] == 'DetailView' && ! empty ( $this->_tpl_vars['fields']['id']['value'] ) )): ?><input title="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_TITLE']; ?> " accessKey="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_KEY']; ?> " class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=DetailView&module=<?php echo $_REQUEST['return_module']; ?> &record=<?php echo $this->_tpl_vars['fields']['id']['value']; ?> '); return false;" type="button" name="button" value="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_LABEL']; ?> " id="CANCEL"> <?php elseif (empty ( $_REQUEST['return_action'] ) || empty ( $_REQUEST['return_id'] ) && ! empty ( $this->_tpl_vars['fields']['id']['value'] )): ?><input title="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_TITLE']; ?> " accessKey="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_KEY']; ?> " class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=index&module=Accounts'); return false;" type="button" name="button" value="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_LABEL']; ?> " id="CANCEL"> <?php else: ?><input title="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_TITLE']; ?> " accessKey="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_KEY']; ?> " class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=index&module=<?php echo $_REQUEST['return_module']; ?> &record=<?php echo $_REQUEST['return_id']; ?> '); return false;" type="button" name="button" value="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_LABEL']; ?> " id="CANCEL"> <?php endif; if ($this->_tpl_vars['bean']->aclAccess('detail')): if (! empty ( $this->_tpl_vars['fields']['id']['value'] ) && $this->_tpl_vars['isAuditEnabled']): ?><input id="btn_view_change_log" title="<?php echo $this->_tpl_vars['APP']['LNK_VIEW_CHANGE_LOG']; ?> " class="button" onclick='open_popup("Audit", "600", "400", "&record=<?php echo $this->_tpl_vars['fields']['id']['value']; ?> &module_name=Accounts", true, false, { "call_back_function":"set_return","form_name":"EditView","field_to_name_array":[] } ); return false;' type="button" value="<?php echo $this->_tpl_vars['APP']['LNK_VIEW_CHANGE_LOG']; ?> "><?php endif; endif; ?> </td> <td align='right'> <?php echo $this->_tpl_vars['PAGINATION']; ?> </td> </tr> </table><?php echo smarty_function_sugar_include(array('include' => $this->_tpl_vars['includes']), $this);?> <span id='tabcounterJS'><script>SUGAR.TabFields=new Array();//this will be used to track tabindexes for references</script></span> <div id="EditView_tabs" > <div > <div id="LBL_ACCOUNT_INFORMATION"> <?php echo smarty_function_counter(array('name' => 'panelFieldCount','start' => 0,'print' => false,'assign' => 'panelFieldCount'), $this);?> <table width="100%" border="0" cellspacing="1" cellpadding="0" class="yui3-skin-sam <?php echo ((is_array($_tmp=@$this->_tpl_vars['def']['templateMeta']['panelClass'])) ? $this->_run_mod_handler('default', true, $_tmp, 'edit view dcQuickEdit edit508') : smarty_modifier_default($_tmp, 'edit view dcQuickEdit edit508')); ?> "> <tr> <th align="left" colspan="8"> <h4><?php echo smarty_function_sugar_translate(array('label' => 'LBL_ACCOUNT_INFORMATION','module' => 'Accounts'), $this);?> </h4> </th> </tr> <?php echo smarty_function_counter(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?> <?php ob_start(); ?> <tr> <td valign="top" id='first_name_label' width='12.5%' scope="col"> <?php ob_start(); echo smarty_function_sugar_translate(array('label' => 'LBL_FIRST_NAME','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?> <label for="first_name"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : smarty_modifier_strip_semicolon($_tmp)); ?> :</label> <span class="required">*</span> </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' > <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <?php if (strlen ( $this->_tpl_vars['fields']['first_name']['value'] ) <= 0): $this->assign('value', $this->_tpl_vars['fields']['first_name']['default_value']); else: $this->assign('value', $this->_tpl_vars['fields']['first_name']['value']); endif; ?> <input type='text' name='<?php echo $this->_tpl_vars['fields']['first_name']['name']; ?> ' id='<?php echo $this->_tpl_vars['fields']['first_name']['name']; ?> ' size='30' maxlength='15' value='<?php echo $this->_tpl_vars['value']; ?> ' title='' accesskey='7' > <td valign="top" id='LBL_FIRST_NAME_label' width='12.5%' scope="col"> &nbsp; </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' > <td valign="top" id='_label' width='%' scope="col"> &nbsp; </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='%' > </tr> <?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?> <?php endif; echo smarty_function_counter(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?> <?php ob_start(); ?> <tr> <td valign="top" id='last_name_label' width='12.5%' scope="col"> <?php ob_start(); echo smarty_function_sugar_translate(array('label' => 'LBL_LAST_NAME','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?> <label for="last_name"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : smarty_modifier_strip_semicolon($_tmp)); ?> :</label> </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' colspan='3'> <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <?php if (strlen ( $this->_tpl_vars['fields']['last_name']['value'] ) <= 0): $this->assign('value', $this->_tpl_vars['fields']['last_name']['default_value']); else: $this->assign('value', $this->_tpl_vars['fields']['last_name']['value']); endif; ?> <input type='text' name='<?php echo $this->_tpl_vars['fields']['last_name']['name']; ?> ' id='<?php echo $this->_tpl_vars['fields']['last_name']['name']; ?> ' size='30' maxlength='15' value='<?php echo $this->_tpl_vars['value']; ?> ' title='' > </tr> <?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?> <?php endif; echo smarty_function_counter(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?> <?php ob_start(); ?> <tr> <td valign="top" id='website_label' width='12.5%' scope="col"> <?php ob_start(); echo smarty_function_sugar_translate(array('label' => 'LBL_WEBSITE','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?> <label for="website"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : smarty_modifier_strip_semicolon($_tmp)); ?> :</label> </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' colspan='3'> <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <?php if (! empty ( $this->_tpl_vars['fields']['website']['value'] )): ?> <input type='text' name='<?php echo $this->_tpl_vars['fields']['website']['name']; ?> ' id='<?php echo $this->_tpl_vars['fields']['website']['name']; ?> ' size='30' maxlength='255' value='<?php echo $this->_tpl_vars['fields']['website']['value']; ?> ' title='' tabindex='0' > <?php else: ?> <input type='text' name='<?php echo $this->_tpl_vars['fields']['website']['name']; ?> ' id='<?php echo $this->_tpl_vars['fields']['website']['name']; ?> ' size='30' maxlength='255' <?php if ($this->_tpl_vars['displayView'] == 'advanced_search' || $this->_tpl_vars['displayView'] == 'basic_search'): ?>value=''<?php else: ?>value='http://'<?php endif; ?> title='' tabindex='0' > <?php endif; ?> </tr> <?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?> <?php endif; echo smarty_function_counter(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?> <?php ob_start(); ?> <tr> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' colspan='2'> <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <script type="text/javascript" src='<?php echo smarty_function_sugar_getjspath(array('file' => "include/SugarFields/Fields/Address/SugarFieldAddress.js"), $this);?> '></script> <fieldset id='BILLING_address_fieldset'> <legend><?php echo smarty_function_sugar_translate(array('label' => 'LBL_BILLING_ADDRESS','module' => ''), $this);?> </legend> <table border="0" cellspacing="1" cellpadding="0" class="edit" width="100%"> <tr> <td valign="top" id="billing_address_street_label" width='25%' scope='row' > <label for="billing_address_street"><?php echo smarty_function_sugar_translate(array('label' => 'LBL_BILLING_STREET','module' => ''), $this);?> :</label> <?php if ($this->_tpl_vars['fields']['billing_address_street']['required'] || false): ?> <span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?> </span> <?php endif; ?> </td> <td width="*"> <textarea id="billing_address_street" name="billing_address_street" maxlength="150" rows="2" cols="30" tabindex="0"><?php echo $this->_tpl_vars['fields']['billing_address_street']['value']; ?> </textarea> </td> </tr> <tr> <td id="billing_address_city_label" width='%' scope='row' > <label for="billing_address_city"><?php echo smarty_function_sugar_translate(array('label' => 'LBL_CITY','module' => ''), $this);?> : <?php if ($this->_tpl_vars['fields']['billing_address_city']['required'] || false): ?> <span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?> </span> <?php endif; ?> </td> <td> <input type="text" name="billing_address_city" id="billing_address_city" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['billing_address_city']['value']; ?> ' tabindex="0"> </td> </tr> <tr> <td id="billing_address_state_label" width='%' scope='row' > <label for="billing_address_state"><?php echo smarty_function_sugar_translate(array('label' => 'LBL_STATE','module' => ''), $this);?> :</label> <?php if ($this->_tpl_vars['fields']['billing_address_state']['required'] || false): ?> <span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?> </span> <?php endif; ?> </td> <td> <input type="text" name="billing_address_state" id="billing_address_state" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['billing_address_state']['value']; ?> ' tabindex="0"> </td> </tr> <tr> <td id="billing_address_postalcode_label" width='%' scope='row' > <label for="billing_address_postalcode"><?php echo smarty_function_sugar_translate(array('label' => 'LBL_POSTAL_CODE','module' => ''), $this);?> :</label> <?php if ($this->_tpl_vars['fields']['billing_address_postalcode']['required'] || false): ?> <span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?> </span> <?php endif; ?> </td> <td> <input type="text" name="billing_address_postalcode" id="billing_address_postalcode" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['billing_address_postalcode']['value']; ?> ' tabindex="0"> </td> </tr> <tr> <td id="billing_address_country_label" width='%' scope='row' > <label for="billing_address_country"><?php echo smarty_function_sugar_translate(array('label' => 'LBL_COUNTRY','module' => ''), $this);?> :</label> <?php if ($this->_tpl_vars['fields']['billing_address_country']['required'] || false): ?> <span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?> </span> <?php endif; ?> </td> <td> <input type="text" name="billing_address_country" id="billing_address_country" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['billing_address_country']['value']; ?> ' tabindex="0"> </td> </tr> <tr> <td colspan='2' NOWRAP>&nbsp;</td> </tr> </table> </fieldset> <script type="text/javascript"> SUGAR.util.doWhen("typeof(SUGAR.AddressField) != 'undefined'", function(){ billing_address = new SUGAR.AddressField("billing_checkbox",'', 'billing'); }); </script> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' colspan='2'> <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <script type="text/javascript" src='<?php echo smarty_function_sugar_getjspath(array('file' => "include/SugarFields/Fields/Address/SugarFieldAddress.js"), $this);?> '></script> <fieldset id='SHIPPING_address_fieldset'> <legend><?php echo smarty_function_sugar_translate(array('label' => 'LBL_SHIPPING_ADDRESS','module' => ''), $this);?> </legend> <table border="0" cellspacing="1" cellpadding="0" class="edit" width="100%"> <tr> <td valign="top" id="shipping_address_street_label" width='25%' scope='row' > <label for="shipping_address_street"><?php echo smarty_function_sugar_translate(array('label' => 'LBL_SHIPPING_STREET','module' => ''), $this);?> :</label> <?php if ($this->_tpl_vars['fields']['shipping_address_street']['required'] || false): ?> <span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?> </span> <?php endif; ?> </td> <td width="*"> <textarea id="shipping_address_street" name="shipping_address_street" maxlength="150" rows="2" cols="30" tabindex="0"><?php echo $this->_tpl_vars['fields']['shipping_address_street']['value']; ?> </textarea> </td> </tr> <tr> <td id="shipping_address_city_label" width='%' scope='row' > <label for="shipping_address_city"><?php echo smarty_function_sugar_translate(array('label' => 'LBL_CITY','module' => ''), $this);?> : <?php if ($this->_tpl_vars['fields']['shipping_address_city']['required'] || false): ?> <span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?> </span> <?php endif; ?> </td> <td> <input type="text" name="shipping_address_city" id="shipping_address_city" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['shipping_address_city']['value']; ?> ' tabindex="0"> </td> </tr> <tr> <td id="shipping_address_state_label" width='%' scope='row' > <label for="shipping_address_state"><?php echo smarty_function_sugar_translate(array('label' => 'LBL_STATE','module' => ''), $this);?> :</label> <?php if ($this->_tpl_vars['fields']['shipping_address_state']['required'] || false): ?> <span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?> </span> <?php endif; ?> </td> <td> <input type="text" name="shipping_address_state" id="shipping_address_state" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['shipping_address_state']['value']; ?> ' tabindex="0"> </td> </tr> <tr> <td id="shipping_address_postalcode_label" width='%' scope='row' > <label for="shipping_address_postalcode"><?php echo smarty_function_sugar_translate(array('label' => 'LBL_POSTAL_CODE','module' => ''), $this);?> :</label> <?php if ($this->_tpl_vars['fields']['shipping_address_postalcode']['required'] || false): ?> <span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?> </span> <?php endif; ?> </td> <td> <input type="text" name="shipping_address_postalcode" id="shipping_address_postalcode" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['shipping_address_postalcode']['value']; ?> ' tabindex="0"> </td> </tr> <tr> <td id="shipping_address_country_label" width='%' scope='row' > <label for="shipping_address_country"><?php echo smarty_function_sugar_translate(array('label' => 'LBL_COUNTRY','module' => ''), $this);?> :</label> <?php if ($this->_tpl_vars['fields']['shipping_address_country']['required'] || false): ?> <span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?> </span> <?php endif; ?> </td> <td> <input type="text" name="shipping_address_country" id="shipping_address_country" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['shipping_address_country']['value']; ?> ' tabindex="0"> </td> </tr> <tr> <td scope='row' NOWRAP> <?php echo smarty_function_sugar_translate(array('label' => 'LBL_COPY_ADDRESS_FROM_LEFT','module' => ''), $this);?> : </td> <td> <input id="shipping_checkbox" name="shipping_checkbox" type="checkbox" onclick="shipping_address.syncFields();"> </td> </tr> </table> </fieldset> <script type="text/javascript"> SUGAR.util.doWhen("typeof(SUGAR.AddressField) != 'undefined'", function(){ shipping_address = new SUGAR.AddressField("shipping_checkbox",'billing', 'shipping'); }); </script> </tr> <?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?> <?php endif; echo smarty_function_counter(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?> <?php ob_start(); ?> <tr> <td valign="top" id='email1_label' width='12.5%' scope="col"> <?php ob_start(); echo smarty_function_sugar_translate(array('label' => 'LBL_EMAIL','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?> <label for="email1"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : smarty_modifier_strip_semicolon($_tmp)); ?> :</label> </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' > <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <?php echo $this->_tpl_vars['EMAIL']; ?> <td valign="top" id='phoneno_label' width='12.5%' scope="col"> <?php ob_start(); echo smarty_function_sugar_translate(array('label' => 'LBL_PHONENO','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?> <label for=""><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : smarty_modifier_strip_semicolon($_tmp)); ?> :</label> </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' > <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <?php echo $this->_tpl_vars['PHONENOS']; ?> </tr> <?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?> <?php endif; echo smarty_function_counter(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?> <?php ob_start(); ?> <tr> <td valign="top" id='description_label' width='12.5%' scope="col"> <?php ob_start(); echo smarty_function_sugar_translate(array('label' => 'LBL_DESCRIPTION','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?> <label for="description"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : smarty_modifier_strip_semicolon($_tmp)); ?> :</label> </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' > <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <?php if (empty ( $this->_tpl_vars['fields']['description']['value'] )): $this->assign('value', $this->_tpl_vars['fields']['description']['default_value']); else: $this->assign('value', $this->_tpl_vars['fields']['description']['value']); endif; ?> <textarea id='<?php echo $this->_tpl_vars['fields']['description']['name']; ?> ' name='<?php echo $this->_tpl_vars['fields']['description']['name']; ?> ' rows="6" cols="80" title='' tabindex="0" ><?php echo $this->_tpl_vars['value']; ?> </textarea> <td valign="top" id='phone_fax_label' width='12.5%' scope="col"> <?php ob_start(); echo smarty_function_sugar_translate(array('label' => 'LBL_FAX','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?> <label for="phone_fax"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : smarty_modifier_strip_semicolon($_tmp)); ?> :</label> </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' > <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <?php if (strlen ( $this->_tpl_vars['fields']['phone_fax']['value'] ) <= 0): $this->assign('value', $this->_tpl_vars['fields']['phone_fax']['default_value']); else: $this->assign('value', $this->_tpl_vars['fields']['phone_fax']['value']); endif; ?> <input type='text' name='<?php echo $this->_tpl_vars['fields']['phone_fax']['name']; ?> ' id='<?php echo $this->_tpl_vars['fields']['phone_fax']['name']; ?> ' size='30' maxlength='100' value='<?php echo $this->_tpl_vars['value']; ?> ' title='' tabindex='0' class="phone" > </tr> <?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?> <?php endif; echo smarty_function_counter(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?> <?php ob_start(); ?> <tr> <td valign="top" id='client_source_label' width='12.5%' scope="col"> <?php ob_start(); echo smarty_function_sugar_translate(array('label' => 'LBL_CLIENT_SOURCE','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?> <label for="client_source"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : smarty_modifier_strip_semicolon($_tmp)); ?> :</label> </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' colspan='3'> <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <?php if (! isset ( $this->_tpl_vars['config']['enable_autocomplete'] ) || $this->_tpl_vars['config']['enable_autocomplete'] == false): ?> <select name="<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> " id="<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> " title='' > <?php if (isset ( $this->_tpl_vars['fields']['client_source']['value'] ) && $this->_tpl_vars['fields']['client_source']['value'] != ''): echo smarty_function_html_options(array('options' => $this->_tpl_vars['fields']['client_source']['options'],'selected' => $this->_tpl_vars['fields']['client_source']['value']), $this);?> <?php else: echo smarty_function_html_options(array('options' => $this->_tpl_vars['fields']['client_source']['options'],'selected' => $this->_tpl_vars['fields']['client_source']['default']), $this);?> <?php endif; ?> </select> <?php else: $this->assign('field_options', $this->_tpl_vars['fields']['client_source']['options']); ob_start(); echo $this->_tpl_vars['fields']['client_source']['value']; $this->_smarty_vars['capture']['field_val'] = ob_get_contents(); ob_end_clean(); $this->assign('field_val', $this->_smarty_vars['capture']['field_val']); ob_start(); echo $this->_tpl_vars['fields']['client_source']['name']; $this->_smarty_vars['capture']['ac_key'] = ob_get_contents(); ob_end_clean(); $this->assign('ac_key', $this->_smarty_vars['capture']['ac_key']); ?> <select style='display:none' name="<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> " id="<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> " title='' > <?php if (isset ( $this->_tpl_vars['fields']['client_source']['value'] ) && $this->_tpl_vars['fields']['client_source']['value'] != ''): echo smarty_function_html_options(array('options' => $this->_tpl_vars['fields']['client_source']['options'],'selected' => $this->_tpl_vars['fields']['client_source']['value']), $this);?> <?php else: echo smarty_function_html_options(array('options' => $this->_tpl_vars['fields']['client_source']['options'],'selected' => $this->_tpl_vars['fields']['client_source']['default']), $this);?> <?php endif; ?> </select> <input id="<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> -input" name="<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> -input" size="30" value="<?php echo ((is_array($_tmp=$this->_tpl_vars['field_val'])) ? $this->_run_mod_handler('lookup', true, $_tmp, $this->_tpl_vars['field_options']) : smarty_modifier_lookup($_tmp, $this->_tpl_vars['field_options'])); ?> " type="text" style="vertical-align: top;"> <span class="id-ff multiple"> <button type="button"><img src="<?php echo smarty_function_sugar_getimagepath(array('file' => "id-ff-down.png"), $this);?> " id="<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> -image"></button><button type="button" id="btn-clear-<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> -input" title="Clear" onclick="SUGAR.clearRelateField(this.form, '<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> -input', '<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> ');sync_<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> ()"><img src="<?php echo smarty_function_sugar_getimagepath(array('file' => "id-ff-clear.png"), $this);?> "></button> </span> <?php echo ' <script> SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo ' = []; '; ?> <?php echo ' (function (){ var selectElem = document.getElementById("'; echo $this->_tpl_vars['fields']['client_source']['name']; echo '"); if (typeof select_defaults =="undefined") select_defaults = []; select_defaults[selectElem.id] = {key:selectElem.value,text:\'\'}; //get default for (i=0;i<selectElem.options.length;i++){ if (selectElem.options[i].value==selectElem.value) select_defaults[selectElem.id].text = selectElem.options[i].innerHTML; } //SUGAR.AutoComplete.{$ac_key}.ds = //get options array from vardefs var options = SUGAR.AutoComplete.getOptionsArray(""); YUI().use(\'datasource\', \'datasource-jsonschema\',function (Y) { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.ds = new Y.DataSource.Function({ source: function (request) { var ret = []; for (i=0;i<selectElem.options.length;i++) if (!(selectElem.options[i].value==\'\' && selectElem.options[i].innerHTML==\'\')) ret.push({\'key\':selectElem.options[i].value,\'text\':selectElem.options[i].innerHTML}); return ret; } }); }); })(); '; ?> <?php echo ' YUI().use("autocomplete", "autocomplete-filters", "autocomplete-highlighters", "node","node-event-simulate", function (Y) { '; ?> SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .inputNode = Y.one('#<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> -input'); SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .inputImage = Y.one('#<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> -image'); SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .inputHidden = Y.one('#<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> '); <?php echo ' function SyncToHidden(selectme){ var selectElem = document.getElementById("'; echo $this->_tpl_vars['fields']['client_source']['name']; echo '"); var doSimulateChange = false; if (selectElem.value!=selectme) doSimulateChange=true; selectElem.value=selectme; for (i=0;i<selectElem.options.length;i++){ selectElem.options[i].selected=false; if (selectElem.options[i].value==selectme) selectElem.options[i].selected=true; } if (doSimulateChange) SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.simulate(\'change\'); } //global variable sync_'; echo $this->_tpl_vars['fields']['client_source']['name']; echo ' = function(){ SyncToHidden(); } function syncFromHiddenToWidget(){ var selectElem = document.getElementById("'; echo $this->_tpl_vars['fields']['client_source']['name']; echo '"); //if select no longer on page, kill timer if (selectElem==null || selectElem.options == null) return; var currentvalue = SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.get(\'value\'); SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.simulate(\'keyup\'); for (i=0;i<selectElem.options.length;i++){ if (selectElem.options[i].value==selectElem.value && document.activeElement != document.getElementById(\''; echo $this->_tpl_vars['fields']['client_source']['name']; ?> -input<?php echo '\')) SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.set(\'value\',selectElem.options[i].innerHTML); } } YAHOO.util.Event.onAvailable("'; echo $this->_tpl_vars['fields']['client_source']['name']; echo '", syncFromHiddenToWidget); '; ?> SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .minQLen = 0; SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .queryDelay = 0; SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .numOptions = <?php echo count($this->_tpl_vars['field_options']); ?> ; if(SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .numOptions >= 300) <?php echo '{ '; ?> SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .minQLen = 1; SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .queryDelay = 200; <?php echo ' } '; ?> if(SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .numOptions >= 3000) <?php echo '{ '; ?> SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .minQLen = 1; SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .queryDelay = 500; <?php echo ' } '; ?> SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .optionsVisible = false; <?php echo ' SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.plug(Y.Plugin.AutoComplete, { activateFirstItem: true, '; ?> minQueryLength: SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .minQLen, queryDelay: SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .queryDelay, zIndex: 99999, <?php echo ' source: SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.ds, resultTextLocator: \'text\', resultHighlighter: \'phraseMatch\', resultFilters: \'phraseMatch\', }); SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.expandHover = function(ex){ var hover = YAHOO.util.Dom.getElementsByClassName(\'dccontent\'); if(hover[0] != null){ if (ex) { var h = \'1000px\'; hover[0].style.height = h; } else{ hover[0].style.height = \'\'; } } } if('; ?> SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .minQLen<?php echo ' == 0){ // expand the dropdown options upon focus SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.on(\'focus\', function () { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.ac.sendRequest(\'\'); SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.optionsVisible = true; }); } SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.on(\'click\', function(e) { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.simulate(\'click\'); }); SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.on(\'dblclick\', function(e) { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.simulate(\'dblclick\'); }); SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.on(\'focus\', function(e) { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.simulate(\'focus\'); }); SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.on(\'mouseup\', function(e) { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.simulate(\'mouseup\'); }); SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.on(\'mousedown\', function(e) { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.simulate(\'mousedown\'); }); SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.on(\'blur\', function(e) { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.simulate(\'blur\'); SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.optionsVisible = false; var selectElem = document.getElementById("'; echo $this->_tpl_vars['fields']['client_source']['name']; echo '"); //if typed value is a valid option, do nothing for (i=0;i<selectElem.options.length;i++) if (selectElem.options[i].innerHTML==SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.get(\'value\')) return; //typed value is invalid, so set the text and the hidden to blank SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.set(\'value\', select_defaults[selectElem.id].text); SyncToHidden(select_defaults[selectElem.id].key); }); // when they click on the arrow image, toggle the visibility of the options SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputImage.ancestor().on(\'click\', function () { if (SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.optionsVisible) { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.blur(); } else { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.focus(); } }); SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.ac.on(\'query\', function () { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.set(\'value\', \'\'); }); SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.ac.on(\'visibleChange\', function (e) { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.expandHover(e.newVal); // expand }); // when they select an option, set the hidden input with the KEY, to be saved SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.ac.on(\'select\', function(e) { SyncToHidden(e.result.raw.key); }); }); </script> '; ?> <?php endif; ?> </tr> <?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?> <?php endif; ?> </table> </div> <?php if ($this->_tpl_vars['panelFieldCount'] == 0): ?> <script>document.getElementById("LBL_ACCOUNT_INFORMATION").style.display='none';</script> <?php endif; ?> <div id="LBL_PANEL_PASSWORD"> <?php echo smarty_function_counter(array('name' => 'panelFieldCount','start' => 0,'print' => false,'assign' => 'panelFieldCount'), $this);?> <table width="100%" border="0" cellspacing="1" cellpadding="0" class="yui3-skin-sam <?php echo ((is_array($_tmp=@$this->_tpl_vars['def']['templateMeta']['panelClass'])) ? $this->_run_mod_handler('default', true, $_tmp, 'edit view dcQuickEdit edit508') : smarty_modifier_default($_tmp, 'edit view dcQuickEdit edit508')); ?> "> <tr> <th align="left" colspan="8"> <h4><?php echo smarty_function_sugar_translate(array('label' => 'LBL_PANEL_PASSWORD','module' => 'Accounts'), $this);?> </h4> </th> </tr> <?php echo smarty_function_counter(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?> <?php ob_start(); ?> <tr> <td valign="top" id='password_label' width='12.5%' scope="col"> <?php ob_start(); echo smarty_function_sugar_translate(array('label' => 'LBL_PASSWORD','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?> <label for="password"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : smarty_modifier_strip_semicolon($_tmp)); ?> :</label> </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' > <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <?php if (strlen ( $this->_tpl_vars['fields']['password']['value'] ) <= 0): $this->assign('value', $this->_tpl_vars['fields']['password']['default_value']); else: $this->assign('value', $this->_tpl_vars['fields']['password']['value']); endif; ?> <input type='text' name='<?php echo $this->_tpl_vars['fields']['password']['name']; ?> ' id='<?php echo $this->_tpl_vars['fields']['password']['name']; ?> ' size='30' maxlength='15' value='<?php echo $this->_tpl_vars['value']; ?> ' title='' > <td valign="top" id='LBL_PASSWORD_label' width='12.5%' scope="col"> &nbsp; </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' > <td valign="top" id='_label' width='%' scope="col"> &nbsp; </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='%' > </tr> <?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?> <?php endif; ?> </table> </div> <?php if ($this->_tpl_vars['panelFieldCount'] == 0): ?> <script>document.getElementById("LBL_PANEL_PASSWORD").style.display='none';</script> <?php endif; ?> <div id="LBL_PANEL_ASSIGNMENT"> <?php echo smarty_function_counter(array('name' => 'panelFieldCount','start' => 0,'print' => false,'assign' => 'panelFieldCount'), $this);?> <table width="100%" border="0" cellspacing="1" cellpadding="0" class="yui3-skin-sam <?php echo ((is_array($_tmp=@$this->_tpl_vars['def']['templateMeta']['panelClass'])) ? $this->_run_mod_handler('default', true, $_tmp, 'edit view dcQuickEdit edit508') : smarty_modifier_default($_tmp, 'edit view dcQuickEdit edit508')); ?> "> <tr> <th align="left" colspan="8"> <h4><?php echo smarty_function_sugar_translate(array('label' => 'LBL_PANEL_ASSIGNMENT','module' => 'Accounts'), $this);?> </h4> </th> </tr> <?php echo smarty_function_counter(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?> <?php ob_start(); ?> <tr> <td valign="top" id='assigned_user_name_label' width='12.5%' scope="col"> <?php ob_start(); echo smarty_function_sugar_translate(array('label' => 'LBL_ASSIGNED_TO','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?> <label for="assigned_user_name"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : smarty_modifier_strip_semicolon($_tmp)); ?> :</label> </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' colspan='3'> <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <input type="text" name="<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?> " class="sqsEnabled" tabindex="0" id="<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?> " size="" value="<?php echo $this->_tpl_vars['fields']['assigned_user_name']['value']; ?> " title='' autocomplete="off" > <input type="hidden" name="<?php echo $this->_tpl_vars['fields']['assigned_user_name']['id_name']; ?> " id="<?php echo $this->_tpl_vars['fields']['assigned_user_name']['id_name']; ?> " value="<?php echo $this->_tpl_vars['fields']['assigned_user_id']['value']; ?> "> <span class="id-ff multiple"> <button type="button" name="btn_<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?> " id="btn_<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?> " tabindex="0" title="<?php echo smarty_function_sugar_translate(array('label' => 'LBL_ACCESSKEY_SELECT_USERS_TITLE'), $this);?> " class="button firstChild" value="<?php echo smarty_function_sugar_translate(array('label' => 'LBL_ACCESSKEY_SELECT_USERS_LABEL'), $this);?> " onclick='open_popup( "<?php echo $this->_tpl_vars['fields']['assigned_user_name']['module']; ?> ", 600, 400, "", true, false, <?php echo '{"call_back_function":"set_return","form_name":"EditView","field_to_name_array":{"id":"assigned_user_id","user_name":"assigned_user_name"}}'; ?> , "single", true );' ><img src="<?php echo smarty_function_sugar_getimagepath(array('file' => "id-ff-select.png"), $this);?> "></button><button type="button" name="btn_clr_<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?> " id="btn_clr_<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?> " tabindex="0" title="<?php echo smarty_function_sugar_translate(array('label' => 'LBL_ACCESSKEY_CLEAR_USERS_TITLE'), $this);?> " class="button lastChild" onclick="SUGAR.clearRelateField(this.form, '<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?> ', '<?php echo $this->_tpl_vars['fields']['assigned_user_name']['id_name']; ?> ');" value="<?php echo smarty_function_sugar_translate(array('label' => 'LBL_ACCESSKEY_CLEAR_USERS_LABEL'), $this);?> " ><img src="<?php echo smarty_function_sugar_getimagepath(array('file' => "id-ff-clear.png"), $this);?> "></button> </span> <script type="text/javascript"> SUGAR.util.doWhen( "typeof(sqs_objects) != 'undefined' && typeof(sqs_objects['<?php echo $this->_tpl_vars['form_name']; ?> _<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?> ']) != 'undefined'", enableQS ); </script> </tr> <?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?> <?php endif; ?> </table> </div> <?php if ($this->_tpl_vars['panelFieldCount'] == 0): ?> <script>document.getElementById("LBL_PANEL_ASSIGNMENT").style.display='none';</script> <?php endif; ?> </div></div> <div class="buttons"> <input type="submit" id="SAVE" value="Save" name="button" title="Save" accessKey="a" class="button primary" onclick="this.form.action.value='Save'; saveClickCheckPrimary(); if(check_form('EditView'))SUGAR.ajaxUI.submitForm(this.form);return false; " value="Save" > <?php if (! empty ( $_REQUEST['return_action'] ) && ( $_REQUEST['return_action'] == 'DetailView' && ! empty ( $_REQUEST['return_id'] ) )): ?><input title="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_TITLE']; ?> " accessKey="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_KEY']; ?> " class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=DetailView&module=<?php echo $_REQUEST['return_module']; ?> &record=<?php echo $_REQUEST['return_id']; ?> '); return false;" name="button" value="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_LABEL']; ?> " type="button" id="CANCEL"> <?php elseif (! empty ( $_REQUEST['return_action'] ) && ( $_REQUEST['return_action'] == 'DetailView' && ! empty ( $this->_tpl_vars['fields']['id']['value'] ) )): ?><input title="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_TITLE']; ?> " accessKey="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_KEY']; ?> " class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=DetailView&module=<?php echo $_REQUEST['return_module']; ?> &record=<?php echo $this->_tpl_vars['fields']['id']['value']; ?> '); return false;" type="button" name="button" value="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_LABEL']; ?> " id="CANCEL"> <?php elseif (empty ( $_REQUEST['return_action'] ) || empty ( $_REQUEST['return_id'] ) && ! empty ( $this->_tpl_vars['fields']['id']['value'] )): ?><input title="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_TITLE']; ?> " accessKey="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_KEY']; ?> " class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=index&module=Accounts'); return false;" type="button" name="button" value="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_LABEL']; ?> " id="CANCEL"> <?php else: ?><input title="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_TITLE']; ?> " accessKey="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_KEY']; ?> " class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=index&module=<?php echo $_REQUEST['return_module']; ?> &record=<?php echo $_REQUEST['return_id']; ?> '); return false;" type="button" name="button" value="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_LABEL']; ?> " id="CANCEL"> <?php endif; if ($this->_tpl_vars['bean']->aclAccess('detail')): if (! empty ( $this->_tpl_vars['fields']['id']['value'] ) && $this->_tpl_vars['isAuditEnabled']): ?><input id="btn_view_change_log" title="<?php echo $this->_tpl_vars['APP']['LNK_VIEW_CHANGE_LOG']; ?> " class="button" onclick='open_popup("Audit", "600", "400", "&record=<?php echo $this->_tpl_vars['fields']['id']['value']; ?> &module_name=Accounts", true, false, { "call_back_function":"set_return","form_name":"EditView","field_to_name_array":[] } ); return false;' type="button" value="<?php echo $this->_tpl_vars['APP']['LNK_VIEW_CHANGE_LOG']; ?> "><?php endif; endif; ?> </div> </form> <?php echo $this->_tpl_vars['set_focus_block']; ?> <script>SUGAR.util.doWhen("document.getElementById('EditView') != null", function(){SUGAR.util.buildAccessKeyLabels();}); </script><?php echo $this->_tpl_vars['overlibStuff']; ?> <script type="text/javascript"> YAHOO.util.Event.onContentReady("EditView", function () { initEditView(document.forms.EditView) }); //window.setTimeout(, 100); window.onbeforeunload = function () { return onUnloadEditView(); }; </script><?php echo ' <script type="text/javascript"> addForm(\'EditView\');addToValidate(\'EditView\', \'name\', \'name\', true,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_NAME','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'date_entered_date\', \'date\', false,\'Date Created\' ); addToValidate(\'EditView\', \'date_modified_date\', \'date\', false,\'Date Modified\' ); addToValidate(\'EditView\', \'modified_user_id\', \'assigned_user_name\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_MODIFIED','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'modified_by_name\', \'relate\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_MODIFIED_NAME','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'created_by\', \'assigned_user_name\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_CREATED','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'created_by_name\', \'relate\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_CREATED','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'description\', \'text\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_DESCRIPTION','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'deleted\', \'bool\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_DELETED','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'assigned_user_id\', \'relate\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_ASSIGNED_TO_ID','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'assigned_user_name\', \'relate\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_ASSIGNED_TO_NAME','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'account_type\', \'enum\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_TYPE','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'industry\', \'enum\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_INDUSTRY','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'annual_revenue\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_ANNUAL_REVENUE','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'phone_fax\', \'phone\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_FAX','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'billing_address_street\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_BILLING_ADDRESS_STREET','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'billing_address_street_2\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_BILLING_ADDRESS_STREET_2','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'billing_address_street_3\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_BILLING_ADDRESS_STREET_3','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'billing_address_street_4\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_BILLING_ADDRESS_STREET_4','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'billing_address_city\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_BILLING_ADDRESS_CITY','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'billing_address_state\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_BILLING_ADDRESS_STATE','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'billing_address_postalcode\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_BILLING_ADDRESS_POSTALCODE','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'billing_address_country\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_BILLING_ADDRESS_COUNTRY','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'rating\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_RATING','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'phone_office\', \'phone\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_PHONE_OFFICE','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'phone_alternate\', \'phone\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_PHONE_ALT','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'website\', \'url\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_WEBSITE','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'ownership\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_OWNERSHIP','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'employees\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_EMPLOYEES','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'ticker_symbol\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_TICKER_SYMBOL','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'shipping_address_street\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_SHIPPING_ADDRESS_STREET','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'shipping_address_street_2\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_SHIPPING_ADDRESS_STREET_2','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'shipping_address_street_3\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_SHIPPING_ADDRESS_STREET_3','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'shipping_address_street_4\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_SHIPPING_ADDRESS_STREET_4','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'shipping_address_city\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_SHIPPING_ADDRESS_CITY','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'shipping_address_state\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_SHIPPING_ADDRESS_STATE','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'shipping_address_postalcode\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_SHIPPING_ADDRESS_POSTALCODE','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'shipping_address_country\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_SHIPPING_ADDRESS_COUNTRY','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'email1\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_EMAIL','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'accountfilter\', \'enum\', false,\''; echo smarty_function_sugar_translate(array('label' => '','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'viewasfilter\', \'enum\', false,\''; echo smarty_function_sugar_translate(array('label' => '','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'client_source\', \'enum\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_CLIENT_SOURCE','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'first_name\', \'varchar\', true,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_FIRST_NAME','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'call_time\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_CALL_TIME','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'last_name\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_LAST_NAME','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'parent_id\', \'id\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_PARENT_ACCOUNT_ID','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'sic_code\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_SIC_CODE','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'parent_name\', \'relate\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_MEMBER_OF','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'email_opt_out\', \'bool\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_EMAIL_OPT_OUT','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'invalid_email\', \'bool\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_INVALID_EMAIL','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'email\', \'email\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_ANY_EMAIL','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'campaign_id\', \'id\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_CAMPAIGN_ID','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'campaign_name\', \'relate\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_CAMPAIGN','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'password\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_PASSWORD','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'zohoid\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_ZOHOID','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'mobile\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_MOBILE','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidateBinaryDependency(\'EditView\', \'assigned_user_name\', \'alpha\', false,\''; echo smarty_function_sugar_translate(array('label' => 'ERR_SQS_NO_MATCH_FIELD','module' => 'Accounts','for_js' => true), $this); echo ': '; echo smarty_function_sugar_translate(array('label' => 'LBL_ASSIGNED_TO','module' => 'Accounts','for_js' => true), $this); echo '\', \'assigned_user_id\' ); </script><script language="javascript">if(typeof sqs_objects == \'undefined\'){var sqs_objects = new Array;}sqs_objects[\'EditView_assigned_user_name\']={"form":"EditView","method":"get_user_array","field_list":["user_name","id"],"populate_list":["assigned_user_name","assigned_user_id"],"required_list":["assigned_user_id"],"conditions":[{"name":"user_name","op":"like_custom","end":"%","value":""}],"limit":"30","no_match_text":"No Match"};</script>'; ?>
acuteventures/CRM
cache/smarty/templates_c/%%F7^F76^F763801C%%EditView.tpl.php
PHP
agpl-3.0
62,985
/* Copyright (C) 2016 Anki Universal Team <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Text; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace AnkiU.UserControls { public sealed partial class RichEditBoxContentDialog : ContentDialog { public string Text { get; set; } public RichEditBoxContentDialog(string text) { this.InitializeComponent(); richEditBox.Document.SetText(TextSetOptions.None, text); } private void OkButtonClickHandler(ContentDialog sender, ContentDialogButtonClickEventArgs args) { string text; richEditBox.Document.GetText(TextGetOptions.None, out text); Text = text; this.Hide(); } private void CancelButtonClickHandler(ContentDialog sender, ContentDialogButtonClickEventArgs args) { Text = null; this.Hide(); } } }
AnkiUniversal/Anki-Universal
AnkiU/UserControls/RichEditBoxContentDialog.xaml.cs
C#
agpl-3.0
1,960
package integration.tests; import static org.junit.Assert.assertEquals; import gr.ntua.vision.monitoring.VismoConfiguration; import gr.ntua.vision.monitoring.VismoVMInfo; import gr.ntua.vision.monitoring.dispatch.VismoEventDispatcher; import gr.ntua.vision.monitoring.events.MonitoringEvent; import gr.ntua.vision.monitoring.notify.VismoEventRegistry; import gr.ntua.vision.monitoring.rules.Rule; import gr.ntua.vision.monitoring.rules.VismoRulesEngine; import gr.ntua.vision.monitoring.service.ClusterHeadNodeFactory; import gr.ntua.vision.monitoring.service.Service; import gr.ntua.vision.monitoring.service.VismoService; import gr.ntua.vision.monitoring.zmq.ZMQFactory; import java.io.IOException; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zeromq.ZContext; /** * This is used to test the general facilities of the {@link VismoService}; thus is should receive events from producers, process * them in a rules engine and dispatch them to consumers. */ public class VismoServiceTest { /** * This is used to count the number of events received. */ private final class EventCountRule extends Rule { /***/ private int counter = 0; /** * Constructor. * * @param engine */ public EventCountRule(final VismoRulesEngine engine) { super(engine); } /** * @param expectedNoEvents */ public void hasSeenExpectedNoEvents(final int expectedNoEvents) { assertEquals(expectedNoEvents, counter); } /** * @see gr.ntua.vision.monitoring.rules.RuleProc#performWith(java.lang.Object) */ @Override public void performWith(final MonitoringEvent e) { if (e != null) ++counter; } } /** the log target. */ private static final Logger log = LoggerFactory.getLogger(VismoServiceTest.class); /***/ private static final int NO_GET_OPS = 100; /***/ private static final int NO_PUT_OPS = 100; /***/ @SuppressWarnings("serial") private static final Properties p = new Properties() { { setProperty("cloud.name", "visioncloud.eu"); setProperty("cloud.heads", "10.0.2.211, 10.0.2.212"); setProperty("cluster.name", "vision-1"); setProperty("cluster.head", "10.0.2.211"); setProperty("producers.point", "tcp://127.0.0.1:56429"); setProperty("consumers.port", "56430"); setProperty("udp.port", "56431"); setProperty("cluster.head.port", "56432"); setProperty("cloud.head.port", "56433"); setProperty("mon.group.addr", "228.5.6.7"); setProperty("mon.group.port", "12345"); setProperty("mon.ping.period", "60000"); setProperty("startup.rules", "PassThroughRule"); setProperty("web.port", "9996"); } }; /***/ EventCountRule countRule; /***/ private final VismoConfiguration conf = new VismoConfiguration(p); /***/ private FakeObjectService obs; /** the object under test. */ private Service service; /** the socket factory. */ private final ZMQFactory socketFactory = new ZMQFactory(new ZContext()); /** * @throws IOException */ @Before public void setUp() throws IOException { obs = new FakeObjectService(new VismoEventDispatcher(socketFactory, conf, "fake-obs")); service = new ClusterHeadNodeFactory(conf, socketFactory) { @Override protected void submitRules(final VismoRulesEngine engine) { countRule = new EventCountRule(engine); countRule.submit(); super.submitRules(engine); } }.build(new VismoVMInfo()); } /***/ @After public void tearDown() { if (service != null) service.halt(); } /** * @throws InterruptedException */ @Test public void vismoDeliversEventsToClient() throws InterruptedException { final VismoEventRegistry reg = new VismoEventRegistry(socketFactory, "tcp://127.0.0.1:" + conf.getConsumersPort()); final CountDownLatch latch = new CountDownLatch(1); final ConsumerHandler consumer = new ConsumerHandler(latch, NO_GET_OPS + NO_PUT_OPS); service.start(); reg.registerToAll(consumer); final long start = System.currentTimeMillis(); doGETs(NO_GET_OPS); doPUTs(NO_PUT_OPS); log.debug("waiting event delivery..."); latch.await(10, TimeUnit.SECONDS); final double dur = (System.currentTimeMillis() - start) / 1000.0; log.debug("{} events delivered to client in {} sec ({} events/sec)", new Object[] { consumer.getNoReceivedEvents(), dur, consumer.getNoReceivedEvents() / dur }); consumerHasReceivedExpectedNoEvents(consumer, NO_GET_OPS + NO_PUT_OPS); } /** * @throws InterruptedException */ @Test public void vismoReceivesEventsFromProducers() throws InterruptedException { service.start(); doGETs(NO_GET_OPS); doPUTs(NO_PUT_OPS); waitForEventsDelivery(2000); assertThatVismoReceivedEvents(); } /***/ private void assertThatVismoReceivedEvents() { countRule.hasSeenExpectedNoEvents(NO_GET_OPS + NO_PUT_OPS); } /** * @param noOps */ private void doGETs(final int noOps) { for (int i = 0; i < noOps; ++i) obs.getEvent("ntua", "bill", "foo-container", "bar-object").send(); } /** * @param noOps */ private void doPUTs(final int noOps) { for (int i = 0; i < noOps; ++i) obs.putEvent("ntua", "bill", "foo-container", "bar-object").send(); } /** * @param consumerHandler * @param expectedNoEvents */ private static void consumerHasReceivedExpectedNoEvents(final ConsumerHandler consumerHandler, final int expectedNoEvents) { assertEquals(expectedNoEvents, consumerHandler.getNoReceivedEvents()); } /** * @param n * @throws InterruptedException */ private static void waitForEventsDelivery(final int n) throws InterruptedException { Thread.sleep(n); } }
spyrosg/VISION-Cloud-Monitoring
vismo-core/src/test/java/integration/tests/VismoServiceTest.java
Java
agpl-3.0
7,451
DELETE FROM `weenie` WHERE `class_Id` = 38241; INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`) VALUES (38241, 'ace38241-kaymoribndumandi', 10, '2019-02-10 00:00:00') /* Creature */; INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`) VALUES (38241, 1, 16) /* ItemType - Creature */ , (38241, 2, 31) /* CreatureType - Human */ , (38241, 6, -1) /* ItemsCapacity */ , (38241, 7, -1) /* ContainersCapacity */ , (38241, 16, 32) /* ItemUseable - Remote */ , (38241, 25, 220) /* Level */ , (38241, 93, 6292504) /* PhysicsState - ReportCollisions, IgnoreCollisions, Gravity, ReportCollisionsAsEnvironment, EdgeSlide */ , (38241, 95, 8) /* RadarBlipColor - Yellow */ , (38241, 113, 1) /* Gender - Male */ , (38241, 133, 4) /* ShowableOnRadar - ShowAlways */ , (38241, 134, 16) /* PlayerKillerStatus - RubberGlue */ , (38241, 188, 2) /* HeritageGroup - Gharundim */ , (38241, 281, 1) /* Faction1Bits */ , (38241, 287, 1001) /* SocietyRankCelhan */ , (38241, 8007, 0) /* PCAPRecordedAutonomousMovement */; INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`) VALUES (38241, 1, True ) /* Stuck */ , (38241, 19, False) /* Attackable */; INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`) VALUES (38241, 54, 3) /* UseRadius */; INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`) VALUES (38241, 1, 'Kaymor ibn Dumandi') /* Name */ , (38241, 5, 'High Priest Task Master') /* Template */ , (38241, 8006, 'AAA9AAAAAAA=') /* PCAPRecordedCurrentMotionState */; INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`) VALUES (38241, 1, 33554433) /* Setup */ , (38241, 2, 150994945) /* MotionTable */ , (38241, 3, 536870913) /* SoundTable */ , (38241, 6, 67108990) /* PaletteBase */ , (38241, 8, 100667446) /* Icon */ , (38241, 9, 83890483) /* EyesTexture */ , (38241, 10, 83890559) /* NoseTexture */ , (38241, 11, 83890601) /* MouthTexture */ , (38241, 15, 67117077) /* HairPalette */ , (38241, 16, 67109567) /* EyesPalette */ , (38241, 17, 67109553) /* SkinPalette */ , (38241, 8001, 9437238) /* PCAPRecordedWeenieHeader - ItemsCapacity, ContainersCapacity, Usable, UseRadius, RadarBlipColor, RadarBehavior */ , (38241, 8003, 4) /* PCAPRecordedObjectDesc - Stuck */ , (38241, 8005, 100355) /* PCAPRecordedPhysicsDesc - CSetup, MTable, STable, Position, Movement */; INSERT INTO `weenie_properties_position` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`) VALUES (38241, 8040, 11993711, 158.402, -39.5452, -17.995, -0.83954, 0, 0, 0.543297) /* PCAPRecordedLocation */ /* @teleloc 0x00B7026F [158.402000 -39.545200 -17.995000] -0.839540 0.000000 0.000000 0.543297 */; INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`) VALUES (38241, 8000, 3359479986) /* PCAPRecordedObjectIID */; INSERT INTO `weenie_properties_attribute` (`object_Id`, `type`, `init_Level`, `level_From_C_P`, `c_P_Spent`) VALUES (38241, 1, 255, 0, 0) /* Strength */ , (38241, 2, 220, 0, 0) /* Endurance */ , (38241, 3, 240, 0, 0) /* Quickness */ , (38241, 4, 240, 0, 0) /* Coordination */ , (38241, 5, 90, 0, 0) /* Focus */ , (38241, 6, 90, 0, 0) /* Self */; INSERT INTO `weenie_properties_attribute_2nd` (`object_Id`, `type`, `init_Level`, `level_From_C_P`, `c_P_Spent`, `current_Level`) VALUES (38241, 1, 125, 0, 0, 235) /* MaxHealth */ , (38241, 3, 110, 0, 0, 330) /* MaxStamina */ , (38241, 5, 55, 0, 0, 145) /* MaxMana */; INSERT INTO `weenie_properties_palette` (`object_Id`, `sub_Palette_Id`, `offset`, `length`) VALUES (38241, 67109553, 0, 24) , (38241, 67109567, 32, 8) , (38241, 67110026, 136, 16) , (38241, 67110026, 96, 12) , (38241, 67110026, 116, 12) , (38241, 67110347, 40, 24) , (38241, 67110385, 160, 8) , (38241, 67110549, 92, 4) , (38241, 67117077, 24, 8); INSERT INTO `weenie_properties_texture_map` (`object_Id`, `index`, `old_Id`, `new_Id`) VALUES (38241, 0, 83889072, 83886685) , (38241, 0, 83889342, 83889386) , (38241, 1, 83887064, 83886807) , (38241, 2, 83887066, 83887051) , (38241, 3, 83889344, 83887054) , (38241, 4, 83887068, 83887054) , (38241, 5, 83887064, 83886807) , (38241, 6, 83887066, 83887051) , (38241, 7, 83889344, 83887054) , (38241, 8, 83887068, 83887054) , (38241, 9, 83887061, 83886687) , (38241, 9, 83887060, 83886686) , (38241, 10, 83887069, 83886782) , (38241, 10, 83886796, 83886817) , (38241, 11, 83887067, 83891213) , (38241, 11, 83886788, 83886802) , (38241, 13, 83887069, 83886782) , (38241, 13, 83886796, 83886817) , (38241, 14, 83887067, 83891213) , (38241, 14, 83886788, 83886802) , (38241, 16, 83886232, 83890685) , (38241, 16, 83886668, 83890483) , (38241, 16, 83886837, 83890559) , (38241, 16, 83886684, 83890601); INSERT INTO `weenie_properties_anim_part` (`object_Id`, `index`, `animation_Id`) VALUES (38241, 0, 16793839) , (38241, 1, 16781848) , (38241, 2, 16781866) , (38241, 3, 16781841) , (38241, 4, 16781838) , (38241, 5, 16781847) , (38241, 6, 16781864) , (38241, 7, 16781840) , (38241, 8, 16781839) , (38241, 9, 16793840) , (38241, 10, 16781872) , (38241, 11, 16781861) , (38241, 12, 16777304) , (38241, 13, 16781871) , (38241, 14, 16781862) , (38241, 15, 16777307) , (38241, 16, 16795662);
LtRipley36706/ACE-World
Database/3-Core/9 WeenieDefaults/SQL/Creature/Human/38241 Kaymor ibn Dumandi.sql
SQL
agpl-3.0
5,865
/* This file is part of VoltDB. * Copyright (C) 2008-2014 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb; import java.util.HashMap; import java.util.Map.Entry; import java.util.Set; import org.voltcore.logging.Level; import org.voltcore.logging.VoltLogger; import org.voltdb.SystemProcedureCatalog.Config; import org.voltdb.catalog.CatalogMap; import org.voltdb.catalog.Procedure; import org.voltdb.compiler.Language; import org.voltdb.groovy.GroovyScriptProcedureDelegate; import org.voltdb.utils.LogKeys; import com.google_voltpatches.common.collect.ImmutableMap; public class LoadedProcedureSet { private static final VoltLogger hostLog = new VoltLogger("HOST"); // user procedures. ImmutableMap<String, ProcedureRunner> procs = ImmutableMap.<String, ProcedureRunner>builder().build(); // map of sysproc fragment ids to system procedures. final HashMap<Long, ProcedureRunner> m_registeredSysProcPlanFragments = new HashMap<Long, ProcedureRunner>(); final ProcedureRunnerFactory m_runnerFactory; final long m_siteId; final int m_siteIndex; final SiteProcedureConnection m_site; public LoadedProcedureSet(SiteProcedureConnection site, ProcedureRunnerFactory runnerFactory, long siteId, int siteIndex) { m_runnerFactory = runnerFactory; m_siteId = siteId; m_siteIndex = siteIndex; m_site = site; } public ProcedureRunner getSysproc(long fragmentId) { synchronized (m_registeredSysProcPlanFragments) { return m_registeredSysProcPlanFragments.get(fragmentId); } } public void registerPlanFragment(final long pfId, final ProcedureRunner proc) { synchronized (m_registeredSysProcPlanFragments) { assert(m_registeredSysProcPlanFragments.containsKey(pfId) == false); m_registeredSysProcPlanFragments.put(pfId, proc); } } public void loadProcedures( CatalogContext catalogContext, BackendTarget backendTarget, CatalogSpecificPlanner csp) { m_registeredSysProcPlanFragments.clear(); ImmutableMap.Builder<String, ProcedureRunner> builder = loadProceduresFromCatalog(catalogContext, backendTarget, csp); loadSystemProcedures(catalogContext, backendTarget, csp, builder); procs = builder.build(); } private ImmutableMap.Builder<String, ProcedureRunner> loadProceduresFromCatalog( CatalogContext catalogContext, BackendTarget backendTarget, CatalogSpecificPlanner csp) { // load up all the stored procedures final CatalogMap<Procedure> catalogProcedures = catalogContext.database.getProcedures(); ImmutableMap.Builder<String, ProcedureRunner> builder = ImmutableMap.<String, ProcedureRunner>builder(); for (final Procedure proc : catalogProcedures) { // Sysprocs used to be in the catalog. Now they aren't. Ignore // sysprocs found in old catalog versions. (PRO-365) if (proc.getTypeName().startsWith("@")) { continue; } ProcedureRunner runner = null; VoltProcedure procedure = null; if (proc.getHasjava()) { final String className = proc.getClassname(); Language lang; try { lang = Language.valueOf(proc.getLanguage()); } catch (IllegalArgumentException e) { // default to java for earlier compiled catalogs lang = Language.JAVA; } Class<?> procClass = null; try { procClass = catalogContext.classForProcedure(className); } catch (final ClassNotFoundException e) { if (className.startsWith("org.voltdb.")) { VoltDB.crashLocalVoltDB("VoltDB does not support procedures with package names " + "that are prefixed with \"org.voltdb\". Please use a different " + "package name and retry. Procedure name was " + className + ".", false, null); } else { VoltDB.crashLocalVoltDB("VoltDB was unable to load a procedure (" + className + ") it expected to be in the " + "catalog jarfile and will now exit.", false, null); } } try { procedure = lang.accept(procedureInstantiator, procClass); } catch (final Exception e) { hostLog.l7dlog( Level.WARN, LogKeys.host_ExecutionSite_GenericException.name(), new Object[] { m_siteId, m_siteIndex }, e); } } else { procedure = new ProcedureRunner.StmtProcedure(); } assert(procedure != null); runner = m_runnerFactory.create(procedure, proc, csp); builder.put(proc.getTypeName().intern(), runner); } return builder; } private static Language.CheckedExceptionVisitor<VoltProcedure, Class<?>, Exception> procedureInstantiator = new Language.CheckedExceptionVisitor<VoltProcedure, Class<?>, Exception>() { @Override public VoltProcedure visitJava(Class<?> p) throws Exception { return (VoltProcedure)p.newInstance(); } @Override public VoltProcedure visitGroovy(Class<?> p) throws Exception { return new GroovyScriptProcedureDelegate(p); } }; private void loadSystemProcedures( CatalogContext catalogContext, BackendTarget backendTarget, CatalogSpecificPlanner csp, ImmutableMap.Builder<String, ProcedureRunner> builder) { Set<Entry<String,Config>> entrySet = SystemProcedureCatalog.listing.entrySet(); for (Entry<String, Config> entry : entrySet) { Config sysProc = entry.getValue(); Procedure proc = sysProc.asCatalogProcedure(); VoltSystemProcedure procedure = null; ProcedureRunner runner = null; final String className = sysProc.getClassname(); Class<?> procClass = null; // this check is for sysprocs that don't have a procedure class if (className != null) { try { procClass = catalogContext.classForProcedure(className); } catch (final ClassNotFoundException e) { if (sysProc.commercial) { continue; } hostLog.l7dlog( Level.WARN, LogKeys.host_ExecutionSite_GenericException.name(), new Object[] { m_siteId, m_siteIndex }, e); VoltDB.crashLocalVoltDB(e.getMessage(), true, e); } try { procedure = (VoltSystemProcedure) procClass.newInstance(); } catch (final InstantiationException e) { hostLog.l7dlog( Level.WARN, LogKeys.host_ExecutionSite_GenericException.name(), new Object[] { m_siteId, m_siteIndex }, e); } catch (final IllegalAccessException e) { hostLog.l7dlog( Level.WARN, LogKeys.host_ExecutionSite_GenericException.name(), new Object[] { m_siteId, m_siteIndex }, e); } runner = m_runnerFactory.create(procedure, proc, csp); procedure.initSysProc(m_site, this, proc, catalogContext.cluster); builder.put(entry.getKey().intern(), runner); } } } public ProcedureRunner getProcByName(String procName) { return procs.get(procName); } }
zheguang/voltdb
src/frontend/org/voltdb/LoadedProcedureSet.java
Java
agpl-3.0
8,988
/** * ISARI Import Scripts File Definitions * ====================================== * * Defining the various files to import as well as their line consumers. */ module.exports = { organizations: require('./organizations.js'), people: require('./people.js'), activities: require('./activities.js'), postProcessing: require('./post-processing.js') };
SciencesPo/isari
scripts/import/files/index.js
JavaScript
agpl-3.0
363
/* * Copyright © Région Nord Pas de Calais-Picardie. * * This file is part of OPEN ENT NG. OPEN ENT NG is a versatile ENT Project based on the JVM and ENT Core Project. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation (version 3 of the License). * * For the sake of explanation, any module that communicate over native * Web protocols, such as HTTP, with OPEN ENT NG is outside the scope of this * license and could be license under its own terms. This is merely considered * normal use of OPEN ENT NG, and does not fall under the heading of "covered work". * * 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. */ package org.entcore.cursus.controllers; import java.net.URL; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Map; import io.vertx.core.http.*; import org.entcore.common.http.filter.ResourceFilter; import org.entcore.common.user.UserInfos; import org.entcore.common.user.UserUtils; import org.entcore.common.utils.MapFactory; import org.entcore.cursus.filters.CursusFilter; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import org.vertx.java.core.http.RouteMatcher; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import fr.wseduc.rs.*; import fr.wseduc.security.ActionType; import fr.wseduc.security.SecuredAction; import fr.wseduc.webutils.Either; import fr.wseduc.webutils.http.BaseController; public class CursusController extends BaseController { //Service private final CursusService service = new CursusService(); //Webservice client & endpoint private HttpClient cursusClient; private final URL wsEndpoint; //Webservice auth request conf private final JsonObject authConf; //Auth reply data & wallets list private Map<String, String> cursusMap; @Override public void init(Vertx vertx, JsonObject config, RouteMatcher rm, Map<String, fr.wseduc.webutils.security.SecuredAction> securedActions) { super.init(vertx, config, rm, securedActions); HttpClientOptions cursusClientOptions = new HttpClientOptions() .setDefaultHost(wsEndpoint.getHost()); if("https".equals(wsEndpoint.getProtocol())){ cursusClientOptions .setSsl(true) .setTrustAll(true) .setDefaultPort(443); } else { cursusClientOptions .setDefaultPort(wsEndpoint.getPort() == -1 ? 80 : wsEndpoint.getPort()); } cursusClient = vertx.createHttpClient(cursusClientOptions); cursusMap = MapFactory.getSyncClusterMap("cursusMap", vertx, false); /* service.refreshToken(new Handler<Boolean>() { public void handle(Boolean res) { if(!res) log.error("[Cursus][refreshToken] Error while retrieving the Token."); else log.info("[Cursus][refreshToken] Token refreshed."); } }); */ if(cursusMap.containsKey("wallets")) return; service.refreshWallets(new Handler<Boolean>() { public void handle(Boolean res) { if(!res) log.error("[Cursus][refreshWallets] Error while retrieving the wallets list."); else log.info("[Cursus][refreshWallets] Wallets list refreshed."); } }); } public CursusController(URL endpoint, final JsonObject conf){ wsEndpoint = endpoint; authConf = conf; } @Put("/refreshToken") @SecuredAction(value = "", type = ActionType.RESOURCE) @ResourceFilter(CursusFilter.class) public void refreshToken(final HttpServerRequest request){ service.refreshToken(new Handler<Boolean>() { public void handle(Boolean success) { if(success){ ok(request); } else { badRequest(request); } } }); } @Put("/refreshWallets") @SecuredAction(value = "", type = ActionType.RESOURCE) @ResourceFilter(CursusFilter.class) public void refreshWallets(final HttpServerRequest request){ service.refreshWallets(new Handler<Boolean>() { public void handle(Boolean success) { if(success){ ok(request); } else { badRequest(request); } } }); } @Get("/sales") @SecuredAction(value = "", type = ActionType.AUTHENTICATED) public void getSales(final HttpServerRequest request){ final String cardNb = request.params().get("cardNb"); if(cardNb == null){ badRequest(request); return; } service.getUserInfo(cardNb, new Handler<Either<String,JsonArray>>() { public void handle(Either<String, JsonArray> result) { if(result.isLeft()){ badRequest(request); return; } final String id = result.right().getValue().getJsonObject(0).getInteger("id").toString(); String birthDateEncoded = result.right().getValue().getJsonObject(0).getString("dateNaissance"); try { birthDateEncoded = birthDateEncoded.replace("/Date(", ""); birthDateEncoded = birthDateEncoded.substring(0, birthDateEncoded.indexOf("+")); final Date birthDate = new Date(Long.parseLong(birthDateEncoded)); UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() { public void handle(UserInfos infos) { DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); try { Date sessionBirthDate = format.parse(infos.getBirthDate()); if(sessionBirthDate.compareTo(birthDate) == 0){ service.getSales(id, cardNb, new Handler<Either<String,JsonArray>>() { public void handle(Either<String, JsonArray> result) { if(result.isLeft()){ badRequest(request); return; } JsonObject finalResult = new JsonObject() .put("wallets", new JsonArray(cursusMap.get("wallets"))) .put("sales", result.right().getValue()); renderJson(request, finalResult); } }); } else { badRequest(request); } } catch (ParseException e) { badRequest(request); return; } } }); } catch(Exception e){ badRequest(request); } } }); } /** * Inner service class. */ private class CursusService{ public void authWrapper(final Handler<Boolean> handler){ JsonObject authObject = new JsonObject(); if(cursusMap.get("auth") != null) authObject = new JsonObject(cursusMap.get("auth")); Long currentDate = Calendar.getInstance().getTimeInMillis(); Long expirationDate = 0l; if(authObject != null) expirationDate = authObject.getLong("tokenInit", 0l) + authConf.getLong("tokenDelay", 1800000l); if(expirationDate < currentDate){ log.info("[Cursus] Token seems to have expired."); refreshToken(handler); } else { handler.handle(true); } } public void refreshToken(final Handler<Boolean> handler){ HttpClientRequest req = cursusClient.post(wsEndpoint.getPath() + "/AuthentificationImpl.svc/json/AuthentificationExtranet", new Handler<HttpClientResponse>() { public void handle(HttpClientResponse response) { if(response.statusCode() >= 300){ handler.handle(false); log.error(response.statusMessage()); return; } response.bodyHandler(new Handler<Buffer>() { public void handle(Buffer body) { log.info("[Cursus][refreshToken] Token refreshed."); JsonObject authData = new JsonObject(body.toString()); authData.put("tokenInit", new Date().getTime()); cursusMap.put("auth", authData.encode()); handler.handle(true); } }); } }); req.putHeader(HttpHeaders.ACCEPT, "application/json; charset=UTF-8") .putHeader(HttpHeaders.CONTENT_TYPE, "application/json"); req.end(authConf.encode()); } public void refreshWallets(final Handler<Boolean> handler){ authWrapper(new Handler<Boolean>() { public void handle(Boolean gotToken) { if(!gotToken){ handler.handle(false); return; } int schoolYear = Calendar.getInstance().get(Calendar.MONTH) < 8 ? Calendar.getInstance().get(Calendar.YEAR) - 1 : Calendar.getInstance().get(Calendar.YEAR); /* JSON */ JsonObject reqBody = new JsonObject(); reqBody .put("numSite", authConf.getString("numSite")) .put("tokenId", new JsonObject(cursusMap.get("auth")).getString("tokenId")) .put("typeListes", new JsonArray() .add(new JsonObject() .put("typeListe", "LST_PORTEMONNAIE") .put("param1", schoolYear + "-" + (schoolYear + 1)) ) ); /* */ /* XML / String reqBody = "<tem:GetListes xmlns:tem=\"http://tempuri.org/\" xmlns:wcf=\"http://schemas.datacontract.org/2004/07/WcfExtranetChequeBL.POCO.Parametres\">" + "<tem:numSite>"+ authConf.getString("numSite") +"</tem:numSite>" + "<tem:typeListes>" + "<wcf:RechercheTypeListe>" + "<wcf:typeListe>LST_PORTEMONNAIE</wcf:typeListe>" + "<wcf:param1>"+ schoolYear + "-" + (schoolYear + 1) +"</wcf:param1>" + "</wcf:RechercheTypeListe>" + "</tem:typeListes>" + "<tem:tokenId>"+ authData.getString("tokenId") +"</tem:tokenId>" + "</tem:GetListes>"; /* */ HttpClientRequest req = cursusClient.post(wsEndpoint.getPath() + "/GeneralImpl.svc/json/GetListes", new Handler<HttpClientResponse>() { public void handle(HttpClientResponse response) { if(response.statusCode() >= 300){ handler.handle(false); log.error(response.statusMessage()); return; } response.bodyHandler(new Handler<Buffer>() { public void handle(Buffer body) { try{ cursusMap.put("wallets", new JsonArray(body.toString()).getJsonObject(0) .getJsonArray("parametres").encode()); handler.handle(true); } catch(Exception e){ handler.handle(false); } } }); } }); req.putHeader(HttpHeaders.ACCEPT, "application/json; charset=UTF-8") .putHeader(HttpHeaders.CONTENT_TYPE, "application/json"); req.end(reqBody.encode()); } }); }; public void getUserInfo(final String cardNb, final Handler<Either<String, JsonArray>> handler){ authWrapper(new Handler<Boolean>() { public void handle(Boolean gotToken) { if(!gotToken){ handler.handle(new Either.Left<String, JsonArray>("[Cursus][getUserInfo] Issue while retrieving token.")); return; } JsonObject reqBody = new JsonObject(); reqBody .put("numSite", authConf.getString("numSite")) .put("tokenId", new JsonObject(cursusMap.get("auth")).getString("tokenId")) .put("filtres", new JsonObject() .put("numeroCarte", cardNb)); HttpClientRequest req = cursusClient.post(wsEndpoint.getPath() + "/BeneficiaireImpl.svc/json/GetListeBeneficiaire", new Handler<HttpClientResponse>() { public void handle(HttpClientResponse response) { if(response.statusCode() >= 300){ handler.handle(new Either.Left<String, JsonArray>("invalid.status.code")); return; } response.bodyHandler(new Handler<Buffer>() { public void handle(Buffer body) { handler.handle(new Either.Right<String, JsonArray>(new JsonArray(body.toString()))); } }); } }); req.putHeader(HttpHeaders.ACCEPT, "application/json; charset=UTF-8") .putHeader(HttpHeaders.CONTENT_TYPE, "application/json"); req.end(reqBody.encode()); } }); } public void getSales(final String numeroDossier, final String cardNb, final Handler<Either<String, JsonArray>> handler){ authWrapper(new Handler<Boolean>() { public void handle(Boolean gotToken) { if(!gotToken){ handler.handle(new Either.Left<String, JsonArray>("[Cursus][getSales] Issue while retrieving token.")); return; } JsonObject reqBody = new JsonObject(); reqBody .put("numeroSite", authConf.getString("numSite")) .put("tokenId", new JsonObject(cursusMap.get("auth")).getString("tokenId")) .put("filtresSoldesBeneficiaire", new JsonObject() .put("numeroDossier", numeroDossier) .put("numeroCarte", cardNb)); HttpClientRequest req = cursusClient.post(wsEndpoint.getPath() + "/BeneficiaireImpl.svc/json/GetSoldesBeneficiaire", new Handler<HttpClientResponse>() { public void handle(HttpClientResponse response) { if(response.statusCode() >= 300){ handler.handle(new Either.Left<String, JsonArray>("invalid.status.code")); return; } response.bodyHandler(new Handler<Buffer>() { public void handle(Buffer body) { handler.handle(new Either.Right<String, JsonArray>(new JsonArray(body.toString()))); } }); } }); req.putHeader(HttpHeaders.ACCEPT, "application/json; charset=UTF-8") .putHeader(HttpHeaders.CONTENT_TYPE, "application/json"); req.end(reqBody.encode()); } }); } } }
OPEN-ENT-NG/cursus
src/main/java/org/entcore/cursus/controllers/CursusController.java
Java
agpl-3.0
13,069
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_71) on Fri Jul 10 16:43:22 IST 2015 --> <title>Uses of Interface com.ephesoft.gxt.core.shared.dto.propertyAccessors.KVExtractionProperties</title> <meta name="date" content="2015-07-10"> <link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface com.ephesoft.gxt.core.shared.dto.propertyAccessors.KVExtractionProperties"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../com/ephesoft/gxt/core/shared/dto/propertyAccessors/KVExtractionProperties.html" title="interface in com.ephesoft.gxt.core.shared.dto.propertyAccessors">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?com/ephesoft/gxt/core/shared/dto/propertyAccessors/class-use/KVExtractionProperties.html" target="_top">Frames</a></li> <li><a href="KVExtractionProperties.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface com.ephesoft.gxt.core.shared.dto.propertyAccessors.KVExtractionProperties" class="title">Uses of Interface<br>com.ephesoft.gxt.core.shared.dto.propertyAccessors.KVExtractionProperties</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../../com/ephesoft/gxt/core/shared/dto/propertyAccessors/KVExtractionProperties.html" title="interface in com.ephesoft.gxt.core.shared.dto.propertyAccessors">KVExtractionProperties</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#com.ephesoft.gxt.core.shared.dto.propertyAccessors">com.ephesoft.gxt.core.shared.dto.propertyAccessors</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="com.ephesoft.gxt.core.shared.dto.propertyAccessors"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../../com/ephesoft/gxt/core/shared/dto/propertyAccessors/KVExtractionProperties.html" title="interface in com.ephesoft.gxt.core.shared.dto.propertyAccessors">KVExtractionProperties</a> in <a href="../../../../../../../../com/ephesoft/gxt/core/shared/dto/propertyAccessors/package-summary.html">com.ephesoft.gxt.core.shared.dto.propertyAccessors</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../../../../../com/ephesoft/gxt/core/shared/dto/propertyAccessors/package-summary.html">com.ephesoft.gxt.core.shared.dto.propertyAccessors</a> declared as <a href="../../../../../../../../com/ephesoft/gxt/core/shared/dto/propertyAccessors/KVExtractionProperties.html" title="interface in com.ephesoft.gxt.core.shared.dto.propertyAccessors">KVExtractionProperties</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../../../../com/ephesoft/gxt/core/shared/dto/propertyAccessors/KVExtractionProperties.html" title="interface in com.ephesoft.gxt.core.shared.dto.propertyAccessors">KVExtractionProperties</a></code></td> <td class="colLast"><span class="strong">KVExtractionProperties.</span><code><strong><a href="../../../../../../../../com/ephesoft/gxt/core/shared/dto/propertyAccessors/KVExtractionProperties.html#properties">properties</a></strong></code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../com/ephesoft/gxt/core/shared/dto/propertyAccessors/KVExtractionProperties.html" title="interface in com.ephesoft.gxt.core.shared.dto.propertyAccessors">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?com/ephesoft/gxt/core/shared/dto/propertyAccessors/class-use/KVExtractionProperties.html" target="_top">Frames</a></li> <li><a href="KVExtractionProperties.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
ungerik/ephesoft
Ephesoft_Community_Release_4.0.2.0/javadocs/com/ephesoft/gxt/core/shared/dto/propertyAccessors/class-use/KVExtractionProperties.html
HTML
agpl-3.0
7,390
// Copyright David Abrahams 2002. // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef UNWIND_TYPE_DWA200222_HPP # define UNWIND_TYPE_DWA200222_HPP # include <boost/python/detail/cv_category.hpp> # include <boost/python/detail/indirect_traits.hpp> # include <boost/type_traits/object_traits.hpp> namespace abt_boost{} namespace boost = abt_boost; namespace abt_boost{ namespace python { namespace detail { #ifndef _MSC_VER //if forward declared, msvc6.5 does not recognize them as inline // forward declaration, required (at least) by Tru64 cxx V6.5-042 template <class Generator, class U> inline typename Generator::result_type unwind_type(U const& p, Generator* = 0); // forward declaration, required (at least) by Tru64 cxx V6.5-042 template <class Generator, class U> inline typename Generator::result_type unwind_type(abt_boost::type<U>*p = 0, Generator* = 0); #endif template <class Generator, class U> inline typename Generator::result_type unwind_type_cv(U* p, cv_unqualified, Generator* = 0) { return Generator::execute(p); } template <class Generator, class U> inline typename Generator::result_type unwind_type_cv(U const* p, const_, Generator* = 0) { return unwind_type(const_cast<U*>(p), (Generator*)0); } template <class Generator, class U> inline typename Generator::result_type unwind_type_cv(U volatile* p, volatile_, Generator* = 0) { return unwind_type(const_cast<U*>(p), (Generator*)0); } template <class Generator, class U> inline typename Generator::result_type unwind_type_cv(U const volatile* p, const_volatile_, Generator* = 0) { return unwind_type(const_cast<U*>(p), (Generator*)0); } template <class Generator, class U> inline typename Generator::result_type unwind_ptr_type(U* p, Generator* = 0) { typedef typename cv_category<U>::type tag; return unwind_type_cv<Generator>(p, tag()); } template <bool is_ptr> struct unwind_helper { template <class Generator, class U> static typename Generator::result_type execute(U p, Generator* = 0) { return unwind_ptr_type(p, (Generator*)0); } }; template <> struct unwind_helper<false> { template <class Generator, class U> static typename Generator::result_type execute(U& p, Generator* = 0) { return unwind_ptr_type(&p, (Generator*)0); } }; template <class Generator, class U> inline typename Generator::result_type #ifndef _MSC_VER unwind_type(U const& p, Generator*) #else unwind_type(U const& p, Generator* = 0) #endif { return unwind_helper<is_pointer<U>::value>::execute(p, (Generator*)0); } enum { direct_ = 0, pointer_ = 1, reference_ = 2, reference_to_pointer_ = 3 }; template <int indirection> struct unwind_helper2; template <> struct unwind_helper2<direct_> { template <class Generator, class U> static typename Generator::result_type execute(U(*)(), Generator* = 0) { return unwind_ptr_type((U*)0, (Generator*)0); } }; template <> struct unwind_helper2<pointer_> { template <class Generator, class U> static typename Generator::result_type execute(U*(*)(), Generator* = 0) { return unwind_ptr_type((U*)0, (Generator*)0); } }; template <> struct unwind_helper2<reference_> { template <class Generator, class U> static typename Generator::result_type execute(U&(*)(), Generator* = 0) { return unwind_ptr_type((U*)0, (Generator*)0); } }; template <> struct unwind_helper2<reference_to_pointer_> { template <class Generator, class U> static typename Generator::result_type execute(U&(*)(), Generator* = 0) { return unwind_ptr_type(U(0), (Generator*)0); } }; // Call this one with both template parameters explicitly specified // and no function arguments: // // return unwind_type<my_generator,T>(); // // Doesn't work if T is an array type; we could handle that case, but // why bother? template <class Generator, class U> inline typename Generator::result_type #ifndef _MSC_VER unwind_type(abt_boost::type<U>*, Generator*) #else unwind_type(abt_boost::type<U>*p =0, Generator* =0) #endif { BOOST_STATIC_CONSTANT(int, indirection = (abt_boost::is_pointer<U>::value ? pointer_ : 0) + (indirect_traits::is_reference_to_pointer<U>::value ? reference_to_pointer_ : abt_boost::is_reference<U>::value ? reference_ : 0)); return unwind_helper2<indirection>::execute((U(*)())0,(Generator*)0); } }}} // namespace abt_boost::python::detail #endif // UNWIND_TYPE_DWA200222_HPP
jbruestle/aggregate_btree
tiny_boost/boost/python/detail/unwind_type.hpp
C++
agpl-3.0
4,739
class Api::AccountsController < ApiController def index @accounts = current_user.accounts respond_with(@accounts) end def show find_account! respond_with(@account) end def update find_account! @account.update(account_params) respond_with(@account) end private def find_account! @account = Account.find_by!(id: params.fetch(:id)) authorize! AccountReadPolicy.new(@account, current_user) end def account_params params.permit(:name, :website_url, :webhook_url, :prefers_archiving) end end
asm-helpful/helpful-web
app/controllers/api/accounts_controller.rb
Ruby
agpl-3.0
555
define(['sylvester', 'sha1', 'PrairieGeom'], function (Sylvester, Sha1, PrairieGeom) { var $V = Sylvester.Vector.create; var Vector = Sylvester.Vector; var Matrix = Sylvester.Matrix; /*****************************************************************************/ /** Creates a PrairieDraw object. @constructor @this {PrairieDraw} @param {HTMLCanvasElement or string} canvas The canvas element to draw on or the ID of the canvas elemnt. @param {Function} drawfcn An optional function that draws on the canvas. */ function PrairieDraw(canvas, drawFcn) { if (canvas) { if (canvas instanceof HTMLCanvasElement) { this._canvas = canvas; } else if (canvas instanceof String || typeof canvas === 'string') { this._canvas = document.getElementById(canvas); } else { //throw new Error("PrairieDraw: unknown object type for constructor") this._canvas = undefined; } if (this._canvas) { this._canvas.prairieDraw = this; this._ctx = this._canvas.getContext('2d'); if (this._ctx.setLineDash === undefined) { this._ctx.setLineDash = function () {}; } this._width = this._canvas.width; this._height = this._canvas.height; this._trans = Matrix.I(3); this._transStack = []; this._initViewAngleX3D = (-Math.PI / 2) * 0.75; this._initViewAngleY3D = 0; this._initViewAngleZ3D = (-Math.PI / 2) * 1.25; this._viewAngleX3D = this._initViewAngleX3D; this._viewAngleY3D = this._initViewAngleY3D; this._viewAngleZ3D = this._initViewAngleZ3D; this._trans3D = PrairieGeom.rotateTransform3D( Matrix.I(4), this._initViewAngleX3D, this._initViewAngleY3D, this._initViewAngleZ3D ); this._trans3DStack = []; this._props = {}; this._initProps(); this._propStack = []; this._options = {}; this._history = {}; this._images = {}; this._redrawCallbacks = []; if (drawFcn) { this.draw = drawFcn.bind(this); } this.save(); this.draw(); this.restoreAll(); } } } /** Creates a new PrairieDraw from a canvas ID. @param {string} id The ID of the canvas element to draw on. @return {PrairieDraw} The new PrairieDraw object. */ PrairieDraw.fromCanvasId = function (id) { var canvas = document.getElementById(id); if (!canvas) { throw new Error('PrairieDraw: unable to find canvas ID: ' + id); } return new PrairieDraw(canvas); }; /** Prototype function to draw on the canvas, should be implemented by children. */ PrairieDraw.prototype.draw = function () {}; /** Redraw the drawing. */ PrairieDraw.prototype.redraw = function () { this.save(); this.draw(); this.restoreAll(); for (var i = 0; i < this._redrawCallbacks.length; i++) { this._redrawCallbacks[i](); } }; /** Add a callback on redraw() calls. */ PrairieDraw.prototype.registerRedrawCallback = function (callback) { this._redrawCallbacks.push(callback.bind(this)); }; /** @private Initialize properties. */ PrairieDraw.prototype._initProps = function () { this._props.viewAngleXMin = -Math.PI / 2 + 1e-6; this._props.viewAngleXMax = -1e-6; this._props.viewAngleYMin = -Infinity; this._props.viewAngleYMax = Infinity; this._props.viewAngleZMin = -Infinity; this._props.viewAngleZMax = Infinity; this._props.arrowLineWidthPx = 2; this._props.arrowLinePattern = 'solid'; this._props.arrowheadLengthRatio = 7; // arrowheadLength / arrowLineWidth this._props.arrowheadWidthRatio = 0.3; // arrowheadWidth / arrowheadLength this._props.arrowheadOffsetRatio = 0.3; // arrowheadOffset / arrowheadLength this._props.circleArrowWrapOffsetRatio = 1.5; this._props.arrowOutOfPageRadiusPx = 5; this._props.textOffsetPx = 4; this._props.textFontSize = 14; this._props.pointRadiusPx = 2; this._props.shapeStrokeWidthPx = 2; this._props.shapeStrokePattern = 'solid'; this._props.shapeOutlineColor = 'rgb(0, 0, 0)'; this._props.shapeInsideColor = 'rgb(255, 255, 255)'; this._props.hiddenLineDraw = true; this._props.hiddenLineWidthPx = 2; this._props.hiddenLinePattern = 'dashed'; this._props.hiddenLineColor = 'rgb(0, 0, 0)'; this._props.centerOfMassStrokeWidthPx = 2; this._props.centerOfMassColor = 'rgb(180, 49, 4)'; this._props.centerOfMassRadiusPx = 5; this._props.rightAngleSizePx = 10; this._props.rightAngleStrokeWidthPx = 1; this._props.rightAngleColor = 'rgb(0, 0, 0)'; this._props.measurementStrokeWidthPx = 1; this._props.measurementStrokePattern = 'solid'; this._props.measurementEndLengthPx = 10; this._props.measurementOffsetPx = 3; this._props.measurementColor = 'rgb(0, 0, 0)'; this._props.groundDepthPx = 10; this._props.groundWidthPx = 10; this._props.groundSpacingPx = 10; this._props.groundOutlineColor = 'rgb(0, 0, 0)'; this._props.groundInsideColor = 'rgb(220, 220, 220)'; this._props.gridColor = 'rgb(200, 200, 200)'; this._props.positionColor = 'rgb(0, 0, 255)'; this._props.angleColor = 'rgb(0, 100, 180)'; this._props.velocityColor = 'rgb(0, 200, 0)'; this._props.angVelColor = 'rgb(100, 180, 0)'; this._props.accelerationColor = 'rgb(255, 0, 255)'; this._props.rotationColor = 'rgb(150, 0, 150)'; this._props.angAccColor = 'rgb(100, 0, 180)'; this._props.angMomColor = 'rgb(255, 0, 0)'; this._props.forceColor = 'rgb(210, 105, 30)'; this._props.momentColor = 'rgb(255, 102, 80)'; }; /*****************************************************************************/ /** The golden ratio. */ PrairieDraw.prototype.goldenRatio = (1 + Math.sqrt(5)) / 2; /** Get the canvas width. @return {number} The canvas width in Px. */ PrairieDraw.prototype.widthPx = function () { return this._width; }; /** Get the canvas height. @return {number} The canvas height in Px. */ PrairieDraw.prototype.heightPx = function () { return this._height; }; /*****************************************************************************/ /** Conversion constants. */ PrairieDraw.prototype.milesPerKilometer = 0.621371; /*****************************************************************************/ /** Scale the coordinate system. @param {Vector} factor Scale factors. */ PrairieDraw.prototype.scale = function (factor) { this._trans = PrairieGeom.scaleTransform(this._trans, factor); }; /** Translate the coordinate system. @param {Vector} offset Translation offset (drawing coords). */ PrairieDraw.prototype.translate = function (offset) { this._trans = PrairieGeom.translateTransform(this._trans, offset); }; /** Rotate the coordinate system. @param {number} angle Angle to rotate by (radians). */ PrairieDraw.prototype.rotate = function (angle) { this._trans = PrairieGeom.rotateTransform(this._trans, angle); }; /** Transform the coordinate system (scale, translate, rotate) to match old points to new. Drawing at the old locations will result in points at the new locations. @param {Vector} old1 The old location of point 1. @param {Vector} old2 The old location of point 2. @param {Vector} new1 The new location of point 1. @param {Vector} new2 The new location of point 2. */ PrairieDraw.prototype.transformByPoints = function (old1, old2, new1, new2) { this._trans = PrairieGeom.transformByPointsTransform(this._trans, old1, old2, new1, new2); }; /*****************************************************************************/ /** Transform a vector from drawing to pixel coords. @param {Vector} vDw Vector in drawing coords. @return {Vector} Vector in pixel coords. */ PrairieDraw.prototype.vec2Px = function (vDw) { return PrairieGeom.transformVec(this._trans, vDw); }; /** Transform a position from drawing to pixel coords. @param {Vector} pDw Position in drawing coords. @return {Vector} Position in pixel coords. */ PrairieDraw.prototype.pos2Px = function (pDw) { return PrairieGeom.transformPos(this._trans, pDw); }; /** Transform a vector from pixel to drawing coords. @param {Vector} vPx Vector in pixel coords. @return {Vector} Vector in drawing coords. */ PrairieDraw.prototype.vec2Dw = function (vPx) { return PrairieGeom.transformVec(this._trans.inverse(), vPx); }; /** Transform a position from pixel to drawing coords. @param {Vector} pPx Position in pixel coords. @return {Vector} Position in drawing coords. */ PrairieDraw.prototype.pos2Dw = function (pPx) { return PrairieGeom.transformPos(this._trans.inverse(), pPx); }; /** @private Returns true if the current transformation is a reflection. @return {bool} Whether the current transformation is a reflection. */ PrairieDraw.prototype._transIsReflection = function () { var det = this._trans.e(1, 1) * this._trans.e(2, 2) - this._trans.e(1, 2) * this._trans.e(2, 1); if (det < 0) { return true; } else { return false; } }; /** Transform a position from normalized viewport [0,1] to drawing coords. @param {Vector} pNm Position in normalized viewport coordinates. @return {Vector} Position in drawing coordinates. */ PrairieDraw.prototype.posNm2Dw = function (pNm) { var pPx = this.posNm2Px(pNm); return this.pos2Dw(pPx); }; /** Transform a position from normalized viewport [0,1] to pixel coords. @param {Vector} pNm Position in normalized viewport coords. @return {Vector} Position in pixel coords. */ PrairieDraw.prototype.posNm2Px = function (pNm) { return $V([pNm.e(1) * this._width, (1 - pNm.e(2)) * this._height]); }; /*****************************************************************************/ /** Set the 3D view to the given angles. @param {number} angleX The rotation angle about the X axis. @param {number} angleY The rotation angle about the Y axis. @param {number} angleZ The rotation angle about the Z axis. @param {bool} clip (Optional) Whether to clip to max/min range (default: true). @param {bool} redraw (Optional) Whether to redraw (default: true). */ PrairieDraw.prototype.setView3D = function (angleX, angleY, angleZ, clip, redraw) { clip = clip === undefined ? true : clip; redraw = redraw === undefined ? true : redraw; this._viewAngleX3D = angleX; this._viewAngleY3D = angleY; this._viewAngleZ3D = angleZ; if (clip) { this._viewAngleX3D = PrairieGeom.clip( this._viewAngleX3D, this._props.viewAngleXMin, this._props.viewAngleXMax ); this._viewAngleY3D = PrairieGeom.clip( this._viewAngleY3D, this._props.viewAngleYMin, this._props.viewAngleYMax ); this._viewAngleZ3D = PrairieGeom.clip( this._viewAngleZ3D, this._props.viewAngleZMin, this._props.viewAngleZMax ); } this._trans3D = PrairieGeom.rotateTransform3D( Matrix.I(4), this._viewAngleX3D, this._viewAngleY3D, this._viewAngleZ3D ); if (redraw) { this.redraw(); } }; /** Reset the 3D view to default. @param {bool} redraw (Optional) Whether to redraw (default: true). */ PrairieDraw.prototype.resetView3D = function (redraw) { this.setView3D( this._initViewAngleX3D, this._initViewAngleY3D, this._initViewAngleZ3D, undefined, redraw ); }; /** Increment the 3D view by the given angles. @param {number} deltaAngleX The incremental rotation angle about the X axis. @param {number} deltaAngleY The incremental rotation angle about the Y axis. @param {number} deltaAngleZ The incremental rotation angle about the Z axis. @param {bool} clip (Optional) Whether to clip to max/min range (default: true). */ PrairieDraw.prototype.incrementView3D = function (deltaAngleX, deltaAngleY, deltaAngleZ, clip) { this.setView3D( this._viewAngleX3D + deltaAngleX, this._viewAngleY3D + deltaAngleY, this._viewAngleZ3D + deltaAngleZ, clip ); }; /*****************************************************************************/ /** Scale the 3D coordinate system. @param {Vector} factor Scale factor. */ PrairieDraw.prototype.scale3D = function (factor) { this._trans3D = PrairieGeom.scaleTransform3D(this._trans3D, factor); }; /** Translate the 3D coordinate system. @param {Vector} offset Translation offset. */ PrairieDraw.prototype.translate3D = function (offset) { this._trans3D = PrairieGeom.translateTransform3D(this._trans3D, offset); }; /** Rotate the 3D coordinate system. @param {number} angleX Angle to rotate by around the X axis (radians). @param {number} angleY Angle to rotate by around the Y axis (radians). @param {number} angleZ Angle to rotate by around the Z axis (radians). */ PrairieDraw.prototype.rotate3D = function (angleX, angleY, angleZ) { this._trans3D = PrairieGeom.rotateTransform3D(this._trans3D, angleX, angleY, angleZ); }; /*****************************************************************************/ /** Transform a position to the view coordinates in 3D. @param {Vector} pDw Position in 3D drawing coords. @return {Vector} Position in 3D viewing coords. */ PrairieDraw.prototype.posDwToVw = function (pDw) { var pVw = PrairieGeom.transformPos3D(this._trans3D, pDw); return pVw; }; /** Transform a position from the view coordinates in 3D. @param {Vector} pVw Position in 3D viewing coords. @return {Vector} Position in 3D drawing coords. */ PrairieDraw.prototype.posVwToDw = function (pVw) { var pDw = PrairieGeom.transformPos3D(this._trans3D.inverse(), pVw); return pDw; }; /** Transform a vector to the view coordinates in 3D. @param {Vector} vDw Vector in 3D drawing coords. @return {Vector} Vector in 3D viewing coords. */ PrairieDraw.prototype.vecDwToVw = function (vDw) { var vVw = PrairieGeom.transformVec3D(this._trans3D, vDw); return vVw; }; /** Transform a vector from the view coordinates in 3D. @param {Vector} vVw Vector in 3D viewing coords. @return {Vector} Vector in 3D drawing coords. */ PrairieDraw.prototype.vecVwToDw = function (vVw) { var vDw = PrairieGeom.transformVec3D(this._trans3D.inverse(), vVw); return vDw; }; /** Transform a position from 3D to 2D drawing coords if necessary. @param {Vector} pDw Position in 2D or 3D drawing coords. @return {Vector} Position in 2D drawing coords. */ PrairieDraw.prototype.pos3To2 = function (pDw) { if (pDw.elements.length === 3) { return PrairieGeom.orthProjPos3D(this.posDwToVw(pDw)); } else { return pDw; } }; /** Transform a vector from 3D to 2D drawing coords if necessary. @param {Vector} vDw Vector in 2D or 3D drawing coords. @param {Vector} pDw Base point of vector (if in 3D). @return {Vector} Vector in 2D drawing coords. */ PrairieDraw.prototype.vec3To2 = function (vDw, pDw) { if (vDw.elements.length === 3) { var qDw = pDw.add(vDw); var p2Dw = this.pos3To2(pDw); var q2Dw = this.pos3To2(qDw); var v2Dw = q2Dw.subtract(p2Dw); return v2Dw; } else { return vDw; } }; /** Transform a position from 2D to 3D drawing coords if necessary (adding z = 0). @param {Vector} pDw Position in 2D or 3D drawing coords. @return {Vector} Position in 3D drawing coords. */ PrairieDraw.prototype.pos2To3 = function (pDw) { if (pDw.elements.length === 2) { return $V([pDw.e(1), pDw.e(2), 0]); } else { return pDw; } }; /** Transform a vector from 2D to 3D drawing coords if necessary (adding z = 0). @param {Vector} vDw Vector in 2D or 3D drawing coords. @return {Vector} Vector in 3D drawing coords. */ PrairieDraw.prototype.vec2To3 = function (vDw) { if (vDw.elements.length === 2) { return $V([vDw.e(1), vDw.e(2), 0]); } else { return vDw; } }; /*****************************************************************************/ /** Set a property. @param {string} name The name of the property. @param {number} value The value to set the property to. */ PrairieDraw.prototype.setProp = function (name, value) { if (!(name in this._props)) { throw new Error('PrairieDraw: unknown property name: ' + name); } this._props[name] = value; }; /** Get a property. @param {string} name The name of the property. @return {number} The current value of the property. */ PrairieDraw.prototype.getProp = function (name) { if (!(name in this._props)) { throw new Error('PrairieDraw: unknown property name: ' + name); } return this._props[name]; }; /** @private Colors. */ PrairieDraw._colors = { black: 'rgb(0, 0, 0)', white: 'rgb(255, 255, 255)', red: 'rgb(255, 0, 0)', green: 'rgb(0, 255, 0)', blue: 'rgb(0, 0, 255)', cyan: 'rgb(0, 255, 255)', magenta: 'rgb(255, 0, 255)', yellow: 'rgb(255, 255, 0)', }; /** @private Get a color property for a given type. @param {string} type Optional type to find the color for. */ PrairieDraw.prototype._getColorProp = function (type) { if (type === undefined) { return this._props.shapeOutlineColor; } var col = type + 'Color'; if (col in this._props) { var c = this._props[col]; if (c in PrairieDraw._colors) { return PrairieDraw._colors[c]; } else { return c; } } else if (type in PrairieDraw._colors) { return PrairieDraw._colors[type]; } else { return type; } }; /** @private Set shape drawing properties for drawing hidden lines. */ PrairieDraw.prototype.setShapeDrawHidden = function () { this._props.shapeStrokeWidthPx = this._props.hiddenLineWidthPx; this._props.shapeStrokePattern = this._props.hiddenLinePattern; this._props.shapeOutlineColor = this._props.hiddenLineColor; }; /*****************************************************************************/ /** Add an external option for this drawing. @param {string} name The option name. @param {object} value The default initial value. */ PrairieDraw.prototype.addOption = function (name, value, triggerRedraw) { if (!(name in this._options)) { this._options[name] = { value: value, resetValue: value, callbacks: {}, triggerRedraw: triggerRedraw === undefined ? true : triggerRedraw, }; } else if (!('value' in this._options[name])) { var option = this._options[name]; option.value = value; option.resetValue = value; for (var p in option.callbacks) { option.callbacks[p](option.value); } } }; /** Set an option to a given value. @param {string} name The option name. @param {object} value The new value for the option. @param {bool} redraw (Optional) Whether to trigger a redraw() (default: true). @param {Object} trigger (Optional) The object that triggered the change. @param {bool} setReset (Optional) Also set this value to be the new reset value (default: false). */ PrairieDraw.prototype.setOption = function (name, value, redraw, trigger, setReset) { redraw = redraw === undefined ? true : redraw; setReset = setReset === undefined ? false : setReset; if (!(name in this._options)) { throw new Error('PrairieDraw: unknown option: ' + name); } var option = this._options[name]; option.value = value; if (setReset) { option.resetValue = value; } for (var p in option.callbacks) { option.callbacks[p](option.value, trigger); } if (redraw) { this.redraw(); } }; /** Get the value of an option. @param {string} name The option name. @return {object} The current value for the option. */ PrairieDraw.prototype.getOption = function (name) { if (!(name in this._options)) { throw new Error('PrairieDraw: unknown option: ' + name); } if (!('value' in this._options[name])) { throw new Error('PrairieDraw: option has no value: ' + name); } return this._options[name].value; }; /** Set an option to the logical negation of its current value. @param {string} name The option name. */ PrairieDraw.prototype.toggleOption = function (name) { if (!(name in this._options)) { throw new Error('PrairieDraw: unknown option: ' + name); } if (!('value' in this._options[name])) { throw new Error('PrairieDraw: option has no value: ' + name); } var option = this._options[name]; option.value = !option.value; for (var p in option.callbacks) { option.callbacks[p](option.value); } this.redraw(); }; /** Register a callback on option changes. @param {string} name The option to register on. @param {Function} callback The callback(value) function. @param {string} callbackID (Optional) The ID of the callback. If omitted, a new unique ID will be generated. */ PrairieDraw.prototype.registerOptionCallback = function (name, callback, callbackID) { if (!(name in this._options)) { throw new Error('PrairieDraw: unknown option: ' + name); } var option = this._options[name]; var useID; if (callbackID === undefined) { var nextIDNumber = 0, curIDNumber; for (var p in option.callbacks) { curIDNumber = parseInt(p, 10); if (isFinite(curIDNumber)) { nextIDNumber = Math.max(nextIDNumber, curIDNumber + 1); } } useID = nextIDNumber.toString(); } else { useID = callbackID; } option.callbacks[useID] = callback.bind(this); option.callbacks[useID](option.value); }; /** Clear the value for the given option. @param {string} name The option to clear. */ PrairieDraw.prototype.clearOptionValue = function (name) { if (!(name in this._options)) { throw new Error('PrairieDraw: unknown option: ' + name); } if ('value' in this._options[name]) { delete this._options[name].value; } this.redraw(); }; /** Reset the value for the given option. @param {string} name The option to reset. */ PrairieDraw.prototype.resetOptionValue = function (name) { if (!(name in this._options)) { throw new Error('PrairieDraw: unknown option: ' + name); } var option = this._options[name]; if (!('resetValue' in option)) { throw new Error('PrairieDraw: option has no resetValue: ' + name); } option.value = option.resetValue; for (var p in option.callbacks) { option.callbacks[p](option.value); } }; /*****************************************************************************/ /** Save the graphics state (properties, options, and transformations). @see restore(). */ PrairieDraw.prototype.save = function () { this._ctx.save(); var oldProps = {}; for (var p in this._props) { oldProps[p] = this._props[p]; } this._propStack.push(oldProps); this._transStack.push(this._trans.dup()); this._trans3DStack.push(this._trans3D.dup()); }; /** Restore the graphics state (properties, options, and transformations). @see save(). */ PrairieDraw.prototype.restore = function () { this._ctx.restore(); if (this._propStack.length === 0) { throw new Error('PrairieDraw: tried to restore() without corresponding save()'); } if (this._propStack.length !== this._transStack.length) { throw new Error('PrairieDraw: incompatible save stack lengths'); } if (this._propStack.length !== this._trans3DStack.length) { throw new Error('PrairieDraw: incompatible save stack lengths'); } this._props = this._propStack.pop(); this._trans = this._transStack.pop(); this._trans3D = this._trans3DStack.pop(); }; /** Restore all outstanding saves. */ PrairieDraw.prototype.restoreAll = function () { while (this._propStack.length > 0) { this.restore(); } if (this._saveTrans !== undefined) { this._trans = this._saveTrans; } }; /*****************************************************************************/ /** Reset the canvas image and drawing context. */ PrairieDraw.prototype.clearDrawing = function () { this._ctx.clearRect(0, 0, this._width, this._height); }; /** Reset everything to the intial state. */ PrairieDraw.prototype.reset = function () { for (var optionName in this._options) { this.resetOptionValue(optionName); } this.resetView3D(false); this.redraw(); }; /** Stop all action and computation. */ PrairieDraw.prototype.stop = function () {}; /*****************************************************************************/ /** Set the visable coordinate sizes. @param {number} xSize The horizontal size of the drawing area in coordinate units. @param {number} ySize The vertical size of the drawing area in coordinate units. @param {number} canvasWidth (Optional) The width of the canvas in px. @param {bool} preserveCanvasSize (Optional) If true, do not resize the canvas to match the coordinate ratio. */ PrairieDraw.prototype.setUnits = function (xSize, ySize, canvasWidth, preserveCanvasSize) { this.clearDrawing(); this._trans = Matrix.I(3); if (canvasWidth !== undefined) { var canvasHeight = Math.floor((ySize / xSize) * canvasWidth); if (this._width !== canvasWidth || this._height !== canvasHeight) { this._canvas.width = canvasWidth; this._canvas.height = canvasHeight; this._width = canvasWidth; this._height = canvasHeight; } preserveCanvasSize = true; } var xScale = this._width / xSize; var yScale = this._height / ySize; if (xScale < yScale) { this._scale = xScale; if (!preserveCanvasSize && xScale !== yScale) { var newHeight = xScale * ySize; this._canvas.height = newHeight; this._height = newHeight; } this.translate($V([this._width / 2, this._height / 2])); this.scale($V([1, -1])); this.scale($V([xScale, xScale])); } else { this._scale = yScale; if (!preserveCanvasSize && xScale !== yScale) { var newWidth = yScale * xSize; this._canvas.width = newWidth; this._width = newWidth; } this.translate($V([this._width / 2, this._height / 2])); this.scale($V([1, -1])); this.scale($V([yScale, yScale])); } this._saveTrans = this._trans; }; /*****************************************************************************/ /** Draw a point. @param {Vector} posDw Position of the point (drawing coords). */ PrairieDraw.prototype.point = function (posDw) { posDw = this.pos3To2(posDw); var posPx = this.pos2Px(posDw); this._ctx.beginPath(); this._ctx.arc(posPx.e(1), posPx.e(2), this._props.pointRadiusPx, 0, 2 * Math.PI); this._ctx.fillStyle = this._props.shapeOutlineColor; this._ctx.fill(); }; /*****************************************************************************/ /** @private Set the stroke/fill styles for drawing lines. @param {string} type The type of line being drawn. */ PrairieDraw.prototype._setLineStyles = function (type) { var col = this._getColorProp(type); this._ctx.strokeStyle = col; this._ctx.fillStyle = col; }; /** Return the dash array for the given line pattern. @param {string} type The type of the dash pattern ('solid', 'dashed', 'dotted'). @return {Array} The numerical array of dash segment lengths. */ PrairieDraw.prototype._dashPattern = function (type) { if (type === 'solid') { return []; } else if (type === 'dashed') { return [6, 6]; } else if (type === 'dotted') { return [2, 2]; } else { throw new Error('PrairieDraw: unknown dash pattern: ' + type); } }; /** Draw a single line given start and end positions. @param {Vector} startDw Initial point of the line (drawing coords). @param {Vector} endDw Final point of the line (drawing coords). @param {string} type Optional type of line being drawn. */ PrairieDraw.prototype.line = function (startDw, endDw, type) { startDw = this.pos3To2(startDw); endDw = this.pos3To2(endDw); var startPx = this.pos2Px(startDw); var endPx = this.pos2Px(endDw); this._ctx.save(); this._setLineStyles(type); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.beginPath(); this._ctx.moveTo(startPx.e(1), startPx.e(2)); this._ctx.lineTo(endPx.e(1), endPx.e(2)); this._ctx.stroke(); this._ctx.restore(); }; /*****************************************************************************/ /** Draw a cubic Bezier segment. @param {Vector} p0Dw The starting point. @param {Vector} p1Dw The first control point. @param {Vector} p2Dw The second control point. @param {Vector} p3Dw The ending point. @param {string} type (Optional) type of line being drawn. */ PrairieDraw.prototype.cubicBezier = function (p0Dw, p1Dw, p2Dw, p3Dw, type) { var p0Px = this.pos2Px(this.pos3To2(p0Dw)); var p1Px = this.pos2Px(this.pos3To2(p1Dw)); var p2Px = this.pos2Px(this.pos3To2(p2Dw)); var p3Px = this.pos2Px(this.pos3To2(p3Dw)); this._ctx.save(); this._setLineStyles(type); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.beginPath(); this._ctx.moveTo(p0Px.e(1), p0Px.e(2)); this._ctx.bezierCurveTo(p1Px.e(1), p1Px.e(2), p2Px.e(1), p2Px.e(2), p3Px.e(1), p3Px.e(2)); this._ctx.stroke(); this._ctx.restore(); }; /*****************************************************************************/ /** @private Draw an arrowhead in pixel coords. @param {Vector} posPx Position of the tip. @param {Vector} dirPx Direction vector that the arrowhead points in. @param {number} lenPx Length of the arrowhead. */ PrairieDraw.prototype._arrowheadPx = function (posPx, dirPx, lenPx) { var dxPx = -(1 - this._props.arrowheadOffsetRatio) * lenPx; var dyPx = this._props.arrowheadWidthRatio * lenPx; this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(dirPx)); this._ctx.beginPath(); this._ctx.moveTo(0, 0); this._ctx.lineTo(-lenPx, dyPx); this._ctx.lineTo(dxPx, 0); this._ctx.lineTo(-lenPx, -dyPx); this._ctx.closePath(); this._ctx.fill(); this._ctx.restore(); }; /** @private Draw an arrowhead. @param {Vector} posDw Position of the tip (drawing coords). @param {Vector} dirDw Direction vector that the arrowhead point in (drawing coords). @param {number} lenPx Length of the arrowhead (pixel coords). */ PrairieDraw.prototype._arrowhead = function (posDw, dirDw, lenPx) { var posPx = this.pos2Px(posDw); var dirPx = this.vec2Px(dirDw); this._arrowheadPx(posPx, dirPx, lenPx); }; /** Draw an arrow given start and end positions. @param {Vector} startDw Initial point of the arrow (drawing coords). @param {Vector} endDw Final point of the arrow (drawing coords). @param {string} type Optional type of vector being drawn. */ PrairieDraw.prototype.arrow = function (startDw, endDw, type) { startDw = this.pos3To2(startDw); endDw = this.pos3To2(endDw); var offsetDw = endDw.subtract(startDw); var offsetPx = this.vec2Px(offsetDw); var arrowLengthPx = offsetPx.modulus(); var lineEndDw, drawArrowHead, arrowheadLengthPx; if (arrowLengthPx < 1) { // if too short, just draw a simple line lineEndDw = endDw; drawArrowHead = false; } else { var arrowheadMaxLengthPx = this._props.arrowheadLengthRatio * this._props.arrowLineWidthPx; arrowheadLengthPx = Math.min(arrowheadMaxLengthPx, arrowLengthPx / 2); var arrowheadCenterLengthPx = (1 - this._props.arrowheadOffsetRatio) * arrowheadLengthPx; var lineLengthPx = arrowLengthPx - arrowheadCenterLengthPx; lineEndDw = startDw.add(offsetDw.x(lineLengthPx / arrowLengthPx)); drawArrowHead = true; } var startPx = this.pos2Px(startDw); var lineEndPx = this.pos2Px(lineEndDw); this.save(); this._ctx.lineWidth = this._props.arrowLineWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.arrowLinePattern)); this._setLineStyles(type); this._ctx.beginPath(); this._ctx.moveTo(startPx.e(1), startPx.e(2)); this._ctx.lineTo(lineEndPx.e(1), lineEndPx.e(2)); this._ctx.stroke(); if (drawArrowHead) { this._arrowhead(endDw, offsetDw, arrowheadLengthPx); } this.restore(); }; /** Draw an arrow given the start position and offset. @param {Vector} startDw Initial point of the arrow (drawing coords). @param {Vector} offsetDw Offset vector of the arrow (drawing coords). @param {string} type Optional type of vector being drawn. */ PrairieDraw.prototype.arrowFrom = function (startDw, offsetDw, type) { var endDw = startDw.add(offsetDw); this.arrow(startDw, endDw, type); }; /** Draw an arrow given the end position and offset. @param {Vector} endDw Final point of the arrow (drawing coords). @param {Vector} offsetDw Offset vector of the arrow (drawing coords). @param {string} type Optional type of vector being drawn. */ PrairieDraw.prototype.arrowTo = function (endDw, offsetDw, type) { var startDw = endDw.subtract(offsetDw); this.arrow(startDw, endDw, type); }; /** Draw an arrow out of the page (circle with centered dot). @param {Vector} posDw The position of the arrow. @param {string} type Optional type of vector being drawn. */ PrairieDraw.prototype.arrowOutOfPage = function (posDw, type) { var posPx = this.pos2Px(posDw); var r = this._props.arrowOutOfPageRadiusPx; this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.beginPath(); this._ctx.arc(0, 0, r, 0, 2 * Math.PI); this._ctx.fillStyle = 'rgb(255, 255, 255)'; this._ctx.fill(); this._ctx.lineWidth = this._props.arrowLineWidthPx; this._setLineStyles(type); this._ctx.stroke(); this._ctx.beginPath(); this._ctx.arc(0, 0, this._props.arrowLineWidthPx * 0.7, 0, 2 * Math.PI); this._ctx.fill(); this._ctx.restore(); }; /** Draw an arrow into the page (circle with times). @param {Vector} posDw The position of the arrow. @param {string} type Optional type of vector being drawn. */ PrairieDraw.prototype.arrowIntoPage = function (posDw, type) { var posPx = this.pos2Px(posDw); var r = this._props.arrowOutOfPageRadiusPx; var rs = r / Math.sqrt(2); this._ctx.save(); this._ctx.lineWidth = this._props.arrowLineWidthPx; this._setLineStyles(type); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.beginPath(); this._ctx.arc(0, 0, r, 0, 2 * Math.PI); this._ctx.fillStyle = 'rgb(255, 255, 255)'; this._ctx.fill(); this._ctx.stroke(); this._ctx.beginPath(); this._ctx.moveTo(-rs, -rs); this._ctx.lineTo(rs, rs); this._ctx.stroke(); this._ctx.beginPath(); this._ctx.moveTo(rs, -rs); this._ctx.lineTo(-rs, rs); this._ctx.stroke(); this._ctx.restore(); }; /*****************************************************************************/ /** Draw a circle arrow by specifying the center and extent. @param {Vector} posDw The center of the circle arrow. @param {number} radDw The radius at the mid-angle. @param {number} centerAngleDw The center angle (counterclockwise from x axis, in radians). @param {number} extentAngleDw The extent of the arrow (counterclockwise, in radians). @param {string} type (Optional) The type of the arrow. @param {bool} fixedRad (Optional) Whether to use a fixed radius (default: false). */ PrairieDraw.prototype.circleArrowCentered = function ( posDw, radDw, centerAngleDw, extentAngleDw, type, fixedRad ) { var startAngleDw = centerAngleDw - extentAngleDw / 2; var endAngleDw = centerAngleDw + extentAngleDw / 2; this.circleArrow(posDw, radDw, startAngleDw, endAngleDw, type, fixedRad); }; /** Draw a circle arrow. @param {Vector} posDw The center of the circle arrow. @param {number} radDw The radius at the mid-angle. @param {number} startAngleDw The starting angle (counterclockwise from x axis, in radians). @param {number} endAngleDw The ending angle (counterclockwise from x axis, in radians). @param {string} type (Optional) The type of the arrow. @param {bool} fixedRad (Optional) Whether to use a fixed radius (default: false). @param {number} idealSegmentSize (Optional) The ideal linear segment size to use (radians). */ PrairieDraw.prototype.circleArrow = function ( posDw, radDw, startAngleDw, endAngleDw, type, fixedRad, idealSegmentSize ) { this.save(); this._ctx.lineWidth = this._props.arrowLineWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.arrowLinePattern)); this._setLineStyles(type); // convert to Px coordinates var startOffsetDw = PrairieGeom.vector2DAtAngle(startAngleDw).x(radDw); var posPx = this.pos2Px(posDw); var startOffsetPx = this.vec2Px(startOffsetDw); var radiusPx = startOffsetPx.modulus(); var startAnglePx = PrairieGeom.angleOf(startOffsetPx); var deltaAngleDw = endAngleDw - startAngleDw; // assume a possibly reflected/rotated but equally scaled Dw/Px transformation var deltaAnglePx = this._transIsReflection() ? -deltaAngleDw : deltaAngleDw; var endAnglePx = startAnglePx + deltaAnglePx; // compute arrowhead properties var startRadiusPx = this._circleArrowRadius( radiusPx, startAnglePx, startAnglePx, endAnglePx, fixedRad ); var endRadiusPx = this._circleArrowRadius( radiusPx, endAnglePx, startAnglePx, endAnglePx, fixedRad ); var arrowLengthPx = radiusPx * Math.abs(endAnglePx - startAnglePx); var arrowheadMaxLengthPx = this._props.arrowheadLengthRatio * this._props.arrowLineWidthPx; var arrowheadLengthPx = Math.min(arrowheadMaxLengthPx, arrowLengthPx / 2); var arrowheadCenterLengthPx = (1 - this._props.arrowheadOffsetRatio) * arrowheadLengthPx; var arrowheadExtraCenterLengthPx = (1 - this._props.arrowheadOffsetRatio / 3) * arrowheadLengthPx; var arrowheadAnglePx = arrowheadCenterLengthPx / endRadiusPx; var arrowheadExtraAnglePx = arrowheadExtraCenterLengthPx / endRadiusPx; var preEndAnglePx = endAnglePx - PrairieGeom.sign(endAnglePx - startAnglePx) * arrowheadAnglePx; var arrowBaseAnglePx = endAnglePx - PrairieGeom.sign(endAnglePx - startAnglePx) * arrowheadExtraAnglePx; this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); idealSegmentSize = idealSegmentSize === undefined ? 0.2 : idealSegmentSize; // radians var numSegments = Math.ceil(Math.abs(preEndAnglePx - startAnglePx) / idealSegmentSize); var i, anglePx, rPx; var offsetPx = PrairieGeom.vector2DAtAngle(startAnglePx).x(startRadiusPx); this._ctx.beginPath(); this._ctx.moveTo(offsetPx.e(1), offsetPx.e(2)); for (i = 1; i <= numSegments; i++) { anglePx = PrairieGeom.linearInterp(startAnglePx, preEndAnglePx, i / numSegments); rPx = this._circleArrowRadius(radiusPx, anglePx, startAnglePx, endAnglePx, fixedRad); offsetPx = PrairieGeom.vector2DAtAngle(anglePx).x(rPx); this._ctx.lineTo(offsetPx.e(1), offsetPx.e(2)); } this._ctx.stroke(); this._ctx.restore(); var arrowBaseRadiusPx = this._circleArrowRadius( radiusPx, arrowBaseAnglePx, startAnglePx, endAnglePx, fixedRad ); var arrowPosPx = posPx.add(PrairieGeom.vector2DAtAngle(endAnglePx).x(endRadiusPx)); var arrowBasePosPx = posPx.add( PrairieGeom.vector2DAtAngle(arrowBaseAnglePx).x(arrowBaseRadiusPx) ); var arrowDirPx = arrowPosPx.subtract(arrowBasePosPx); var arrowPosDw = this.pos2Dw(arrowPosPx); var arrowDirDw = this.vec2Dw(arrowDirPx); this._arrowhead(arrowPosDw, arrowDirDw, arrowheadLengthPx); this.restore(); }; /** @private Compute the radius at a certain angle within a circle arrow. @param {number} midRadPx The radius at the midpoint of the circle arrow. @param {number} anglePx The angle at which to find the radius. @param {number} startAnglePx The starting angle (counterclockwise from x axis, in radians). @param {number} endAnglePx The ending angle (counterclockwise from x axis, in radians). @return {number} The radius at the given angle (pixel coords). @param {bool} fixedRad (Optional) Whether to use a fixed radius (default: false). */ PrairieDraw.prototype._circleArrowRadius = function ( midRadPx, anglePx, startAnglePx, endAnglePx, fixedRad ) { if (fixedRad !== undefined && fixedRad === true) { return midRadPx; } if (Math.abs(endAnglePx - startAnglePx) < 1e-4) { return midRadPx; } var arrowheadMaxLengthPx = this._props.arrowheadLengthRatio * this._props.arrowLineWidthPx; /* jshint laxbreak: true */ var spacingPx = arrowheadMaxLengthPx * this._props.arrowheadWidthRatio * this._props.circleArrowWrapOffsetRatio; var circleArrowWrapDensity = (midRadPx * Math.PI * 2) / spacingPx; var midAnglePx = (startAnglePx + endAnglePx) / 2; var offsetAnglePx = (anglePx - midAnglePx) * PrairieGeom.sign(endAnglePx - startAnglePx); if (offsetAnglePx > 0) { return midRadPx * (1 + offsetAnglePx / circleArrowWrapDensity); } else { return midRadPx * Math.exp(offsetAnglePx / circleArrowWrapDensity); } }; /*****************************************************************************/ /** Draw an arc in 3D. @param {Vector} posDw The center of the arc. @param {number} radDw The radius of the arc. @param {Vector} normDw (Optional) The normal vector to the plane containing the arc (default: z axis). @param {Vector} refDw (Optional) The reference vector to measure angles from (default: an orthogonal vector to normDw). @param {number} startAngleDw (Optional) The starting angle (counterclockwise from refDw about normDw, in radians, default: 0). @param {number} endAngleDw (Optional) The ending angle (counterclockwise from refDw about normDw, in radians, default: 2 pi). @param {string} type (Optional) The type of the line. @param {Object} options (Optional) Various options. */ PrairieDraw.prototype.arc3D = function ( posDw, radDw, normDw, refDw, startAngleDw, endAngleDw, options ) { posDw = this.pos2To3(posDw); normDw = normDw === undefined ? Vector.k : normDw; refDw = refDw === undefined ? PrairieGeom.chooseNormVec(normDw) : refDw; var fullCircle = startAngleDw === undefined && endAngleDw === undefined; startAngleDw = startAngleDw === undefined ? 0 : startAngleDw; endAngleDw = endAngleDw === undefined ? 2 * Math.PI : endAngleDw; options = options === undefined ? {} : options; var idealSegmentSize = options.idealSegmentSize === undefined ? (2 * Math.PI) / 40 : options.idealSegmentSize; var uDw = PrairieGeom.orthComp(refDw, normDw).toUnitVector(); var vDw = normDw.toUnitVector().cross(uDw); var numSegments = Math.ceil(Math.abs(endAngleDw - startAngleDw) / idealSegmentSize); var points = []; var theta, p; for (var i = 0; i <= numSegments; i++) { theta = PrairieGeom.linearInterp(startAngleDw, endAngleDw, i / numSegments); p = posDw.add(uDw.x(radDw * Math.cos(theta))).add(vDw.x(radDw * Math.sin(theta))); points.push(this.pos3To2(p)); } if (fullCircle) { points.pop(); this.polyLine(points, true, false); } else { this.polyLine(points); } }; /*****************************************************************************/ /** Draw a circle arrow in 3D. @param {Vector} posDw The center of the arc. @param {number} radDw The radius of the arc. @param {Vector} normDw (Optional) The normal vector to the plane containing the arc (default: z axis). @param {Vector} refDw (Optional) The reference vector to measure angles from (default: x axis). @param {number} startAngleDw (Optional) The starting angle (counterclockwise from refDw about normDw, in radians, default: 0). @param {number} endAngleDw (Optional) The ending angle (counterclockwise from refDw about normDw, in radians, default: 2 pi). @param {string} type (Optional) The type of the line. @param {Object} options (Optional) Various options. */ PrairieDraw.prototype.circleArrow3D = function ( posDw, radDw, normDw, refDw, startAngleDw, endAngleDw, type, options ) { posDw = this.pos2To3(posDw); normDw = normDw || Vector.k; refDw = refDw || Vector.i; startAngleDw = startAngleDw === undefined ? 0 : startAngleDw; endAngleDw = endAngleDw === undefined ? 2 * Math.PI : endAngleDw; options = options === undefined ? {} : options; var idealSegmentSize = options.idealSegmentSize === undefined ? (2 * Math.PI) / 40 : options.idealSegmentSize; var uDw = PrairieGeom.orthComp(refDw, normDw).toUnitVector(); var vDw = normDw.toUnitVector().cross(uDw); var numSegments = Math.ceil(Math.abs(endAngleDw - startAngleDw) / idealSegmentSize); var points = []; var theta, p; for (var i = 0; i <= numSegments; i++) { theta = PrairieGeom.linearInterp(startAngleDw, endAngleDw, i / numSegments); p = posDw.add(uDw.x(radDw * Math.cos(theta))).add(vDw.x(radDw * Math.sin(theta))); points.push(this.pos3To2(p)); } this.polyLineArrow(points, type); }; /** Label a circle line in 3D. @param {string} labelText The label text. @param {Vector} labelAnchor The label anchor (first coord -1 to 1 along the line, second -1 to 1 transverse). @param {Vector} posDw The center of the arc. @param {number} radDw The radius of the arc. @param {Vector} normDw (Optional) The normal vector to the plane containing the arc (default: z axis). @param {Vector} refDw (Optional) The reference vector to measure angles from (default: x axis). @param {number} startAngleDw (Optional) The starting angle (counterclockwise from refDw about normDw, in radians, default: 0). @param {number} endAngleDw (Optional) The ending angle (counterclockwise from refDw about normDw, in radians, default: 2 pi). */ PrairieDraw.prototype.labelCircleLine3D = function ( labelText, labelAnchor, posDw, radDw, normDw, refDw, startAngleDw, endAngleDw ) { if (labelText === undefined) { return; } posDw = this.pos2To3(posDw); normDw = normDw || Vector.k; refDw = refDw || Vector.i; startAngleDw = startAngleDw === undefined ? 0 : startAngleDw; endAngleDw = endAngleDw === undefined ? 2 * Math.PI : endAngleDw; var uDw = PrairieGeom.orthComp(refDw, normDw).toUnitVector(); var vDw = normDw.toUnitVector().cross(uDw); var theta = PrairieGeom.linearInterp(startAngleDw, endAngleDw, (labelAnchor.e(1) + 1) / 2); var p = posDw.add(uDw.x(radDw * Math.cos(theta))).add(vDw.x(radDw * Math.sin(theta))); var p2Dw = this.pos3To2(p); var t3Dw = uDw.x(-Math.sin(theta)).add(vDw.x(Math.cos(theta))); var n3Dw = uDw.x(Math.cos(theta)).add(vDw.x(Math.sin(theta))); var t2Px = this.vec2Px(this.vec3To2(t3Dw, p)); var n2Px = this.vec2Px(this.vec3To2(n3Dw, p)); n2Px = PrairieGeom.orthComp(n2Px, t2Px); t2Px = t2Px.toUnitVector(); n2Px = n2Px.toUnitVector(); var oPx = t2Px.x(labelAnchor.e(1)).add(n2Px.x(labelAnchor.e(2))); var oDw = this.vec2Dw(oPx); var aDw = oDw.x(-1).toUnitVector(); var anchor = aDw.x(1.0 / Math.abs(aDw.max())).x(Math.abs(labelAnchor.max())); this.text(p2Dw, anchor, labelText); }; /*****************************************************************************/ /** Draw a sphere. @param {Vector} posDw Position of the sphere center. @param {number} radDw Radius of the sphere. @param {bool} filled (Optional) Whether to fill the sphere (default: false). */ PrairieDraw.prototype.sphere = function (posDw, radDw, filled) { filled = filled === undefined ? false : filled; var posVw = this.posDwToVw(posDw); var edgeDw = posDw.add($V([radDw, 0, 0])); var edgeVw = this.posDwToVw(edgeDw); var radVw = edgeVw.subtract(posVw).modulus(); var posDw2 = PrairieGeom.orthProjPos3D(posVw); this.circle(posDw2, radVw, filled); }; /** Draw a circular slice on a sphere. @param {Vector} posDw Position of the sphere center. @param {number} radDw Radius of the sphere. @param {Vector} normDw Normal vector to the circle. @param {number} distDw Distance from sphere center to circle center along normDw. @param {string} drawBack (Optional) Whether to draw the back line (default: true). @param {string} drawFront (Optional) Whether to draw the front line (default: true). @param {Vector} refDw (Optional) The reference vector to measure angles from (default: an orthogonal vector to normDw). @param {number} startAngleDw (Optional) The starting angle (counterclockwise from refDw about normDw, in radians, default: 0). @param {number} endAngleDw (Optional) The ending angle (counterclockwise from refDw about normDw, in radians, default: 2 pi). */ PrairieDraw.prototype.sphereSlice = function ( posDw, radDw, normDw, distDw, drawBack, drawFront, refDw, startAngleDw, endAngleDw ) { var cRDwSq = radDw * radDw - distDw * distDw; if (cRDwSq <= 0) { return; } var cRDw = Math.sqrt(cRDwSq); var circlePosDw = posDw.add(normDw.toUnitVector().x(distDw)); drawBack = drawBack === undefined ? true : drawBack; drawFront = drawFront === undefined ? true : drawFront; var normVw = this.vecDwToVw(normDw); if (PrairieGeom.orthComp(Vector.k, normVw).modulus() < 1e-10) { // looking straight down on the circle if (distDw > 0) { // front side, completely visible this.arc3D(circlePosDw, cRDw, normDw, refDw, startAngleDw, endAngleDw); } else if (distDw < 0) { // back side, completely invisible this.save(); this.setShapeDrawHidden(); this.arc3D(circlePosDw, cRDw, normDw, refDw, startAngleDw, endAngleDw); this.restore(); } // if distDw == 0 then it's a great circle, don't draw it return; } var refVw; if (refDw === undefined) { refVw = PrairieGeom.orthComp(Vector.k, normVw); refDw = this.vecVwToDw(refVw); } refVw = this.vecDwToVw(refDw); var uVw = refVw.toUnitVector(); var vVw = normVw.toUnitVector().cross(uVw); var dVw = this.vecDwToVw(normDw.toUnitVector().x(distDw)); var cRVw = this.vecDwToVw(refDw.toUnitVector().x(cRDw)).modulus(); var A = -dVw.e(3); var B = uVw.e(3) * cRVw; var C = vVw.e(3) * cRVw; var BCMag = Math.sqrt(B * B + C * C); var AN = A / BCMag; var phi = Math.atan2(C, B); if (AN <= -1) { // only front if (drawFront) { this.arc3D(circlePosDw, cRDw, normDw, refDw, startAngleDw, endAngleDw); } } else if (AN >= 1) { // only back if (drawBack && this._props.hiddenLineDraw) { this.save(); this.setShapeDrawHidden(); this.arc3D(circlePosDw, cRDw, normDw, refDw, startAngleDw, endAngleDw); this.restore(); } } else { // front and back var acosAN = Math.acos(AN); var theta1 = phi + acosAN; var theta2 = phi + 2 * Math.PI - acosAN; var i, intersections, range; if (drawBack && this._props.hiddenLineDraw) { this.save(); this.setShapeDrawHidden(); if (theta2 > theta1) { if (startAngleDw === undefined || endAngleDw === undefined) { this.arc3D(circlePosDw, cRDw, normDw, refDw, theta1, theta2); } else { intersections = PrairieGeom.intersectAngleRanges( [theta1, theta2], [startAngleDw, endAngleDw] ); for (i = 0; i < intersections.length; i++) { range = intersections[i]; this.arc3D(circlePosDw, cRDw, normDw, refDw, range[0], range[1]); } } } this.restore(); } if (drawFront) { if (startAngleDw === undefined || endAngleDw === undefined) { this.arc3D(circlePosDw, cRDw, normDw, refDw, theta2, theta1 + 2 * Math.PI); } else { intersections = PrairieGeom.intersectAngleRanges( [theta2, theta1 + 2 * Math.PI], [startAngleDw, endAngleDw] ); for (i = 0; i < intersections.length; i++) { range = intersections[i]; this.arc3D(circlePosDw, cRDw, normDw, refDw, range[0], range[1]); } } } } }; /*****************************************************************************/ /** Label an angle with an inset label. @param {Vector} pos The corner position. @param {Vector} p1 Position of first other point. @param {Vector} p2 Position of second other point. @param {string} label The label text. */ PrairieDraw.prototype.labelAngle = function (pos, p1, p2, label) { pos = this.pos3To2(pos); p1 = this.pos3To2(p1); p2 = this.pos3To2(p2); var v1 = p1.subtract(pos); var v2 = p2.subtract(pos); var vMid = v1.add(v2).x(0.5); var anchor = vMid.x(-1.8 / PrairieGeom.supNorm(vMid)); this.text(pos, anchor, label); }; /*****************************************************************************/ /** Draw an arc. @param {Vector} centerDw The center of the circle. @param {Vector} radiusDw The radius of the circle (or major axis for ellipses). @param {number} startAngle (Optional) The start angle of the arc (radians, default: 0). @param {number} endAngle (Optional) The end angle of the arc (radians, default: 2 pi). @param {bool} filled (Optional) Whether to fill the arc (default: false). @param {Number} aspect (Optional) The aspect ratio (major / minor) (default: 1). */ PrairieDraw.prototype.arc = function (centerDw, radiusDw, startAngle, endAngle, filled, aspect) { startAngle = startAngle === undefined ? 0 : startAngle; endAngle = endAngle === undefined ? 2 * Math.PI : endAngle; filled = filled === undefined ? false : filled; aspect = aspect === undefined ? 1 : aspect; var centerPx = this.pos2Px(centerDw); var offsetDw = $V([radiusDw, 0]); var offsetPx = this.vec2Px(offsetDw); var radiusPx = offsetPx.modulus(); var anglePx = PrairieGeom.angleOf(offsetPx); this._ctx.save(); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.save(); this._ctx.translate(centerPx.e(1), centerPx.e(2)); this._ctx.rotate(anglePx); this._ctx.scale(1, 1 / aspect); this._ctx.beginPath(); this._ctx.arc(0, 0, radiusPx, -endAngle, -startAngle); this._ctx.restore(); if (filled) { this._ctx.fill(); } this._ctx.stroke(); this._ctx.restore(); }; /*****************************************************************************/ /** Draw a polyLine (closed or open). @param {Array} pointsDw A list of drawing coordinates that form the polyLine. @param {bool} closed (Optional) Whether the shape should be closed (default: false). @param {bool} filled (Optional) Whether the shape should be filled (default: true). */ PrairieDraw.prototype.polyLine = function (pointsDw, closed, filled) { if (pointsDw.length < 2) { return; } this._ctx.save(); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.beginPath(); var pDw = this.pos3To2(pointsDw[0]); var pPx = this.pos2Px(pDw); this._ctx.moveTo(pPx.e(1), pPx.e(2)); for (var i = 1; i < pointsDw.length; i++) { pDw = this.pos3To2(pointsDw[i]); pPx = this.pos2Px(pDw); this._ctx.lineTo(pPx.e(1), pPx.e(2)); } if (closed !== undefined && closed === true) { this._ctx.closePath(); if (filled === undefined || filled === true) { this._ctx.fill(); } } this._ctx.stroke(); this._ctx.restore(); }; /** Draw a polyLine arrow. @param {Array} pointsDw A list of drawing coordinates that form the polyLine. */ PrairieDraw.prototype.polyLineArrow = function (pointsDw, type) { if (pointsDw.length < 2) { return; } // convert the line to pixel coords and find its length var pointsPx = []; var i; var polyLineLengthPx = 0; for (i = 0; i < pointsDw.length; i++) { pointsPx.push(this.pos2Px(this.pos3To2(pointsDw[i]))); if (i > 0) { polyLineLengthPx += pointsPx[i].subtract(pointsPx[i - 1]).modulus(); } } // shorten the line to fit the arrowhead, dropping points and moving the last point var drawArrowHead, arrowheadEndPx, arrowheadOffsetPx, arrowheadLengthPx; if (polyLineLengthPx < 1) { // if too short, don't draw the arrowhead drawArrowHead = false; } else { drawArrowHead = true; var arrowheadMaxLengthPx = this._props.arrowheadLengthRatio * this._props.arrowLineWidthPx; arrowheadLengthPx = Math.min(arrowheadMaxLengthPx, polyLineLengthPx / 2); var arrowheadCenterLengthPx = (1 - this._props.arrowheadOffsetRatio) * arrowheadLengthPx; var lengthToRemovePx = arrowheadCenterLengthPx; i = pointsPx.length - 1; arrowheadEndPx = pointsPx[i]; var segmentLengthPx; while (i > 0) { segmentLengthPx = pointsPx[i].subtract(pointsPx[i - 1]).modulus(); if (lengthToRemovePx > segmentLengthPx) { lengthToRemovePx -= segmentLengthPx; pointsPx.pop(); i--; } else { pointsPx[i] = PrairieGeom.linearInterpVector( pointsPx[i], pointsPx[i - 1], lengthToRemovePx / segmentLengthPx ); break; } } var arrowheadBasePx = pointsPx[i]; arrowheadOffsetPx = arrowheadEndPx.subtract(arrowheadBasePx); } // draw the line this._ctx.save(); this._ctx.lineWidth = this._props.arrowLineWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.arrowLinePattern)); this._setLineStyles(type); this._ctx.beginPath(); var pPx = pointsPx[0]; this._ctx.moveTo(pPx.e(1), pPx.e(2)); for (i = 1; i < pointsPx.length; i++) { pPx = pointsPx[i]; this._ctx.lineTo(pPx.e(1), pPx.e(2)); } this._ctx.stroke(); // draw the arrowhead if (drawArrowHead) { i = pointsPx[i]; this._arrowheadPx(arrowheadEndPx, arrowheadOffsetPx, arrowheadLengthPx); } this._ctx.restore(); }; /*****************************************************************************/ /** Draw a circle. @param {Vector} centerDw The center in drawing coords. @param {number} radiusDw the radius in drawing coords. @param {bool} filled (Optional) Whether to fill the circle (default: true). */ PrairieDraw.prototype.circle = function (centerDw, radiusDw, filled) { filled = filled === undefined ? true : filled; var centerPx = this.pos2Px(centerDw); var offsetDw = $V([radiusDw, 0]); var offsetPx = this.vec2Px(offsetDw); var radiusPx = offsetPx.modulus(); this._ctx.save(); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.beginPath(); this._ctx.arc(centerPx.e(1), centerPx.e(2), radiusPx, 0, 2 * Math.PI); if (filled) { this._ctx.fill(); } this._ctx.stroke(); this._ctx.restore(); }; /** Draw a filled circle. @param {Vector} centerDw The center in drawing coords. @param {number} radiusDw the radius in drawing coords. */ PrairieDraw.prototype.filledCircle = function (centerDw, radiusDw) { var centerPx = this.pos2Px(centerDw); var offsetDw = $V([radiusDw, 0]); var offsetPx = this.vec2Px(offsetDw); var radiusPx = offsetPx.modulus(); this._ctx.save(); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.fillStyle = this._props.shapeOutlineColor; this._ctx.beginPath(); this._ctx.arc(centerPx.e(1), centerPx.e(2), radiusPx, 0, 2 * Math.PI); this._ctx.fill(); this._ctx.restore(); }; /*****************************************************************************/ /** Draw a triagular distributed load @param {Vector} startDw The first point (in drawing coordinates) of the distributed load @param {Vector} endDw The end point (in drawing coordinates) of the distributed load @param {number} sizeStartDw length of the arrow at startDw @param {number} sizeEndDw length of the arrow at endDw @param {string} label the arrow size at startDw @param {string} label the arrow size at endDw @param {boolean} true if arrow heads are towards the line that connects points startDw and endDw, opposite direction if false @param {boolean} true if arrow points up (positive y-axis), false otherwise */ PrairieDraw.prototype.triangularDistributedLoad = function ( startDw, endDw, sizeStartDw, sizeEndDw, labelStart, labelEnd, arrowToLine, arrowDown ) { var LengthDw = endDw.subtract(startDw); var L = LengthDw.modulus(); if (arrowDown) { var sizeStartDwSign = sizeStartDw; var sizeEndDwSign = sizeEndDw; } else { var sizeStartDwSign = -sizeStartDw; var sizeEndDwSign = -sizeEndDw; } var nSpaces = Math.ceil((2 * L) / sizeStartDw); var spacing = L / nSpaces; var inc = 0; this.save(); this.setProp('shapeOutlineColor', 'rgb(255,0,0)'); this.setProp('arrowLineWidthPx', 1); this.setProp('arrowheadLengthRatio', 11); if (arrowToLine) { this.line(startDw.add($V([0, sizeStartDwSign])), endDw.add($V([0, sizeEndDwSign]))); var startArrow = startDw.add($V([0, sizeStartDwSign])); var endArrow = startDw; for (i = 0; i <= nSpaces; i++) { this.arrow( startArrow.add($V([inc, (inc * (sizeEndDwSign - sizeStartDwSign)) / L])), endArrow.add($V([inc, 0])) ); inc = inc + spacing; } this.text(startArrow, $V([2, 0]), labelStart); this.text( startArrow.add( $V([inc - spacing, ((inc - spacing) * (sizeEndDwSign - sizeStartDwSign)) / L]) ), $V([-2, 0]), labelEnd ); } else { this.line(startDw, endDw); var startArrow = startDw; var endArrow = startDw.subtract($V([0, sizeStartDwSign])); for (i = 0; i <= nSpaces; i++) { this.arrow( startArrow.add($V([inc, 0])), endArrow.add($V([inc, (-inc * (sizeEndDwSign - sizeStartDwSign)) / L])) ); inc = inc + spacing; } this.text(endArrow, $V([2, 0]), labelStart); this.text( endArrow.add( $V([inc - spacing, (-(inc - spacing) * (sizeEndDwSign - sizeStartDwSign)) / L]) ), $V([-2, 0]), labelEnd ); } this.restore(); }; /*****************************************************************************/ /** Draw a rod with hinge points at start and end and the given width. @param {Vector} startDw The first hinge point (center of circular end) in drawing coordinates. @param {Vector} startDw The second hinge point (drawing coordinates). @param {number} widthDw The width of the rod (drawing coordinates). */ PrairieDraw.prototype.rod = function (startDw, endDw, widthDw) { var offsetLengthDw = endDw.subtract(startDw); var offsetWidthDw = offsetLengthDw .rotate(Math.PI / 2, $V([0, 0])) .toUnitVector() .x(widthDw); var startPx = this.pos2Px(startDw); var offsetLengthPx = this.vec2Px(offsetLengthDw); var offsetWidthPx = this.vec2Px(offsetWidthDw); var lengthPx = offsetLengthPx.modulus(); var rPx = offsetWidthPx.modulus() / 2; this._ctx.save(); this._ctx.translate(startPx.e(1), startPx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(offsetLengthPx)); this._ctx.beginPath(); this._ctx.moveTo(0, rPx); this._ctx.arcTo(lengthPx + rPx, rPx, lengthPx + rPx, -rPx, rPx); this._ctx.arcTo(lengthPx + rPx, -rPx, 0, -rPx, rPx); this._ctx.arcTo(-rPx, -rPx, -rPx, rPx, rPx); this._ctx.arcTo(-rPx, rPx, 0, rPx, rPx); if (this._props.shapeInsideColor !== 'none') { this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.fill(); } this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.stroke(); this._ctx.restore(); }; /** Draw a L-shape rod with hinge points at start, center and end, and the given width. @param {Vector} startDw The first hinge point (center of circular end) in drawing coordinates. @param {Vector} centerDw The second hinge point (drawing coordinates). @param {Vector} endDw The third hinge point (drawing coordinates). @param {number} widthDw The width of the rod (drawing coordinates). */ PrairieDraw.prototype.LshapeRod = function (startDw, centerDw, endDw, widthDw) { var offsetLength1Dw = centerDw.subtract(startDw); var offsetLength2Dw = endDw.subtract(centerDw); var offsetWidthDw = offsetLength1Dw .rotate(Math.PI / 2, $V([0, 0])) .toUnitVector() .x(widthDw); var startPx = this.pos2Px(startDw); var centerPx = this.pos2Px(centerDw); var endPx = this.pos2Px(endDw); var offsetLength1Px = this.vec2Px(offsetLength1Dw); var offsetLength2Px = this.vec2Px(offsetLength2Dw); var offsetWidthPx = this.vec2Px(offsetWidthDw); var length1Px = offsetLength1Px.modulus(); var length2Px = offsetLength2Px.modulus(); var rPx = offsetWidthPx.modulus() / 2; this._ctx.save(); this._ctx.translate(startPx.e(1), startPx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(offsetLength1Px)); this._ctx.beginPath(); this._ctx.moveTo(0, rPx); var beta = -PrairieGeom.angleFrom(offsetLength1Px, offsetLength2Px); var x1 = length1Px + rPx / Math.sin(beta) - rPx / Math.tan(beta); var y1 = rPx; var x2 = length1Px + length2Px * Math.cos(beta); var y2 = -length2Px * Math.sin(beta); var x3 = x2 + rPx * Math.sin(beta); var y3 = y2 + rPx * Math.cos(beta); var x4 = x3 + rPx * Math.cos(beta); var y4 = y3 - rPx * Math.sin(beta); var x5 = x2 + rPx * Math.cos(beta); var y5 = y2 - rPx * Math.sin(beta); var x6 = x5 - rPx * Math.sin(beta); var y6 = y5 - rPx * Math.cos(beta); var x7 = length1Px - rPx / Math.sin(beta) + rPx / Math.tan(beta); var y7 = -rPx; this._ctx.arcTo(x1, y1, x3, y3, rPx); this._ctx.arcTo(x4, y4, x5, y5, rPx); this._ctx.arcTo(x6, y6, x7, y7, rPx); this._ctx.arcTo(x7, y7, 0, -rPx, rPx); this._ctx.arcTo(-rPx, -rPx, -rPx, rPx, rPx); this._ctx.arcTo(-rPx, rPx, 0, rPx, rPx); if (this._props.shapeInsideColor !== 'none') { this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.fill(); } this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.stroke(); this._ctx.restore(); }; /** Draw a T-shape rod with hinge points at start, center, center-end and end, and the given width. @param {Vector} startDw The first hinge point (center of circular end) in drawing coordinates. @param {Vector} centerDw The second hinge point (drawing coordinates). @param {Vector} endDw The third hinge point (drawing coordinates). @param {Vector} centerEndDw The fourth hinge point (drawing coordinates). @param {number} widthDw The width of the rod (drawing coordinates). */ PrairieDraw.prototype.TshapeRod = function (startDw, centerDw, endDw, centerEndDw, widthDw) { var offsetStartRodDw = centerDw.subtract(startDw); var offsetEndRodDw = endDw.subtract(centerDw); var offsetCenterRodDw = centerEndDw.subtract(centerDw); var offsetWidthDw = offsetStartRodDw .rotate(Math.PI / 2, $V([0, 0])) .toUnitVector() .x(widthDw); var startPx = this.pos2Px(startDw); var centerPx = this.pos2Px(centerDw); var endPx = this.pos2Px(endDw); var offsetStartRodPx = this.vec2Px(offsetStartRodDw); var offsetEndRodPx = this.vec2Px(offsetEndRodDw); var offsetCenterRodPx = this.vec2Px(offsetCenterRodDw); var offsetWidthPx = this.vec2Px(offsetWidthDw); var lengthStartRodPx = offsetStartRodPx.modulus(); var lengthEndRodPx = offsetEndRodPx.modulus(); var lengthCenterRodPx = offsetCenterRodPx.modulus(); var rPx = offsetWidthPx.modulus() / 2; this._ctx.save(); this._ctx.translate(startPx.e(1), startPx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(offsetStartRodPx)); this._ctx.beginPath(); this._ctx.moveTo(0, rPx); var angleStartToEnd = PrairieGeom.angleFrom(offsetStartRodPx, offsetEndRodPx); var angleEndToCenter = PrairieGeom.angleFrom(offsetEndRodPx, offsetCenterRodPx); if (Math.abs(angleEndToCenter) < Math.PI) { var length1Px = lengthStartRodPx; var length2Px = lengthEndRodPx; var length3Px = lengthCenterRodPx; var beta = -angleStartToEnd; var alpha = -angleEndToCenter; } else { var length1Px = lengthStartRodPx; var length2Px = lengthCenterRodPx; var length3Px = lengthEndRodPx; var beta = -PrairieGeom.angleFrom(offsetStartRodPx, offsetCenterRodPx); var alpha = angleEndToCenter; } var x1 = length1Px + rPx / Math.sin(beta) - rPx / Math.tan(beta); var y1 = rPx; var x2 = length1Px + length2Px * Math.cos(beta); var y2 = -length2Px * Math.sin(beta); var x3 = x2 + rPx * Math.sin(beta); var y3 = y2 + rPx * Math.cos(beta); var x4 = x3 + rPx * Math.cos(beta); var y4 = y3 - rPx * Math.sin(beta); var x5 = x2 + rPx * Math.cos(beta); var y5 = y2 - rPx * Math.sin(beta); var x6 = x5 - rPx * Math.sin(beta); var y6 = y5 - rPx * Math.cos(beta); var x7 = length1Px + rPx * Math.cos(beta) * (1 / Math.sin(alpha) + 1 / Math.tan(alpha) - Math.tan(beta)); var y7 = -rPx / Math.cos(beta) - rPx * Math.sin(beta) * (1 / Math.sin(alpha) + 1 / Math.tan(alpha) - Math.tan(beta)); var x8 = length1Px + length3Px * Math.cos(beta + alpha); var y8 = -length3Px * Math.sin(beta + alpha); var x9 = x8 + rPx * Math.sin(beta + alpha); var y9 = y8 + rPx * Math.cos(beta + alpha); var x10 = x9 + rPx * Math.cos(beta + alpha); var y10 = y9 - rPx * Math.sin(beta + alpha); var x11 = x8 + rPx * Math.cos(beta + alpha); var y11 = y8 - rPx * Math.sin(beta + alpha); var x12 = x11 - rPx * Math.sin(beta + alpha); var y12 = y11 - rPx * Math.cos(beta + alpha); var x13 = length1Px - rPx / Math.sin(beta + alpha) + rPx / Math.tan(beta + alpha); var y13 = -rPx; this._ctx.arcTo(x1, y1, x3, y3, rPx); this._ctx.arcTo(x4, y4, x5, y5, rPx); this._ctx.arcTo(x6, y6, x7, y7, rPx); this._ctx.arcTo(x7, y7, x9, y9, rPx); this._ctx.arcTo(x10, y10, x11, y11, rPx); this._ctx.arcTo(x12, y12, x13, y13, rPx); this._ctx.arcTo(x13, y13, 0, -rPx, rPx); this._ctx.arcTo(-rPx, -rPx, -rPx, rPx, rPx); this._ctx.arcTo(-rPx, rPx, 0, rPx, rPx); if (this._props.shapeInsideColor !== 'none') { this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.fill(); } this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.stroke(); this._ctx.restore(); }; /** Draw a pivot. @param {Vector} baseDw The center of the base (drawing coordinates). @param {Vector} hingeDw The hinge point (center of circular end) in drawing coordinates. @param {number} widthDw The width of the pivot (drawing coordinates). */ PrairieDraw.prototype.pivot = function (baseDw, hingeDw, widthDw) { var offsetLengthDw = hingeDw.subtract(baseDw); var offsetWidthDw = offsetLengthDw .rotate(Math.PI / 2, $V([0, 0])) .toUnitVector() .x(widthDw); var basePx = this.pos2Px(baseDw); var offsetLengthPx = this.vec2Px(offsetLengthDw); var offsetWidthPx = this.vec2Px(offsetWidthDw); var lengthPx = offsetLengthPx.modulus(); var rPx = offsetWidthPx.modulus() / 2; this._ctx.save(); this._ctx.translate(basePx.e(1), basePx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(offsetLengthPx)); this._ctx.beginPath(); this._ctx.moveTo(0, rPx); this._ctx.arcTo(lengthPx + rPx, rPx, lengthPx + rPx, -rPx, rPx); this._ctx.arcTo(lengthPx + rPx, -rPx, 0, -rPx, rPx); this._ctx.lineTo(0, -rPx); this._ctx.closePath(); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.fill(); this._ctx.stroke(); this._ctx.restore(); }; /** Draw a square with a given base point and center. @param {Vector} baseDw The mid-point of the base (drawing coordinates). @param {Vector} centerDw The center of the square (drawing coordinates). */ PrairieDraw.prototype.square = function (baseDw, centerDw) { var basePx = this.pos2Px(baseDw); var centerPx = this.pos2Px(centerDw); var offsetPx = centerPx.subtract(basePx); var rPx = offsetPx.modulus(); this._ctx.save(); this._ctx.translate(basePx.e(1), basePx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(offsetPx)); this._ctx.beginPath(); this._ctx.rect(0, -rPx, 2 * rPx, 2 * rPx); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.fill(); this._ctx.stroke(); this._ctx.restore(); }; /** Draw an axis-aligned rectangle with a given width and height, centered at the origin. @param {number} widthDw The width of the rectangle. @param {number} heightDw The height of the rectangle. @param {number} centerDw Optional: The center of the rectangle (default: the origin). @param {number} angleDw Optional: The rotation angle of the rectangle (default: zero). @param {bool} filled Optional: Whether to fill the rectangle (default: true). */ PrairieDraw.prototype.rectangle = function (widthDw, heightDw, centerDw, angleDw, filled) { centerDw = centerDw === undefined ? $V([0, 0]) : centerDw; angleDw = angleDw === undefined ? 0 : angleDw; var pointsDw = [ $V([-widthDw / 2, -heightDw / 2]), $V([widthDw / 2, -heightDw / 2]), $V([widthDw / 2, heightDw / 2]), $V([-widthDw / 2, heightDw / 2]), ]; var closed = true; filled = filled === undefined ? true : filled; this.save(); this.translate(centerDw); this.rotate(angleDw); this.polyLine(pointsDw, closed, filled); this.restore(); }; /** Draw a rectangle with the given corners and height. @param {Vector} pos1Dw First corner of the rectangle. @param {Vector} pos2Dw Second corner of the rectangle. @param {number} heightDw The height of the rectangle. */ PrairieDraw.prototype.rectangleGeneric = function (pos1Dw, pos2Dw, heightDw) { var dDw = PrairieGeom.perp(pos2Dw.subtract(pos1Dw)).toUnitVector().x(heightDw); var pointsDw = [pos1Dw, pos2Dw, pos2Dw.add(dDw), pos1Dw.add(dDw)]; var closed = true; this.polyLine(pointsDw, closed); }; /** Draw a ground element. @param {Vector} posDw The position of the ground center (drawing coordinates). @param {Vector} normDw The outward normal (drawing coordinates). @param (number} lengthDw The total length of the ground segment. */ PrairieDraw.prototype.ground = function (posDw, normDw, lengthDw) { var tangentDw = normDw .rotate(Math.PI / 2, $V([0, 0])) .toUnitVector() .x(lengthDw); var posPx = this.pos2Px(posDw); var normPx = this.vec2Px(normDw); var tangentPx = this.vec2Px(tangentDw); var lengthPx = tangentPx.modulus(); var groundDepthPx = Math.min(lengthPx, this._props.groundDepthPx); this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(normPx) - Math.PI / 2); this._ctx.beginPath(); this._ctx.rect(-lengthPx / 2, -groundDepthPx, lengthPx, groundDepthPx); this._ctx.fillStyle = this._props.groundInsideColor; this._ctx.fill(); this._ctx.beginPath(); this._ctx.moveTo(-lengthPx / 2, 0); this._ctx.lineTo(lengthPx / 2, 0); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.groundOutlineColor; this._ctx.stroke(); this._ctx.restore(); }; /** Draw a ground element with hashed shading. @param {Vector} posDw The position of the ground center (drawing coords). @param {Vector} normDw The outward normal (drawing coords). @param (number} lengthDw The total length of the ground segment (drawing coords). @param {number} offsetDw (Optional) The offset of the shading (drawing coords). */ PrairieDraw.prototype.groundHashed = function (posDw, normDw, lengthDw, offsetDw) { offsetDw = offsetDw === undefined ? 0 : offsetDw; var tangentDw = normDw .rotate(Math.PI / 2, $V([0, 0])) .toUnitVector() .x(lengthDw); var offsetVecDw = tangentDw.toUnitVector().x(offsetDw); var posPx = this.pos2Px(posDw); var normPx = this.vec2Px(normDw); var tangentPx = this.vec2Px(tangentDw); var lengthPx = tangentPx.modulus(); var offsetVecPx = this.vec2Px(offsetVecDw); var offsetPx = offsetVecPx.modulus() * PrairieGeom.sign(offsetDw); this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(normPx) + Math.PI / 2); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.groundOutlineColor; this._ctx.beginPath(); this._ctx.moveTo(-lengthPx / 2, 0); this._ctx.lineTo(lengthPx / 2, 0); this._ctx.stroke(); var startX = offsetPx % this._props.groundSpacingPx; var x = startX; while (x < lengthPx / 2) { this._ctx.beginPath(); this._ctx.moveTo(x, 0); this._ctx.lineTo(x - this._props.groundWidthPx, this._props.groundDepthPx); this._ctx.stroke(); x += this._props.groundSpacingPx; } x = startX - this._props.groundSpacingPx; while (x > -lengthPx / 2) { this._ctx.beginPath(); this._ctx.moveTo(x, 0); this._ctx.lineTo(x - this._props.groundWidthPx, this._props.groundDepthPx); this._ctx.stroke(); x -= this._props.groundSpacingPx; } this._ctx.restore(); }; /** Draw an arc ground element. @param {Vector} centerDw The center of the circle. @param {Vector} radiusDw The radius of the circle. @param {number} startAngle (Optional) The start angle of the arc (radians, default: 0). @param {number} endAngle (Optional) The end angle of the arc (radians, default: 2 pi). @param {bool} outside (Optional) Whether to draw the ground outside the curve (default: true). */ PrairieDraw.prototype.arcGround = function (centerDw, radiusDw, startAngle, endAngle, outside) { startAngle = startAngle === undefined ? 0 : startAngle; endAngle = endAngle === undefined ? 2 * Math.PI : endAngle; outside = outside === undefined ? true : outside; var centerPx = this.pos2Px(centerDw); var offsetDw = $V([radiusDw, 0]); var offsetPx = this.vec2Px(offsetDw); var radiusPx = offsetPx.modulus(); var groundDepthPx = Math.min(radiusPx, this._props.groundDepthPx); var groundOffsetPx = outside ? groundDepthPx : -groundDepthPx; this._ctx.save(); // fill the shaded area this._ctx.beginPath(); this._ctx.arc(centerPx.e(1), centerPx.e(2), radiusPx, -endAngle, -startAngle, false); this._ctx.arc( centerPx.e(1), centerPx.e(2), radiusPx + groundOffsetPx, -startAngle, -endAngle, true ); this._ctx.fillStyle = this._props.groundInsideColor; this._ctx.fill(); // draw the ground surface this._ctx.beginPath(); this._ctx.arc(centerPx.e(1), centerPx.e(2), radiusPx, -endAngle, -startAngle); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.groundOutlineColor; this._ctx.stroke(); this._ctx.restore(); }; /** Draw a center-of-mass object. @param {Vector} posDw The position of the center of mass. */ PrairieDraw.prototype.centerOfMass = function (posDw) { var posPx = this.pos2Px(posDw); var r = this._props.centerOfMassRadiusPx; this._ctx.save(); this._ctx.lineWidth = this._props.centerOfMassStrokeWidthPx; this._ctx.strokeStyle = this._props.centerOfMassColor; this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.beginPath(); this._ctx.moveTo(-r, 0); this._ctx.lineTo(r, 0); this._ctx.stroke(); this._ctx.beginPath(); this._ctx.moveTo(0, -r); this._ctx.lineTo(0, r); this._ctx.stroke(); this._ctx.beginPath(); this._ctx.arc(0, 0, r, 0, 2 * Math.PI); this._ctx.stroke(); this._ctx.restore(); }; /** Draw a measurement line. @param {Vector} startDw The start position of the measurement. @param {Vector} endDw The end position of the measurement. @param {string} text The measurement label. */ PrairieDraw.prototype.measurement = function (startDw, endDw, text) { var startPx = this.pos2Px(startDw); var endPx = this.pos2Px(endDw); var offsetPx = endPx.subtract(startPx); var d = offsetPx.modulus(); var h = this._props.measurementEndLengthPx; var o = this._props.measurementOffsetPx; this._ctx.save(); this._ctx.lineWidth = this._props.measurementStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.measurementStrokePattern)); this._ctx.strokeStyle = this._props.measurementColor; this._ctx.translate(startPx.e(1), startPx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(offsetPx)); this._ctx.beginPath(); this._ctx.moveTo(0, o); this._ctx.lineTo(0, o + h); this._ctx.stroke(); this._ctx.beginPath(); this._ctx.moveTo(d, o); this._ctx.lineTo(d, o + h); this._ctx.stroke(); this._ctx.beginPath(); this._ctx.moveTo(0, o + h / 2); this._ctx.lineTo(d, o + h / 2); this._ctx.stroke(); this._ctx.restore(); var orthPx = offsetPx .rotate(-Math.PI / 2, $V([0, 0])) .toUnitVector() .x(-o - h / 2); var lineStartPx = startPx.add(orthPx); var lineEndPx = endPx.add(orthPx); var lineStartDw = this.pos2Dw(lineStartPx); var lineEndDw = this.pos2Dw(lineEndPx); this.labelLine(lineStartDw, lineEndDw, $V([0, -1]), text); }; /** Draw a right angle. @param {Vector} posDw The position angle point. @param {Vector} dirDw The baseline direction (angle is counter-clockwise from this direction in 2D). @param {Vector} normDw (Optional) The third direction (required for 3D). */ PrairieDraw.prototype.rightAngle = function (posDw, dirDw, normDw) { if (dirDw.modulus() < 1e-20) { return; } var posPx, dirPx, normPx; if (posDw.elements.length === 3) { posPx = this.pos2Px(this.pos3To2(posDw)); var d = this.vec2To3(this.vec2Dw($V([this._props.rightAngleSizePx, 0]))).modulus(); dirPx = this.vec2Px(this.vec3To2(dirDw.toUnitVector().x(d), posDw)); normPx = this.vec2Px(this.vec3To2(normDw.toUnitVector().x(d), posDw)); } else { posPx = this.pos2Px(posDw); dirPx = this.vec2Px(dirDw).toUnitVector().x(this._props.rightAngleSizePx); if (normDw !== undefined) { normPx = this.vec2Px(normDw).toUnitVector().x(this._props.rightAngleSizePx); } else { normPx = dirPx.rotate(-Math.PI / 2, $V([0, 0])); } } this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.lineWidth = this._props.rightAngleStrokeWidthPx; this._ctx.strokeStyle = this._props.rightAngleColor; this._ctx.beginPath(); this._ctx.moveTo(dirPx.e(1), dirPx.e(2)); this._ctx.lineTo(dirPx.e(1) + normPx.e(1), dirPx.e(2) + normPx.e(2)); this._ctx.lineTo(normPx.e(1), normPx.e(2)); this._ctx.stroke(); this._ctx.restore(); }; /** Draw a right angle (improved version). @param {Vector} p0Dw The base point. @param {Vector} p1Dw The first other point. @param {Vector} p2Dw The second other point. */ PrairieDraw.prototype.rightAngleImproved = function (p0Dw, p1Dw, p2Dw) { var p0Px = this.pos2Px(this.pos3To2(p0Dw)); var p1Px = this.pos2Px(this.pos3To2(p1Dw)); var p2Px = this.pos2Px(this.pos3To2(p2Dw)); var d1Px = p1Px.subtract(p0Px); var d2Px = p2Px.subtract(p0Px); var minDLen = Math.min(d1Px.modulus(), d2Px.modulus()); if (minDLen < 1e-10) { return; } var rightAngleSizePx = Math.min(minDLen / 2, this._props.rightAngleSizePx); d1Px = d1Px.toUnitVector().x(rightAngleSizePx); d2Px = d2Px.toUnitVector().x(rightAngleSizePx); p1Px = p0Px.add(d1Px); p2Px = p0Px.add(d2Px); var p12Px = p1Px.add(d2Px); this._ctx.save(); this._ctx.lineWidth = this._props.rightAngleStrokeWidthPx; this._ctx.strokeStyle = this._props.rightAngleColor; this._ctx.beginPath(); this._ctx.moveTo(p1Px.e(1), p1Px.e(2)); this._ctx.lineTo(p12Px.e(1), p12Px.e(2)); this._ctx.lineTo(p2Px.e(1), p2Px.e(2)); this._ctx.stroke(); this._ctx.restore(); }; /*****************************************************************************/ /** Draw text. @param {Vector} posDw The position to draw at. @param {Vector} anchor The anchor on the text that will be located at pos (in -1 to 1 local coordinates). @param {string} text The text to draw. If text begins with "TEX:" then it is interpreted as LaTeX. @param {bool} boxed (Optional) Whether to draw a white box behind the text (default: false). @param {Number} angle (Optional) The rotation angle (radians, default: 0). */ PrairieDraw.prototype.text = function (posDw, anchor, text, boxed, angle) { if (text === undefined) { return; } boxed = boxed === undefined ? false : boxed; angle = angle === undefined ? 0 : angle; var posPx = this.pos2Px(this.pos3To2(posDw)); var offsetPx; if (text.length >= 4 && text.slice(0, 4) === 'TEX:') { var texText = text.slice(4); var hash = Sha1.hash(texText); this._texts = this._texts || {}; var img; if (hash in this._texts) { img = this._texts[hash]; var xPx = (-(anchor.e(1) + 1) / 2) * img.width; var yPx = ((anchor.e(2) - 1) / 2) * img.height; //var offsetPx = anchor.toUnitVector().x(Math.abs(anchor.max()) * this._props.textOffsetPx); offsetPx = anchor.x(this._props.textOffsetPx); var textBorderPx = 5; this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.rotate(angle); if (boxed) { this._ctx.save(); this._ctx.fillStyle = 'white'; this._ctx.fillRect( xPx - offsetPx.e(1) - textBorderPx, yPx + offsetPx.e(2) - textBorderPx, img.width + 2 * textBorderPx, img.height + 2 * textBorderPx ); this._ctx.restore(); } this._ctx.drawImage(img, xPx - offsetPx.e(1), yPx + offsetPx.e(2)); this._ctx.restore(); } else { var imgSrc = 'text/' + hash + '.png'; img = new Image(); var that = this; img.onload = function () { that.redraw(); if (that.trigger) { that.trigger('imgLoad'); } }; img.src = imgSrc; this._texts[hash] = img; } } else { var align, baseline, bbRelOffset; /* jshint indent: false */ switch (PrairieGeom.sign(anchor.e(1))) { case -1: align = 'left'; bbRelOffset = 0; break; case 0: align = 'center'; bbRelOffset = 0.5; break; case 1: align = 'right'; bbRelOffset = 1; break; } switch (PrairieGeom.sign(anchor.e(2))) { case -1: baseline = 'bottom'; break; case 0: baseline = 'middle'; break; case 1: baseline = 'top'; break; } this.save(); this._ctx.textAlign = align; this._ctx.textBaseline = baseline; this._ctx.translate(posPx.e(1), posPx.e(2)); offsetPx = anchor.toUnitVector().x(Math.abs(anchor.max()) * this._props.textOffsetPx); var drawPx = $V([-offsetPx.e(1), offsetPx.e(2)]); var metrics = this._ctx.measureText(text); var d = this._props.textOffsetPx; //var bb0 = drawPx.add($V([-metrics.actualBoundingBoxLeft - d, -metrics.actualBoundingBoxAscent - d])); //var bb1 = drawPx.add($V([metrics.actualBoundingBoxRight + d, metrics.actualBoundingBoxDescent + d])); var textHeight = this._props.textFontSize; var bb0 = drawPx.add($V([-bbRelOffset * metrics.width - d, -d])); var bb1 = drawPx.add($V([(1 - bbRelOffset) * metrics.width + d, textHeight + d])); if (boxed) { this._ctx.save(); this._ctx.fillStyle = 'white'; this._ctx.fillRect(bb0.e(1), bb0.e(2), bb1.e(1) - bb0.e(1), bb1.e(2) - bb0.e(2)); this._ctx.restore(); } this._ctx.font = this._props.textFontSize.toString() + 'px serif'; this._ctx.fillText(text, drawPx.e(1), drawPx.e(2)); this.restore(); } }; /** Draw text to label a line. @param {Vector} startDw The start position of the line. @param {Vector} endDw The end position of the line. @param {Vector} pos The position relative to the line (-1 to 1 local coordinates, x along the line, y orthogonal). @param {string} text The text to draw. @param {Vector} anchor (Optional) The anchor position on the text. */ PrairieDraw.prototype.labelLine = function (startDw, endDw, pos, text, anchor) { if (text === undefined) { return; } startDw = this.pos3To2(startDw); endDw = this.pos3To2(endDw); var midpointDw = startDw.add(endDw).x(0.5); var offsetDw = endDw.subtract(startDw).x(0.5); var pDw = midpointDw.add(offsetDw.x(pos.e(1))); var u1Dw = offsetDw.toUnitVector(); var u2Dw = u1Dw.rotate(Math.PI / 2, $V([0, 0])); var oDw = u1Dw.x(pos.e(1)).add(u2Dw.x(pos.e(2))); var a = oDw.x(-1).toUnitVector().x(Math.abs(pos.max())); if (anchor !== undefined) { a = anchor; } this.text(pDw, a, text); }; /** Draw text to label a circle line. @param {Vector} posDw The center of the circle line. @param {number} radDw The radius at the mid-angle. @param {number} startAngleDw The starting angle (counterclockwise from x axis, in radians). @param {number} endAngleDw The ending angle (counterclockwise from x axis, in radians). @param {Vector} pos The position relative to the line (-1 to 1 local coordinates, x along the line, y orthogonal). @param {string} text The text to draw. @param {bool} fixedRad (Optional) Whether to use a fixed radius (default: false). */ PrairieDraw.prototype.labelCircleLine = function ( posDw, radDw, startAngleDw, endAngleDw, pos, text, fixedRad ) { // convert to Px coordinates var startOffsetDw = PrairieGeom.vector2DAtAngle(startAngleDw).x(radDw); var posPx = this.pos2Px(posDw); var startOffsetPx = this.vec2Px(startOffsetDw); var radiusPx = startOffsetPx.modulus(); var startAnglePx = PrairieGeom.angleOf(startOffsetPx); var deltaAngleDw = endAngleDw - startAngleDw; // assume a possibly reflected/rotated but equally scaled Dw/Px transformation var deltaAnglePx = this._transIsReflection() ? -deltaAngleDw : deltaAngleDw; var endAnglePx = startAnglePx + deltaAnglePx; var textAnglePx = ((1.0 - pos.e(1)) / 2.0) * startAnglePx + ((1.0 + pos.e(1)) / 2.0) * endAnglePx; var u1Px = PrairieGeom.vector2DAtAngle(textAnglePx); var u2Px = u1Px.rotate(-Math.PI / 2, $V([0, 0])); var u1Dw = this.vec2Dw(u1Px).toUnitVector(); var u2Dw = this.vec2Dw(u2Px).toUnitVector(); var oDw = u1Dw.x(pos.e(2)).add(u2Dw.x(pos.e(1))); var aDw = oDw.x(-1).toUnitVector(); var a = aDw.x(1.0 / Math.abs(aDw.max())).x(Math.abs(pos.max())); var rPx = this._circleArrowRadius(radiusPx, textAnglePx, startAnglePx, endAnglePx, fixedRad); var pPx = u1Px.x(rPx).add(posPx); var pDw = this.pos2Dw(pPx); this.text(pDw, a, text); }; /** Find the anchor for the intersection of several lines. @param {Vector} labelPoint The point to be labeled. @param {Array} points The end of the lines that meet at labelPoint. @return {Vector} The anchor offset. */ PrairieDraw.prototype.findAnchorForIntersection = function (labelPointDw, pointsDw) { // find the angles on the unit circle for each of the lines var labelPointPx = this.pos2Px(this.pos3To2(labelPointDw)); var i, v; var angles = []; for (i = 0; i < pointsDw.length; i++) { v = this.pos2Px(this.pos3To2(pointsDw[i])).subtract(labelPointPx); v = $V([v.e(1), -v.e(2)]); if (v.modulus() > 1e-6) { angles.push(PrairieGeom.angleOf(v)); } } if (angles.length === 0) { return $V([1, 0]); } // save the first angle to tie-break later var tieBreakAngle = angles[0]; // find the biggest gap between angles (might be multiple) angles.sort(function (a, b) { return a - b; }); var maxAngleDiff = angles[0] - angles[angles.length - 1] + 2 * Math.PI; var maxIs = [0]; var angleDiff; for (i = 1; i < angles.length; i++) { angleDiff = angles[i] - angles[i - 1]; if (angleDiff > maxAngleDiff - 1e-6) { if (angleDiff > maxAngleDiff + 1e-6) { // we are clearly greater maxAngleDiff = angleDiff; maxIs = [i]; } else { // we are basically equal maxIs.push(i); } } } // tie-break by choosing the first angle CCW from the tieBreakAngle var minCCWDiff = 2 * Math.PI; var angle, bestAngle; for (i = 0; i < maxIs.length; i++) { angle = angles[maxIs[i]] - maxAngleDiff / 2; angleDiff = angle - tieBreakAngle; if (angleDiff < 0) { angleDiff += 2 * Math.PI; } if (angleDiff < minCCWDiff) { minCCWDiff = angleDiff; bestAngle = angle; } } // find anchor from bestAngle var dir = PrairieGeom.vector2DAtAngle(bestAngle); dir = dir.x(1 / PrairieGeom.supNorm(dir)); return dir.x(-1); }; /** Label the intersection of several lines. @param {Vector} labelPoint The point to be labeled. @param {Array} points The end of the lines that meet at labelPoint. @param {String} label The label text. @param {Number} scaleOffset (Optional) Scale factor for the offset (default: 1). */ PrairieDraw.prototype.labelIntersection = function (labelPoint, points, label, scaleOffset) { scaleOffset = scaleOffset === undefined ? 1 : scaleOffset; var anchor = this.findAnchorForIntersection(labelPoint, points); this.text(labelPoint, anchor.x(scaleOffset), label); }; /*****************************************************************************/ PrairieDraw.prototype.clearHistory = function (name) { if (name in this._history) { delete this._history[name]; } else { console.log('WARNING: history not found: ' + name); } }; PrairieDraw.prototype.clearAllHistory = function () { this._history = {}; }; /** Save the history of a data value. @param {string} name The history variable name. @param {number} dt The time resolution to save at. @param {number} maxTime The maximum age of history to save. @param {number} curTime The current time. @param {object} curValue The current data value. @return {Array} A history array of vectors of the form [time, value]. */ PrairieDraw.prototype.history = function (name, dt, maxTime, curTime, curValue) { if (!(name in this._history)) { this._history[name] = [[curTime, curValue]]; } else { var h = this._history[name]; if (h.length < 2) { h.push([curTime, curValue]); } else { var prevPrevTime = h[h.length - 2][0]; if (curTime - prevPrevTime < dt) { // new time jump will still be short, replace the last record h[h.length - 1] = [curTime, curValue]; } else { // new time jump would be too long, just add the new record h.push([curTime, curValue]); } } // discard old values as necessary var i = 0; while (curTime - h[i][0] > maxTime && i < h.length - 1) { i++; } if (i > 0) { this._history[name] = h.slice(i); } } return this._history[name]; }; PrairieDraw.prototype.pairsToVectors = function (pairArray) { var vectorArray = []; for (var i = 0; i < pairArray.length; i++) { vectorArray.push($V(pairArray[i])); } return vectorArray; }; PrairieDraw.prototype.historyToTrace = function (data) { var trace = []; for (var i = 0; i < data.length; i++) { trace.push(data[i][1]); } return trace; }; /** Plot a history sequence. @param {Vector} originDw The lower-left position of the axes. @param {Vector} sizeDw The size of the axes (vector from lower-left to upper-right). @param {Vector} sizeData The size of the axes in data coordinates. @param {number} timeOffset The horizontal position for the current time. @param {string} yLabel The vertical axis label. @param {Array} data An array of [time, value] arrays to plot. @param {string} type (Optional) The type of line being drawn. */ PrairieDraw.prototype.plotHistory = function ( originDw, sizeDw, sizeData, timeOffset, yLabel, data, type ) { var scale = $V([sizeDw.e(1) / sizeData.e(1), sizeDw.e(2) / sizeData.e(2)]); var lastTime = data[data.length - 1][0]; var offset = $V([timeOffset - lastTime, 0]); var plotData = PrairieGeom.scalePoints( PrairieGeom.translatePoints(this.pairsToVectors(data), offset), scale ); this.save(); this.translate(originDw); this.save(); this.setProp('arrowLineWidthPx', 1); this.setProp('arrowheadLengthRatio', 11); this.arrow($V([0, 0]), $V([sizeDw.e(1), 0])); this.arrow($V([0, 0]), $V([0, sizeDw.e(2)])); this.text($V([sizeDw.e(1), 0]), $V([1, 1.5]), 'TEX:$t$'); this.text($V([0, sizeDw.e(2)]), $V([1.5, 1]), yLabel); this.restore(); var col = this._getColorProp(type); this.setProp('shapeOutlineColor', col); this.setProp('pointRadiusPx', '4'); this.save(); this._ctx.beginPath(); var bottomLeftPx = this.pos2Px($V([0, 0])); var topRightPx = this.pos2Px(sizeDw); var offsetPx = topRightPx.subtract(bottomLeftPx); this._ctx.rect(bottomLeftPx.e(1), 0, offsetPx.e(1), this._height); this._ctx.clip(); this.polyLine(plotData, false); this.restore(); this.point(plotData[plotData.length - 1]); this.restore(); }; /** Draw a history of positions as a faded line. @param {Array} history History data, array of [time, position] pairs, where position is a vector. @param {number} t Current time. @param {number} maxT Maximum history time. @param {Array} currentRGB RGB triple for current time color. @param {Array} oldRGB RGB triple for old time color. */ PrairieDraw.prototype.fadeHistoryLine = function (history, t, maxT, currentRGB, oldRGB) { if (history.length < 2) { return; } for (var i = history.length - 2; i >= 0; i--) { // draw line backwards so newer segments are on top var pT = history[i][0]; var pDw1 = history[i][1]; var pDw2 = history[i + 1][1]; var alpha = (t - pT) / maxT; var rgb = PrairieGeom.linearInterpArray(currentRGB, oldRGB, alpha); var color = 'rgb(' + rgb[0].toFixed(0) + ', ' + rgb[1].toFixed(0) + ', ' + rgb[2].toFixed(0) + ')'; this.line(pDw1, pDw2, color); } }; /*****************************************************************************/ PrairieDraw.prototype.mouseDown3D = function (event) { event.preventDefault(); this._mouseDown3D = true; this._lastMouseX3D = event.clientX; this._lastMouseY3D = event.clientY; }; PrairieDraw.prototype.mouseUp3D = function () { this._mouseDown3D = false; }; PrairieDraw.prototype.mouseMove3D = function (event) { if (!this._mouseDown3D) { return; } var deltaX = event.clientX - this._lastMouseX3D; var deltaY = event.clientY - this._lastMouseY3D; this._lastMouseX3D = event.clientX; this._lastMouseY3D = event.clientY; this.incrementView3D(deltaY * 0.01, 0, deltaX * 0.01); }; PrairieDraw.prototype.activate3DControl = function () { /* Listen just on the canvas for mousedown, but on whole window * for move/up. This allows mouseup while off-canvas (and even * off-window) to be captured. Ideally we should also listen for * mousedown on the whole window and use mouseEventOnCanvas(), but * this is broken on Canary for some reason (some areas off-canvas * don't work). The advantage of listening for mousedown on the * whole window is that we can get the event during the "capture" * phase rather than the later "bubble" phase, allowing us to * preventDefault() before things like select-drag starts. */ this._canvas.addEventListener('mousedown', this.mouseDown3D.bind(this), true); window.addEventListener('mouseup', this.mouseUp3D.bind(this), true); window.addEventListener('mousemove', this.mouseMove3D.bind(this), true); }; /*****************************************************************************/ PrairieDraw.prototype.mouseDownTracking = function (event) { event.preventDefault(); this._mouseDownTracking = true; this._lastMouseXTracking = event.pageX; this._lastMouseYTracking = event.pageY; }; PrairieDraw.prototype.mouseUpTracking = function () { this._mouseDownTracking = false; }; PrairieDraw.prototype.mouseMoveTracking = function (event) { if (!this._mouseDownTracking) { return; } this._lastMouseXTracking = event.pageX; this._lastMouseYTracking = event.pageY; }; PrairieDraw.prototype.activateMouseTracking = function () { this._canvas.addEventListener('mousedown', this.mouseDownTracking.bind(this), true); window.addEventListener('mouseup', this.mouseUpTracking.bind(this), true); window.addEventListener('mousemove', this.mouseMoveTracking.bind(this), true); }; PrairieDraw.prototype.mouseDown = function () { if (this._mouseDownTracking !== undefined) { return this._mouseDownTracking; } else { return false; } }; PrairieDraw.prototype.mousePositionDw = function () { var xPx = this._lastMouseXTracking - this._canvas.offsetLeft; var yPx = this._lastMouseYTracking - this._canvas.offsetTop; var posPx = $V([xPx, yPx]); var posDw = this.pos2Dw(posPx); return posDw; }; /*****************************************************************************/ /** Creates a PrairieDrawAnim object. @constructor @this {PrairieDraw} @param {HTMLCanvasElement or string} canvas The canvas element to draw on or the ID of the canvas elemnt. @param {Function} drawfcn An optional function that draws on the canvas at time t. */ function PrairieDrawAnim(canvas, drawFcn) { PrairieDraw.call(this, canvas, null); this._drawTime = 0; this._deltaTime = 0; this._running = false; this._sequences = {}; this._animStateCallbacks = []; this._animStepCallbacks = []; if (drawFcn) { this.draw = drawFcn.bind(this); } this.save(); this.draw(0); this.restoreAll(); } PrairieDrawAnim.prototype = new PrairieDraw(); /** @private Store the appropriate version of requestAnimationFrame. Use this like: prairieDraw.requestAnimationFrame.call(window, this.callback.bind(this)); We can't do prairieDraw.requestAnimationFrame(callback), because that would run requestAnimationFrame in the context of prairieDraw ("this" would be prairieDraw), and requestAnimationFrame needs "this" to be "window". We need to pass this.callback.bind(this) as the callback function rather than just this.callback as otherwise the callback functions is called from "window" context, and we want it to be called from the context of our own object. */ /* jshint laxbreak: true */ if (typeof window !== 'undefined') { PrairieDrawAnim.prototype._requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; } /** Prototype function to draw on the canvas, should be implemented by children. @param {number} t Current animation time in seconds. */ PrairieDrawAnim.prototype.draw = function (t) { /* jshint unused: false */ }; /** Start the animation. */ PrairieDrawAnim.prototype.startAnim = function () { if (!this._running) { this._running = true; this._startFrame = true; this._requestAnimationFrame.call(window, this._callback.bind(this)); for (var i = 0; i < this._animStateCallbacks.length; i++) { this._animStateCallbacks[i](true); } } }; /** Stop the animation. */ PrairieDrawAnim.prototype.stopAnim = function () { this._running = false; for (var i = 0; i < this._animStateCallbacks.length; i++) { this._animStateCallbacks[i](false); } }; /** Toggle the animation. */ PrairieDrawAnim.prototype.toggleAnim = function () { if (this._running) { this.stopAnim(); } else { this.startAnim(); } }; /** Register a callback on animation state changes. @param {Function} callback The callback(animated) function. */ PrairieDrawAnim.prototype.registerAnimCallback = function (callback) { this._animStateCallbacks.push(callback.bind(this)); callback.apply(this, [this._running]); }; /** Register a callback on animation steps. @param {Function} callback The callback(t) function. */ PrairieDrawAnim.prototype.registerAnimStepCallback = function (callback) { this._animStepCallbacks.push(callback.bind(this)); }; /** @private Callback function to handle the animationFrame events. */ PrairieDrawAnim.prototype._callback = function (tMS) { if (this._startFrame) { this._startFrame = false; this._timeOffset = tMS - this._drawTime; } var animTime = tMS - this._timeOffset; this._deltaTime = (animTime - this._drawTime) / 1000; this._drawTime = animTime; var t = animTime / 1000; for (var i = 0; i < this._animStepCallbacks.length; i++) { this._animStepCallbacks[i](t); } this.save(); this.draw(t); this._deltaTime = 0; this.restoreAll(); if (this._running) { this._requestAnimationFrame.call(window, this._callback.bind(this)); } }; /** Get the elapsed time since the last redraw. return {number} Elapsed time in seconds. */ PrairieDrawAnim.prototype.deltaTime = function () { return this._deltaTime; }; /** Redraw the drawing at the current time. */ PrairieDrawAnim.prototype.redraw = function () { if (!this._running) { this.save(); this.draw(this._drawTime / 1000); this.restoreAll(); } }; /** Reset the animation time to zero. @param {bool} redraw (Optional) Whether to redraw (default: true). */ PrairieDrawAnim.prototype.resetTime = function (redraw) { this._drawTime = 0; for (var i = 0; i < this._animStepCallbacks.length; i++) { this._animStepCallbacks[i](0); } this._startFrame = true; if (redraw === undefined || redraw === true) { this.redraw(); } }; /** Reset everything to the intial state. */ PrairieDrawAnim.prototype.reset = function () { for (var optionName in this._options) { this.resetOptionValue(optionName); } this.resetAllSequences(); this.clearAllHistory(); this.stopAnim(); this.resetView3D(false); this.resetTime(false); this.redraw(); }; /** Stop all action and computation. */ PrairieDrawAnim.prototype.stop = function () { this.stopAnim(); }; PrairieDrawAnim.prototype.lastDrawTime = function () { return this._drawTime / 1000; }; /*****************************************************************************/ PrairieDrawAnim.prototype.mouseDownAnimOnClick = function (event) { event.preventDefault(); this.startAnim(); }; PrairieDrawAnim.prototype.activateAnimOnClick = function () { this._canvas.addEventListener('mousedown', this.mouseDownAnimOnClick.bind(this), true); }; /*****************************************************************************/ /** Interpolate between different states in a sequence. @param {Array} states An array of objects, each specifying scalar or vector state values. @param {Array} transTimes Transition times. transTimes[i] is the transition time from states[i] to states[i+1]. @param {Array} holdTimes Hold times for the corresponding state. @param {Array} t Current time. @return Object with state variables set to current values, as well as t being the time within the current transition (0 if holding), index being the current state index (or the next state if transitioning), and alpha being the proportion of the current transition (0 if holding). */ PrairieDrawAnim.prototype.sequence = function (states, transTimes, holdTimes, t) { var totalTime = 0; var i; for (i = 0; i < states.length; i++) { totalTime += transTimes[i]; totalTime += holdTimes[i]; } var ts = t % totalTime; totalTime = 0; var state = {}; var e, ip; var lastTotalTime = 0; for (i = 0; i < states.length; i++) { ip = i === states.length - 1 ? 0 : i + 1; totalTime += transTimes[i]; if (totalTime > ts) { // in transition from i to i+1 state.t = ts - lastTotalTime; state.index = i; state.alpha = state.t / (totalTime - lastTotalTime); for (e in states[i]) { state[e] = PrairieGeom.linearInterp(states[i][e], states[ip][e], state.alpha); } return state; } lastTotalTime = totalTime; totalTime += holdTimes[i]; if (totalTime > ts) { // holding at i+1 state.t = 0; state.index = ip; state.alpha = 0; for (e in states[i]) { state[e] = states[ip][e]; } return state; } lastTotalTime = totalTime; } }; /*****************************************************************************/ /** Interpolate between different states in a sequence under external prompting. @param {string} name Name of this transition sequence. @param {Array} states An array of objects, each specifying scalar or vector state values. @param {Array} transTimes Transition times. transTimes[i] is the transition time from states[i] to states[i+1]. @param {Array} t Current animation time. @return Object with state variables set to current values, as well as t being the time within the current transition (0 if holding), index being the current state index (or the next state if transitioning), and alpha being the proportion of the current transition (0 if holding). */ PrairieDrawAnim.prototype.controlSequence = function (name, states, transTimes, t) { if (!(name in this._sequences)) { this._sequences[name] = { index: 0, inTransition: false, startTransition: false, indefiniteHold: true, callbacks: [], }; } var seq = this._sequences[name]; var state; var transTime = 0; if (seq.startTransition) { seq.startTransition = false; seq.inTransition = true; seq.indefiniteHold = false; seq.startTime = t; } if (seq.inTransition) { transTime = t - seq.startTime; } if (seq.inTransition && transTime >= transTimes[seq.index]) { seq.inTransition = false; seq.indefiniteHold = true; seq.index = (seq.index + 1) % states.length; delete seq.startTime; } if (!seq.inTransition) { state = PrairieGeom.dupState(states[seq.index]); state.index = seq.index; state.t = 0; state.alpha = 0; state.inTransition = false; return state; } var alpha = transTime / transTimes[seq.index]; var nextIndex = (seq.index + 1) % states.length; state = PrairieGeom.linearInterpState(states[seq.index], states[nextIndex], alpha); state.t = transTime; state.index = seq.index; state.alpha = alpha; state.inTransition = true; return state; }; /** Start the next transition for the given sequence. @param {string} name Name of the sequence to transition. @param {string} stateName (Optional) Only transition if we are currently in stateName. */ PrairieDrawAnim.prototype.stepSequence = function (name, stateName) { if (!(name in this._sequences)) { throw new Error('PrairieDraw: unknown sequence: ' + name); } var seq = this._sequences[name]; if (!seq.lastState.indefiniteHold) { return; } if (stateName !== undefined) { if (seq.lastState.name !== stateName) { return; } } seq.startTransition = true; this.startAnim(); }; /*****************************************************************************/ /** Interpolate between different states (new version). @param {string} name Name of this transition sequence. @param {Array} states An array of objects, each specifying scalar or vector state values. @param {Array} transTimes Transition times. transTimes[i] is the transition time from states[i] to states[i+1]. @param {Array} holdtimes Hold times for each state. A negative value means to hold until externally triggered. @param {Array} t Current animation time. @return Object with state variables set to current values, as well as t being the time within the current transition (0 if holding), index being the current state index (or the next state if transitioning), and alpha being the proportion of the current transition (0 if holding). */ PrairieDrawAnim.prototype.newSequence = function ( name, states, transTimes, holdTimes, interps, names, t ) { var seq = this._sequences[name]; if (seq === undefined) { this._sequences[name] = { startTransition: false, lastState: {}, callbacks: [], initialized: false, }; seq = this._sequences[name]; } var i; if (!seq.initialized) { seq.initialized = true; for (var e in states[0]) { if (typeof states[0][e] === 'number') { seq.lastState[e] = states[0][e]; } else if (typeof states[0][e] === 'function') { seq.lastState[e] = states[0][e](null, 0); } } seq.lastState.inTransition = false; seq.lastState.indefiniteHold = false; seq.lastState.index = 0; seq.lastState.name = names[seq.lastState.index]; seq.lastState.t = 0; seq.lastState.realT = t; if (holdTimes[0] < 0) { seq.lastState.indefiniteHold = true; } for (i = 0; i < seq.callbacks.length; i++) { seq.callbacks[i]('enter', seq.lastState.index, seq.lastState.name); } } if (seq.startTransition) { seq.startTransition = false; seq.lastState.inTransition = true; seq.lastState.indefiniteHold = false; seq.lastState.t = 0; seq.lastState.realT = t; for (i = 0; i < seq.callbacks.length; i++) { seq.callbacks[i]('exit', seq.lastState.index, seq.lastState.name); } } var endTime, nextIndex; while (true) { nextIndex = (seq.lastState.index + 1) % states.length; if (seq.lastState.inTransition) { endTime = seq.lastState.realT + transTimes[seq.lastState.index]; if (t >= endTime) { seq.lastState = this._interpState( seq.lastState, states[nextIndex], interps, endTime, endTime ); seq.lastState.inTransition = false; seq.lastState.index = nextIndex; seq.lastState.name = names[seq.lastState.index]; if (holdTimes[nextIndex] < 0) { seq.lastState.indefiniteHold = true; } else { seq.lastState.indefiniteHold = false; } for (i = 0; i < seq.callbacks.length; i++) { seq.callbacks[i]('enter', seq.lastState.index, seq.lastState.name); } } else { return this._interpState(seq.lastState, states[nextIndex], interps, t, endTime); } } else { endTime = seq.lastState.realT + holdTimes[seq.lastState.index]; if (holdTimes[seq.lastState.index] >= 0 && t > endTime) { seq.lastState = this._extrapState(seq.lastState, states[seq.lastState.index], endTime); seq.lastState.inTransition = true; seq.lastState.indefiniteHold = false; for (i = 0; i < seq.callbacks.length; i++) { seq.callbacks[i]('exit', seq.lastState.index, seq.lastState.name); } } else { return this._extrapState(seq.lastState, states[seq.lastState.index], t); } } } }; PrairieDrawAnim.prototype._interpState = function (lastState, nextState, interps, t, tFinal) { var s1 = PrairieGeom.dupState(nextState); s1.realT = tFinal; s1.t = tFinal - lastState.realT; var s = {}; var alpha = (t - lastState.realT) / (tFinal - lastState.realT); for (var e in nextState) { if (e in interps) { s[e] = interps[e](lastState, s1, t - lastState.realT); } else { s[e] = PrairieGeom.linearInterp(lastState[e], s1[e], alpha); } } s.realT = t; s.t = Math.min(t - lastState.realT, s1.t); s.index = lastState.index; s.inTransition = lastState.inTransition; s.indefiniteHold = lastState.indefiniteHold; return s; }; PrairieDrawAnim.prototype._extrapState = function (lastState, lastStateData, t) { var s = {}; for (var e in lastStateData) { if (typeof lastStateData[e] === 'number') { s[e] = lastStateData[e]; } else if (typeof lastStateData[e] === 'function') { s[e] = lastStateData[e](lastState, t - lastState.realT); } } s.realT = t; s.t = t - lastState.realT; s.index = lastState.index; s.inTransition = lastState.inTransition; s.indefiniteHold = lastState.indefiniteHold; return s; }; /** Register a callback on animation sequence events. @param {string} seqName The sequence to register on. @param {Function} callback The callback(event, index, stateName) function. */ PrairieDrawAnim.prototype.registerSeqCallback = function (seqName, callback) { if (!(seqName in this._sequences)) { throw new Error('PrairieDraw: unknown sequence: ' + seqName); } var seq = this._sequences[seqName]; seq.callbacks.push(callback.bind(this)); if (seq.inTransition) { callback.apply(this, ['exit', seq.lastState.index, seq.lastState.name]); } else { callback.apply(this, ['enter', seq.lastState.index, seq.lastState.name]); } }; /** Make a two-state sequence transitioning to and from 0 and 1. @param {string} name The name of the sequence; @param {number} transTime The transition time between the two states. @return {number} The current state (0 to 1). */ PrairieDrawAnim.prototype.activationSequence = function (name, transTime, t) { var stateZero = { trans: 0 }; var stateOne = { trans: 1 }; var states = [stateZero, stateOne]; var transTimes = [transTime, transTime]; var holdTimes = [-1, -1]; var interps = {}; var names = ['zero', 'one']; var state = this.newSequence(name, states, transTimes, holdTimes, interps, names, t); return state.trans; }; PrairieDrawAnim.prototype.resetSequence = function (name) { var seq = this._sequences[name]; if (seq !== undefined) { seq.initialized = false; } }; PrairieDrawAnim.prototype.resetAllSequences = function () { for (var name in this._sequences) { this.resetSequence(name); } }; /*****************************************************************************/ PrairieDraw.prototype.drawImage = function (imgSrc, posDw, anchor, widthDw) { var img; if (imgSrc in this._images) { // FIXME: should check that the image is really loaded, in case we are fired beforehand (also for text images). img = this._images[imgSrc]; var posPx = this.pos2Px(posDw); var scale; if (widthDw === undefined) { scale = 1; } else { var offsetDw = $V([widthDw, 0]); var offsetPx = this.vec2Px(offsetDw); var widthPx = offsetPx.modulus(); scale = widthPx / img.width; } var xPx = (-(anchor.e(1) + 1) / 2) * img.width; var yPx = ((anchor.e(2) - 1) / 2) * img.height; this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.scale(scale, scale); this._ctx.translate(xPx, yPx); this._ctx.drawImage(img, 0, 0); this._ctx.restore(); } else { img = new Image(); var that = this; img.onload = function () { that.redraw(); if (that.trigger) { that.trigger('imgLoad'); } }; img.src = imgSrc; this._images[imgSrc] = img; } }; /*****************************************************************************/ PrairieDraw.prototype.mouseEventPx = function (event) { var element = this._canvas; var xPx = event.pageX; var yPx = event.pageY; do { xPx -= element.offsetLeft; yPx -= element.offsetTop; /* jshint boss: true */ // suppress warning for assignment on next line } while ((element = element.offsetParent)); xPx *= this._canvas.width / this._canvas.scrollWidth; yPx *= this._canvas.height / this._canvas.scrollHeight; var posPx = $V([xPx, yPx]); return posPx; }; PrairieDraw.prototype.mouseEventDw = function (event) { var posPx = this.mouseEventPx(event); var posDw = this.pos2Dw(posPx); return posDw; }; PrairieDraw.prototype.mouseEventOnCanvas = function (event) { var posPx = this.mouseEventPx(event); console.log(posPx.e(1), posPx.e(2), this._width, this._height); /* jshint laxbreak: true */ if ( posPx.e(1) >= 0 && posPx.e(1) <= this._width && posPx.e(2) >= 0 && posPx.e(2) <= this._height ) { console.log(true); return true; } console.log(false); return false; }; PrairieDraw.prototype.reportMouseSample = function (event) { var posDw = this.mouseEventDw(event); var numDecPlaces = 2; /* jshint laxbreak: true */ console.log( '$V([' + posDw.e(1).toFixed(numDecPlaces) + ', ' + posDw.e(2).toFixed(numDecPlaces) + ']),' ); }; PrairieDraw.prototype.activateMouseSampling = function () { this._canvas.addEventListener('click', this.reportMouseSample.bind(this)); }; /*****************************************************************************/ PrairieDraw.prototype.activateMouseLineDraw = function () { if (this._mouseLineDrawActive === true) { return; } this._mouseLineDrawActive = true; this.mouseLineDraw = false; this.mouseLineDrawing = false; if (this._mouseLineDrawInitialized !== true) { this._mouseLineDrawInitialized = true; if (this._mouseDrawCallbacks === undefined) { this._mouseDrawCallbacks = []; } this._canvas.addEventListener('mousedown', this.mouseLineDrawMousedown.bind(this), true); window.addEventListener('mouseup', this.mouseLineDrawMouseup.bind(this), true); window.addEventListener('mousemove', this.mouseLineDrawMousemove.bind(this), true); } /* for (var i = 0; i < this._mouseDrawCallbacks.length; i++) { this._mouseDrawCallbacks[i](); } this.redraw(); */ }; PrairieDraw.prototype.deactivateMouseLineDraw = function () { this._mouseLineDrawActive = false; this.mouseLineDraw = false; this.mouseLineDrawing = false; this.redraw(); }; PrairieDraw.prototype.mouseLineDrawMousedown = function (event) { if (!this._mouseLineDrawActive) { return; } event.preventDefault(); var posDw = this.mouseEventDw(event); this.mouseLineDrawStart = posDw; this.mouseLineDrawEnd = posDw; this.mouseLineDrawing = true; this.mouseLineDraw = true; for (var i = 0; i < this._mouseDrawCallbacks.length; i++) { this._mouseDrawCallbacks[i](); } this.redraw(); }; PrairieDraw.prototype.mouseLineDrawMousemove = function (event) { if (!this._mouseLineDrawActive) { return; } if (!this.mouseLineDrawing) { return; } this.mouseLineDrawEnd = this.mouseEventDw(event); for (var i = 0; i < this._mouseDrawCallbacks.length; i++) { this._mouseDrawCallbacks[i](); } this.redraw(); // FIXME: add rate-limiting }; PrairieDraw.prototype.mouseLineDrawMouseup = function () { if (!this._mouseLineDrawActive) { return; } if (!this.mouseLineDrawing) { return; } this.mouseLineDrawing = false; for (var i = 0; i < this._mouseDrawCallbacks.length; i++) { this._mouseDrawCallbacks[i](); } this.redraw(); }; PrairieDraw.prototype.mouseLineDrawMouseout = function (event) { if (!this._mouseLineDrawActive) { return; } if (!this.mouseLineDrawing) { return; } this.mouseLineDrawEnd = this.mouseEventDw(event); this.mouseLineDrawing = false; for (var i = 0; i < this._mouseDrawCallbacks.length; i++) { this._mouseDrawCallbacks[i](); } this.redraw(); }; PrairieDraw.prototype.registerMouseLineDrawCallback = function (callback) { if (this._mouseDrawCallbacks === undefined) { this._mouseDrawCallbacks = []; } this._mouseDrawCallbacks.push(callback.bind(this)); }; /*****************************************************************************/ /** Plot a line graph. @param {Array} data Array of vectors to plot. @param {Vector} originDw The lower-left position of the axes. @param {Vector} sizeDw The size of the axes (vector from lower-left to upper-right). @param {Vector} originData The lower-left position of the axes in data coordinates. @param {Vector} sizeData The size of the axes in data coordinates. @param {string} xLabel The vertical axis label. @param {string} yLabel The vertical axis label. @param {string} type (Optional) The type of line being drawn. @param {string} drawAxes (Optional) Whether to draw the axes (default: true). @param {string} drawPoint (Optional) Whether to draw the last point (default: true). @param {string} pointLabel (Optional) Label for the last point (default: undefined). @param {string} pointAnchor (Optional) Anchor for the last point label (default: $V([0, -1])). @param {Object} options (Optional) Plotting options: horizAxisPos: "bottom", "top", or a numerical value in data coordinates (default: "bottom") vertAxisPos: "left", "right", or a numerical value in data coordinates (default: "left") */ PrairieDraw.prototype.plot = function ( data, originDw, sizeDw, originData, sizeData, xLabel, yLabel, type, drawAxes, drawPoint, pointLabel, pointAnchor, options ) { drawAxes = drawAxes === undefined ? true : drawAxes; drawPoint = drawPoint === undefined ? true : drawPoint; options = options === undefined ? {} : options; var horizAxisPos = options.horizAxisPos === undefined ? 'bottom' : options.horizAxisPos; var vertAxisPos = options.vertAxisPos === undefined ? 'left' : options.vertAxisPos; var drawXGrid = options.drawXGrid === undefined ? false : options.drawXGrid; var drawYGrid = options.drawYGrid === undefined ? false : options.drawYGrid; var dXGrid = options.dXGrid === undefined ? 1 : options.dXGrid; var dYGrid = options.dYGrid === undefined ? 1 : options.dYGrid; var drawXTickLabels = options.drawXTickLabels === undefined ? false : options.drawXTickLabels; var drawYTickLabels = options.drawYTickLabels === undefined ? false : options.drawYTickLabels; var xLabelPos = options.xLabelPos === undefined ? 1 : options.xLabelPos; var yLabelPos = options.yLabelPos === undefined ? 1 : options.yLabelPos; var xLabelAnchor = options.xLabelAnchor === undefined ? $V([1, 1.5]) : options.xLabelAnchor; var yLabelAnchor = options.yLabelAnchor === undefined ? $V([1.5, 1]) : options.yLabelAnchor; var yLabelRotate = options.yLabelRotate === undefined ? false : options.yLabelRotate; this.save(); this.translate(originDw); // grid var ix0 = Math.ceil(originData.e(1) / dXGrid); var ix1 = Math.floor((originData.e(1) + sizeData.e(1)) / dXGrid); var x0 = 0; var x1 = sizeDw.e(1); var iy0 = Math.ceil(originData.e(2) / dYGrid); var iy1 = Math.floor((originData.e(2) + sizeData.e(2)) / dYGrid); var y0 = 0; var y1 = sizeDw.e(2); var i, x, y; if (drawXGrid) { for (i = ix0; i <= ix1; i++) { x = PrairieGeom.linearMap( originData.e(1), originData.e(1) + sizeData.e(1), 0, sizeDw.e(1), i * dXGrid ); this.line($V([x, y0]), $V([x, y1]), 'grid'); } } if (drawYGrid) { for (i = iy0; i <= iy1; i++) { y = PrairieGeom.linearMap( originData.e(2), originData.e(2) + sizeData.e(2), 0, sizeDw.e(2), i * dYGrid ); this.line($V([x0, y]), $V([x1, y]), 'grid'); } } var label; if (drawXTickLabels) { for (i = ix0; i <= ix1; i++) { x = PrairieGeom.linearMap( originData.e(1), originData.e(1) + sizeData.e(1), 0, sizeDw.e(1), i * dXGrid ); label = String(i * dXGrid); this.text($V([x, y0]), $V([0, 1]), label); } } if (drawYTickLabels) { for (i = iy0; i <= iy1; i++) { y = PrairieGeom.linearMap( originData.e(2), originData.e(2) + sizeData.e(2), 0, sizeDw.e(2), i * dYGrid ); label = String(i * dYGrid); this.text($V([x0, y]), $V([1, 0]), label); } } // axes var axisX, axisY; if (vertAxisPos === 'left') { axisX = 0; } else if (vertAxisPos === 'right') { axisX = sizeDw.e(1); } else { axisX = PrairieGeom.linearMap( originData.e(1), originData.e(1) + sizeData.e(1), 0, sizeDw.e(1), vertAxisPos ); } if (horizAxisPos === 'bottom') { axisY = 0; } else if (horizAxisPos === 'top') { axisY = sizeDw.e(2); } else { axisY = PrairieGeom.linearMap( originData.e(2), originData.e(2) + sizeData.e(2), 0, sizeDw.e(2), horizAxisPos ); } if (drawAxes) { this.save(); this.setProp('arrowLineWidthPx', 1); this.setProp('arrowheadLengthRatio', 11); this.arrow($V([0, axisY]), $V([sizeDw.e(1), axisY])); this.arrow($V([axisX, 0]), $V([axisX, sizeDw.e(2)])); x = xLabelPos * sizeDw.e(1); y = yLabelPos * sizeDw.e(2); this.text($V([x, axisY]), xLabelAnchor, xLabel); var angle = yLabelRotate ? -Math.PI / 2 : 0; this.text($V([axisX, y]), yLabelAnchor, yLabel, undefined, angle); this.restore(); } var col = this._getColorProp(type); this.setProp('shapeOutlineColor', col); this.setProp('pointRadiusPx', '4'); var bottomLeftPx = this.pos2Px($V([0, 0])); var topRightPx = this.pos2Px(sizeDw); var offsetPx = topRightPx.subtract(bottomLeftPx); this.save(); this.scale(sizeDw); this.scale($V([1 / sizeData.e(1), 1 / sizeData.e(2)])); this.translate(originData.x(-1)); this.save(); this._ctx.beginPath(); this._ctx.rect(bottomLeftPx.e(1), 0, offsetPx.e(1), this._height); this._ctx.clip(); this.polyLine(data, false); this.restore(); if (drawPoint) { this.point(data[data.length - 1]); if (pointLabel !== undefined) { if (pointAnchor === undefined) { pointAnchor = $V([0, -1]); } this.text(data[data.length - 1], pointAnchor, pointLabel); } } this.restore(); this.restore(); }; /*****************************************************************************/ return { PrairieDraw: PrairieDraw, PrairieDrawAnim: PrairieDrawAnim, }; });
PrairieLearn/PrairieLearn
public/localscripts/calculationQuestion/PrairieDraw.js
JavaScript
agpl-3.0
137,277
#-- # Copyright (C) 2007, 2008 Johan Sørensen <[email protected]> # Copyright (C) 2008 David A. Cuadrado <[email protected]> # Copyright (C) 2008 Tim Dysinger <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #++ require File.dirname(__FILE__) + '/../spec_helper' describe Project do def create_project(options={}) Project.new({ :title => "foo project", :slug => "foo", :description => "my little project", :user => users(:johan) }.merge(options)) end it "should have valid associations" do create_project.should have_valid_associations end it "should have a title to be valid" do project = create_project(:title => nil) project.should_not be_valid project.title = "foo" project.should be_valid end it "should have a slug to be valid" do project = create_project(:slug => nil) project.should_not be_valid end it "should have a unique slug to be valid" do p1 = create_project p1.save! p2 = create_project(:slug => "FOO") p2.should_not be_valid p2.should have(1).error_on(:slug) end it "should have an alphanumeric slug" do project = create_project(:slug => "asd asd") project.valid? project.should_not be_valid end it "should downcase the slug before validation" do project = create_project(:slug => "FOO") project.valid? project.slug.should == "foo" end it "creates an initial repository for itself" do project = create_project project.save project.repositories.should_not == [] project.repositories.first.name.should == "mainline" project.repositories.first.user.should == project.user project.user.can_write_to?(project.repositories.first).should == true end it "creates the wiki repository on create" do project = create_project(:slug => "my-new-project") project.save! project.wiki_repository.should be_instance_of(Repository) project.wiki_repository.name.should == "my-new-project#{Repository::WIKI_NAME_SUFFIX}" project.wiki_repository.kind.should == Repository::KIND_WIKI project.repositories.should_not include(project.wiki_repository) end it "finds a project by slug or raises" do Project.find_by_slug!(projects(:johans).slug).should == projects(:johans) proc{ Project.find_by_slug!("asdasdasd") }.should raise_error(ActiveRecord::RecordNotFound) end it "has the slug as its params" do projects(:johans).to_param.should == projects(:johans).slug end it "knows if a user is a admin on a project" do projects(:johans).admin?(users(:johan)).should == true projects(:johans).admin?(users(:moe)).should == false projects(:johans).admin?(:false).should == false end it "knows if a user can delete the project" do project = projects(:johans) project.can_be_deleted_by?(users(:moe)).should == false project.can_be_deleted_by?(users(:johan)).should == false # since it has > 1 repos project.repositories.last.destroy project.reload.can_be_deleted_by?(users(:johan)).should == true end it "should strip html tags" do project = create_project(:description => "<h1>Project A</h1>\n<b>Project A</b> is a....") project.stripped_description.should == "Project A\nProject A is a...." end # it "should strip html tags, except highlights" do # project = create_project(:description => %Q{<h1>Project A</h1>\n<strong class="highlight">Project A</strong> is a....}) # project.stripped_description.should == %Q(Project A\n<strong class="highlight">Project A</strong> is a....) # end it "should have valid urls ( prepending http:// if needed )" do project = projects(:johans) [ :home_url, :mailinglist_url, :bugtracker_url ].each do |attr| project.should be_valid project.send("#{attr}=", 'http://blah.com') project.should be_valid project.send("#{attr}=", 'ftp://blah.com') project.should_not be_valid project.send("#{attr}=", 'blah.com') project.should be_valid project.send(attr).should == 'http://blah.com' end end it "should not prepend http:// to empty urls" do project = projects(:johans) [ :home_url, :mailinglist_url, :bugtracker_url ].each do |attr| project.send("#{attr}=", '') project.send(attr).should be_blank project.send("#{attr}=", nil) project.send(attr).should be_blank end end it "should find or create an associated wiki repo" do project = projects(:johans) repo = repositories(:johans) repo.kind = Repository::KIND_WIKI project.wiki_repository = repo project.save! project.reload.wiki_repository.should == repo end it "should have a wiki repository" do project = projects(:johans) project.wiki_repository.should == repositories(:johans_wiki) project.repositories.should_not include(repositories(:johans_wiki)) project.repository_clones.should_not include(repositories(:johans_wiki)) end describe "Project events" do before(:each) do @project = projects(:johans) @user = users(:johan) @repository = @project.repositories.first end it "should create an event from the action name" do @project.create_event(Action::CREATE_PROJECT, @repository, @user, "", "").should_not == nil end it "should create an event even without a valid id" do @project.create_event(52342, @repository, @user).should_not == nil end it "creates valid attributes on the event" do e = @project.create_event(Action::COMMIT, @repository, @user, "somedata", "a body") e.should be_valid e.new_record?.should == false e.reload e.action.should == Action::COMMIT e.target.should == @repository e.project.should == @project e.user.should == @user e.data.should == "somedata" e.body.should == "a body" end end end
almonteb/scoot
spec/models/project_spec.rb
Ruby
agpl-3.0
6,546
/* * LICENCE : CloudUnit is available under the Affero Gnu Public License GPL V3 : https://www.gnu.org/licenses/agpl-3.0.html * but CloudUnit is licensed too under a standard commercial license. * Please contact our sales team if you would like to discuss the specifics of our Enterprise license. * If you are not sure whether the GPL is right for you, * you can always test our software under the GPL and inspect the source code before you contact us * about purchasing a commercial license. * * LEGAL TERMS : "CloudUnit" is a registered trademark of Treeptik and can't be used to endorse * or promote products derived from this project without prior written permission from Treeptik. * Products or services derived from this software may not be called "CloudUnit" * nor may "Treeptik" or similar confusing terms appear in their names without prior written permission. * For any questions, contact us : [email protected] */ package fr.treeptik.cloudunit.modules.redis; import fr.treeptik.cloudunit.modules.AbstractModuleControllerTestIT; /** * Created by guillaume on 01/10/16. */ public class Wildfly8Redis32ModuleControllerTestIT extends AbstractModuleControllerTestIT { public Wildfly8Redis32ModuleControllerTestIT() { super.server = "wildfly-8"; super.module = "redis-3-2"; super.numberPort = "6379"; super.managerPrefix = ""; super.managerSuffix = ""; super.managerPageContent = ""; } @Override protected void checkConnection(String forwardedPort) { new CheckRedisConnection().invoke(forwardedPort); } }
Treeptik/cloudunit
cu-manager/src/test/java/fr/treeptik/cloudunit/modules/redis/Wildfly8Redis32ModuleControllerTestIT.java
Java
agpl-3.0
1,612
# # Bold - more than just blogging. # Copyright (C) 2015-2016 Jens Krämer <[email protected]> # # This file is part of Bold. # # Bold is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # Bold 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Bold. If not, see <http://www.gnu.org/licenses/>. # # Base class for controllers delivering content to the public # # Does site lookup by hostname / alias and runs requests in the context of the # site's configured time zone and locale. class FrontendController < BaseController layout :determine_layout prepend_before_action :set_site around_action :use_site_time_zone # in dev mode, Rails' standard error handling is fine. unless Rails.env.development? # order matters, least specific has to be first rescue_from Exception, with: :handle_error rescue_from Bold::SetupNeeded, with: :handle_404 rescue_from Bold::NotFound, with: :handle_404 rescue_from Bold::SiteNotFound, with: :handle_404_or_goto_admin rescue_from ActionController::InvalidAuthenticityToken, with: :handle_error rescue_from ActionController::UnknownFormat, with: :handle_404 end decorate_assigned :site, :content, :tag, :author, :category private def find_content if params[:path].blank? current_site.homepage elsif @permalink = current_site.permalinks.find_by_path(params[:path]) @destination = @permalink.destination (@destination.is_a?(Content) && @destination.published?) ? @destination : nil end end def render_content(content = @content, options = {}) original_content = @content @content = content options[:status] ||= :ok respond_to do |format| format.html do options[:template] = content.get_template.file render options end format.any { head options[:status] } end @content = original_content end def determine_layout current_site.theme.layout.present? ? 'content' : 'default_content' end def handle_404_or_goto_admin if request.host == Bold::Config['backend_host'] redirect_to bold_sites_url else handle_404 end end # Finds the current site based on http host or server_name header # # For the dev environment there is a fallback to the first site # found when none matched. Other environments will yield a # SiteNotFound error instead. # # Override #find_current_site or Site::for_request to customize the # detection of the current site. def set_site @site = Bold.current_site = find_current_site raise Bold::SiteNotFound unless site_selected? end def available_locales super.tap do |locales| if (site_locales = current_site.available_locales).present? locales &= site_locales end end end def auto_locale if current_site.detect_user_locale? return http_accept_language.compatible_language_from available_locales end end def use_site_time_zone(&block) if site_selected? current_site.in_time_zone &block else block.call end end def find_current_site Site.for_hostname(request.host) end def handle_404(*args) # we enforce rendering of html even if it was an image or something else # that wasn't found. if site = Bold.current_site and page = site.notfound_page render_content page, status: :not_found else respond_to do |format| format.html { render 'errors/404', layout: 'error', status: 404, formats: :html } format.any { head :not_found } end end end def handle_error(*args) unless performed? # avoid DoubleRenderError if site = Bold.current_site and page = site.error_page render_content page, status: 500, formats: :html else render 'errors/500', layout: 'error', status: 500, formats: :html end end if exception = args.first Rails.logger.warn exception Rails.logger.info exception.backtrace.join("\n") if defined? Airbrake Airbrake.notify exception end end end def do_not_track? request.headers['DNT'] == '1' end helper_method :do_not_track? end
bold-app/bold
app/controllers/frontend_controller.rb
Ruby
agpl-3.0
4,629
#include "fitz-imp.h" #include <assert.h> #include <string.h> #include <stdio.h> #include <time.h> struct fz_style_context_s { int refs; char *user_css; int use_document_css; }; static void fz_new_style_context(fz_context *ctx) { if (ctx) { ctx->style = fz_malloc_struct(ctx, fz_style_context); ctx->style->refs = 1; ctx->style->user_css = NULL; ctx->style->use_document_css = 1; } } static fz_style_context *fz_keep_style_context(fz_context *ctx) { if (!ctx) return NULL; return fz_keep_imp(ctx, ctx->style, &ctx->style->refs); } static void fz_drop_style_context(fz_context *ctx) { if (!ctx) return; if (fz_drop_imp(ctx, ctx->style, &ctx->style->refs)) { fz_free(ctx, ctx->style->user_css); fz_free(ctx, ctx->style); } } /* Toggle whether to respect document styles in HTML and EPUB. */ void fz_set_use_document_css(fz_context *ctx, int use) { ctx->style->use_document_css = use; } /* Return whether to respect document styles in HTML and EPUB. */ int fz_use_document_css(fz_context *ctx) { return ctx->style->use_document_css; } /* Set the user stylesheet source text for use with HTML and EPUB. */ void fz_set_user_css(fz_context *ctx, const char *user_css) { fz_free(ctx, ctx->style->user_css); ctx->style->user_css = user_css ? fz_strdup(ctx, user_css) : NULL; } /* Get the user stylesheet source text. */ const char *fz_user_css(fz_context *ctx) { return ctx->style->user_css; } static void fz_new_tuning_context(fz_context *ctx) { if (ctx) { ctx->tuning = fz_malloc_struct(ctx, fz_tuning_context); ctx->tuning->refs = 1; ctx->tuning->image_decode = fz_default_image_decode; ctx->tuning->image_scale = fz_default_image_scale; } } static fz_tuning_context *fz_keep_tuning_context(fz_context *ctx) { if (!ctx) return NULL; return fz_keep_imp(ctx, ctx->tuning, &ctx->tuning->refs); } static void fz_drop_tuning_context(fz_context *ctx) { if (!ctx) return; if (fz_drop_imp(ctx, ctx->tuning, &ctx->tuning->refs)) { fz_free(ctx, ctx->tuning); } } /* Set the tuning function to use for image decode. image_decode: Function to use. arg: Opaque argument to be passed to tuning function. */ void fz_tune_image_decode(fz_context *ctx, fz_tune_image_decode_fn *image_decode, void *arg) { ctx->tuning->image_decode = image_decode ? image_decode : fz_default_image_decode; ctx->tuning->image_decode_arg = arg; } /* Set the tuning function to use for image scaling. image_scale: Function to use. arg: Opaque argument to be passed to tuning function. */ void fz_tune_image_scale(fz_context *ctx, fz_tune_image_scale_fn *image_scale, void *arg) { ctx->tuning->image_scale = image_scale ? image_scale : fz_default_image_scale; ctx->tuning->image_scale_arg = arg; } static void fz_init_random_context(fz_context *ctx) { if (!ctx) return; ctx->seed48[0] = 0; ctx->seed48[1] = 0; ctx->seed48[2] = 0; ctx->seed48[3] = 0xe66d; ctx->seed48[4] = 0xdeec; ctx->seed48[5] = 0x5; ctx->seed48[6] = 0xb; fz_srand48(ctx, (uint32_t)time(NULL)); } /* Free a context and its global state. The context and all of its global state is freed, and any buffered warnings are flushed (see fz_flush_warnings). If NULL is passed in nothing will happen. */ void fz_drop_context(fz_context *ctx) { if (!ctx) return; /* Other finalisation calls go here (in reverse order) */ fz_drop_document_handler_context(ctx); fz_drop_glyph_cache_context(ctx); fz_drop_store_context(ctx); fz_drop_style_context(ctx); fz_drop_tuning_context(ctx); fz_drop_colorspace_context(ctx); fz_drop_font_context(ctx); fz_flush_warnings(ctx); assert(ctx->error.top == ctx->error.stack); /* Free the context itself */ ctx->alloc.free(ctx->alloc.user, ctx); } static void fz_init_error_context(fz_context *ctx) { ctx->error.top = ctx->error.stack; ctx->error.errcode = FZ_ERROR_NONE; ctx->error.message[0] = 0; ctx->warn.message[0] = 0; ctx->warn.count = 0; } /* Allocate context containing global state. The global state contains an exception stack, resource store, etc. Most functions in MuPDF take a context argument to be able to reference the global state. See fz_drop_context for freeing an allocated context. alloc: Supply a custom memory allocator through a set of function pointers. Set to NULL for the standard library allocator. The context will keep the allocator pointer, so the data it points to must not be modified or freed during the lifetime of the context. locks: Supply a set of locks and functions to lock/unlock them, intended for multi-threaded applications. Set to NULL when using MuPDF in a single-threaded applications. The context will keep the locks pointer, so the data it points to must not be modified or freed during the lifetime of the context. max_store: Maximum size in bytes of the resource store, before it will start evicting cached resources such as fonts and images. FZ_STORE_UNLIMITED can be used if a hard limit is not desired. Use FZ_STORE_DEFAULT to get a reasonable size. May return NULL. */ fz_context * fz_new_context_imp(const fz_alloc_context *alloc, const fz_locks_context *locks, size_t max_store, const char *version) { fz_context *ctx; if (strcmp(version, FZ_VERSION)) { fprintf(stderr, "cannot create context: incompatible header (%s) and library (%s) versions\n", version, FZ_VERSION); return NULL; } if (!alloc) alloc = &fz_alloc_default; if (!locks) locks = &fz_locks_default; ctx = Memento_label(alloc->malloc(alloc->user, sizeof(fz_context)), "fz_context"); if (!ctx) { fprintf(stderr, "cannot create context (phase 1)\n"); return NULL; } memset(ctx, 0, sizeof *ctx); ctx->user = NULL; ctx->alloc = *alloc; ctx->locks = *locks; ctx->error.print = fz_default_error_callback; ctx->warn.print = fz_default_warning_callback; fz_init_error_context(ctx); fz_init_aa_context(ctx); fz_init_random_context(ctx); /* Now initialise sections that are shared */ fz_try(ctx) { fz_new_store_context(ctx, max_store); fz_new_glyph_cache_context(ctx); fz_new_colorspace_context(ctx); fz_new_font_context(ctx); fz_new_document_handler_context(ctx); fz_new_style_context(ctx); fz_new_tuning_context(ctx); } fz_catch(ctx) { fprintf(stderr, "cannot create context (phase 2)\n"); fz_drop_context(ctx); return NULL; } return ctx; } /* Make a clone of an existing context. This function is meant to be used in multi-threaded applications where each thread requires its own context, yet parts of the global state, for example caching, are shared. ctx: Context obtained from fz_new_context to make a copy of. ctx must have had locks and lock/functions setup when created. The two contexts will share the memory allocator, resource store, locks and lock/unlock functions. They will each have their own exception stacks though. May return NULL. */ fz_context * fz_clone_context(fz_context *ctx) { fz_context *new_ctx; /* We cannot safely clone the context without having locking/ * unlocking functions. */ if (ctx == NULL || (ctx->locks.lock == fz_locks_default.lock && ctx->locks.unlock == fz_locks_default.unlock)) return NULL; new_ctx = ctx->alloc.malloc(ctx->alloc.user, sizeof(fz_context)); if (!new_ctx) return NULL; /* First copy old context, including pointers to shared contexts */ memcpy(new_ctx, ctx, sizeof (fz_context)); /* Reset error context to initial state. */ fz_init_error_context(new_ctx); /* Then keep lock checking happy by keeping shared contexts with new context */ fz_keep_document_handler_context(new_ctx); fz_keep_style_context(new_ctx); fz_keep_tuning_context(new_ctx); fz_keep_font_context(new_ctx); fz_keep_colorspace_context(new_ctx); fz_keep_store_context(new_ctx); fz_keep_glyph_cache(new_ctx); return new_ctx; } /* Set the user field in the context. NULL initially, this field can be set to any opaque value required by the user. It is copied on clones. */ void fz_set_user_context(fz_context *ctx, void *user) { if (ctx != NULL) ctx->user = user; } /* Read the user field from the context. */ void *fz_user_context(fz_context *ctx) { if (ctx == NULL) return NULL; return ctx->user; }
fluks/mupdf-x11-bookmarks
source/fitz/context.c
C
agpl-3.0
8,170
<?php declare(strict_types=1); /** * @copyright 2019 Christoph Wurst <[email protected]> * * @author 2019 Christoph Wurst <[email protected]> * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace OCA\Mail\Events; use Horde_Mime_Mail; use OCA\Mail\Account; use OCA\Mail\Model\IMessage; use OCA\Mail\Model\NewMessageData; use OCA\Mail\Model\RepliedMessageData; use OCP\EventDispatcher\Event; class MessageSentEvent extends Event { /** @var Account */ private $account; /** @var NewMessageData */ private $newMessageData; /** @var null|RepliedMessageData */ private $repliedMessageData; /** @var int|null */ private $draftUid; /** @var IMessage */ private $message; /** @var Horde_Mime_Mail */ private $mail; public function __construct(Account $account, NewMessageData $newMessageData, ?RepliedMessageData $repliedMessageData, ?int $draftUid = null, IMessage $message, Horde_Mime_Mail $mail) { parent::__construct(); $this->account = $account; $this->newMessageData = $newMessageData; $this->repliedMessageData = $repliedMessageData; $this->draftUid = $draftUid; $this->message = $message; $this->mail = $mail; } public function getAccount(): Account { return $this->account; } public function getNewMessageData(): NewMessageData { return $this->newMessageData; } public function getRepliedMessageData(): ?RepliedMessageData { return $this->repliedMessageData; } public function getDraftUid(): ?int { return $this->draftUid; } public function getMessage(): IMessage { return $this->message; } public function getMail(): Horde_Mime_Mail { return $this->mail; } }
ChristophWurst/mail
lib/Events/MessageSentEvent.php
PHP
agpl-3.0
2,380
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>The source code</title> <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="../resources/prettify/prettify.js"></script> <style type="text/css"> .highlight { display: block; background-color: #ddd; } </style> <script type="text/javascript"> function highlight() { document.getElementById(location.hash.replace(/#/, "")).className = "highlight"; } </script> </head> <body onload="prettyPrint(); highlight();"> <pre class="prettyprint lang-js"><span id='jslet-ui-DBSpinEdit'>/** </span> * @class * @extend jslet.ui.DBFieldControl * * DBSpinEdit. * * @example * var jsletParam = {type:&quot;DBSpinEdit&quot;,dataset:&quot;employee&quot;,field:&quot;age&quot;, minValue:18, maxValue: 100, step: 5}; * * //1. Declaring: * &lt;div data-jslet='type:&quot;DBSpinEdit&quot;,dataset:&quot;employee&quot;,field:&quot;age&quot;, minValue:18, maxValue: 100, step: 5'&gt;&lt;/div&gt; * or * &lt;div data-jslet='jsletParam'&gt;&lt;/div&gt; * * //2. Binding * &lt;div id=&quot;ctrlId&quot;&gt;&lt;/div&gt; * //Js snippet * var el = document.getElementById('ctrlId'); * jslet.ui.bindControl(el, jsletParam); * * //3. Create dynamically * jslet.ui.createControl(jsletParam, document.body); */ jslet.ui.DBSpinEdit = jslet.Class.create(jslet.ui.DBFieldControl, { <span id='jslet-ui-DBSpinEdit-method-initialize'> /** </span> * @protected * @override */ initialize: function ($super, el, params) { var Z = this; Z.allProperties = 'styleClass,dataset,field,step'; Z._step = 1; $super(el, params); }, <span id='jslet-ui-DBSpinEdit-property-step'> /** </span> * @property * * Set or get step. * * @param {Integer | undefined} step Step value. * * @return {this | Integer} */ step: function(step) { if(step === undefined) { return this._step; } jslet.Checker.test('DBSpinEdit.step', step).isNumber(); this._step = step; return this; }, <span id='jslet-ui-DBSpinEdit-method-isValidTemplateTag'> /** </span> * @protected * @override */ isValidTemplateTag: function (el) { var tag = el.tagName.toLowerCase(); return tag == 'div'; }, <span id='jslet-ui-DBSpinEdit-method-bind'> /** </span> * @protected * @override */ bind: function () { var Z = this, jqEl = jQuery(Z.el); if(!jqEl.hasClass('jl-spinedit')) { jqEl.addClass('input-group jl-spinedit'); } Z._createControl(); Z.renderAll(); }, _createControl: function() { var Z = this, jqEl = jQuery(Z.el), s = '&lt;input type=&quot;text&quot; class=&quot;form-control&quot;&gt;' + '&lt;div class=&quot;jl-spinedit-btn-group&quot;&gt;' + '&lt;button class=&quot;btn btn-default jl-spinedit-up&quot; tabindex=&quot;-1&quot;&gt;&lt;i class=&quot;fa fa-caret-up&quot;&gt;&lt;/i&gt;&lt;/button&gt;' + '&lt;button class=&quot;btn btn-default jl-spinedit-down&quot; tabindex=&quot;-1&quot;&gt;&lt;i class=&quot;fa fa-caret-down&quot;&gt;&lt;/i&gt;&lt;/button&gt;'; jqEl.html(s); var editor = jqEl.find('input')[0], upButton = jqEl.find('.jl-spinedit-up')[0], downButton = jqEl.find('.jl-spinedit-down')[0]; Z.editor = editor; editor.name = Z._field; jQuery(Z.editor).on(&quot;keydown&quot;, function(event){ if(Z._isDisabled()) { return; } var keyCode = event.keyCode; if(keyCode === jslet.ui.KeyCode.UP) { Z.decValue(); event.preventDefault(); return; } if(keyCode === jslet.ui.KeyCode.DOWN) { Z.incValue(); event.preventDefault(); return; } }); new jslet.ui.DBText(editor, { dataset: Z._dataset, field: Z._field, beforeUpdateToDataset: Z.beforeUpdateToDataset, valueIndex: Z._valueIndex, tabIndex: Z._tabIndex }); var jqBtn = jQuery(upButton); jqBtn.on('click', function () { Z.incValue(); }); jqBtn.focus(function(event) { jslet.ui.globalFocusManager.activeDataset(Z._dataset.name()).activeField(Z._field).activeValueIndex(Z._valueIndex); }); jqBtn.blur(function(event) { jslet.ui.globalFocusManager.activeDataset(null).activeField(null).activeValueIndex(null); }); jqBtn = jQuery(downButton); jqBtn.on('click', function () { Z.decValue(); }); jqBtn.focus(function(event) { jslet.ui.globalFocusManager.activeDataset(Z._dataset.name()).activeField(Z._field).activeValueIndex(Z._valueIndex); }); jqBtn.blur(function(event) { jslet.ui.globalFocusManager.activeDataset(null).activeField(null).activeValueIndex(null); }); }, _isDisabled: function() { var Z = this, fldObj = Z._dataset.getField(Z._field); return fldObj.disabled() || fldObj.readOnly(); }, beforeUpdateToDataset: function () { var Z = this, val = Z.el.value; var fldObj = Z._dataset.getField(Z._field), range = fldObj.dataRange(), minValue = Number.NEGATIVE_INFINITY, maxValue = Number.POSITIVE_INFINITY; if(range) { if(range.min || range.min === 0) { minValue = parseFloat(range.min); } if(range.max || range.min === 0) { maxValue = parseFloat(range.max); } } if (val) { val = parseFloat(val); } jQuery(Z.el).attr('aria-valuenow', val); Z.el.value = val; return true; }, setValueToDataset: function (val) { var Z = this; if (Z.silence) { return; } Z.silence = true; if (val === undefined) { val = Z.value; } try { Z._dataset.setFieldValue(Z._field, val, Z._valueIndex); } finally { Z.silence = false; } }, incValue: function () { var Z = this, val = Z.getValue(); if (!val) { val = 0; } var maxValue = Z._getRange().maxValue; if (val === maxValue) { return; } else if (val &lt; maxValue) { val += Z._step; } else { val = maxValue; } if (val &gt; maxValue) { val = maxValue; } jQuery(Z.el).attr('aria-valuenow', val); Z.setValueToDataset(val); return this; }, _getRange: function() { var Z = this, fldObj = Z._dataset.getField(Z._field), range = fldObj.dataRange(), minValue = Number.NEGATIVE_INFINITY, maxValue = Number.POSITIVE_INFINITY; if(range) { if(range.min || range.min === 0) { minValue = parseFloat(range.min); } if(range.max || range.min === 0) { maxValue = parseFloat(range.max); } } return {minValue: minValue, maxValue: maxValue}; }, decValue: function () { var Z = this, val = Z.getValue(); if (!val) { val = 0; } var minValue = Z._getRange().minValue; if (val === minValue) { return; } else if (val &gt; minValue) { val -= Z._step; } else { val = minValue; } if (val &lt; minValue) val = minValue; jQuery(Z.el).attr('aria-valuenow', val); Z.setValueToDataset(val); return this; }, <span id='jslet-ui-DBSpinEdit-method-innerFocus'> /** </span> * @protected * @override */ innerFocus: function() { this.editor.focus(); }, <span id='jslet-ui-DBSpinEdit-method-doMetaChanged'> /** </span> * @protected * @override */ doMetaChanged: function($super, metaName) { $super(metaName); var Z = this, jqEl = jQuery(this.el), fldObj = Z._dataset.getField(Z._field); if(!metaName || metaName == 'disabled' || metaName == 'readOnly') { var disabled = fldObj.disabled() || fldObj.readOnly(), jqUpBtn = jqEl.find('.jl-spinedit-up'), jqDownBtn = jqEl.find('.jl-spinedit-down'); if (disabled) { jqUpBtn.attr('disabled', 'disabled'); jqDownBtn.attr('disabled', 'disabled'); } else { jqUpBtn.attr('disabled', false); jqDownBtn.attr('disabled', false); } } if(!metaName || metaName == 'dataRange') { var range = fldObj.dataRange(); jqEl.attr('aria-valuemin', range &amp;&amp; (range.min || range.min === 0) ? range.min: ''); jqEl.attr('aria-valuemin', range &amp;&amp; (range.max || range.max === 0) ? range.max: ''); } if(!metaName || metaName == 'tabIndex') { Z.setTabIndex(); } }, <span id='jslet-ui-DBSpinEdit-method-renderAll'> /** </span> * @override */ renderAll: function(){ this.refreshControl(jslet.data.RefreshEvent.updateAllEvent(), true); return this; }, <span id='jslet-ui-DBSpinEdit-method-tableId'> /** </span> * @protected * @override */ tableId: function($super, tableId){ $super(tableId); this.editor.jslet.tableId(tableId); }, <span id='jslet-ui-DBSpinEdit-method-destroy'> /** </span> * @override */ destroy: function(){ var jqEl = jQuery(this.el); jQuery(this.editor).off(); this.editor = null; jqEl.find('.jl-upbtn-up').off(); jqEl.find('.jl-downbtn-up').off(); } }); jslet.ui.register('DBSpinEdit', jslet.ui.DBSpinEdit); jslet.ui.DBSpinEdit.htmlTemplate = '&lt;div&gt;&lt;/div&gt;'; </pre> </body> </html>
jslet/jslet
docs/source/jslet.dbspinedit.html
HTML
agpl-3.0
8,843
<?php /** * plentymarkets shopware connector * Copyright © 2013-2014 plentymarkets GmbH * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License, supplemented by an additional * permission, and of our proprietary license can be found * in the LICENSE file you have received along with this program. * * 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 Affero General Public License for more details. * * "plentymarkets" is a registered trademark of plentymarkets GmbH. * "shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, titles and interests in the * above trademarks remain entirely with the trademark owners. * * @copyright Copyright (c) 2014, plentymarkets GmbH (http://www.plentymarkets.com) * @author Daniel Bächtle <[email protected]> */ /** * I am a generated class and am required for communicating with plentymarkets. */ class PlentySoapRequest_GetMeasureUnitConfig { /** * @var string */ public $Lang; }
naturdrogerie/plentymarkets-shopware-connector
Components/Soap/Models/PlentySoapRequest/GetMeasureUnitConfig.php
PHP
agpl-3.0
1,411
var clover = new Object(); // JSON: {classes : [{name, id, sl, el, methods : [{sl, el}, ...]}, ...]} clover.pageData = {"classes":[{"el":162,"id":11268,"methods":[{"el":52,"sc":2,"sl":50},{"el":138,"sc":2,"sl":54},{"el":147,"sc":2,"sl":140},{"el":161,"sc":2,"sl":149}],"name":"ChiSquaredWeighting","sl":46}]} // JSON: {test_ID : {"methods": [ID1, ID2, ID3...], "name" : "testXXX() void"}, ...}; clover.testTargets = {} // JSON: { lines : [{tests : [testid1, testid2, testid3, ...]}, ...]}; clover.srcFileLines = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
cm-is-dog/rapidminer-studio-core
report/html/com/rapidminer/operator/features/weighting/ChiSquaredWeighting.js
JavaScript
agpl-3.0
1,169
DELETE FROM `weenie` WHERE `class_Id` = 19384; INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`) VALUES (19384, 'gagindwellingssign', 1, '2019-02-10 00:00:00') /* Generic */; INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`) VALUES (19384, 1, 128) /* ItemType - Misc */ , (19384, 5, 9000) /* EncumbranceVal */ , (19384, 16, 1) /* ItemUseable - No */ , (19384, 19, 125) /* Value */ , (19384, 93, 1048) /* PhysicsState - ReportCollisions, IgnoreCollisions, Gravity */; INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`) VALUES (19384, 1, True ) /* Stuck */; INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`) VALUES (19384, 1, 'Gajin Dwellings') /* Name */; INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`) VALUES (19384, 1, 33557697) /* Setup */ , (19384, 8, 100667499) /* Icon */ , (19384, 8001, 2097176) /* PCAPRecordedWeenieHeader - Value, Usable, Burden */ , (19384, 8003, 20) /* PCAPRecordedObjectDesc - Stuck, Attackable */ , (19384, 8005, 32769) /* PCAPRecordedPhysicsDesc - CSetup, Position */; INSERT INTO `weenie_properties_position` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`) VALUES (19384, 8040, 1449197825, 2.66, -50.119, 0, -0.707107, 0, 0, -0.707107) /* PCAPRecordedLocation */ /* @teleloc 0x56610101 [2.660000 -50.119000 0.000000] -0.707107 0.000000 0.000000 -0.707107 */; INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`) VALUES (19384, 8000, 1969623043) /* PCAPRecordedObjectIID */;
LtRipley36706/ACE-World
Database/3-Core/9 WeenieDefaults/SQL/Generic/Misc/19384 Gajin Dwellings.sql
SQL
agpl-3.0
1,718
import _ from 'underscore' import Base from '../graphs/base' import DayBinner from '../graphs/DayBinner' import WeekBinner from '../graphs/WeekBinner' import MonthBinner from '../graphs/MonthBinner' import ScaleByBins from '../graphs/ScaleByBins' import helpers from '../helpers' import I18n from 'i18n!page_views' // # // Parent class for all graphs that have a date-aligned x-axis. Note: Left // padding for this graph style is space from the frame to the start date's // tick mark, not the leading graph element's edge. Similarly, right padding // is space from the frame to the end date's tick, not the trailing graph // element's edge. This is necessary to keep the date graphs aligned. const defaultOptions = { // # // The date for the left end of the graph. Required. startDate: null, // # // The date for the right end of the graph. Required. endDate: null, // # // The size of the date tick marks, in pixels. tickSize: 5, // # // If any date is outside the bounds of the graph, we have a clipped date clippedDate: false } export default class DateAlignedGraph extends Base { // # // Takes an element and options, same as for Base. Recognizes the options // described above in addition to the options for Base. constructor(div, options) { super(...arguments) // mixin ScaleByBins functionality _.extend(this, ScaleByBins) // check for required options if (options.startDate == null) throw new Error('startDate is required') if (options.endDate == null) throw new Error('endDate is required') // copy in recognized options with defaults for (const key in defaultOptions) { const defaultValue = defaultOptions[key] this[key] = options[key] != null ? options[key] : defaultValue } this.initScale() } // # // Set up X-axis scale initScale() { const interior = this.width - this.leftPadding - this.rightPadding // mixin for the appropriate bin size // use a minimum of 10 pixels for bar width plus spacing before consolidating this.binner = new DayBinner(this.startDate, this.endDate) if (this.binner.count() * 10 > interior) this.binner = new WeekBinner(this.startDate, this.endDate) if (this.binner.count() * 10 > interior) this.binner = new MonthBinner(this.startDate, this.endDate) // scale the x-axis for the number of bins return this.scaleByBins(this.binner.count()) } // # // Reset the graph chrome. Adds an x-axis with daily ticks and weekly (on // Mondays) labels. reset() { super.reset(...arguments) if (this.startDate) this.initScale() return this.drawDateAxis() } // # // Convert a date to a bin index. dateBin(date) { return this.binner.bin(date) } // # // Convert a date to its bin's x-coordinate. binnedDateX(date) { return this.binX(this.dateBin(date)) } // # // Given a datetime, return the floor and ceil as calculated by the binner dateExtent(datetime) { const floor = this.binner.reduce(datetime) return [floor, this.binner.nextTick(floor)] } // # // Given a datetime and a datetime range, return a number from 0.0 to 1.0 dateFraction(datetime, floorDate, ceilDate) { const deltaSeconds = datetime.getTime() - floorDate.getTime() const totalSeconds = ceilDate.getTime() - floorDate.getTime() return deltaSeconds / totalSeconds } // # // Convert a date to an intra-bin x-coordinate. dateX(datetime) { const minX = this.leftMargin const maxX = this.leftMargin + this.width const [floorDate, ceilDate] = this.dateExtent(datetime) const floorX = this.binnedDateX(floorDate) const ceilX = this.binnedDateX(ceilDate) const fraction = this.dateFraction(datetime, floorDate, ceilDate) if (datetime.getTime() < this.startDate.getTime()) { // out of range, left this.clippedDate = true return minX } else if (datetime.getTime() > this.endDate.getTime()) { // out of range, right this.clippedDate = true return maxX } else { // in range return floorX + fraction * (ceilX - floorX) } } // # // Draw a guide along the x-axis. Each day gets a pair of ticks; one from // the top of the frame, the other from the bottom. The ticks are replaced // by a full vertical grid line on Mondays, accompanied by a label. drawDateAxis() { // skip if we haven't set start/end dates yet (@reset will be called by // Base's constructor before we set startDate or endDate) if (this.startDate == null || this.endDate == null) return return this.binner.eachTick((tick, chrome) => { const x = this.binnedDateX(tick) if (chrome && chrome.label) return this.dateLabel(x, this.topMargin + this.height, chrome.label) }) } // # // Draw label text at (x, y). dateLabel(x, y, text) { const label = this.paper.text(x, y, text) return label.attr({fill: this.frameColor}) } // # // Get date text for a bin binDateText(bin) { const lastDay = this.binner.nextTick(bin.date).addDays(-1) const daysBetween = helpers.daysBetween(bin.date, lastDay) if (daysBetween < 1) { // single-day bucket: label the date return I18n.l('date.formats.medium', bin.date) } else if (daysBetween < 7) { // one-week bucket: label the start and end days; include the year only with the end day unless they're different return I18n.t('%{start_date} - %{end_date}', { start_date: I18n.l( bin.date.getFullYear() === lastDay.getFullYear() ? 'date.formats.short' : 'date.formats.medium', bin.date ), end_date: I18n.l('date.formats.medium', lastDay) }) } else { // one-month bucket; label the month and year return I18n.l('date.formats.medium_month', bin.date) } } }
instructure/analytics
app/jsx/graphs/DateAlignedGraph.js
JavaScript
agpl-3.0
5,859
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>operator&gt;=</title> <link rel="stylesheet" href="apiReference.css" type="text/css" /> <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" /> <link rel="start" href="index.html" title="Berkeley DB C++ Standard Template Library API Reference" /> <link rel="up" href="db_vector_base_iterator.html" title="Chapter 12.  Db_vector_base_iterator" /> <link rel="prev" href="stldb_vector_base_iteratoroperator_le.html" title="operator&lt;=" /> <link rel="next" href="stldb_vector_base_iteratoroperator_gt.html" title="operator&gt;" /> </head> <body> <div xmlns="" class="navheader"> <div class="libver"> <p>Library Version 12.1.6.0</p> </div> <table width="100%" summary="Navigation header"> <tr> <th colspan="3" align="center">operator&gt;=</th> </tr> <tr> <td width="20%" align="left"><a accesskey="p" href="stldb_vector_base_iteratoroperator_le.html">Prev</a> </td> <th width="60%" align="center">Chapter 12.  Db_vector_base_iterator </th> <td width="20%" align="right"> <a accesskey="n" href="stldb_vector_base_iteratoroperator_gt.html">Next</a></td> </tr> </table> <hr /> </div> <div class="sect1" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h2 class="title" style="clear: both"><a id="stldb_vector_base_iteratoroperator_ge"></a>operator&gt;=</h2> </div> </div> </div> <div class="sect2" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h3 class="title"><a id="stldb_vector_base_iteratoroperator_ge_details"></a>Function Details</h3> </div> </div> </div> <pre class="programlisting"> bool operator&gt;=(const self &amp;itr) const </pre> <p>Greater equal comparison operator. </p> <div class="sect3" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h4 class="title"><a id="idp1167176"></a>Parameters</h4> </div> </div> </div> <div class="sect4" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h5 class="title"><a id="idp1175480"></a>itr</h5> </div> </div> </div> <p>The iterator to compare against. </p> </div> </div> <div class="sect3" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h4 class="title"><a id="idp1172856"></a>Return Value</h4> </div> </div> </div> <p>True if this iterator is greater than or equal to itr. </p> </div> </div> <div class="sect2" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h3 class="title"><a id="idp1171776"></a>Group: Iterator comparison operators</h3> </div> </div> </div> <p>The way to compare two iterators is to compare the index values of the two elements they point to.</p> <p>The iterator sitting on an element with less index is regarded to be smaller. And the invalid iterator sitting after last element is greater than any other iterators, because it is assumed to have an index equal to last element's index plus one; The invalid iterator sitting before first element is less than any other iterators because it is assumed to have an index -1. </p> </div> <div class="sect2" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h3 class="title"><a id="idp1171096"></a>Class</h3> </div> </div> </div> <p> <a class="link" href="db_vector_base_iterator.html" title="Chapter 12.  Db_vector_base_iterator">db_vector_base_iterator</a> </p> </div> </div> <div class="navfooter"> <hr /> <table width="100%" summary="Navigation footer"> <tr> <td width="40%" align="left"><a accesskey="p" href="stldb_vector_base_iteratoroperator_le.html">Prev</a> </td> <td width="20%" align="center"> <a accesskey="u" href="db_vector_base_iterator.html">Up</a> </td> <td width="40%" align="right"> <a accesskey="n" href="stldb_vector_base_iteratoroperator_gt.html">Next</a></td> </tr> <tr> <td width="40%" align="left" valign="top">operator&lt;= </td> <td width="20%" align="center"> <a accesskey="h" href="index.html">Home</a> </td> <td width="40%" align="right" valign="top"> operator&gt;</td> </tr> </table> </div> </body> </html>
hyc/BerkeleyDB
docs/api_reference/STL/stldb_vector_base_iteratoroperator_ge.html
HTML
agpl-3.0
5,227
<?php /** * Output functions * Processing text for output such as pulling out URLs and extracting excerpts * * @package Elgg * @subpackage Core */ /** * Takes a string and turns any URLs into formatted links * * @param string $text The input string * * @return string The output string with formatted links **/ function parse_urls($text) { // @todo this causes problems with <attr = "val"> // must be in <attr="val"> format (no space). // By default htmlawed rewrites tags to this format. // if PHP supported conditional negative lookbehinds we could use this: // $r = preg_replace_callback('/(?<!=)(?<![ ])?(?<!["\'])((ht|f)tps?:\/\/[^\s\r\n\t<>"\'\!\(\),]+)/i', // // we can put , in the list of excluded char but need to keep . because of domain names. // it is removed in the callback. $r = preg_replace_callback('/(?<!=)(?<!["\'])((ht|f)tps?:\/\/[^\s\r\n\t<>"\'\!\(\),]+)/i', create_function( '$matches', ' $url = $matches[1]; $period = \'\'; if (substr($url, -1, 1) == \'.\') { $period = \'.\'; $url = trim($url, \'.\'); } $urltext = str_replace("/", "/<wbr />", $url); return "<a href=\"$url\" target=\"_blank\">$urltext</a>$period"; ' ), $text); return $r; } /** * Create paragraphs from text with line spacing * * @param string $pee The string * @deprecated Use elgg_autop instead * @todo Add deprecation warning in 1.9 * * @return string **/ function autop($pee) { return elgg_autop($pee); } /** * Create paragraphs from text with line spacing * * @param string $string The string * * @return string **/ function elgg_autop($string) { return ElggAutoP::getInstance()->process($string); } /** * Parse src variables to '//' instead of 'http(s)://' * * @param string $string The string * * @return string */ function minds_autosrc($string){ global $CONFIG; $replace = '//'; if($CONFIG->cdn_url){ $doc = new DOMDocument(); @$doc->loadHTML($string); $tags = $doc->getElementsByTagName('img'); foreach ($tags as $tag) { $src = $tag->getAttribute('src'); if($src){ $src = $CONFIG->cdn_url . 'thumbProxy?src='.urlencode($src).'&width=auto'; $tag->setAttribute('src', $src); } } $tags = $doc->getElementsByTagName('iframe'); foreach ($tags as $tag) { $src = $tag->getAttribute('src'); if($src){ $src = str_replace("http://", "//", $src); $tag->setAttribute('src', $src); } } return $doc->saveHTML(); } $output = str_replace( "src=\"http://", "src=\"$replace", $string ); return $output; } /** * Returns an excerpt. * Will return up to n chars stopping at the nearest space. * If no spaces are found (like in Japanese) will crop off at the * n char mark. Adds ... if any text was chopped. * * @param string $text The full text to excerpt * @param int $num_chars Return a string up to $num_chars long * * @return string * @since 1.7.2 */ function elgg_get_excerpt($text, $num_chars = 250) { $text = trim(elgg_strip_tags($text)); $string_length = elgg_strlen($text); if ($string_length <= $num_chars) { return $text; } // handle cases $excerpt = elgg_substr($text, 0, $num_chars); $space = elgg_strrpos($excerpt, ' ', 0); // don't crop if can't find a space. if ($space === FALSE) { $space = $num_chars; } $excerpt = trim(elgg_substr($excerpt, 0, $space)); if ($string_length != elgg_strlen($excerpt)) { $excerpt .= '...'; } return $excerpt; } /** * Handles formatting of ampersands in urls * * @param string $url The URL * * @return string * @since 1.7.1 */ function elgg_format_url($url) { return preg_replace('/&(?!amp;)/', '&amp;', $url); } /** * Converts an associative array into a string of well-formed attributes * * @note usually for HTML, but could be useful for XML too... * * @param array $attrs An associative array of attr => val pairs * * @return string HTML attributes to be inserted into a tag (e.g., <tag $attrs>) */ function elgg_format_attributes(array $attrs) { $attrs = elgg_clean_vars($attrs); $attributes = array(); if (isset($attrs['js'])) { //@todo deprecated notice? if (!empty($attrs['js'])) { $attributes[] = $attrs['js']; } unset($attrs['js']); } foreach ($attrs as $attr => $val) { $attr = strtolower($attr); if ($val === TRUE) { $val = $attr; //e.g. checked => TRUE ==> checked="checked" } // ignore $vars['entity'] => ElggEntity stuff if ($val !== NULL && $val !== false && (is_array($val) || !is_object($val))) { // allow $vars['class'] => array('one', 'two'); // @todo what about $vars['style']? Needs to be semi-colon separated... if (is_array($val)) { $val = implode(' ', $val); } $val = htmlspecialchars($val, ENT_QUOTES, 'UTF-8', false); $attributes[] = "$attr=\"$val\""; } } return implode(' ', $attributes); } /** * Preps an associative array for use in {@link elgg_format_attributes()}. * * Removes all the junk that {@link elgg_view()} puts into $vars. * Maintains backward compatibility with attributes like 'internalname' and 'internalid' * * @note This function is called automatically by elgg_format_attributes(). No need to * call it yourself before using elgg_format_attributes(). * * @param array $vars The raw $vars array with all it's dirtiness (config, url, etc.) * * @return array The array, ready to be used in elgg_format_attributes(). * @access private */ function elgg_clean_vars(array $vars = array()) { unset($vars['config']); unset($vars['url']); unset($vars['user']); // backwards compatibility code if (isset($vars['internalname'])) { $vars['name'] = $vars['internalname']; unset($vars['internalname']); } if (isset($vars['internalid'])) { $vars['id'] = $vars['internalid']; unset($vars['internalid']); } if (isset($vars['__ignoreInternalid'])) { unset($vars['__ignoreInternalid']); } if (isset($vars['__ignoreInternalname'])) { unset($vars['__ignoreInternalname']); } return $vars; } /** * Converts shorthand urls to absolute urls. * * If the url is already absolute or protocol-relative, no change is made. * * @example * elgg_normalize_url(''); // 'http://my.site.com/' * elgg_normalize_url('dashboard'); // 'http://my.site.com/dashboard' * elgg_normalize_url('http://google.com/'); // no change * elgg_normalize_url('//google.com/'); // no change * * @param string $url The URL to normalize * * @return string The absolute url */ function elgg_normalize_url($url) { // see https://bugs.php.net/bug.php?id=51192 // from the bookmarks save action. $php_5_2_13_and_below = version_compare(PHP_VERSION, '5.2.14', '<'); $php_5_3_0_to_5_3_2 = version_compare(PHP_VERSION, '5.3.0', '>=') && version_compare(PHP_VERSION, '5.3.3', '<'); if ($php_5_2_13_and_below || $php_5_3_0_to_5_3_2) { $tmp_address = str_replace("-", "", $url); $validated = filter_var($tmp_address, FILTER_VALIDATE_URL); } else { $validated = filter_var($url, FILTER_VALIDATE_URL); } // work around for handling absoluate IRIs (RFC 3987) - see #4190 if (!$validated && (strpos($url, 'http:') === 0) || (strpos($url, 'https:') === 0)) { $validated = true; } if ($validated) { // all normal URLs including mailto: return $url; } elseif (preg_match("#^(\#|\?|//)#i", $url)) { // '//example.com' (Shortcut for protocol.) // '?query=test', #target return $url; } elseif (stripos($url, 'javascript:') === 0 || stripos($url, 'mailto:') === 0) { // 'javascript:' and 'mailto:' // Not covered in FILTER_VALIDATE_URL return $url; } elseif (preg_match("#^[^/]*\.php(\?.*)?$#i", $url)) { // 'install.php', 'install.php?step=step' return elgg_get_site_url() . $url; } elseif (preg_match("#^[^/]*\.#i", $url)) { // 'example.com', 'example.com/subpage' return "http://$url"; } else { // 'page/handler', 'mod/plugin/file.php' // trim off any leading / because the site URL is stored // with a trailing / return elgg_get_site_url() . ltrim($url, '/'); } } /** * When given a title, returns a version suitable for inclusion in a URL * * @param string $title The title * * @return string The optimised title * @since 1.7.2 */ function elgg_get_friendly_title($title) { // return a URL friendly title to short circuit normal title formatting $params = array('title' => $title); $result = elgg_trigger_plugin_hook('format', 'friendly:title', $params, NULL); if ($result) { return $result; } // handle some special cases $title = str_replace('&amp;', 'and', $title); // quotes and angle brackets stored in the database as html encoded $title = htmlspecialchars_decode($title); $title = ElggTranslit::urlize($title); return $title; } /** * Formats a UNIX timestamp in a friendly way (eg "less than a minute ago") * * @see elgg_view_friendly_time() * * @param int $time A UNIX epoch timestamp * * @return string The friendly time string * @since 1.7.2 */ function elgg_get_friendly_time($time) { // return a time string to short circuit normal time formatting $params = array('time' => $time); $result = elgg_trigger_plugin_hook('format', 'friendly:time', $params, NULL); if ($result) { return $result; } $diff = time() - (int)$time; $minute = 60; $hour = $minute * 60; $day = $hour * 24; if ($diff < $minute) { return elgg_echo("friendlytime:justnow"); } else if ($diff < $hour) { $diff = round($diff / $minute); if ($diff == 0) { $diff = 1; } if ($diff > 1) { return elgg_echo("friendlytime:minutes", array($diff)); } else { return elgg_echo("friendlytime:minutes:singular", array($diff)); } } else { return date("F j, Y", $time); } /*} else if ($diff < $day) { $diff = round($diff / $hour); if ($diff == 0) { $diff = 1; } if ($diff > 1) { return elgg_echo("friendlytime:hours", array($diff)); } else { return elgg_echo("friendlytime:hours:singular", array($diff)); } } else { $diff = round($diff / $day); if ($diff == 0) { $diff = 1; } if ($diff > 1) { return elgg_echo("friendlytime:days", array($diff)); } else { return elgg_echo("friendlytime:days:singular", array($diff)); } }*/ } /** * Strip tags and offer plugins the chance. * Plugins register for output:strip_tags plugin hook. * Original string included in $params['original_string'] * * @param string $string Formatted string * * @return string String run through strip_tags() and any plugin hooks. */ function elgg_strip_tags($string) { $params['original_string'] = $string; $string = strip_tags($string); $string = elgg_trigger_plugin_hook('format', 'strip_tags', $params, $string); return $string; } /** * Apply html_entity_decode() to a string while re-entitising HTML * special char entities to prevent them from being decoded back to their * unsafe original forms. * * This relies on html_entity_decode() not translating entities when * doing so leaves behind another entity, e.g. &amp;gt; if decoded would * create &gt; which is another entity itself. This seems to escape the * usual behaviour where any two paired entities creating a HTML tag are * usually decoded, i.e. a lone &gt; is not decoded, but &lt;foo&gt; would * be decoded to <foo> since it creates a full tag. * * Note: This function is poorly explained in the manual - which is really * bad given its potential for misuse on user input already escaped elsewhere. * Stackoverflow is littered with advice to use this function in the precise * way that would lead to user input being capable of injecting arbitrary HTML. * * @param string $string * * @return string * * @author Pádraic Brady * @copyright Copyright (c) 2010 Pádraic Brady (http://blog.astrumfutura.com) * @license Released under dual-license GPL2/MIT by explicit permission of Pádraic Brady * * @access private */ function _elgg_html_decode($string) { $string = str_replace( array('&gt;', '&lt;', '&amp;', '&quot;', '&#039;'), array('&amp;gt;', '&amp;lt;', '&amp;amp;', '&amp;quot;', '&amp;#039;'), $string ); $string = html_entity_decode($string, ENT_NOQUOTES, 'UTF-8'); $string = str_replace( array('&amp;gt;', '&amp;lt;', '&amp;amp;', '&amp;quot;', '&amp;#039;'), array('&gt;', '&lt;', '&amp;', '&quot;', '&#039;'), $string ); return $string; } /** * Unit tests for Output * * @param string $hook unit_test * @param string $type system * @param mixed $value Array of tests * @param mixed $params Params * * @return array * @access private */ function output_unit_test($hook, $type, $value, $params) { global $CONFIG; $value[] = $CONFIG->path . 'engine/tests/api/output.php'; return $value; } /** * Initialise the Output subsystem. * * @return void * @access private */ function output_init() { elgg_register_plugin_hook_handler('unit_test', 'system', 'output_unit_test'); } elgg_register_event_handler('init', 'system', 'output_init');
Minds/engine
lib/output.php
PHP
agpl-3.0
13,041
SavedSearchSelect.$inject = ['session', 'savedSearch']; export function SavedSearchSelect(session, savedSearch) { return { link: function(scope) { savedSearch.getUserSavedSearches(session.identity).then(function(res) { scope.searches = res; }); } }; }
lnogues/superdesk-client-core
scripts/superdesk-search/directives/SavedSearchSelect.js
JavaScript
agpl-3.0
316
#!/usr/bin/env python # Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Essentia # # Essentia is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation (FSF), 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 Affero GNU General Public License # version 3 along with this program. If not, see http://www.gnu.org/licenses/ from essentia_test import * from essentia.streaming import TCToTotal as sTCToTotal class TestTCToTotal(TestCase): def testEmpty(self): gen = VectorInput([]) tcToTotal = sTCToTotal() p = Pool() gen.data >> tcToTotal.envelope tcToTotal.TCToTotal >> (p, 'lowlevel.tctototal') run(gen) self.assertRaises(KeyError, lambda: p['lowlevel.tctototal']) def testOneValue(self): gen = VectorInput([1]) tcToTotal = sTCToTotal() p = Pool() gen.data >> tcToTotal.envelope tcToTotal.TCToTotal >> (p, 'lowlevel.tctototal') self.assertRaises(RuntimeError, lambda: run(gen)) def testRegression(self): envelope = range(22050) envelope.reverse() envelope = range(22050) + envelope gen = VectorInput(envelope) tcToTotal = sTCToTotal() p = Pool() gen.data >> tcToTotal.envelope tcToTotal.TCToTotal >> (p, 'lowlevel.tctototal') run(gen) self.assertAlmostEqual(p['lowlevel.tctototal'], TCToTotal()(envelope)) suite = allTests(TestTCToTotal) if __name__ == '__main__': TextTestRunner(verbosity=2).run(suite)
arseneyr/essentia
test/src/unittest/sfx/test_tctototal_streaming.py
Python
agpl-3.0
2,098
# Copyright 2015 ACSONE SA/NV # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class PosConfig(models.Model): _inherit = "pos.config" account_analytic_id = fields.Many2one( comodel_name="account.analytic.account", string="Analytic Account" )
OCA/account-analytic
pos_analytic_by_config/models/pos_config.py
Python
agpl-3.0
318
// Copyright 2015 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package context_test import ( jc "github.com/juju/testing/checkers" "github.com/juju/utils" "github.com/juju/utils/set" gc "gopkg.in/check.v1" "gopkg.in/juju/names.v2" "github.com/juju/juju/apiserver/params" "github.com/juju/juju/provider/dummy" "github.com/juju/juju/state" "github.com/juju/juju/storage" "github.com/juju/juju/storage/poolmanager" "github.com/juju/juju/storage/provider" "github.com/juju/juju/worker/uniter/runner/context" ) type unitStorageSuite struct { HookContextSuite expectedStorageNames set.Strings charmName string initCons map[string]state.StorageConstraints ch *state.Charm initialStorageInstancesCount int } var _ = gc.Suite(&unitStorageSuite{}) const ( testPool = "block" testPersistentPool = "block-persistent" ) func (s *unitStorageSuite) SetUpTest(c *gc.C) { s.HookContextSuite.SetUpTest(c) setupTestStorageSupport(c, s.State) } func (s *unitStorageSuite) TestAddUnitStorage(c *gc.C) { s.createStorageBlockUnit(c) count := uint64(1) s.assertUnitStorageAdded(c, map[string]params.StorageConstraints{ "allecto": params.StorageConstraints{Count: &count}}) } func (s *unitStorageSuite) TestAddUnitStorageIgnoresBlocks(c *gc.C) { s.createStorageBlockUnit(c) count := uint64(1) s.BlockDestroyModel(c, "TestAddUnitStorageIgnoresBlocks") s.BlockRemoveObject(c, "TestAddUnitStorageIgnoresBlocks") s.BlockAllChanges(c, "TestAddUnitStorageIgnoresBlocks") s.assertUnitStorageAdded(c, map[string]params.StorageConstraints{ "allecto": params.StorageConstraints{Count: &count}}) } func (s *unitStorageSuite) TestAddUnitStorageZeroCount(c *gc.C) { s.createStorageBlockUnit(c) cons := map[string]params.StorageConstraints{ "allecto": params.StorageConstraints{}} ctx := s.addUnitStorage(c, cons) // Flush the context with a success. err := ctx.Flush("success", nil) c.Assert(err, gc.ErrorMatches, `.*count must be specified.*`) // Make sure no storage instances was added after, err := s.State.AllStorageInstances() c.Assert(err, jc.ErrorIsNil) c.Assert(len(after)-s.initialStorageInstancesCount, gc.Equals, 0) s.assertExistingStorage(c, after) } func (s *unitStorageSuite) TestAddUnitStorageWithSize(c *gc.C) { s.createStorageBlockUnit(c) size := uint64(1) cons := map[string]params.StorageConstraints{ "allecto": params.StorageConstraints{Size: &size}} ctx := s.addUnitStorage(c, cons) // Flush the context with a success. err := ctx.Flush("success", nil) c.Assert(err, gc.ErrorMatches, `.*only count can be specified.*`) // Make sure no storage instances was added after, err := s.State.AllStorageInstances() c.Assert(err, jc.ErrorIsNil) c.Assert(len(after)-s.initialStorageInstancesCount, gc.Equals, 0) s.assertExistingStorage(c, after) } func (s *unitStorageSuite) TestAddUnitStorageWithPool(c *gc.C) { s.createStorageBlockUnit(c) cons := map[string]params.StorageConstraints{ "allecto": params.StorageConstraints{Pool: "loop"}} ctx := s.addUnitStorage(c, cons) // Flush the context with a success. err := ctx.Flush("success", nil) c.Assert(err, gc.ErrorMatches, `.*only count can be specified.*`) // Make sure no storage instances was added after, err := s.State.AllStorageInstances() c.Assert(err, jc.ErrorIsNil) c.Assert(len(after)-s.initialStorageInstancesCount, gc.Equals, 0) s.assertExistingStorage(c, after) } func (s *unitStorageSuite) TestAddUnitStorageAccumulated(c *gc.C) { s.createStorageBlock2Unit(c) count := uint64(1) s.assertUnitStorageAdded(c, map[string]params.StorageConstraints{ "multi2up": params.StorageConstraints{Count: &count}}, map[string]params.StorageConstraints{ "multi1to10": params.StorageConstraints{Count: &count}}) } func (s *unitStorageSuite) TestAddUnitStorageAccumulatedSame(c *gc.C) { s.createStorageBlock2Unit(c) count := uint64(1) s.assertUnitStorageAdded(c, map[string]params.StorageConstraints{ "multi2up": params.StorageConstraints{Count: &count}}, map[string]params.StorageConstraints{ "multi2up": params.StorageConstraints{Count: &count}}) } func setupTestStorageSupport(c *gc.C, s *state.State) { stsetts := state.NewStateSettings(s) poolManager := poolmanager.New(stsetts, storage.ChainedProviderRegistry{ dummy.StorageProviders(), provider.CommonStorageProviders(), }) _, err := poolManager.Create(testPool, provider.LoopProviderType, map[string]interface{}{"it": "works"}) c.Assert(err, jc.ErrorIsNil) _, err = poolManager.Create(testPersistentPool, "modelscoped", map[string]interface{}{"persistent": true}) c.Assert(err, jc.ErrorIsNil) } func (s *unitStorageSuite) createStorageEnabledUnit(c *gc.C) { s.ch = s.AddTestingCharm(c, s.charmName) s.service = s.AddTestingServiceWithStorage(c, s.charmName, s.ch, s.initCons) s.unit = s.AddUnit(c, s.service) s.assertStorageCreated(c) s.createHookSupport(c) } func (s *unitStorageSuite) createStorageBlockUnit(c *gc.C) { s.charmName = "storage-block" s.initCons = map[string]state.StorageConstraints{ "data": makeStorageCons("block", 1024, 1), } s.createStorageEnabledUnit(c) s.assertStorageCreated(c) s.createHookSupport(c) } func (s *unitStorageSuite) createStorageBlock2Unit(c *gc.C) { s.charmName = "storage-block2" s.initCons = map[string]state.StorageConstraints{ "multi1to10": makeStorageCons("loop", 0, 3), } s.createStorageEnabledUnit(c) s.assertStorageCreated(c) s.createHookSupport(c) } func (s *unitStorageSuite) assertStorageCreated(c *gc.C) { all, err := s.State.AllStorageInstances() c.Assert(err, jc.ErrorIsNil) s.initialStorageInstancesCount = len(all) s.expectedStorageNames = set.NewStrings() for _, one := range all { s.expectedStorageNames.Add(one.StorageName()) } } func (s *unitStorageSuite) createHookSupport(c *gc.C) { password, err := utils.RandomPassword() err = s.unit.SetPassword(password) c.Assert(err, jc.ErrorIsNil) s.st = s.OpenAPIAs(c, s.unit.Tag(), password) s.uniter, err = s.st.Uniter() c.Assert(err, jc.ErrorIsNil) c.Assert(s.uniter, gc.NotNil) s.apiUnit, err = s.uniter.Unit(s.unit.Tag().(names.UnitTag)) c.Assert(err, jc.ErrorIsNil) err = s.unit.SetCharmURL(s.ch.URL()) c.Assert(err, jc.ErrorIsNil) } func makeStorageCons(pool string, size, count uint64) state.StorageConstraints { return state.StorageConstraints{Pool: pool, Size: size, Count: count} } func (s *unitStorageSuite) addUnitStorage(c *gc.C, cons ...map[string]params.StorageConstraints) *context.HookContext { // Get the context. ctx := s.getHookContext(c, s.State.ModelUUID(), -1, "", noProxies) c.Assert(ctx.UnitName(), gc.Equals, s.unit.Name()) for _, one := range cons { for storage, _ := range one { s.expectedStorageNames.Add(storage) } ctx.AddUnitStorage(one) } return ctx } func (s *unitStorageSuite) assertUnitStorageAdded(c *gc.C, cons ...map[string]params.StorageConstraints) { ctx := s.addUnitStorage(c, cons...) // Flush the context with a success. err := ctx.Flush("success", nil) c.Assert(err, jc.ErrorIsNil) after, err := s.State.AllStorageInstances() c.Assert(err, jc.ErrorIsNil) c.Assert(len(after)-s.initialStorageInstancesCount, gc.Equals, len(cons)) s.assertExistingStorage(c, after) } func (s *unitStorageSuite) assertExistingStorage(c *gc.C, all []state.StorageInstance) { for _, one := range all { c.Assert(s.expectedStorageNames.Contains(one.StorageName()), jc.IsTrue) } }
mjs/juju
worker/uniter/runner/context/unitStorage_test.go
GO
agpl-3.0
7,517
OC.L10N.register( "encryption", { "Missing recovery key password" : "Brakujące hasło klucza odzyskiwania", "Please repeat the recovery key password" : "Proszę powtórz nowe hasło klucza odzyskiwania", "Repeated recovery key password does not match the provided recovery key password" : "Hasła klucza odzyskiwania nie zgadzają się", "Recovery key successfully enabled" : "Klucz odzyskiwania włączony", "Could not enable recovery key. Please check your recovery key password!" : "Nie można włączyć klucza odzyskiwania. Proszę sprawdzić swoje hasło odzyskiwania!", "Recovery key successfully disabled" : "Klucz odzyskiwania wyłączony", "Could not disable recovery key. Please check your recovery key password!" : "Nie można wyłączyć klucza odzyskiwania. Proszę sprawdzić swoje hasło odzyskiwania!", "Missing parameters" : "Brakujące dane", "Please provide the old recovery password" : "Podaj stare hasło odzyskiwania", "Please provide a new recovery password" : "Podaj nowe hasło odzyskiwania", "Please repeat the new recovery password" : "Proszę powtórz nowe hasło odzyskiwania", "Password successfully changed." : "Zmiana hasła udana.", "Could not change the password. Maybe the old password was not correct." : "Nie można zmienić hasła. Może stare hasło nie było poprawne.", "Recovery Key disabled" : "Klucz odzyskiwania wyłączony", "Recovery Key enabled" : "Klucz odzyskiwania włączony", "Could not enable the recovery key, please try again or contact your administrator" : "Nie można włączyć klucza odzyskiwania. Proszę spróbować ponownie lub skontakuj sie z administratorem", "Could not update the private key password." : "Nie można zmienić hasła klucza prywatnego.", "The old password was not correct, please try again." : "Stare hasło nie było poprawne. Spróbuj jeszcze raz.", "The current log-in password was not correct, please try again." : "Obecne hasło logowania nie było poprawne. Spróbuj ponownie.", "Private key password successfully updated." : "Pomyślnie zaktualizowano hasło klucza prywatnego.", "You need to migrate your encryption keys from the old encryption (ownCloud <= 8.0) to the new one. Please run 'occ encryption:migrate' or contact your administrator" : "Musisz przenieść swoje klucze szyfrowania ze starego sposobu szyfrowania (Nextcloud <= 8,0) na nowy. Proszę uruchomić 'occ encryption:migrate' lub skontaktować się z administratorem", "Invalid private key for encryption app. Please update your private key password in your personal settings to recover access to your encrypted files." : "Nieprawidłowy klucz prywatny do szyfrowania aplikacji. Należy zaktualizować hasło klucza prywatnego w ustawieniach osobistych, aby odzyskać dostęp do zaszyfrowanych plików.", "Encryption App is enabled, but your keys are not initialized. Please log-out and log-in again." : "Aplikacja szyfrująca jest włączona, ale Twoje klucze nie są zainicjowane. Proszę się wylogować i zalogować ponownie.", "Please enable server side encryption in the admin settings in order to use the encryption module." : "Aby móc korzystać z modułu szyfrowania trzeba włączyć w panelu administratora szyfrowanie po stronie serwera. ", "Encryption app is enabled and ready" : "Szyfrowanie aplikacja jest włączone i gotowe", "Bad Signature" : "Zła sygnatura", "Missing Signature" : "Brakująca sygnatura", "one-time password for server-side-encryption" : "jednorazowe hasło do serwera szyfrowania strony", "Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you." : "Nie można odszyfrować tego pliku, prawdopodobnie jest to plik udostępniony. Poproś właściciela pliku o ponowne udostępnianie pliku Tobie.", "Can not read this file, probably this is a shared file. Please ask the file owner to reshare the file with you." : "Nie można odczytać tego pliku, prawdopodobnie plik nie jest współdzielony. Proszę zwrócić się do właściciela pliku, aby udostępnił go dla Ciebie.", "Default encryption module" : "Domyślny moduł szyfrujący", "Hey there,\n\nthe admin enabled server-side-encryption. Your files were encrypted using the password '%s'.\n\nPlease login to the web interface, go to the section 'basic encryption module' of your personal settings and update your encryption password by entering this password into the 'old log-in password' field and your current login-password.\n\n" : "Hej tam,\n\nadmin włączył szyfrowanie po stronie serwera. Twoje pliki zostały zaszyfrowane przy użyciu hasła '%s'.\n\nProszę zalogować się do interfejsu internetowego, przejdź do sekcji Nextcloud podstawowy moduł szyfrowania, następnie osobiste ustawienia i zaktualizuj hasło szyfrowania wpisując aktualny login, w polu stare hasło logowania wpisz stare hasło, a następnie aktualne hasło.\n\n", "The share will expire on %s." : "Ten zasób wygaśnie %s", "Cheers!" : "Dzięki!", "Hey there,<br><br>the admin enabled server-side-encryption. Your files were encrypted using the password <strong>%s</strong>.<br><br>Please login to the web interface, go to the section \"basic encryption module\" of your personal settings and update your encryption password by entering this password into the \"old log-in password\" field and your current login-password.<br><br>" : "Hej tam,<br><br>admin włączył szyfrowanie po stronie serwera. Twoje pliki zostały zaszyfrowane przy użyciu hasła <strong>%s</strong>.<br><br>Proszę zalogować się do interfejsu internetowego, przejdź do sekcji Nextcloud podstawowy moduł szyfrowania, następnie osobiste ustawienia i zaktualizuj hasło szyfrowania wpisując aktualny login, w polu stare hasło logowania wpisz stare hasło, a następnie aktualne hasło.<br><br>", "Encryption app is enabled but your keys are not initialized, please log-out and log-in again" : "Szyfrowanie w aplikacji jest włączone, ale klucze nie są zainicjowane. Prosimy wylogować się i ponownie zalogować się.", "Encrypt the home storage" : "Szyfrowanie przechowywanie w domu", "Enabling this option encrypts all files stored on the main storage, otherwise only files on external storage will be encrypted" : "Włączenie tej opcji spowoduje szyfrowanie wszystkich plików zapisanych na pamięci wewnętrznej. W innym wypadku szyfrowane będą tylko pliki na pamięci zewnętrznej.", "Enable recovery key" : "Włącz klucz odzyskiwania", "Disable recovery key" : "Wyłącz klucz odzyskiwania", "The recovery key is an extra encryption key that is used to encrypt files. It allows recovery of a user's files if the user forgets his or her password." : "Kluczem do odzyskiwania jest dodatkowy klucz szyfrujący, który służy do szyfrowania plików. Umożliwia on odzyskanie plików użytkownika, jeśli użytkownik zapomni swoje hasło.", "Recovery key password" : "Hasło klucza odzyskiwania", "Repeat recovery key password" : "Powtórz hasło klucza odzyskiwania", "Change recovery key password:" : "Zmień hasło klucza odzyskiwania", "Old recovery key password" : "Stare hasło klucza odzyskiwania", "New recovery key password" : "Nowe hasło klucza odzyskiwania", "Repeat new recovery key password" : "Powtórz nowe hasło klucza odzyskiwania", "Change Password" : "Zmień hasło", "Basic encryption module" : "Podstawowy moduł szyfrujący", "Your private key password no longer matches your log-in password." : "Hasło Twojego klucza prywatnego nie pasuje już do Twojego hasła logowania.", "Set your old private key password to your current log-in password:" : "Ustaw stare hasło klucza prywatnego na aktualne hasło logowania:", " If you don't remember your old password you can ask your administrator to recover your files." : "Jeśli nie pamiętasz swojego starego hasła, poproś swojego administratora, aby odzyskać pliki.", "Old log-in password" : "Stare hasło logowania", "Current log-in password" : "Bieżące hasło logowania", "Update Private Key Password" : "Aktualizacja hasła klucza prywatnego", "Enable password recovery:" : "Włącz hasło odzyskiwania:", "Enabling this option will allow you to reobtain access to your encrypted files in case of password loss" : "Włączenie tej opcji umożliwia otrzymać dostęp do zaszyfrowanych plików w przypadku utraty hasła", "Enabled" : "Włączone", "Disabled" : "Wyłączone" }, "nplurals=4; plural=(n==1 ? 0 : (n%10>=2 && n%10<=4) && (n%100<12 || n%100>14) ? 1 : n!=1 && (n%10>=0 && n%10<=1) || (n%10>=5 && n%10<=9) || (n%100>=12 && n%100<=14) ? 2 : 3);");
michaelletzgus/nextcloud-server
apps/encryption/l10n/pl.js
JavaScript
agpl-3.0
8,768
import { Ability } from "./ability"; import { search } from "./utility/pathfinding"; import { Hex } from "./utility/hex"; import * as arrayUtils from "./utility/arrayUtils"; import { Drop } from "./drops"; import { Effect } from "./effect"; /** * Creature Class * * Creature contains all creatures properties and attacks */ export class Creature { /* Attributes * * NOTE : attributes and variables starting with $ are jquery element * and jquery function can be called dirrectly from them. * * // Jquery attributes * $display : Creature representation * $effects : Effects container (inside $display) * * // Normal attributes * x : Integer : Hex coordinates * y : Integer : Hex coordinates * pos : Object : Pos object for hex comparison {x,y} * * name : String : Creature name * id : Integer : Creature Id incrementing for each creature starting to 1 * size : Integer : Creature size in hexes (1,2 or 3) * type : Integer : Type of the creature stocked in the database * team : Integer : Owner's ID (0,1,2 or 3) * player : Player : Player object shortcut * hexagons : Array : Array containing the hexes where the creature is * * dead : Boolean : True if dead * stats : Object : Object containing stats of the creature * statsAlt : Object : Object containing the alteration value for each stat //todo * abilities : Array : Array containing the 4 abilities * remainingMove : Integer : Remaining moves allowed untill the end of turn * */ /* Constructor(obj) * * obj : Object : Object containing all creature stats * */ constructor(obj, game) { // Engine this.game = game; this.name = obj.name; this.id = game.creatureIdCounter++; this.x = obj.x - 0; this.y = obj.y - 0; this.pos = { x: this.x, y: this.y }; this.size = obj.size - 0; this.type = obj.type; this.level = obj.level - 0; this.realm = obj.realm; this.animation = obj.animation; this.display = obj.display; this.drop = obj.drop; this._movementType = "normal"; if (obj.movementType) { this._movementType = obj.movementType; } this.hexagons = []; // Game this.team = obj.team; // = playerID (0,1,2,3) this.player = game.players[obj.team]; this.dead = false; this.killer = undefined; this.hasWait = false; this.travelDist = 0; this.effects = []; this.dropCollection = []; this.protectedFromFatigue = (this.type == "--") ? true : false; this.turnsActive = 0; // Statistics this.baseStats = { health: obj.stats.health - 0, regrowth: obj.stats.regrowth - 0, endurance: obj.stats.endurance - 0, energy: obj.stats.energy - 0, meditation: obj.stats.meditation - 0, initiative: obj.stats.initiative - 0, offense: obj.stats.offense - 0, defense: obj.stats.defense - 0, movement: obj.stats.movement - 0, pierce: obj.stats.pierce - 0, slash: obj.stats.slash - 0, crush: obj.stats.crush - 0, shock: obj.stats.shock - 0, burn: obj.stats.burn - 0, frost: obj.stats.frost - 0, poison: obj.stats.poison - 0, sonic: obj.stats.sonic - 0, mental: obj.stats.mental - 0, moveable: true, fatigueImmunity: false, frozen: false, // Extra energy required for abilities reqEnergy: 0 }; this.stats = $j.extend({}, this.baseStats); //Copy this.health = obj.stats.health; this.endurance = obj.stats.endurance; this.energy = obj.stats.energy; this.remainingMove = 0; //Default value recovered each turn // Abilities this.abilities = [ new Ability(this, 0, game), new Ability(this, 1, game), new Ability(this, 2, game), new Ability(this, 3, game) ]; this.updateHex(); let dp = (this.type !== "--") ? "" : (this.team === 0) ? "red" : (this.team === 1) ? "blue" : (this.team === 2) ? "orange" : "green"; // Creature Container this.grp = game.Phaser.add.group(game.grid.creatureGroup, "creatureGrp_" + this.id); this.grp.alpha = 0; // Adding sprite this.sprite = this.grp.create(0, 0, this.name + dp + '_cardboard'); this.sprite.anchor.setTo(0.5, 1); // Placing sprite this.sprite.x = ((!this.player.flipped) ? this.display["offset-x"] : 90 * this.size - this.sprite.texture.width - this.display["offset-x"]) + this.sprite.texture.width / 2; this.sprite.y = this.display["offset-y"] + this.sprite.texture.height; // Placing Group this.grp.x = this.hexagons[this.size - 1].displayPos.x; this.grp.y = this.hexagons[this.size - 1].displayPos.y; this.facePlayerDefault(); // Hint Group this.hintGrp = game.Phaser.add.group(this.grp, "creatureHintGrp_" + this.id); this.hintGrp.x = 45 * this.size; this.hintGrp.y = -this.sprite.texture.height + 5; // Health indicator this.healthIndicatorGroup = game.Phaser.add.group(this.grp, "creatureHealthGrp_" + this.id); // Adding background sprite this.healthIndicatorSprite = this.healthIndicatorGroup.create( this.player.flipped ? 19 : 19 + 90 * (this.size - 1), 49, "p" + this.team + '_health'); // Add text this.healthIndicatorText = game.Phaser.add.text( this.player.flipped ? 45 : 45 + 90 * (this.size - 1), 63, this.health, { font: "bold 15pt Play", fill: "#fff", align: "center", stroke: "#000", strokeThickness: 6 }); this.healthIndicatorText.anchor.setTo(0.5, 0.5); this.healthIndicatorGroup.add(this.healthIndicatorText); // Hide it this.healthIndicatorGroup.alpha = 0; // State variable for displaying endurance/fatigue text this.fatigueText = ""; // Adding Himself to creature arrays and queue game.creatures[this.id] = this; this.delayable = true; this.delayed = false; this.materializationSickness = (this.type == "--") ? false : true; this.noActionPossible = false; } /* summon() * * Summon animation * */ summon() { let game = this.game; game.queue.addByInitiative(this); game.updateQueueDisplay(); game.grid.orderCreatureZ(); if (game.grid.materialize_overlay) { game.grid.materialize_overlay.alpha = 0.5; game.Phaser.add.tween(game.grid.materialize_overlay) .to({ alpha: 0 }, 500, Phaser.Easing.Linear.None) .start(); } game.Phaser.add.tween(this.grp) .to({ alpha: 1 }, 500, Phaser.Easing.Linear.None) .start(); // Reveal and position health indicator this.updateHealth(); this.healthShow(); // Trigger trap under this.hexagons.forEach((hex) => { hex.activateTrap(game.triggers.onStepIn, this); }); // Pickup drop this.pickupDrop(); } healthHide() { this.healthIndicatorGroup.alpha = 0; } healthShow() { this.healthIndicatorGroup.alpha = 1; } /* activate() * * Activate the creature by showing movement range and binding controls to this creature * */ activate() { this.travelDist = 0; this.oldEnergy = this.energy; this.oldHealth = this.health; this.noActionPossible = false; let game = this.game; let stats = this.stats; let varReset = function () { this.game.onReset(this); // Variables reset this.updateAlteration(); this.remainingMove = stats.movement; if (!this.materializationSickness) { // Fatigued creatures (endurance 0) should not regenerate, but fragile // ones (max endurance 0) should anyway if (!this.isFatigued()) { this.heal(stats.regrowth, true); if (stats.meditation > 0) { this.recharge(stats.meditation); } } else { if (stats.regrowth < 0) { this.heal(stats.regrowth, true); } else { this.hint("♦", 'damage'); } } } else { this.hint("♣", 'damage'); } setTimeout(() => { game.UI.energyBar.animSize(this.energy / stats.energy); game.UI.healthBar.animSize(this.health / stats.health); }, 1000); this.endurance = stats.endurance; this.abilities.forEach((ability) => { ability.reset(); }); }.bind(this); // Frozen effect if (stats.frozen) { varReset(); var interval = setInterval(() => { if (!game.turnThrottle) { clearInterval(interval); game.skipTurn({ tooltip: "Frozen" }); } }, 50); return; } if (!this.hasWait) { varReset(); // Trigger game.onStartPhase(this); } this.materializationSickness = false; var interval = setInterval(() => { if (!game.freezedInput) { clearInterval(interval); if (game.turn >= game.minimumTurnBeforeFleeing) { game.UI.btnFlee.changeState("normal"); } game.startTimer(); this.queryMove(); } }, 50); } /* deactivate(wait) * * wait : Boolean : Deactivate while waiting or not * * Preview the creature position at the given coordinates * */ deactivate(wait) { let game = this.game; this.hasWait = this.delayed = !!wait; this.stats.frozen = false; // Effects triggers if (!wait) { this.turnsActive += 1; game.onEndPhase(this); } this.delayable = false; } /* wait() * * Move the creature to the end of the queue * */ wait() { let abilityAvailable = false; if (this.delayed) { return; } // If at least one ability has not been used this.abilities.forEach((ability) => { abilityAvailable = abilityAvailable || !ability.used; }); if (this.remainingMove > 0 && abilityAvailable) { this.delay(this.game.activeCreature === this); this.deactivate(true); } } delay(excludeActiveCreature) { let game = this.game; game.queue.delay(this); this.delayable = false; this.delayed = true; this.hint("Delayed", "msg_effects"); game.updateQueueDisplay(excludeActiveCreature); } /* queryMove() * * launch move action query * */ queryMove(o) { let game = this.game; if (this.dead) { // Creatures can die during their turns from trap effects; make sure this // function doesn't do anything return; } // Once Per Damage Abilities recover game.creatures.forEach((creature) => { //For all Creature if (creature instanceof Creature) { creature.abilities.forEach((ability) => { if (game.triggers.oncePerDamageChain.test(ability.getTrigger())) { ability.setUsed(false); } }); } }); let remainingMove = this.remainingMove; // No movement range if unmoveable if (!this.stats.moveable) { remainingMove = 0; } o = $j.extend({ targeting:false, noPath: false, isAbility: false, ownCreatureHexShade: true, range: game.grid.getMovementRange( this.x, this.y, remainingMove, this.size, this.id), callback: function (hex, args) { if (hex.x == args.creature.x && hex.y == args.creature.y) { // Prevent null movement game.activeCreature.queryMove(); return; } game.gamelog.add({ action: "move", target: { x: hex.x, y: hex.y } }); args.creature.delayable = false; game.UI.btnDelay.changeState("disabled"); args.creature.moveTo(hex, { animation: args.creature.movementType() === "flying" ? "fly" : "walk", callback: function () { game.activeCreature.queryMove(); } }); } }, o); if (!o.isAbility) { if (game.UI.selectedAbility != -1) { this.hint("Canceled", 'gamehintblack'); } $j("#abilities .ability").removeClass("active"); game.UI.selectAbility(-1); game.UI.checkAbilities(); game.UI.updateQueueDisplay(); } game.grid.orderCreatureZ(); this.facePlayerDefault(); this.updateHealth(); if (this.movementType() === "flying") { o.range = game.grid.getFlyingRange( this.x, this.y, remainingMove, this.size, this.id); } let selectNormal = function (hex, args) { args.creature.tracePath(hex); }; let selectFlying = function (hex, args) { args.creature.tracePosition({ x: hex.x, y: hex.y, overlayClass: "creature moveto selected player" + args.creature.team }); }; let select = (o.noPath || this.movementType() === "flying") ? selectFlying : selectNormal; if (this.noActionPossible) { game.grid.querySelf({ fnOnConfirm: function () { game.UI.btnSkipTurn.click(); }, fnOnCancel: function () { }, confirmText: "Skip turn" }); } else { game.grid.queryHexes({ fnOnSelect: select, fnOnConfirm: o.callback, args: { creature: this, args: o.args }, // Optional args size: this.size, flipped: this.player.flipped, id: this.id, hexes:  o.range, ownCreatureHexShade: o.ownCreatureHexShade, targeting: o.targeting }); } } /* previewPosition(hex) * * hex : Hex : Position * * Preview the creature position at the given Hex * */ previewPosition(hex) { let game = this.game; game.grid.cleanOverlay("hover h_player" + this.team); if (!game.grid.hexes[hex.y][hex.x].isWalkable(this.size, this.id)) { return; // Break if not walkable } this.tracePosition({ x: hex.x, y: hex.y, overlayClass: "hover h_player" + this.team }); } /* cleanHex() * * Clean current creature hexagons * */ cleanHex() { this.hexagons.forEach((hex) => { hex.creature = undefined; }); this.hexagons = []; } /* updateHex() * * Update the current hexes containing the creature and their display * */ updateHex() { let count = this.size, i; for (i = 0; i < count; i++) { this.hexagons.push(this.game.grid.hexes[this.y][this.x - i]); } this.hexagons.forEach((hex) => { hex.creature = this; }); } /* faceHex(facefrom,faceto) * * facefrom : Hex or Creature : Hex to face from * faceto : Hex or Creature : Hex to face * * Face creature at given hex * */ faceHex(faceto, facefrom, ignoreCreaHex, attackFix) { if (!facefrom) { facefrom = (this.player.flipped) ? this.hexagons[this.size - 1] : this.hexagons[0]; } if (ignoreCreaHex && this.hexagons.indexOf(faceto) != -1 && this.hexagons.indexOf(facefrom) != -1) { this.facePlayerDefault(); return; } if (faceto instanceof Creature) { faceto = (faceto.size < 2) ? faceto.hexagons[0] : faceto.hexagons[1]; } if (faceto.x == facefrom.x && faceto.y == facefrom.y) { this.facePlayerDefault(); return; } if (attackFix && this.size > 1) { //only works on 2hex creature targeting the adjacent row if (facefrom.y % 2 === 0) { if (faceto.x - this.player.flipped == facefrom.x) { this.facePlayerDefault(); return; } } else { if (faceto.x + 1 - this.player.flipped == facefrom.x) { this.facePlayerDefault(); return; } } } if (facefrom.y % 2 === 0) { var flipped = (faceto.x <= facefrom.x); } else { var flipped = (faceto.x < facefrom.x); } if (flipped) { this.sprite.scale.setTo(-1, 1); } else { this.sprite.scale.setTo(1, 1); } this.sprite.x = ((!flipped) ? this.display["offset-x"] : 90 * this.size - this.sprite.texture.width - this.display["offset-x"]) + this.sprite.texture.width / 2; } /* facePlayerDefault() * * Face default direction * */ facePlayerDefault() { if (this.player.flipped) { this.sprite.scale.setTo(-1, 1); } else { this.sprite.scale.setTo(1, 1); } this.sprite.x = ((!this.player.flipped) ? this.display["offset-x"] : 90 * this.size - this.sprite.texture.width - this.display["offset-x"]) + this.sprite.texture.width / 2; } /* moveTo(hex,opts) * * hex : Hex : Destination Hex * opts : Object : Optional args object * * Move the creature along a calculated path to the given coordinates * */ moveTo(hex, opts) { let game = this.game, defaultOpt = { callback: function () { return true; }, callbackStepIn: function () { return true; }, animation: this.movementType() === "flying" ? "fly" : "walk", ignoreMovementPoint: false, ignorePath: false, customMovementPoint: 0, overrideSpeed: 0, turnAroundOnComplete: true }, path; opts = $j.extend(defaultOpt, opts); // Teleportation ignores moveable if (this.stats.moveable || opts.animation === "teleport") { let x = hex.x; let y = hex.y; if (opts.ignorePath || opts.animation == "fly") { path = [hex]; } else { path = this.calculatePath(x, y); } if (path.length === 0) { return; // Break if empty path } game.grid.xray(new Hex(0, 0, false, game)); // Clean Xray this.travelDist = 0; game.animations[opts.animation](this, path, opts); } else { game.log("This creature cannot be moved"); } let interval = setInterval(() => { if (!game.freezedInput) { clearInterval(interval); opts.callback(); } }, 100); } /* tracePath(hex) * * hex : Hex : Destination Hex * * Trace the path from the current possition to the given coordinates * */ tracePath(hex) { let game = this.game, x = hex.x, y = hex.y, path = this.calculatePath(x, y); // Store path in grid to be able to compare it later if (path.length === 0) { return; // Break if empty path } path.forEach((item) => { this.tracePosition({ x: item.x, y: item.y, displayClass: "adj", drawOverCreatureTiles: false }); }); // Trace path // Highlight final position var last = arrayUtils.last(path); this.tracePosition({ x: last.x, y: last.y, overlayClass: "creature moveto selected player" + this.team, drawOverCreatureTiles: false }); } tracePosition(args) { let defaultArgs = { x: this.x, y: this.y, overlayClass: "", displayClass: "", drawOverCreatureTiles: true }; args = $j.extend(defaultArgs, args); for (let i = 0; i < this.size; i++) { let canDraw = true; if(!args.drawOverCreatureTiles){ // then check to ensure this is not a creature tile for(let j = 0; j < this.hexagons.length;j++){ if(this.hexagons[j].x == args.x-i && this.hexagons[j].y == args.y){ canDraw = false; break; } } } if(canDraw){ let hex = this.game.grid.hexes[args.y][args.x - i]; this.game.grid.cleanHex(hex); hex.overlayVisualState(args.overlayClass); hex.displayVisualState(args.displayClass); } } } /* calculatePath(x,y) * * x : Integer : Destination coordinates * y : Integer : Destination coordinates * * return : Array : Array containing the path hexes * */ calculatePath(x, y) { let game = this.game; return search( game.grid.hexes[this.y][this.x], game.grid.hexes[y][x], this.size, this.id, this.game.grid ); // Calculate path } /* calcOffset(x,y) * * x : Integer : Destination coordinates * y : Integer : Destination coordinates * * return : Object : New position taking into acount the size, orientation and obstacle {x,y} * * Return the first possible position for the creature at the given coordinates * */ calcOffset(x, y) { let offset = (game.players[this.team].flipped) ? this.size - 1 : 0, mult = (game.players[this.team].flipped) ? 1 : -1, // For FLIPPED player game = this.game; for (let i = 0; i < this.size; i++) { // Try next hexagons to see if they fit if ((x + offset - i * mult >= game.grid.hexes[y].length) || (x + offset - i * mult < 0)) { continue; } if (game.grid.hexes[y][x + offset - i * mult].isWalkable(this.size, this.id)) { x += offset - i * mult; break; } } return { x: x, y: y }; } /* getInitiative() * * return : Integer : Initiative value to order the queue * */ getInitiative() { // To avoid 2 identical initiative return this.stats.initiative * 500 - this.id; } /* adjacentHexes(dist) * * dist : Integer : Distance in hexagons * * return : Array : Array of adjacent hexagons * */ adjacentHexes(dist, clockwise) { let game = this.game; // TODO Review this algo to allow distance if (!!clockwise) { let hexes = [], c; let o = (this.y % 2 === 0) ? 1 : 0; if (this.size == 1) { c = [{ y: this.y, x: this.x + 1 }, { y: this.y - 1, x: this.x + o }, { y: this.y - 1, x: this.x - 1 + o }, { y: this.y, x: this.x - 1 }, { y: this.y + 1, x: this.x - 1 + o }, { y: this.y + 1, x: this.x + o } ]; } if (this.size == 2) { c = [{ y: this.y, x: this.x + 1 }, { y: this.y - 1, x: this.x + o }, { y: this.y - 1, x: this.x - 1 + o }, { y: this.y - 1, x: this.x - 2 + o }, { y: this.y, x: this.x - 2 }, { y: this.y + 1, x: this.x - 2 + o }, { y: this.y + 1, x: this.x - 1 + o }, { y: this.y + 1, x: this.x + o } ]; } if (this.size == 3) { c = [{ y: this.y, x: this.x + 1 }, { y: this.y - 1, x: this.x + o }, { y: this.y - 1, x: this.x - 1 + o }, { y: this.y - 1, x: this.x - 2 + o }, { y: this.y - 1, x: this.x - 3 + o }, { y: this.y, x: this.x - 3 }, { y: this.y + 1, x: this.x - 3 + o }, { y: this.y + 1, x: this.x - 2 + o }, { y: this.y + 1, x: this.x - 1 + o }, { y: this.y + 1, x: this.x + o } ]; } let total = c.length; for (let i = 0; i < total; i++) { const { x, y } = c[i]; if (game.grid.hexExists(y, x)) { hexes.push(game.grid.hexes[y][x]); } } return hexes; } if (this.size > 1) { let hexes = this.hexagons[0].adjacentHex(dist); let lasthexes = this.hexagons[this.size - 1].adjacentHex(dist); hexes.forEach((hex) => { if (arrayUtils.findPos(this.hexagons, hex)) { arrayUtils.removePos(hexes, hex); } // Remove from array if own creature hex }); lasthexes.forEach((hex) => { // If node doesnt already exist in final collection and if it's not own creature hex if (!arrayUtils.findPos(hexes, hex) && !arrayUtils.findPos(this.hexagons, hex)) { hexes.push(hex); } }); return hexes; } else { return this.hexagons[0].adjacentHex(dist); } } /** * Restore energy up to the max limit * amount: amount of energy to restore */ recharge(amount) { this.energy = Math.min(this.stats.energy, this.energy + amount); } /* heal(amount) * * amount : Damage : Amount of health point to restore */ heal(amount, isRegrowth) { let game = this.game; // Cap health point amount = Math.min(amount, this.stats.health - this.health); if (this.health + amount < 1) { amount = this.health - 1; // Cap to 1hp } this.health += amount; // Health display Update this.updateHealth(isRegrowth); if (amount > 0) { if (isRegrowth) { this.hint("+" + amount + " ♥", 'healing d' + amount); } else { this.hint("+" + amount, 'healing d' + amount); } game.log("%CreatureName" + this.id + "% recovers +" + amount + " health"); } else if (amount === 0) { if (isRegrowth) { this.hint("♦", 'msg_effects'); } else { this.hint("!", 'msg_effects'); } } else { if (isRegrowth) { this.hint(amount + " ♠", 'damage d' + amount); } else { this.hint(amount, 'damage d ' + amount); } game.log("%CreatureName" + this.id + "% loses " + amount + " health"); } game.onHeal(this, amount); } /* takeDamage(damage) * * damage : Damage : Damage object * * return : Object : Contains damages dealed and if creature is killed or not */ takeDamage(damage, o) { let game = this.game; if (this.dead) { game.log("%CreatureName" + this.id + "% is already dead, aborting takeDamage call."); return; } let defaultOpt = { ignoreRetaliation: false, isFromTrap: false }; o = $j.extend(defaultOpt, o); // Determine if melee attack damage.melee = false; this.adjacentHexes(1).forEach((hex) => { if (damage.attacker == hex.creature) { damage.melee = true; } }); damage.target = this; damage.isFromTrap = o.isFromTrap; // Trigger game.onUnderAttack(this, damage); game.onAttack(damage.attacker, damage); // Calculation if (damage.status === "") { // Damages let dmg = damage.applyDamage(); let dmgAmount = dmg.total; if (!isFinite(dmgAmount)) { // Check for Damage Errors this.hint("Error", 'damage'); game.log("Oops something went wrong !"); return { damages: 0, kill: false }; } this.health -= dmgAmount; this.health = (this.health < 0) ? 0 : this.health; // Cap this.addFatigue(dmgAmount); // Display let nbrDisplayed = (dmgAmount) ? "-" + dmgAmount : 0; this.hint(nbrDisplayed, 'damage d' + dmgAmount); if (!damage.noLog) { game.log("%CreatureName" + this.id + "% is hit : " + nbrDisplayed + " health"); } // If Health is empty if (this.health <= 0) { this.die(damage.attacker); return { damages: dmg, damageObj: damage, kill: true }; // Killed } // Effects damage.effects.forEach((effect) => { this.addEffect(effect); }); // Unfreeze if taking non-zero damage if (dmgAmount > 0) { this.stats.frozen = false; } // Health display Update // Note: update health after adding effects as some effects may affect // health display this.updateHealth(); game.UI.updateFatigue(); // Trigger if (!o.ignoreRetaliation) { game.onDamage(this, damage); } return { damages: dmg, damageObj: damage, kill: false }; // Not Killed } else { if (damage.status == "Dodged") { // If dodged if (!damage.noLog) { game.log("%CreatureName" + this.id + "% dodged the attack"); } } if (damage.status == "Shielded") { // If Shielded if (!damage.noLog) { game.log("%CreatureName" + this.id + "% shielded the attack"); } } if (damage.status == "Disintegrated") { // If Disintegrated if (!damage.noLog) { game.log("%CreatureName" + this.id + "% has been disintegrated"); } this.die(damage.attacker); } // Hint this.hint(damage.status, 'damage ' + damage.status.toLowerCase()); } return { damageObj: damage, kill: false }; // Not killed } updateHealth(noAnimBar) { let game = this.game; if (this == game.activeCreature && !noAnimBar) { game.UI.healthBar.animSize(this.health / this.stats.health); } // Dark Priest plasma shield when inactive if (this.type == "--") { if (this.hasCreaturePlayerGotPlasma() && this !== game.activeCreature) { this.displayPlasmaShield(); } else { this.displayHealthStats() } } else { this.displayHealthStats(); } } displayHealthStats() { if (this.stats.frozen) { this.healthIndicatorSprite.loadTexture("p" + this.team + "_frozen"); } else { this.healthIndicatorSprite.loadTexture("p" + this.team + "_health"); } this.healthIndicatorText.setText(this.health); } displayPlasmaShield() { this.healthIndicatorSprite.loadTexture("p" + this.team + "_plasma"); this.healthIndicatorText.setText(this.player.plasma); } hasCreaturePlayerGotPlasma() { return this.player.plasma > 0; } addFatigue(dmgAmount) { if (!this.stats.fatigueImmunity) { this.endurance -= dmgAmount; this.endurance = this.endurance < 0 ? 0 : this.endurance; // Cap } this.game.UI.updateFatigue(); } /* addEffect(effect) * * effect : Effect : Effect object * */ addEffect(effect, specialString, specialHint) { let game = this.game; if (!effect.stackable && this.findEffect(effect.name).length !== 0) { //G.log(this.player.name+"'s "+this.name+" is already affected by "+effect.name); return false; } effect.target = this; this.effects.push(effect); game.onEffectAttach(this, effect); this.updateAlteration(); if (effect.name !== "") { if (specialHint || effect.specialHint) { this.hint(specialHint, 'msg_effects'); } else { this.hint(effect.name, 'msg_effects'); } if (specialString) { game.log(specialString); } else { game.log("%CreatureName" + this.id + "% is affected by " + effect.name); } } } /** * Add effect, but if the effect is already attached, replace it with the new * effect. * Note that for stackable effects, this is the same as addEffect() * * effect - the effect to add */ replaceEffect(effect) { if (!effect.stackable && this.findEffect(effect.name).length !== 0) { this.removeEffect(effect.name); } this.addEffect(effect); } /** * Remove an effect by name * * name - name of effect */ removeEffect(name) { let totalEffects = this.effects.length; for (var i = 0; i < totalEffects; i++) { if (this.effects[i].name === name) { this.effects.splice(i, 1); break; } } } hint(text, cssClass) { let game = this.game, tooltipSpeed = 250, tooltipDisplaySpeed = 500, tooltipTransition = Phaser.Easing.Linear.None; let hintColor = { confirm: { fill: "#ffffff", stroke: "#000000" }, gamehintblack: { fill: "#ffffff", stroke: "#000000" }, healing: { fill: "#00ff00" }, msg_effects: { fill: "#ffff00" } }; let style = $j.extend({ font: "bold 20pt Play", fill: "#ff0000", align: "center", stroke: "#000000", strokeThickness: 2 }, hintColor[cssClass]); // Remove constant element this.hintGrp.forEach((grpHintElem) => { if (grpHintElem.cssClass == 'confirm') { grpHintElem.cssClass = "confirm_deleted"; grpHintElem.tweenAlpha = game.Phaser.add.tween(grpHintElem).to({ alpha: 0 }, tooltipSpeed, tooltipTransition).start(); grpHintElem.tweenAlpha.onComplete.add(function () { this.destroy(); }, grpHintElem); } }, this, true); var hint = game.Phaser.add.text(0, 50, text, style); hint.anchor.setTo(0.5, 0.5); hint.alpha = 0; hint.cssClass = cssClass; if (cssClass == 'confirm') { hint.tweenAlpha = game.Phaser.add.tween(hint) .to({ alpha: 1 }, tooltipSpeed, tooltipTransition) .start(); } else { hint.tweenAlpha = game.Phaser.add.tween(hint) .to({ alpha: 1 }, tooltipSpeed, tooltipTransition) .to({ alpha: 1 }, tooltipDisplaySpeed, tooltipTransition) .to({ alpha: 0 }, tooltipSpeed, tooltipTransition).start(); hint.tweenAlpha.onComplete.add(function () { this.destroy(); }, hint); } this.hintGrp.add(hint); // Stacking this.hintGrp.forEach((grpHintElem) => { let index = this.hintGrp.total - this.hintGrp.getIndex(grpHintElem) - 1; let offset = -50 * index; if (grpHintElem.tweenPos) { grpHintElem.tweenPos.stop(); } grpHintElem.tweenPos = game.Phaser.add.tween(grpHintElem).to({ y: offset }, tooltipSpeed, tooltipTransition).start(); }, this, true); } /* updateAlteration() * * Update the stats taking into account the effects' alteration * */ updateAlteration() { this.stats = $j.extend({}, this.baseStats); // Copy let buffDebuffArray = this.effects; buffDebuffArray.forEach((buff) => { $j.each(buff.alterations, (key, value) => { if (typeof value == "string") { // Multiplication Buff if (value.match(/\*/)) { this.stats[key] = eval(this.stats[key] + value); } // Division Debuff if (value.match(/\//)) { this.stats[key] = eval(this.stats[key] + value); } } // Usual Buff/Debuff if ((typeof value) == "number") { this.stats[key] += value; } // Boolean Buff/Debuff if ((typeof value) == "boolean") { this.stats[key] = value; } }); }); this.stats.endurance = Math.max(this.stats.endurance, 0); this.endurance = Math.min(this.endurance, this.stats.endurance); this.energy = Math.min(this.energy, this.stats.energy); this.remainingMove = Math.min(this.remainingMove, this.stats.movement); } /* die() * * kill animation. remove creature from queue and from hexes * * killer : Creature : Killer of this creature * */ die(killer) { let game = this.game; game.log("%CreatureName" + this.id + "% is dead"); this.dead = true; // Triggers game.onCreatureDeath(this); this.killer = killer.player; let isDeny = (this.killer.flipped == this.player.flipped); // Drop item if (game.unitDrops == 1 && this.drop) { var offsetX = (this.player.flipped) ? this.x - this.size + 1 : this.x; new Drop(this.drop.name, this.drop.health, this.drop.energy, offsetX, this.y, game); } if (!game.firstKill && !isDeny) { // First Kill this.killer.score.push({ type: "firstKill" }); game.firstKill = true; } if (this.type == "--") { // If Dark Priest if (isDeny) { // TEAM KILL (DENY) this.killer.score.push({ type: "deny", creature: this }); } else { // Humiliation this.killer.score.push({ type: "humiliation", player: this.team }); } } if (!this.undead) { // Only if not undead if (isDeny) { // TEAM KILL (DENY) this.killer.score.push({ type: "deny", creature: this }); } else { // KILL this.killer.score.push({ type: "kill", creature: this }); } } if (this.player.isAnnihilated()) { // Remove humiliation as annihilation is an upgrade let total = this.killer.score.length; for (let i = 0; i < total; i++) { var s = this.killer.score[i]; if (s.type == "humiliation") { if (s.player == this.team) { this.killer.score.splice(i, 1); } break; } } // ANNIHILATION this.killer.score.push({ type: "annihilation", player: this.team }); } if (this.type == "--") { this.player.deactivate(); // Here because of score calculation } // Kill animation var tweenSprite = game.Phaser.add.tween(this.sprite).to({ alpha: 0 }, 500, Phaser.Easing.Linear.None).start(); var tweenHealth = game.Phaser.add.tween(this.healthIndicatorGroup).to({ alpha: 0 }, 500, Phaser.Easing.Linear.None).start(); tweenSprite.onComplete.add(() => { this.sprite.destroy(); }); tweenHealth.onComplete.add(() => { this.healthIndicatorGroup.destroy(); }); this.cleanHex(); game.queue.remove(this); game.updateQueueDisplay(); game.grid.updateDisplay(); if (game.activeCreature === this) { game.nextCreature(); return; } //End turn if current active creature die // As hex occupation changes, path must be recalculated for the current creature not the dying one game.activeCreature.queryMove(); // Queue cleaning game.UI.updateActivebox(); game.UI.updateQueueDisplay(); // Just in case } isFatigued() { return this.endurance === 0 && !this.isFragile(); } isFragile() { return this.stats.endurance === 0; } /* getHexMap() * * shortcut convenience function to grid.getHexMap */ getHexMap(map, invertFlipped) { var x = (this.player.flipped ? !invertFlipped : invertFlipped) ? this.x + 1 - this.size : this.x; return this.game.grid.getHexMap(x, this.y - map.origin[1], 0 - map.origin[0], (this.player.flipped ? !invertFlipped : invertFlipped), map); } getBuffDebuff(stat) { let buffDebuffArray = this.effects.concat(this.dropCollection), buff = 0, debuff = 0, buffObjs = { effects: [], drops: [] }; let addToBuffObjs = function (obj) { if (obj instanceof Effect) { buffObjs.effects.push(obj); } else if (obj instanceof Drop) { buffObjs.drops.push(obj); } }; buffDebuffArray.forEach((buff) => { let o = buff; $j.each(buff.alterations, (key, value) => { if (typeof value == "string") { if (key === stat || stat === undefined) { // Multiplication Buff if (value.match(/\*/)) { addToBuffObjs(o); let base = this.stats[key]; let result = eval(this.stats[key] + value); if (result > base) { buff += result - base; } else { debuff += result - base; } } // Division Debuff if (value.match(/\//)) { addToBuffObjs(o); let base = this.stats[key]; let result = eval(this.stats[key] + value); if (result > base) { buff += result - base; } else { debuff += result - base; } } } } // Usual Buff/Debuff if ((typeof value) == "number") { if (key === stat || stat === undefined) { addToBuffObjs(o); if (value > 0) { buff += value; } else { debuff += value; } } } }); }); return { buff: buff, debuff: debuff, objs: buffObjs }; } findEffect(name) { let ret = []; this.effects.forEach((effect) => { if (effect.name == name) { ret.push(effect); } }); return ret; } // Make units transparent xray(enable) { let game = this.game; if (enable) { game.Phaser.add.tween(this.grp) .to({ alpha: 0.5 }, 250, Phaser.Easing.Linear.None) .start(); } else { game.Phaser.add.tween(this.grp) .to({ alpha: 1 }, 250, Phaser.Easing.Linear.None) .start(); } } pickupDrop() { this.hexagons.forEach((hex) => { hex.pickupDrop(this); }); } /** * Get movement type for this creature * @return {string} "normal", "hover", or "flying" */ movementType() { let totalAbilities = this.abilities.length; // If the creature has an ability that modifies movement type, use that, // otherwise use the creature's base movement type for (let i = 0; i < totalAbilities; i++) { if ('movementType' in this.abilities[i]) { return this.abilities[i].movementType(); } } return this._movementType; } }
ShaneWalsh/AncientBeast
src/creature.js
JavaScript
agpl-3.0
37,616
<!DOCTYPE html> <html lang="en" > <head> <title>40123226 - CDW11 網頁 (虎尾科大MDE)</title> <!-- Using the latest rendering mode for IE --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style type="text/css"> /*some stuff for output/input prompts*/ div.cell{border:1px solid transparent;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;display:flex;flex-direction:column;align-items:stretch}div.cell.selected{border-radius:4px;border:thin #ababab solid} div.cell.edit_mode{border-radius:4px;border:thin #008000 solid} div.cell{width:100%;padding:5px 5px 5px 0;margin:0;outline:none} div.prompt{min-width:11ex;padding:.4em;margin:0;font-family:monospace;text-align:right;line-height:1.21429em} @media (max-width:480px){div.prompt{text-align:left}}div.inner_cell{display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;display:flex;flex-direction:column;align-items:stretch;-webkit-box-flex:1;-moz-box-flex:1;box-flex:1;flex:1} div.input_area{border:1px solid #cfcfcf;border-radius:4px;background:#f7f7f7;line-height:1.21429em} div.prompt:empty{padding-top:0;padding-bottom:0} div.input{page-break-inside:avoid;display:-webkit-box;-webkit-box-orient:horizontal;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:horizontal;-moz-box-align:stretch;display:box;box-orient:horizontal;box-align:stretch;} div.inner_cell{width:90%;} div.input_area{border:1px solid #cfcfcf;border-radius:4px;background:#f7f7f7;} div.input_prompt{color:navy;border-top:1px solid transparent;} div.output_wrapper{margin-top:5px;position:relative;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;width:100%;} div.output_scroll{height:24em;width:100%;overflow:auto;border-radius:4px;-webkit-box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);-moz-box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);} div.output_collapsed{margin:0px;padding:0px;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;width:100%;} div.out_prompt_overlay{height:100%;padding:0px 0.4em;position:absolute;border-radius:4px;} div.out_prompt_overlay:hover{-webkit-box-shadow:inset 0 0 1px #000000;-moz-box-shadow:inset 0 0 1px #000000;box-shadow:inset 0 0 1px #000000;background:rgba(240, 240, 240, 0.5);} div.output_prompt{color:darkred;} a.anchor-link:link{text-decoration:none;padding:0px 20px;visibility:hidden;} h1:hover .anchor-link,h2:hover .anchor-link,h3:hover .anchor-link,h4:hover .anchor-link,h5:hover .anchor-link,h6:hover .anchor-link{visibility:visible;} /* end stuff for output/input prompts*/ .highlight-ipynb .hll { background-color: #ffffcc } .highlight-ipynb { background: #f8f8f8; } .highlight-ipynb .c { color: #408080; font-style: italic } /* Comment */ .highlight-ipynb .err { border: 1px solid #FF0000 } /* Error */ .highlight-ipynb .k { color: #008000; font-weight: bold } /* Keyword */ .highlight-ipynb .o { color: #666666 } /* Operator */ .highlight-ipynb .cm { color: #408080; font-style: italic } /* Comment.Multiline */ .highlight-ipynb .cp { color: #BC7A00 } /* Comment.Preproc */ .highlight-ipynb .c1 { color: #408080; font-style: italic } /* Comment.Single */ .highlight-ipynb .cs { color: #408080; font-style: italic } /* Comment.Special */ .highlight-ipynb .gd { color: #A00000 } /* Generic.Deleted */ .highlight-ipynb .ge { font-style: italic } /* Generic.Emph */ .highlight-ipynb .gr { color: #FF0000 } /* Generic.Error */ .highlight-ipynb .gh { color: #000080; font-weight: bold } /* Generic.Heading */ .highlight-ipynb .gi { color: #00A000 } /* Generic.Inserted */ .highlight-ipynb .go { color: #888888 } /* Generic.Output */ .highlight-ipynb .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ .highlight-ipynb .gs { font-weight: bold } /* Generic.Strong */ .highlight-ipynb .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ .highlight-ipynb .gt { color: #0044DD } /* Generic.Traceback */ .highlight-ipynb .kc { color: #008000; font-weight: bold } /* Keyword.Constant */ .highlight-ipynb .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */ .highlight-ipynb .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */ .highlight-ipynb .kp { color: #008000 } /* Keyword.Pseudo */ .highlight-ipynb .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */ .highlight-ipynb .kt { color: #B00040 } /* Keyword.Type */ .highlight-ipynb .m { color: #666666 } /* Literal.Number */ .highlight-ipynb .s { color: #BA2121 } /* Literal.String */ .highlight-ipynb .na { color: #7D9029 } /* Name.Attribute */ .highlight-ipynb .nb { color: #008000 } /* Name.Builtin */ .highlight-ipynb .nc { color: #0000FF; font-weight: bold } /* Name.Class */ .highlight-ipynb .no { color: #880000 } /* Name.Constant */ .highlight-ipynb .nd { color: #AA22FF } /* Name.Decorator */ .highlight-ipynb .ni { color: #999999; font-weight: bold } /* Name.Entity */ .highlight-ipynb .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ .highlight-ipynb .nf { color: #0000FF } /* Name.Function */ .highlight-ipynb .nl { color: #A0A000 } /* Name.Label */ .highlight-ipynb .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ .highlight-ipynb .nt { color: #008000; font-weight: bold } /* Name.Tag */ .highlight-ipynb .nv { color: #19177C } /* Name.Variable */ .highlight-ipynb .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ .highlight-ipynb .w { color: #bbbbbb } /* Text.Whitespace */ .highlight-ipynb .mf { color: #666666 } /* Literal.Number.Float */ .highlight-ipynb .mh { color: #666666 } /* Literal.Number.Hex */ .highlight-ipynb .mi { color: #666666 } /* Literal.Number.Integer */ .highlight-ipynb .mo { color: #666666 } /* Literal.Number.Oct */ .highlight-ipynb .sb { color: #BA2121 } /* Literal.String.Backtick */ .highlight-ipynb .sc { color: #BA2121 } /* Literal.String.Char */ .highlight-ipynb .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */ .highlight-ipynb .s2 { color: #BA2121 } /* Literal.String.Double */ .highlight-ipynb .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ .highlight-ipynb .sh { color: #BA2121 } /* Literal.String.Heredoc */ .highlight-ipynb .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ .highlight-ipynb .sx { color: #008000 } /* Literal.String.Other */ .highlight-ipynb .sr { color: #BB6688 } /* Literal.String.Regex */ .highlight-ipynb .s1 { color: #BA2121 } /* Literal.String.Single */ .highlight-ipynb .ss { color: #19177C } /* Literal.String.Symbol */ .highlight-ipynb .bp { color: #008000 } /* Name.Builtin.Pseudo */ .highlight-ipynb .vc { color: #19177C } /* Name.Variable.Class */ .highlight-ipynb .vg { color: #19177C } /* Name.Variable.Global */ .highlight-ipynb .vi { color: #19177C } /* Name.Variable.Instance */ .highlight-ipynb .il { color: #666666 } /* Literal.Number.Integer.Long */ </style> <style type="text/css"> /* Overrides of notebook CSS for static HTML export */ div.entry-content { overflow: visible; padding: 8px; } .input_area { padding: 0.2em; } a.heading-anchor { white-space: normal; } .rendered_html code { font-size: .8em; } pre.ipynb { color: black; background: #f7f7f7; border: none; box-shadow: none; margin-bottom: 0; padding: 0; margin: 0px; font-size: 13px; } /* remove the prompt div from text cells */ div.text_cell .prompt { display: none; } /* remove horizontal padding from text cells, */ /* so it aligns with outer body text */ div.text_cell_render { padding: 0.5em 0em; } img.anim_icon{padding:0; border:0; vertical-align:middle; -webkit-box-shadow:none; -box-shadow:none} </style> <script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML" type="text/javascript"></script> <script type="text/javascript"> init_mathjax = function() { if (window.MathJax) { // MathJax loaded MathJax.Hub.Config({ tex2jax: { inlineMath: [ ['$','$'], ["\\(","\\)"] ], displayMath: [ ['$$','$$'], ["\\[","\\]"] ] }, displayAlign: 'left', // Change this to 'center' to center equations. "HTML-CSS": { styles: {'.MathJax_Display': {"margin": 0}} } }); MathJax.Hub.Queue(["Typeset",MathJax.Hub]); } } init_mathjax(); </script> <meta name="author" content="kmol" /> <meta name="keywords" content="40123226" /> <!-- Open Graph tags --> <meta property="og:site_name" content="CDW11 網頁 (虎尾科大MDE)" /> <meta property="og:type" content="website"/> <meta property="og:title" content="CDW11 網頁 (虎尾科大MDE)"/> <meta property="og:url" content="http://cdw11-40323200.rhcloud.com/static/blog"/> <meta property="og:description" content="CDW11 網頁 (虎尾科大MDE)"/> <!-- Bootstrap --> <link rel="stylesheet" href="http://cdw11-40323200.rhcloud.com/static/blog/theme/css/bootstrap.united.min.css" type="text/css"/> <link href="http://cdw11-40323200.rhcloud.com/static/blog/theme/css/font-awesome.min.css" rel="stylesheet"> <link href="http://cdw11-40323200.rhcloud.com/static/blog/theme/css/pygments/monokai.css" rel="stylesheet"> <link href="http://cdw11-40323200.rhcloud.com/static/blog/theme/tipuesearch/tipuesearch.css" rel="stylesheet"> <link rel="stylesheet" href="http://cdw11-40323200.rhcloud.com/static/blog/theme/css/style.css" type="text/css"/> <link href="http://cdw11-40323200.rhcloud.com/static/blog/feeds/all.atom.xml" type="application/atom+xml" rel="alternate" title="CDW11 網頁 (虎尾科大MDE) ATOM Feed"/> <script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shCore.js"></script> <script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushJScript.js"></script> <script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushJava.js"></script> <script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushPython.js"></script> <script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushSql.js"></script> <script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushXml.js"></script> <script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushPhp.js"></script> <script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushCpp.js"></script> <script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushCss.js"></script> <script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushCSharp.js"></script> <script type='text/javascript'> (function(){ var corecss = document.createElement('link'); var themecss = document.createElement('link'); var corecssurl = "http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/css/shCore.css"; if ( corecss.setAttribute ) { corecss.setAttribute( "rel", "stylesheet" ); corecss.setAttribute( "type", "text/css" ); corecss.setAttribute( "href", corecssurl ); } else { corecss.rel = "stylesheet"; corecss.href = corecssurl; } document.getElementsByTagName("head")[0].insertBefore( corecss, document.getElementById("syntaxhighlighteranchor") ); var themecssurl = "http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/css/shThemeDefault.css?ver=3.0.9b"; if ( themecss.setAttribute ) { themecss.setAttribute( "rel", "stylesheet" ); themecss.setAttribute( "type", "text/css" ); themecss.setAttribute( "href", themecssurl ); } else { themecss.rel = "stylesheet"; themecss.href = themecssurl; } //document.getElementById("syntaxhighlighteranchor").appendChild(themecss); document.getElementsByTagName("head")[0].insertBefore( themecss, document.getElementById("syntaxhighlighteranchor") ); })(); SyntaxHighlighter.config.strings.expandSource = '+ expand source'; SyntaxHighlighter.config.strings.help = '?'; SyntaxHighlighter.config.strings.alert = 'SyntaxHighlighter\n\n'; SyntaxHighlighter.config.strings.noBrush = 'Can\'t find brush for: '; SyntaxHighlighter.config.strings.brushNotHtmlScript = 'Brush wasn\'t configured for html-script option: '; SyntaxHighlighter.defaults['pad-line-numbers'] = false; SyntaxHighlighter.defaults['toolbar'] = false; SyntaxHighlighter.all(); </script> </head> <body> <div class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="http://cdw11-40323200.rhcloud.com/static/blog/" class="navbar-brand"> CDW11 網頁 (虎尾科大MDE) </a> </div> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav"> <li > <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag1.html">Ag1</a> </li> <li > <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag10.html">Ag10</a> </li> <li > <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag100.html">Ag100</a> </li> <li > <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag4.html">Ag4</a> </li> <li > <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag7.html">Ag7</a> </li> <li > <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag8.html">Ag8</a> </li> <li > <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg1.html">Bg1</a> </li> <li > <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg10.html">Bg10</a> </li> <li > <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg11.html">Bg11</a> </li> <li > <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg2.html">Bg2</a> </li> <li > <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg3.html">Bg3</a> </li> <li > <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg4.html">Bg4</a> </li> <li > <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg5.html">Bg5</a> </li> <li > <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg8.html">Bg8</a> </li> <li > <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg9.html">Bg9</a> </li> <li > <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/g3.html">G3</a> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li><span> <form class="navbar-search" action="http://cdw11-40323200.rhcloud.com/static/blog/search.html"> <input type="text" class="search-query" placeholder="Search" name="q" id="tipue_search_input" required> </form></span> </li> <li><a href="http://cdw11-40323200.rhcloud.com/static/blog/archives.html"><i class="fa fa-th-list"></i><span class="icon-label">Archives</span></a></li> </ul> </div> <!-- /.navbar-collapse --> </div> </div> <!-- /.navbar --> <!-- Banner --> <!-- End Banner --> <div class="container"> <div class="row"> <div class="col-sm-9"> <article> <h2><a href="http://cdw11-40323200.rhcloud.com/static/blog/40123226-cdw11-bao-gao.html">40123226 cdw11 報告</a></h2> <div class="summary"><p>啟動 cdw11 協同專案</p> <a class="btn btn-default btn-xs" href="http://cdw11-40323200.rhcloud.com/static/blog/40123226-cdw11-bao-gao.html">more ...</a> </div> </article> <hr/> </div> <div class="col-sm-3" id="sidebar"> <aside> <section class="well well-sm"> <ul class="list-group list-group-flush"> <li class="list-group-item"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Recent Posts</span></h4> <ul class="list-group" id="recentposts"> <li class="list-group-item"> <a href="http://cdw11-40323200.rhcloud.com/static/blog/40123226-cdw11-bao-gao.html"> 40123226 cdw11 報告 </a> </li> </ul> </li> <li class="list-group-item"><a href="http://cdw11-40323200.rhcloud.com/static/blog/categories.html"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Categories</span></h4></a> <ul class="list-group" id="categories"> <li class="list-group-item"> <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag1.html"> <i class="fa fa-folder-open fa-lg"></i> ag1 </a> </li> <li class="list-group-item"> <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag10.html"> <i class="fa fa-folder-open fa-lg"></i> ag10 </a> </li> <li class="list-group-item"> <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag100.html"> <i class="fa fa-folder-open fa-lg"></i> ag100 </a> </li> <li class="list-group-item"> <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag4.html"> <i class="fa fa-folder-open fa-lg"></i> ag4 </a> </li> <li class="list-group-item"> <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag7.html"> <i class="fa fa-folder-open fa-lg"></i> ag7 </a> </li> <li class="list-group-item"> <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag8.html"> <i class="fa fa-folder-open fa-lg"></i> ag8 </a> </li> <li class="list-group-item"> <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg1.html"> <i class="fa fa-folder-open fa-lg"></i> bg1 </a> </li> <li class="list-group-item"> <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg10.html"> <i class="fa fa-folder-open fa-lg"></i> bg10 </a> </li> <li class="list-group-item"> <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg11.html"> <i class="fa fa-folder-open fa-lg"></i> bg11 </a> </li> <li class="list-group-item"> <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg2.html"> <i class="fa fa-folder-open fa-lg"></i> bg2 </a> </li> <li class="list-group-item"> <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg3.html"> <i class="fa fa-folder-open fa-lg"></i> bg3 </a> </li> <li class="list-group-item"> <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg4.html"> <i class="fa fa-folder-open fa-lg"></i> bg4 </a> </li> <li class="list-group-item"> <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg5.html"> <i class="fa fa-folder-open fa-lg"></i> bg5 </a> </li> <li class="list-group-item"> <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg8.html"> <i class="fa fa-folder-open fa-lg"></i> bg8 </a> </li> <li class="list-group-item"> <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg9.html"> <i class="fa fa-folder-open fa-lg"></i> bg9 </a> </li> <li class="list-group-item"> <a href="http://cdw11-40323200.rhcloud.com/static/blog/category/g3.html"> <i class="fa fa-folder-open fa-lg"></i> g3 </a> </li> </ul> </li> <li class="list-group-item"><a href="http://cdw11-40323200.rhcloud.com/static/blog/tags.html"><h4><i class="fa fa-tags fa-lg"></i><span class="icon-label">Tags</span></h4></a> <ul class="list-group list-inline tagcloud" id="tags"> </ul> </li> <li class="list-group-item"><h4><i class="fa fa-external-link-square fa-lg"></i><span class="icon-label">Links</span></h4> <ul class="list-group" id="links"> <li class="list-group-item"> <a href="http://getpelican.com/" target="_blank"> Pelican </a> </li> <li class="list-group-item"> <a href="https://github.com/DandyDev/pelican-bootstrap3/" target="_blank"> pelican-bootstrap3 </a> </li> <li class="list-group-item"> <a href="https://github.com/getpelican/pelican-plugins" target="_blank"> pelican-plugins </a> </li> <li class="list-group-item"> <a href="https://github.com/Tipue/Tipue-Search" target="_blank"> Tipue search </a> </li> </ul> </li> </ul> </section> </aside> </div> </div> </div> <footer> <div class="container"> <hr> <div class="row"> <div class="col-xs-10">&copy; 2016 kmol &middot; Powered by <a href="https://github.com/DandyDev/pelican-bootstrap3" target="_blank">pelican-bootstrap3</a>, <a href="http://docs.getpelican.com/" target="_blank">Pelican</a>, <a href="http://getbootstrap.com" target="_blank">Bootstrap</a> </div> <div class="col-xs-2"><p class="pull-right"><i class="fa fa-arrow-up"></i> <a href="#">Back to top</a></p></div> </div> </div> </footer> <script src="http://cdw11-40323200.rhcloud.com/static/blog/theme/js/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="http://cdw11-40323200.rhcloud.com/static/blog/theme/js/bootstrap.min.js"></script> <!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) --> <script src="http://cdw11-40323200.rhcloud.com/static/blog/theme/js/respond.min.js"></script> <!-- Disqus --> <script type="text/javascript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = 'cadlabmanual'; // required: replace example with your forum shortname /* * * DON'T EDIT BELOW THIS LINE * * */ (function () { var s = document.createElement('script'); s.async = true; s.type = 'text/javascript'; s.src = '//' + disqus_shortname + '.disqus.com/count.js'; (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s); }()); </script> <!-- End Disqus Code --> </body> </html>
tsrnnash/bg8-cdw11
static/blog/tag/40123226.html
HTML
agpl-3.0
26,219
class GroupSerializer < ActiveModel::Serializer embed :ids, include: true attributes :id, :organisation_id, :cohort_id, :key, :name, :created_at, :description, :members_can_add_members, :members_can_create_subgroups, :members_can_start_discussions, :members_can_edit_discussions, :members_can_edit_comments, :members_can_raise_proposals, :members_can_vote, :memberships_count, :members_count, :visible_to, :membership_granted_upon, :discussion_privacy_options, :logo_url_medium, :cover_url_desktop, :has_discussions, :has_multiple_admins has_one :parent, serializer: GroupSerializer, root: 'groups' def logo_url_medium object.logo.url(:medium) end def include_logo_url_medium? object.logo.present? end def cover_url_desktop object.cover_photo.url(:desktop) end def include_cover_url_desktop? object.cover_photo.present? end def members_can_raise_proposals object.members_can_raise_motions end def has_discussions object.discussions_count > 0 end def has_multiple_admins object.admins.count > 1 end end
kimihito/loomio
app/serializers/group_serializer.rb
Ruby
agpl-3.0
1,358
/* sb0t ares chat server Copyright (C) 2017 AresChat This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; namespace core.Udp { class UdpNode { public IPAddress IP { get; set; } public ushort Port { get; set; } public int Ack { get; set; } public int Try { get; set; } public ulong LastConnect { get; set; } public ulong LastSentIPS { get; set; } public EndPoint EndPoint { get { return new IPEndPoint(this.IP, this.Port); } } } }
AresChat/sb0t
core/Udp/UdpNode.cs
C#
agpl-3.0
1,310
#pragma once #include <memory> #include "FullBlock.h" #include "BlockEntity.h" class BlockSource; class BlockPos; class BlockSourceListener { public: virtual ~BlockSourceListener(); virtual void onSourceCreated(BlockSource &); virtual void onSourceDestroyed(BlockSource &); virtual void onBlocksDirty(BlockSource &, int, int, int, int, int, int); virtual void onAreaChanged(BlockSource &, BlockPos const &, BlockPos const &); virtual void onBlockChanged(BlockSource &, BlockPos const &, FullBlock, FullBlock, int); virtual void onBrightnessChanged(BlockSource &, BlockPos const &); virtual void onBlockEntityChanged(BlockSource &, BlockEntity &); virtual void onBlockEntityRemoved(BlockSource &, std::unique_ptr<BlockEntity>); virtual void onBlockEvent(BlockSource &, int, int, int, int, int); };
KsyMC/MCPE-addons
NewDimension/jni/minecraftpe/BlockSourceListener.h
C
agpl-3.0
810
<html> <heac> <meta charset="UTF-8"> <title>Test for MPI.js</title> <script type="text/javascript" src="MPI.js"></script> <script type="text/javascript" src="MPIupdateable.js"></script> <script type="text/javascript" src="mpitests.js"></script> <script> MPImain.run(); </script> </head> <body> See console for test output </body> </html>
hanelyp/javascript
MPI/mpitest.html
HTML
agpl-3.0
368
class Admin::AdminSerializer < ActiveModel::Serializer attributes :id, :name, :email, :teachers def teachers teacher_ids = User.find(object.id).teacher_ids teachers_data = TeachersData.run(teacher_ids) teachers_data.map{|t| Admin::TeacherSerializer.new(t, root: false) } end end
ddmck/Empirical-Core
app/serializers/admin/admin_serializer.rb
Ruby
agpl-3.0
299
#!/usr/bin/python #-*- coding: utf-8 -*- ########################################################### # © 2011 Daniel 'grindhold' Brendle and Team # # This file is part of Skarphed. # # Skarphed is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License # as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later # version. # # Skarphed 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public # License along with Skarphed. # If not, see http://www.gnu.org/licenses/. ########################################################### import os from daemon import Daemon from time import sleep from StringIO import StringIO from traceback import print_exc from skarphedcore.configuration import Configuration from skarphedcore.database import Database from skarphedcore.core import Core from skarphedcore.module import Module from common.errors import OperationException class Operation(object): """ Contais everything necessary to Handle Operations """ STATUS_PENDING = 0 STATUS_ACTIVE = 1 STATUS_FAILED = 2 VALID_STORAGE_TYPES = ('int','bool','str','unicode') def __init__(self, parent_id = None): """ """ self._id = None self._parent = parent_id self._values = {} @classmethod def drop_operation(cls,operation_id): """ Drops an Operation, identified by it's Operation Id and it's children recursively Drop deletes the Operations from Database """ db = Database() stmnt = "SELECT OPE_ID FROM OPERATIONS WHERE OPE_OPE_PARENT = ? AND OPE_STATUS IN (0, 2) ;" cur = db.query(stmnt,(operation_id,)) for row in cur.fetchallmap(): cls.drop_operation(row["OPE_ID"]) stmnt = "DELETE FROM OPERATIONS WHERE OPE_ID = ? AND OPE_STATUS IN (0, 2) ;" db.query(stmnt,(operation_id,),commit=True) @classmethod def retry_operation(cls,operation_id): """ Resets the state of an operation and it's children recursively to 0 (PENDING) The operation is identified by a given operationId """ db = Database() stmnt = "SELECT OPE_ID FROM OPERATIONS WHERE OPE_OPE_PARENT = ? AND OPE_STATUS = 2 ;" cur = db.query(stmnt,(operation_id,)) for row in cur.fetchallmap(): cls.retry_operation(row["OPE_ID"]) stmnt = "UPDATE OPERATIONS SET OPE_STATUS = 0 WHERE OPE_ID = ? AND OPE_STATUS = 2 ;" db.query(stmnt,(operation_id,),commit=True) @classmethod def cancel_operation(cls,operation_id): """ Cancels an Operation, identified by it's Operation Id and it's children recursively Cancel Deletes the Operation from Database """ db = Database() stmnt = "SELECT OPE_ID FROM OPERATIONS WHERE OPE_OPE_PARENT = ? AND OPE_STATUS = 0 ;" cur = db.query(stmnt,(operation_id,)) for row in cur.fetchallmap(): cls.cancel_operation(row["OPE_ID"]) stmnt = "DELETE FROM OPERATIONS WHERE OPE_ID = ? AND OPE_STATUS = 0 ;" db.query(stmnt,(operation_id,),commit=True) @classmethod def restore_operation(cls, operation_record): """ Restore an Operationobject stored in the database by a Dataset consisting of the operation's ID and the operation's TYPE: For example: {"OPE_ID": 100, "OPE_TYPE": "TestOperation"} Restores the Operationobject's _values-attribute by the data saved in the DB-Table OPERATIONDATA """ classname = operation_record["OPE_TYPE"] module = "" #TODO Implement modulename from database if Operation belongs to Module is_operation_of_module = False exec """ try: type(%(class)s) except NameError,e: is_operation_of_module = True"""%{'class':classname} if is_operation_of_module: exec """ from %(module)s import %(class)s operation = %(class)s()"""%{'class':classname,'module':module} else: exec """ operation = %(class)s()"""%{'class':classname} operation.set_id(operation_record['OPE_ID']) db = Database() stmnt = "SELECT OPD_KEY, OPD_VALUE, OPD_TYPE FROM OPERATIONDATA WHERE OPD_OPE_ID = ? ;" cur = db.query(stmnt,(operation_record["OPE_ID"],)) for row in cur.fetchallmap(): val = row["OPD_VALUE"] exec """val = %s(val)"""%row["OPD_TYPE"] operation.set_value(row["OPD_KEY"], val) return operation @classmethod def process_children(cls, operation): """ Recursively executes the workloads of Operation's Childoperations It hereby catches exceptions in the workloads, sets the OPE_STATUS to 2 (FAILED) if a catch occurs, then passes the exception on to the higher layer. If an Operation succeeds, it's entry in DB gets deleted """ db = Database() stmnt = "SELECT OPE_ID, OPE_TYPE FROM OPERATIONS WHERE OPE_OPE_PARENT = ? ORDER BY OPE_INVOKED ;" stmnt_lock = "UPDATE OPERATIONS SET OPE_STATUS = 1 WHERE OPE_ID = ? ;" cur = db.query(stmnt,(operation.get_id(),)) for row in cur.fetchallmap(): child_operation = cls.restore_operation(row) db.query(stmnt_lock,(child_operation.get_id(),),commit=True) try: cls.process_children(child_operation) child_operation.do_workload() except Exception,e: stmnt_err = "UPDATE OPERATIONS SET OPE_STATUS = 2 WHERE OPE_ID = ? ;" db.query(stmnt_err,(int(row["OPE_ID"]),),commit=True) #TODO GENERATE ERROR IN LOG raise e stmnt_delete = "DELETE FROM OPERATIONS WHERE OPE_ID = ?;" db.query(stmnt_delete,(child_operation.get_id(),),commit=True) @classmethod def process_next(cls): """ Sets the status of the next toplevel operation to 1 (ACTIVE) Fetches the next toplevel-operation from the database, applies a FILESYSTEMLOCK! Which is /tmp/scv_operating.lck !!! """ db = Database() configuration = Configuration() if os.path.exists(configuration.get_entry("core.webpath")+"/scv_operating.lck"): return False lockfile = open(configuration.get_entry("core.webpath")+"/scv_operating.lck","w") lockfile.close() stmnt_lock = "UPDATE OPERATIONS SET OPE_STATUS = 1 \ WHERE OPE_ID IN ( \ SELECT OPE_ID FROM OPERATIONS \ WHERE OPE_OPE_PARENT IS NULL AND OPE_STATUS = 0 \ AND OPE_INVOKED = ( \ SELECT MIN(OPE_INVOKED) FROM OPERATIONS \ WHERE OPE_OPE_PARENT IS NULL AND OPE_STATUS = 0) \ ) ;" stmnt = "SELECT OPE_ID, OPE_TYPE FROM OPERATIONS WHERE OPE_OPE_PARENT IS NULL AND OPE_STATUS = 1 ;" db.query(stmnt_lock,commit=True) cur = db.query(stmnt) res = cur.fetchallmap() if len(res) > 0: operation = cls.restore_operation(res[0]) try: cls.process_children(operation) operation.do_workload() except Exception, e: stmnt_err = "UPDATE OPERATIONS SET OPE_STATUS = 2 WHERE OPE_ID = ? ;" db.query(stmnt_err,(operation.get_id(),),commit=True) error = StringIO() print_exc(None,error) Core().log(error.getvalue()) ret = True else: ret = False stmnt_delete = "DELETE FROM OPERATIONS WHERE OPE_STATUS = 1 ;" db.query(stmnt_delete,commit=True) db.commit() try: os.unlink(configuration.get_entry("core.webpath")+"/scv_operating.lck") except OSError,e : raise OperationException(OperationException.get_msg(0)) return ret @classmethod def get_current_operations_for_gui(cls, operation_types=None): """ Returns all Operations in an associative array. The array's indices are the operationIDs The Objects contain all information about the operations, including the Data """ db = Database() #TODO CHECK HOW LISTS ARE HANDLED IN FDB if operation_types is not None and type(operation_types) == list: stmnt = "SELECT OPE_ID, OPE_OPE_PARENT, OPE_INVOKED, OPE_TYPE, OPE_STATUS FROM OPERATIONS WHERE OPE_TYPE IN (?) ORDER BY OPE_INVOKED ;" cur = db.query(stmnt,(operation_types)) else: stmnt = "SELECT OPE_ID, OPE_OPE_PARENT, OPE_INVOKED, OPE_TYPE, OPE_STATUS FROM OPERATIONS ORDER BY OPE_INVOKED ;" cur = db.query(stmnt) ret = {} for row in cur.fetchallmap(): operation = cls.restore_operation(row) custom_values = operation.get_values() ret[row["OPE_ID"]] = {"id":row["OPE_ID"], "parent":row["OPE_OPE_PARENT"], "invoked":str(row["OPE_INVOKED"]), "type":row["OPE_TYPE"], "status":row["OPE_STATUS"], "data":custom_values} return ret def get_values(self): """ trivial """ return self._values def get_value(self,key): """ trivial """ return self._values(key) def set_value(self,key,value): """ trivial """ self._values[key] = value def set_parent(self,parent_id): """ trivial """ self._parent = parent_id def get_parent(self): """ trivial """ return self._parent def set_db_id(self): """ Get a new Operation Id from the Database and assign it to this Operation if this Operation's id is null. Afterwards return the new Id """ if self._id is None: self._id = Database().get_seq_next('OPE_GEN') return self._id def set_id(self, nr): """ trivial """ self._id = nr def get_id(self): """ trivial """ return self._id def store(self): """ Stores this Operation to database. Also saves every user defined value in $_values as long as it is a valid type """ db = Database() self.set_db_id() stmnt = "UPDATE OR INSERT INTO OPERATIONS (OPE_ID, OPE_OPE_PARENT, OPE_INVOKED, OPE_TYPE) \ VALUES (?,?,CURRENT_TIMESTAMP,?) MATCHING (OPE_ID);" db.query(stmnt,(self._id,self._parent,self.__class__.__name__),commit=True) stmnt = "UPDATE OR INSERT INTO OPERATIONDATA (OPD_OPE_ID, OPD_KEY, OPD_VALUE, OPD_TYPE) \ VALUES ( ?, ?, ?, ?) MATCHING(OPD_OPE_ID,OPD_KEY);" for key, value in self._values.items(): typ = str(type(value)).replace("<type '","",1).replace("'>","",1) if typ not in Operation.VALID_STORAGE_TYPES: continue db.query(stmnt,(self._id,key,value,typ),commit=True) def do_workload(self): """ This method must be overridden by inheriting classes. The code inside this method will be executed when the Operation is processed by Operation.processNext or Operation.processChild """ pass #MODULEINVOLVED class ModuleOperation(Operation): """ Abstracts Operations that have to do with modules """ def __init__(self): """ trivial """ Operation.__init__(self) def set_values(self,module): """ Sets this operations values from module metadata """ if type(module) == dict: self.set_value("name",module["name"]) self.set_value("hrname",module["hrname"]) self.set_value("version_major",module["version_major"]) self.set_value("version_minor",module["version_minor"]) self.set_value("revision",module["revision"]) if module.has_key("signature"): self.set_value("signature",module["signature"]) elif module.__class__.__name__ == "Module": pass #TODO IMPLEMENT / DISCUSS AFTER IMPLEMENTING MODULE-SUBSYSTEM def get_meta(self): """ trivial """ return self._values @classmethod def get_currently_processed_modules(cls): """ Returns an Array of ModuleOperation-Objects that are currently listedin the queue """ db = Database() stmnt = "SELECT OPE_ID, OPE_OPE_PARENT, OPE_TYPE FROM OPERATIONS \ WHERE OPE_TYPE = 'ModuleInstallOperation' \ or OPE_TYPE = 'ModuleUninstallOperation' ;" cur = db.query(stmnt); ret = [] for row in cur.fetchallmap(): ret.append(Operation.restore_operation(row).get_meta()) return ret def optimize_queue(self): """ abtract """ pass #MODULEINVOLVED class ModuleInstallOperation(ModuleOperation): """ Manages the process to install a module to this server """ def __init__(self): """ trivial """ ModuleOperation.__init__(self) def do_workload(self): """ tell the module manager to install a specific module. """ Module.install_module(self.get_meta()) def optimize_queue(self): """ optimizes the queue. """ pass #TODO Implement #MODULEINVOLVED class ModuleUninstallOperation(ModuleOperation): """ Manages the process to uninstall a module to this server """ def __init__(self): """ trivial """ ModuleOperation.__init__(self) def do_workload(self): """ tell the module manager to install a specific module. """ module = Module.get_module_by_name(self._values["name"]) module_manager.uninstall_module(module) def optimize_queue(self): """ optimizes the queue. """ pass #TODO Implement #MODULEINVOLVED class ModuleUpdateOperation(ModuleOperation): """ Manages the process to uninstall a module to this server """ def __init__(self): """ trivial """ ModuleOperation.__init__(self) def do_workload(self): """ tell the module manager to install a specific module. """ module = Module.get_module_by_name(self._values["name"]) module_manager.update_module(module) def optimize_queue(self): """ optimizes the queue. """ pass #TODO Implement class FailOperation(Operation): """ For unittest purposes: An Operation that always fails """ def __init__(self): """ trivial """ Operation.__init__(self) def do_workload(self): """ simply fail """ raise Exception("Failoperation failed") class TestOperation(Operation): """ For unittest purposes: An Operation that always succeds """ def __init__(self): """ trivial """ Operation.__init__(self) def do_workload(self): """ simply succeed """ pass class OperationDaemon(Daemon): """ This is the deamon that runs to actually execute the scheduled operations """ def __init__(self, pidfile): """ Initialize the deamon """ Daemon.__init__(self,pidfile) def stop(self): configuration = Configuration() if os.path.exists(configuration.get_entry("core.webpath")+"/scv_operating.lck"): os.remove(configuration.get_entry("core.webpath")+"/scv_operating.lck") Daemon.stop(self) def run(self): """ Do work if there is work to do, otherwise check every two seconds for new work. """ while True: while Operation.process_next(): pass sleep(2)
skarphed/skarphed
core/lib/operation.py
Python
agpl-3.0
16,724
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>ActiveJob::Execution</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" href="../../css/reset.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../css/main.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../css/github.css" type="text/css" media="screen" /> <script src="../../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script> <script src="../../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script> <script src="../../js/main.js" type="text/javascript" charset="utf-8"></script> <script src="../../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div class="banner"> <span>Ruby on Rails 4.2.3</span><br /> <h1> <span class="type">Module</span> ActiveJob::Execution </h1> <ul class="files"> <li><a href="../../files/__/__/__/__/usr/local/lib64/ruby/gems/2_1_0/gems/activejob-4_2_3/lib/active_job/execution_rb.html">/usr/local/lib64/ruby/gems/2.1.0/gems/activejob-4.2.3/lib/active_job/execution.rb</a></li> </ul> </div> <div id="bodyContent"> <div id="content"> <!-- Namespace --> <div class="sectiontitle">Namespace</div> <ul> <li> <span class="type">MODULE</span> <a href="Execution/ClassMethods.html">ActiveJob::Execution::ClassMethods</a> </li> </ul> <!-- Method ref --> <div class="sectiontitle">Methods</div> <dl class="methods"> <dt>P</dt> <dd> <ul> <li> <a href="#method-i-perform">perform</a>, </li> <li> <a href="#method-i-perform_now">perform_now</a> </li> </ul> </dd> </dl> <!-- Includes --> <div class="sectiontitle">Included Modules</div> <ul> <li> <a href="../ActiveSupport/Rescuable.html"> ActiveSupport::Rescuable </a> </li> </ul> <!-- Methods --> <div class="sectiontitle">Instance Public methods</div> <div class="method"> <div class="title method-title" id="method-i-perform"> <b>perform</b>(*) <a href="../../classes/ActiveJob/Execution.html#method-i-perform" name="method-i-perform" class="permalink">Link</a> </div> <div class="description"> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('method-i-perform_source')" id="l_method-i-perform_source">show</a> </p> <div id="method-i-perform_source" class="dyn-source"> <pre><span class="ruby-comment"># File ../../../../usr/local/lib64/ruby/gems/2.1.0/gems/activejob-4.2.3/lib/active_job/execution.rb, line 38</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">perform</span>(<span class="ruby-operator">*</span>) <span class="ruby-identifier">fail</span> <span class="ruby-constant">NotImplementedError</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div class="method"> <div class="title method-title" id="method-i-perform_now"> <b>perform_now</b>() <a href="../../classes/ActiveJob/Execution.html#method-i-perform_now" name="method-i-perform_now" class="permalink">Link</a> </div> <div class="description"> <p>Performs the job immediately. The job is not sent to the queueing adapter but directly executed by blocking the execution of others until it&#39;s finished.</p> <pre><code>MyJob.new(*args).perform_now </code></pre> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('method-i-perform_now_source')" id="l_method-i-perform_now_source">show</a> </p> <div id="method-i-perform_now_source" class="dyn-source"> <pre><span class="ruby-comment"># File ../../../../usr/local/lib64/ruby/gems/2.1.0/gems/activejob-4.2.3/lib/active_job/execution.rb, line 29</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">perform_now</span> <span class="ruby-identifier">deserialize_arguments_if_needed</span> <span class="ruby-identifier">run_callbacks</span> <span class="ruby-value">:perform</span> <span class="ruby-keyword">do</span> <span class="ruby-identifier">perform</span>(<span class="ruby-operator">*</span><span class="ruby-identifier">arguments</span>) <span class="ruby-keyword">end</span> <span class="ruby-keyword">rescue</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-identifier">exception</span> <span class="ruby-identifier">rescue_with_handler</span>(<span class="ruby-identifier">exception</span>) <span class="ruby-operator">||</span> <span class="ruby-identifier">raise</span>(<span class="ruby-identifier">exception</span>) <span class="ruby-keyword">end</span></pre> </div> </div> </div> </div> </div> </body> </html>
FiloSpaTeam/thinks
doc/api/classes/ActiveJob/Execution.html
HTML
agpl-3.0
6,265
/* Lodo is a layered to-do list (Outliner) Copyright (C) 2015 Keith Morrow. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License v3 as published by the Free Software Foundation. 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package lodo import java.util.UUID import japgolly.scalajs.react._ import japgolly.scalajs.react.vdom.prefix_<^._ import Helper._ object NotebookSelector { case class Props(b: Dashboard.Backend, itemMap: ItemMap, selectedNotebook: Option[UUID], isAdding: Boolean, isCompleteHidden: Boolean, isQuickAdd: Boolean) case class State(isNotebookAdding: Boolean = false, addText: String = "", isDragOver: Boolean = false) class Backend(t: BackendScope[Props, State]) { def onClickAdd() = { t.modState(s => s.copy(isNotebookAdding = !s.isNotebookAdding)) } def onFocus(e: ReactEventI) = e.currentTarget.select() def onEdit(e: ReactEventI) = t.modState(s => s.copy(addText = e.currentTarget.value)) def onSubmit(e: ReactEvent) = { e.preventDefault() t.modState(s => { t.props.b.onNotebookAddComplete(AddOp(Item(UUID.randomUUID, None, time(), s.addText))) s.copy(isNotebookAdding = t.props.isQuickAdd, addText = "") }) } def onDragEnter(e: ReactDragEvent) = { e.stopPropagation() e.preventDefault() t.modState(_.copy(isDragOver = true)) } def onDragLeave(e: ReactDragEvent) = { e.stopPropagation() e.preventDefault() t.modState(_.copy(isDragOver = false)) } def onDragOver(e: ReactDragEvent) = { e.stopPropagation() e.preventDefault() } def onDrop(e: ReactDragEvent): Unit = { e.stopPropagation() e.preventDefault() t.modState(_.copy(isDragOver = false)) val src = UUID.fromString(e.dataTransfer.getData("lodo")) val item = t.props.itemMap(Some(src)) item.map(item => { t.props.b.moveAndSelectNotebook(MoveOp(item, None, time()), item.id) }) } } val notebookSelector = ReactComponentB[Props]("NotebookSelector") .initialState(State()) .backend(new Backend(_)) .render((P, S, B) => <.ul(^.cls := "nav nav-sidebar", P.itemMap.notebooks() .zipWithIndex .map { case (c, i) => Notebook(Notebook.Props(P.b, P.selectedNotebook, P.isAdding, P.itemMap, c, i)) }, if (S.isNotebookAdding) <.li( <.a(^.href := "#", <.form(^.onSubmit ==> B.onSubmit, <.input(^.onFocus ==> B.onFocus, ^.autoFocus := true, ^.onChange ==> B.onEdit) ) ) ) else <.li( ^.classSet(("dragover", S.isDragOver)), ^.onDragEnter ==> B.onDragEnter, ^.onDragLeave ==> B.onDragLeave, ^.onDragOver ==> B.onDragOver, ^.onDrop ==> B.onDrop, ^.title := "Create new notebook", <.a(^.href := "#", ^.onClick --> B.onClickAdd(), <.span(^.cls := "glyphicon glyphicon-plus"), <.span(^.classSet(("draghidden", !S.isDragOver)), " Create notebook from item" ) ) ) ) ) .build def apply(props: Props) = notebookSelector(props) }
k3d3/lodo
lodo/js/src/main/scala/components/NotebookSelector.scala
Scala
agpl-3.0
3,834
<?php /* This file is part of Incipio. Incipio is an enterprise resource planning for Junior Enterprise Copyright (C) 2012-2014 Florian Lefevre. Incipio is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Incipio 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Incipio as the file LICENSE. If not, see <http://www.gnu.org/licenses/>. */ namespace mgate\PersonneBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use JMS\SecurityExtraBundle\Annotation\Secure; use mgate\PersonneBundle\Entity\Poste; use mgate\PersonneBundle\Entity\Personne; use mgate\PersonneBundle\Form\PosteType; class PosteController extends Controller { /** * @Secure(roles="ROLE_SUIVEUR") */ public function ajouterAction() { $em = $this->getDoctrine()->getManager(); $poste = new Poste; $form = $this->createForm(new PosteType, $poste); if( $this->get('request')->getMethod() == 'POST' ) { $form->bind($this->get('request')); if( $form->isValid() ) { $em->persist($poste); $em->flush(); return $this->redirect( $this->generateUrl('mgatePersonne_poste_voir', array('id' => $poste->getId())) ); } } return $this->render('mgatePersonneBundle:Poste:ajouter.html.twig', array( 'form' => $form->createView(), )); } /** * Affiche la liste des pages et permet aux admin d'ajouter un poste * @Secure(roles="ROLE_MEMBRE") */ public function indexAction($page) { $em = $this->getDoctrine()->getManager(); $entities = $em->getRepository('mgatePersonneBundle:Poste')->findAll(); // On récupère le service $security = $this->get('security.context'); // On récupère le token $token = $security->getToken(); // on récupère l'utilisateur $user = $token->getUser(); if($security->isGranted('ROLE_ADMIN')){ $poste = new Poste; $form = $this->createForm(new PosteType, $poste); return $this->render('mgatePersonneBundle:Poste:index.html.twig', array( 'postes' => $entities, 'form' => $form->createView() )); } return $this->render('mgatePersonneBundle:Poste:index.html.twig', array( 'postes' => $entities, )); } /** * @Secure(roles="ROLE_MEMBRE") */ public function voirAction($id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('mgatePersonneBundle:Poste')->find($id); if (!$entity) { throw $this->createNotFoundException('Le poste demandé n\'existe pas !'); } //$deleteForm = $this->createDeleteForm($id); return $this->render('mgatePersonneBundle:Poste:voir.html.twig', array( 'poste' => $entity, /*'delete_form' => $deleteForm->createView(), */)); } /** * @Secure(roles="ROLE_SUIVEUR") */ public function modifierAction($id) { $em = $this->getDoctrine()->getManager(); if( ! $poste = $em->getRepository('mgate\PersonneBundle\Entity\Poste')->find($id) ) throw $this->createNotFoundException('Le poste demandé n\'existe pas !'); // On passe l'$article récupéré au formulaire $form = $this->createForm(new PosteType, $poste); $deleteForm = $this->createDeleteForm($id); if( $this->get('request')->getMethod() == 'POST' ) { $form->bind($this->get('request')); if( $form->isValid() ) { $em->persist($poste); $em->flush(); return $this->redirect( $this->generateUrl('mgatePersonne_poste_voir', array('id' => $poste->getId())) ); } } return $this->render('mgatePersonneBundle:Poste:modifier.html.twig', array( 'form' => $form->createView(), 'delete_form' => $deleteForm->createView(), )); } /** * @Secure(roles="ROLE_SUIVEUR") */ public function deleteAction($id) { $form = $this->createDeleteForm($id); $request = $this->getRequest(); $form->bind($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); if( ! $entity = $em->getRepository('mgate\PersonneBundle\Entity\Poste')->find($id) ) throw $this->createNotFoundException('Le poste demandé n\'existe pas !'); foreach($entity->getMembres() as $membre) $membre->setPoste(null); //$entity->setMembres(null); $em->remove($entity); $em->flush(); } return $this->redirect($this->generateUrl('mgatePersonne_poste_homepage')); } private function createDeleteForm($id) { return $this->createFormBuilder(array('id' => $id)) ->add('id', 'hidden') ->getForm() ; } }
Emagine-JE/Incipio
src/mgate/PersonneBundle/Controller/PosteController.php
PHP
agpl-3.0
5,768
// Copyright 2016 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package state import ( "math/big" "github.com/ethereumproject/go-ethereum/common" ) type journalEntry interface { undo(*StateDB) } type journal []journalEntry type ( // Changes to the account trie. createObjectChange struct { account *common.Address } resetObjectChange struct { prev *StateObject } suicideChange struct { account *common.Address prev bool // whether account had already suicided prevbalance *big.Int } // Changes to individual accounts. balanceChange struct { account *common.Address prev *big.Int } nonceChange struct { account *common.Address prev uint64 } storageChange struct { account *common.Address key, prevalue common.Hash } codeChange struct { account *common.Address prevcode, prevhash []byte } // Changes to other state values. refundChange struct { prev *big.Int } addLogChange struct { txhash common.Hash } ) func (ch createObjectChange) undo(s *StateDB) { s.GetStateObject(*ch.account).deleted = true delete(s.stateObjects, *ch.account) delete(s.stateObjectsDirty, *ch.account) } func (ch resetObjectChange) undo(s *StateDB) { s.setStateObject(ch.prev) } func (ch suicideChange) undo(s *StateDB) { obj := s.GetStateObject(*ch.account) if obj != nil { obj.suicided = ch.prev obj.setBalance(ch.prevbalance) } } func (ch balanceChange) undo(s *StateDB) { s.GetStateObject(*ch.account).setBalance(ch.prev) } func (ch nonceChange) undo(s *StateDB) { s.GetStateObject(*ch.account).setNonce(ch.prev) } func (ch codeChange) undo(s *StateDB) { s.GetStateObject(*ch.account).setCode(common.BytesToHash(ch.prevhash), ch.prevcode) } func (ch storageChange) undo(s *StateDB) { s.GetStateObject(*ch.account).setState(ch.key, ch.prevalue) } func (ch refundChange) undo(s *StateDB) { s.refund = ch.prev } func (ch addLogChange) undo(s *StateDB) { logs := s.logs[ch.txhash] if len(logs) == 1 { delete(s.logs, ch.txhash) } else { s.logs[ch.txhash] = logs[:len(logs)-1] } }
adrianbrink/tendereum
vendor/github.com/ethereumproject/go-ethereum/core/state/journal.go
GO
agpl-3.0
2,808
using NetEOC.Auth.Data; using NetEOC.Auth.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace NetEOC.Auth.Services { public class OrganizationService { public OrganizationRepository OrganizationRepository { get; set; } public OrganizationMemberRepository OrganizationMemberRepository { get; set; } public OrganizationAdminRepository OrganizationAdminRepository { get; set; } public OrganizationService() { OrganizationRepository = new OrganizationRepository(); OrganizationAdminRepository = new OrganizationAdminRepository(); OrganizationMemberRepository = new OrganizationMemberRepository(); } public async Task<Organization> Create(Organization organization) { if (!ValidateOrganization(organization)) throw new ArgumentException("Invalid Organization!"); if(organization.Id != Guid.Empty) { Organization existing = await Update(organization); if (existing != null) return existing; } return await OrganizationRepository.Create(organization); } public async Task<Organization> GetById(Guid id) { return await OrganizationRepository.Get(id); } public async Task<Organization[]> GetByOwnerId(Guid ownerId) { return await OrganizationRepository.GetByOwnerId(ownerId); } public async Task<Organization> Update(Organization organization) { if (!ValidateOrganization(organization)) throw new ArgumentException("Invalid Organization!"); if (organization.Id == Guid.Empty) throw new ArgumentException("Organization has no id!"); //merge organization Organization existing = await GetById(organization.Id); if (existing == null) return null; if (!string.IsNullOrWhiteSpace(organization.Name)) existing.Name = organization.Name; if (!string.IsNullOrWhiteSpace(organization.Description)) existing.Description = organization.Description; if (organization.Data != null) { foreach (var kv in organization.Data) { if (existing.Data.ContainsKey(kv.Key)) { existing.Data[kv.Key] = kv.Value; } else { existing.Data.Add(kv.Key, kv.Value); } } } return await OrganizationRepository.Update(existing); } public async Task<bool> Delete(Guid organizationId) { return await OrganizationRepository.Delete(organizationId); } public async Task<Guid[]> GetOrganizationMembers(Guid organizationId) { return (await OrganizationMemberRepository.GetByOrganizationId(organizationId)).Select(x => x.UserId).ToArray(); } public async Task<Guid[]> GetOrganizationAdmins(Guid organizationId) { return (await OrganizationAdminRepository.GetByOrganizationId(organizationId)).Select(x => x.UserId).ToArray(); } public async Task<OrganizationMember> AddMemberToOrganization(Guid organizationId, Guid userId) { OrganizationMember[] memberships = await OrganizationMemberRepository.GetByUserId(userId); OrganizationMember membership = memberships.FirstOrDefault(x => x.OrganizationId == organizationId); if (membership == null) { membership = new OrganizationMember { OrganizationId = organizationId, UserId = userId }; membership = await OrganizationMemberRepository.Create(membership); } return membership; } public async Task<bool> RemoveMemberFromOrganization(Guid organizationId, Guid userId) { OrganizationMember[] memberships = await OrganizationMemberRepository.GetByUserId(userId); OrganizationMember membership = memberships.FirstOrDefault(x => x.OrganizationId == organizationId); bool success = false; if (membership != null) { success = await OrganizationMemberRepository.Delete(membership.Id); } return success; } public async Task<OrganizationAdmin> AddAdminToOrganization(Guid organizationId, Guid userId) { OrganizationAdmin[] memberships = await OrganizationAdminRepository.GetByUserId(userId); OrganizationAdmin membership = memberships.FirstOrDefault(x => x.OrganizationId == organizationId); if (membership == null) { membership = new OrganizationAdmin { OrganizationId = organizationId, UserId = userId }; membership = await OrganizationAdminRepository.Create(membership); } return membership; } public async Task<bool> RemoveAdminFromOrganization(Guid organizationId, Guid userId) { OrganizationAdmin[] memberships = await OrganizationAdminRepository.GetByUserId(userId); OrganizationAdmin membership = memberships.FirstOrDefault(x => x.OrganizationId == organizationId); bool success = false; if (membership != null) { success = await OrganizationAdminRepository.Delete(membership.Id); } return success; } private bool ValidateOrganization(Organization organization) { if (organization.OwnerId == Guid.Empty) throw new ArgumentException("Organization must have an owner!"); if (string.IsNullOrWhiteSpace(organization.Name)) throw new ArgumentException("Organization must have a name!"); return true; } } }
neteoc/neteoc-server
Source/Services/NetEOC.Auth/Services/OrganizationService.cs
C#
agpl-3.0
6,031
.form-field { overflow: hidden; } /* Order of the field attributes */ .form-wrap.form-builder .frmb .form-elements { display: flex; flex-direction: column; } .form-wrap.form-builder .frmb .form-field .form-group { order: 100; } .required-wrap { order: 0 !important; } .name-wrap { order: 1 !important; } .label-wrap { order: 2 !important; } .subtype-wrap { order: 3 !important; } .separator-wrap { order: 50 !important; margin-top: 10px; border-top: 1px dashed grey; padding-top: 10px; } .access-wrap { order: 110 !important; } .separator-field label, .separator-field .copy-button, .separator-field .toggle-form { display: none !important; } .separator-wrap label, .separator-wrap .input-wrap { display: none !important; } .separator-wrap { order: 50 !important; margin-top: 10px; border-top: 1px dashed grey; padding-top: 10px; } .form-wrap.form-builder .frmb .form-elements .input-wrap { width: 70%; } .form-wrap.form-builder .frmb .form-elements .false-label:first-child, .form-wrap.form-builder .frmb .form-elements label:first-child { width: 25%; } .titre-field .required-wrap, .titre-field .name-wrap { display: none !important; } .map-field .label-wrap, .map-field .value-wrap, .map-field .name-wrap { display: none !important; } .date-field .value-wrap { display: none !important; } .image-field .value-wrap, .image-field .name-wrap { display: none !important; } .image-field .name2-wrap { order: 1 !important; } .select-field .field-options, .radio-group-field .field-options, .checkbox-group-field .field-options { display: none !important; } .form-wrap.form-builder .frmb .form-elements .false-label:first-child, .form-wrap.form-builder .frmb .form-elements label:first-child { white-space: normal; text-overflow: initial; } .form-wrap.form-builder .form-elements .form-group > label { white-space: normal !important; } .listId-wrap, .formId-wrap { display: none !important; } .textarea-field .maxlength-wrap, .textarea-field .subtype-wrap { display: none !important; } .file-field .subtype-wrap { display: none !important; } .inscriptionliste-field .required-wrap, .inscriptionliste-field .name-wrap, .inscriptionliste-field .value-wrap { display: none !important; } .labelhtml-field .required-wrap, .labelhtml-field .name-wrap, .labelhtml-field .value-wrap, .labelhtml-field .label-wrap { display: none !important; } .utilisateur_wikini-field .required-wrap, .utilisateur_wikini-field .name-wrap, .utilisateur_wikini-field .value-wrap, .utilisateur_wikini-field .label-wrap { display: none !important; } .acls-field .required-wrap, .acls-field .name-wrap, .acls-field .value-wrap, .acls-field .label-wrap { display: none !important; } .metadatas-field .required-wrap, .metadatas-field .name-wrap, .metadatas-field .value-wrap, .metadatas-field .label-wrap { display: none !important; } .listefichesliees-field .required-wrap, .listefichesliees-field .name-wrap, .listefichesliees-field .value-wrap, .listefichesliees-field .label-wrap { display: none !important; } .bookmarklet-field .required-wrap { display: none !important; } .custom-field .required-wrap, .custom-field .name-wrap, .custom-field .value-wrap, .custom-field .label-wrap { display: none !important; } xmp { overflow: auto; } /* Redefine .fa class when icon- class exists, because redefined by form-builder.min.js*/ .fa[class*=" icon-"]::before, .fa[class^="icon-"]::before { font-family: inherit; font-weight: inherit; font-style: inherit; margin: 0; font-variant: inherit; line-height: inherit; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; width: inherit; text-transform: inherit; } /* Make the list of fields smaller */ .form-wrap.form-builder .frmb-control li { padding: 5px 10px; font-size: 15px; } .form-wrap.form-builder .frmb li { padding: 5px 10px; } .form-wrap.form-builder .frmb li:first-child { padding-top: 10px; } .form-wrap.form-builder .frmb .field-label { font-weight: bold; } .form-wrap.form-builder .frmb .prev-holder { font-size: 15px; } .form-wrap.form-builder .frmb .prev-holder input:not([type=file]), .form-wrap.form-builder .frmb .prev-holder textarea { border-radius: 3px; border: 1px solid #ccc; box-shadow: none; }
YesWiki/yeswiki
tools/bazar/presentation/styles/form-edit-template.css
CSS
agpl-3.0
4,259
package com.wirecard.acqp.two; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; @Ignore @SuppressWarnings("javadoc") public class ThreadingLongrunningTest { /** * The number of threads to use in this test. */ private static final int NUM_THREADS = 12; /** * Flag to indicate the concurrent test has failed. */ private boolean failed; @Test public void testConcurrently() { final ParserHardeningLongrunningTest pt = new ParserHardeningLongrunningTest(); final String msg = "F0F1F0F0723C440188E18008F1F9F5F4F0F5F6F2F0F0F0F0F0F0F0F0F0F0F0F1F4F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F5F0F5F0F1F2F0F1F3F0F3F0F9F5F8F9F2F7F8F1F3F0F3F0F9F0F1F2F0F1F5F1F1F5F4F1F1F8F1F2F0F6F0F1F3F4F0F1F0F6F2F0F0F3F5F0F0F1F2F0F1F4F5F4F9F3F5F482F0F0F0F0F0F0F1D9C5E3D382F0F0F0F0F0F0F1404040C3C3C240E3F140E28899A340D581948540404040404040C3C3C240E3F140E28899A340D340D7C1D5F0F6F0E3F6F1F0F5F0F0F0F0F1F9F2F0F35C5C5CF4F2F0F7F0F1F0F3F2F1F2F4F3F2F891C982A884F6E38581889492C1C2C5C1C1C1C699D894A8E7A694F07EF9F7F8F0F2F1F1F0F2F5F1F0F0F0F0F6F0F0F0F5F9F1D7C1D5F1F2"; Runnable runnable = new Runnable() { public void run() { try { pt.testParserHardeningJCB(); pt.testParserHardeningMC(); String fieldValue = MsgAccessoryImpl.readFieldValue(msg, "MASTERCARD", "2"); assertEquals("PAN (Field 2) was not read correctly.", "5405620000000000014", fieldValue); String mti = MsgAccessoryImpl.readFieldValue(msg, "MASTERCARD", "0"); assertEquals("mti was not read correctly.", "0100", mti); pt.testParserHardeningVisa(); } catch (Exception e) { failed = true; } } }; Thread[] threads = new Thread[NUM_THREADS]; for (int i = 0; i < NUM_THREADS; i++) { threads[i] = new Thread(runnable); } for (int i = 0; i < NUM_THREADS; i++) { threads[i].start(); } for (int i = 0; i < NUM_THREADS; i++) { try { threads[i].join(); } catch (InterruptedException e) { failed = true; } } assertFalse(failed); } // @Test obsolet but temp // public void testGetFieldValueMixedgetFieldMethods() // throws IllegalArgumentException, ISOException, // IllegalStateException, UnsupportedEncodingException { // // // UtilityMethodAccess after construktor // String msg = // "F0F1F0F0723C440188E18008F1F9F5F4F0F5F6F2F0F0F0F0F0F0F0F0F0F0F0F1F4F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F5F0F5F0F1F2F0F1F3F0F3F0F9F5F8F9F2F7F8F1F3F0F3F0F9F0F1F2F0F1F5F1F1F5F4F1F1F8F1F2F0F6F0F1F3F4F0F1F0F6F2F0F0F3F5F0F0F1F2F0F1F4F5F4F9F3F5F482F0F0F0F0F0F0F1D9C5E3D382F0F0F0F0F0F0F1404040C3C3C240E3F140E28899A340D581948540404040404040C3C3C240E3F140E28899A340D340D7C1D5F0F6F0E3F6F1F0F5F0F0F0F0F1F9F2F0F35C5C5CF4F2F0F7F0F1F0F3F2F1F2F4F3F2F891C982A884F6E38581889492C1C2C5C1C1C1C699D894A8E7A694F07EF9F7F8F0F2F1F1F0F2F5F1F0F0F0F0F6F0F0F0F5F9F1D7C1D5F1F2"; // assertEquals("PAN (Field 2) was not read correctly.", // "5405620000000000014", // msgAccessoryInitial.getFieldValue(msg, "MASTERCARD", "2")); // // assertEquals("PAN (Field 2) was not equal.", // "5400041234567898", // msgAccessoryInitial.getFieldValue("2")); // // // UtilityMethodAccess after construktor // assertEquals("PAN (Field 2) was not read correctly.", // "5405620000000000014", // msgAccessoryInitial.getFieldValue(msg, "MASTERCARD", "2")); // // } }
wakantanka/get_iso_8583
src/test/java/com/wirecard/acqp/two/ThreadingLongrunningTest.java
Java
agpl-3.0
3,989
/* gzlib.c -- zlib functions common to reading and writing gzip files * Copyright (C) 2004-2017 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ #include "gzguts.h" #if defined(_WIN32) && !defined(__BORLANDC__) # define LSEEK _lseeki64 #else #if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 # define LSEEK lseek64 #else # define LSEEK lseek #endif #endif /* Local functions */ local void gz_reset OF((gz_statep)); local gzFile gz_open OF((const void *, int, const char *)); #if defined UNDER_CE /* Map the Windows error number in ERROR to a locale-dependent error message string and return a pointer to it. Typically, the values for ERROR come from GetLastError. The string pointed to shall not be modified by the application, but may be overwritten by a subsequent call to gz_strwinerror The gz_strwinerror function does not change the current setting of GetLastError. */ char ZLIB_INTERNAL *gz_strwinerror (error) DWORD error; { static char buf[1024]; wchar_t *msgbuf; DWORD lasterr = GetLastError(); DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, error, 0, /* Default language */ (LPVOID)&msgbuf, 0, NULL); if (chars != 0) { /* If there is an \r\n appended, zap it. */ if (chars >= 2 && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') { chars -= 2; msgbuf[chars] = 0; } if (chars > sizeof (buf) - 1) { chars = sizeof (buf) - 1; msgbuf[chars] = 0; } wcstombs(buf, msgbuf, chars + 1); LocalFree(msgbuf); } else { sprintf(buf, "unknown win32 error (%ld)", error); } SetLastError(lasterr); return buf; } #endif /* UNDER_CE */ /* Reset gzip file state */ local void gz_reset(state) gz_statep state; { state->x.have = 0; /* no output data available */ if (state->mode == GZ_READ) { /* for reading ... */ state->eof = 0; /* not at end of file */ state->past = 0; /* have not read past end yet */ state->how = LOOK; /* look for gzip header */ } else /* for writing ... */ state->reset = 0; /* no deflateReset pending */ state->seek = 0; /* no seek request pending */ gz_error(state, Z_OK, NULL); /* clear error */ state->x.pos = 0; /* no uncompressed data yet */ state->strm.avail_in = 0; /* no input data yet */ } /* Open a gzip file either by name or file descriptor. */ local gzFile gz_open(path, fd, mode) const void *path; int fd; const char *mode; { gz_statep state; z_size_t len; int oflag; #ifdef O_CLOEXEC int cloexec = 0; #endif #ifdef O_EXCL int exclusive = 0; #endif /* check input */ if (path == NULL) return NULL; /* allocate gzFile structure to return */ state = (gz_statep)malloc(sizeof(gz_state)); if (state == NULL) return NULL; state->size = 0; /* no buffers allocated yet */ state->want = GZBUFSIZE; /* requested buffer size */ state->msg = NULL; /* no error message yet */ /* interpret mode */ state->mode = GZ_NONE; state->level = Z_DEFAULT_COMPRESSION; state->strategy = Z_DEFAULT_STRATEGY; state->direct = 0; while (*mode) { if (*mode >= '0' && *mode <= '9') state->level = *mode - '0'; else switch (*mode) { case 'r': state->mode = GZ_READ; break; #ifndef NO_GZCOMPRESS case 'w': state->mode = GZ_WRITE; break; case 'a': state->mode = GZ_APPEND; break; #endif case '+': /* can't read and write at the same time */ free(state); return NULL; case 'b': /* ignore -- will request binary anyway */ break; #ifdef O_CLOEXEC case 'e': cloexec = 1; break; #endif #ifdef O_EXCL case 'x': exclusive = 1; break; #endif case 'f': state->strategy = Z_FILTERED; break; case 'h': state->strategy = Z_HUFFMAN_ONLY; break; case 'R': state->strategy = Z_RLE; break; case 'F': state->strategy = Z_FIXED; break; case 'T': state->direct = 1; break; default: /* could consider as an error, but just ignore */ ; } mode++; } /* must provide an "r", "w", or "a" */ if (state->mode == GZ_NONE) { free(state); return NULL; } /* can't force transparent read */ if (state->mode == GZ_READ) { if (state->direct) { free(state); return NULL; } state->direct = 1; /* for empty file */ } /* save the path name for error messages */ #ifdef WIDECHAR if (fd == -2) { len = wcstombs(NULL, path, 0); if (len == (z_size_t)-1) len = 0; } else #endif len = strlen((const char *)path); state->path = (char *)malloc(len + 1); if (state->path == NULL) { free(state); return NULL; } #ifdef WIDECHAR if (fd == -2) if (len) wcstombs(state->path, path, len + 1); else *(state->path) = 0; else #endif #if !defined(NO_snprintf) && !defined(NO_vsnprintf) (void)snprintf(state->path, len + 1, "%s", (const char *)path); #else strcpy(state->path, path); #endif /* compute the flags for open() */ oflag = #ifdef O_LARGEFILE O_LARGEFILE | #endif #ifdef O_BINARY O_BINARY | #endif #ifdef O_CLOEXEC (cloexec ? O_CLOEXEC : 0) | #endif (state->mode == GZ_READ ? O_RDONLY : (O_WRONLY | O_CREAT | #ifdef O_EXCL (exclusive ? O_EXCL : 0) | #endif (state->mode == GZ_WRITE ? O_TRUNC : O_APPEND))); /* open the file with the appropriate flags (or just use fd) */ state->fd = fd > -1 ? fd : ( #ifdef WIDECHAR fd == -2 ? _wopen(path, oflag, 0666) : #endif open((const char *)path, oflag, 0666)); if (state->fd == -1) { free(state->path); free(state); return NULL; } if (state->mode == GZ_APPEND) { LSEEK(state->fd, 0, SEEK_END); /* so gzoffset() is correct */ state->mode = GZ_WRITE; /* simplify later checks */ } /* save the current position for rewinding (only if reading) */ if (state->mode == GZ_READ) { state->start = LSEEK(state->fd, 0, SEEK_CUR); if (state->start == -1) state->start = 0; } /* initialize stream */ gz_reset(state); /* return stream */ return (gzFile)state; } /* -- see zlib.h -- */ gzFile ZEXPORT gzopen(path, mode) const char *path; const char *mode; { return gz_open(path, -1, mode); } /* -- see zlib.h -- */ gzFile ZEXPORT gzopen64(path, mode) const char *path; const char *mode; { return gz_open(path, -1, mode); } /* -- see zlib.h -- */ gzFile ZEXPORT gzdopen(fd, mode) int fd; const char *mode; { char *path; /* identifier for error messages */ gzFile gz; if (fd == -1 || (path = (char *)malloc(7 + 3 * sizeof(int))) == NULL) return NULL; #if !defined(NO_snprintf) && !defined(NO_vsnprintf) (void)snprintf(path, 7 + 3 * sizeof(int), "<fd:%d>", fd); #else sprintf(path, "<fd:%d>", fd); /* for debugging */ #endif gz = gz_open(path, fd, mode); free(path); return gz; } /* -- see zlib.h -- */ #ifdef WIDECHAR gzFile ZEXPORT gzopen_w(path, mode) const wchar_t *path; const char *mode; { return gz_open(path, -2, mode); } #endif /* -- see zlib.h -- */ int ZEXPORT gzbuffer(file, size) gzFile file; unsigned size; { gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return -1; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return -1; /* make sure we haven't already allocated memory */ if (state->size != 0) return -1; /* check and set requested size */ if ((size << 1) < size) return -1; /* need to be able to double it */ if (size < 2) size = 2; /* need two bytes to check magic header */ state->want = size; return 0; } /* -- see zlib.h -- */ int ZEXPORT gzrewind(file) gzFile file; { gz_statep state; /* get internal structure */ if (file == NULL) return -1; state = (gz_statep)file; /* check that we're reading and that there's no error */ if (state->mode != GZ_READ || (state->err != Z_OK && state->err != Z_BUF_ERROR)) return -1; /* back up and start over */ if (LSEEK(state->fd, state->start, SEEK_SET) == -1) return -1; gz_reset(state); return 0; } /* -- see zlib.h -- */ z_off64_t ZEXPORT gzseek64(file, offset, whence) gzFile file; z_off64_t offset; int whence; { unsigned n; z_off64_t ret; gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return -1; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return -1; /* check that there's no error */ if (state->err != Z_OK && state->err != Z_BUF_ERROR) return -1; /* can only seek from start or relative to current position */ if (whence != SEEK_SET && whence != SEEK_CUR) return -1; /* normalize offset to a SEEK_CUR specification */ if (whence == SEEK_SET) offset -= state->x.pos; else if (state->seek) offset += state->skip; state->seek = 0; /* if within raw area while reading, just go there */ if (state->mode == GZ_READ && state->how == COPY && state->x.pos + offset >= 0) { ret = LSEEK(state->fd, offset - (z_off64_t)state->x.have, SEEK_CUR); if (ret == -1) return -1; state->x.have = 0; state->eof = 0; state->past = 0; state->seek = 0; gz_error(state, Z_OK, NULL); state->strm.avail_in = 0; state->x.pos += offset; return state->x.pos; } /* calculate skip amount, rewinding if needed for back seek when reading */ if (offset < 0) { if (state->mode != GZ_READ) /* writing -- can't go backwards */ return -1; offset += state->x.pos; if (offset < 0) /* before start of file! */ return -1; if (gzrewind(file) == -1) /* rewind, then skip to offset */ return -1; } /* if reading, skip what's in output buffer (one less gzgetc() check) */ if (state->mode == GZ_READ) { n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > offset ? (unsigned)offset : state->x.have; state->x.have -= n; state->x.next += n; state->x.pos += n; offset -= n; } /* request skip (if not zero) */ if (offset) { state->seek = 1; state->skip = offset; } return state->x.pos + offset; } /* -- see zlib.h -- */ z_off_t ZEXPORT gzseek(file, offset, whence) gzFile file; z_off_t offset; int whence; { z_off64_t ret; ret = gzseek64(file, (z_off64_t)offset, whence); return ret == (z_off_t)ret ? (z_off_t)ret : -1; } /* -- see zlib.h -- */ z_off64_t ZEXPORT gztell64(file) gzFile file; { gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return -1; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return -1; /* return position */ return state->x.pos + (state->seek ? state->skip : 0); } /* -- see zlib.h -- */ z_off_t ZEXPORT gztell(file) gzFile file; { z_off64_t ret; ret = gztell64(file); return ret == (z_off_t)ret ? (z_off_t)ret : -1; } /* -- see zlib.h -- */ z_off64_t ZEXPORT gzoffset64(file) gzFile file; { z_off64_t offset; gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return -1; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return -1; /* compute and return effective offset in file */ offset = LSEEK(state->fd, 0, SEEK_CUR); if (offset == -1) return -1; if (state->mode == GZ_READ) /* reading */ offset -= state->strm.avail_in; /* don't count buffered input */ return offset; } /* -- see zlib.h -- */ z_off_t ZEXPORT gzoffset(file) gzFile file; { z_off64_t ret; ret = gzoffset64(file); return ret == (z_off_t)ret ? (z_off_t)ret : -1; } /* -- see zlib.h -- */ int ZEXPORT gzeof(file) gzFile file; { gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return 0; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return 0; /* return end-of-file state */ return state->mode == GZ_READ ? state->past : 0; } /* -- see zlib.h -- */ const char * ZEXPORT gzerror(file, errnum) gzFile file; int *errnum; { gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return NULL; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return NULL; /* return error information */ if (errnum != NULL) *errnum = state->err; return state->err == Z_MEM_ERROR ? "out of memory" : (state->msg == NULL ? "" : state->msg); } /* -- see zlib.h -- */ void ZEXPORT gzclearerr(file) gzFile file; { gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return; /* clear error and end-of-file */ if (state->mode == GZ_READ) { state->eof = 0; state->past = 0; } gz_error(state, Z_OK, NULL); } /* Create an error message in allocated memory and set state->err and state->msg accordingly. Free any previous error message already there. Do not try to free or allocate space if the error is Z_MEM_ERROR (out of memory). Simply save the error message as a static string. If there is an allocation failure constructing the error message, then convert the error to out of memory. */ void ZLIB_INTERNAL gz_error(state, err, msg) gz_statep state; int err; const char *msg; { /* free previously allocated message and clear */ if (state->msg != NULL) { if (state->err != Z_MEM_ERROR) free(state->msg); state->msg = NULL; } /* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */ if (err != Z_OK && err != Z_BUF_ERROR) state->x.have = 0; /* set error code, and if no message, then done */ state->err = err; if (msg == NULL) return; /* for an out of memory error, return literal string when requested */ if (err == Z_MEM_ERROR) return; /* construct error message with path */ if ((state->msg = (char *)malloc(strlen(state->path) + strlen(msg) + 3)) == NULL) { state->err = Z_MEM_ERROR; return; } #if !defined(NO_snprintf) && !defined(NO_vsnprintf) (void)snprintf(state->msg, strlen(state->path) + strlen(msg) + 3, "%s%s%s", state->path, ": ", msg); #else strcpy(state->msg, state->path); strcat(state->msg, ": "); strcat(state->msg, msg); #endif } #ifndef INT_MAX /* portably return maximum value for an int (when limits.h presumed not available) -- we need to do this to cover cases where 2's complement not used, since C standard permits 1's complement and sign-bit representations, otherwise we could just use ((unsigned)-1) >> 1 */ unsigned ZLIB_INTERNAL gz_intmax() { unsigned p, q; p = 1; do { q = p; p <<= 1; p++; } while (p > q); return q >> 1; } #endif
sagiadinos/garlic-player
src/ext/zlib/gzlib.c
C
agpl-3.0
16,709
<?php class m151218_144423_update_et_operationnote_biometry_view extends CDbMigration { public function up() { $this->execute('CREATE OR REPLACE VIEW et_ophtroperationnote_biometry AS SELECT eol.id, eol.eye_id, eol.last_modified_date, target_refraction_left, target_refraction_right, (SELECT name FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_left) as lens_left, (SELECT description FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_left) as lens_description_left, (SELECT acon FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_left) AS lens_acon_left, (SELECT name FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_right) as lens_right, (SELECT description FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_right) as lens_description_right, (SELECT acon FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_right) AS lens_acon_right, k1_left, k1_right, k2_left, k2_right, axis_k1_left, axis_k1_right, axial_length_left, axial_length_right, snr_left, snr_right, iol_power_left, iol_power_right, predicted_refraction_left, predicted_refraction_right, patient_id, k2_axis_left, k2_axis_right, delta_k_left, delta_k_right, delta_k_axis_left, delta_k_axis_right, acd_left, acd_right, (SELECT name FROM dicom_eye_status oes WHERE oes.id=lens_id_left) as status_left, (SELECT name FROM dicom_eye_status oes WHERE oes.id=lens_id_right) as status_right, comments, eoc.event_id FROM et_ophinbiometry_measurement eol JOIN et_ophinbiometry_calculation eoc ON eoc.event_id=eol.event_id JOIN et_ophinbiometry_selection eos ON eos.event_id=eol.event_id JOIN event ev ON ev.id=eol.event_id JOIN episode ep ON ep.id=ev.episode_id ORDER BY eol.last_modified_date;'); } public function down() { $this->execute('CREATE OR REPLACE VIEW et_ophtroperationnote_biometry AS SELECT eol.id, eol.eye_id, eol.last_modified_date, target_refraction_left, target_refraction_right, (SELECT name FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_left) as lens_left, (SELECT description FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_left) as lens_description_left, (SELECT acon FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_left) AS lens_acon_left, (SELECT name FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_right) as lens_right, (SELECT description FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_right) as lens_description_right, (SELECT acon FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_right) AS lens_acon_right, k1_left, k1_right, k2_left, k2_right, axis_k1_left, axis_k1_right, axial_length_left, axial_length_right, snr_left, snr_right, iol_power_left, iol_power_right, predicted_refraction_left, predicted_refraction_right, patient_id FROM et_ophinbiometry_measurement eol JOIN et_ophinbiometry_calculation eoc ON eoc.event_id=eol.event_id JOIN et_ophinbiometry_selection eos ON eos.event_id=eol.event_id JOIN event ev ON ev.id=eol.event_id JOIN episode ep ON ep.id=ev.episode_id ORDER BY eol.last_modified_date;'); } }
FiviumAustralia/OpenEyes
protected/modules/OphInBiometry/migrations/m151218_144423_update_et_operationnote_biometry_view.php
PHP
agpl-3.0
3,374
#!/bin/bash # cve <file1> [<file2> ...] # # Pour éditer un ou plusieurs fichier(s) existant(s) sous CVS. # - fait un "cvs update" si besoin (status "Needs patch") # - fait un "cvs edit" pour déclarer aux autres users qu'on édite le fichier # (voir la commande "cvs editors") # - utilise l'éditeur préféré déclaré dans la variable $EDITOR # (c) 2003-2005 Julien Moreau # 2002-03 Creation # 2005-01 Updates # Last version under CVS (GMT): # $Header: /cvs/CVS-tools/cve.sh,v 1.6 2012-11-23 10:08:38 jmoreau Exp $ nbps=1 # Nombre de paramètres souhaités (sans option) nom_cmde=`basename $0` # Nom de la commande usage="Usage: $nom_cmde [-h]" # Message d'aide usage=$usage"\n\tAffiche ce message d'aide.\n" usage=$usage"\nUsage: $nom_cmde <filename> [...]" usage=$usage"\n\tÉdite des fichiers CVS en posant des verrous d'écriture." if test `uname` != "HP-UX" ; then e="-e" ; fi # Compatibilité HP-UX/Linux if [ $# -lt 0 -o "$1" = "-h" -o "$1" = "--help" ] ; then # Vérif params echo $e $usage 1>&2 ; exit 2 # Aide puis fin fi if test -z "$EDITOR" then if test -z "$USER" then export USER=`whoami` fi echo "$USER"|grep -q moreau if [ -n "$DISPLAY" -a "$?" -eq 0 ] then export EDITOR='gvim -geom 128x50' else export EDITOR=vi fi fi while [ "$#" -ge 1 ] do file="$1" lstatus=`cvs status "$file"|grep ^'File:'` status=`echo "$lstatus"|sed 's|.*Status: ||'` if test -n "$lstatus" ; then echo "$lstatus" ; fi case "$status" in 'Up-to-date') ;; 'Locally Modified') ;; 'Locally Added') ;; 'Needs Patch') cvs update ;; 'Needs Checkout') cvs update "$file" ;; *) exit 3 ;; esac editors=`cvs editors "$file"|cut -f-4` nb_editors=`echo $editors|grep -v ^$|wc -l` if [ $nb_editors -eq 0 ] ; then cvs edit "$file" && $EDITOR "$file" else ki="" if [ "$nb_editors" -eq 1 ] ; then ki=`cvs editors "$file"|cut -f2` ; fi if test "$ki" = `whoami` ; then echo "Vous êtes déjà éditeur de ce fichier." sleep 2 $EDITOR "$file" else echo -e "Il y a déjà $nb_editors éditeur(s) de $file !\n$editors" fi fi shift done
PixEye/PixShellScripts
cvs-edit.sh
Shell
agpl-3.0
2,128
""" Application file for the code snippets app. """ from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class SnippetsConfig(AppConfig): """ Application configuration class for the code snippets app. """ name = 'apps.snippets' verbose_name = _('Code snippets')
TamiaLab/carnetdumaker
apps/snippets/apps.py
Python
agpl-3.0
323
{"":{"domain":"ckan","lang":"no","plural-forms":"nplurals=2; plural=(n != 1);"},"Cancel":[null,"Avbryt"],"Edit":[null,"Rediger"],"Follow":[null,"Følg"],"Loading...":[null,"Laster..."],"URL":[null,"URL"],"Unfollow":[null,"Ikke følg"],"Upload a file":[null,"Last opp en fil"]}
sergitrilles/geoctheme
ckanext/geoc_theme/public/base/i18n/no.min.js
JavaScript
agpl-3.0
276
#ifndef __SEGMENTER_H__ #define __SEGMENTER_H__ // includes #include "media_set.h" #include "common.h" // constants #define INVALID_SEGMENT_COUNT UINT_MAX #define SEGMENT_FROM_TIMESTAMP_MARGIN (100) // in case of clipping, a segment may start up to 2 frames before the segment boundary #define MIN_SEGMENT_DURATION (500) #define MAX_SEGMENT_DURATION (600000) // enums enum { MDP_MAX, MDP_MIN, }; // typedefs struct segmenter_conf_s; typedef struct segmenter_conf_s segmenter_conf_t; typedef struct { uint32_t segment_index; uint32_t repeat_count; uint64_t time; uint64_t duration; bool_t discontinuity; } segment_duration_item_t; typedef struct { segment_duration_item_t* items; uint32_t item_count; uint32_t segment_count; uint32_t timescale; uint32_t discontinuities; uint64_t start_time; uint64_t end_time; uint64_t duration; } segment_durations_t; typedef struct { request_context_t* request_context; segmenter_conf_t* conf; media_clip_timing_t timing; uint32_t segment_index; int64_t first_key_frame_offset; vod_array_part_t* key_frame_durations; bool_t allow_last_segment; // no discontinuity uint64_t last_segment_end; // discontinuity uint32_t initial_segment_index; // gop uint64_t time; } get_clip_ranges_params_t; typedef struct { uint32_t min_clip_index; uint32_t max_clip_index; uint64_t clip_time; media_range_t* clip_ranges; uint32_t clip_count; uint32_t clip_relative_segment_index; } get_clip_ranges_result_t; typedef uint32_t (*segmenter_get_segment_count_t)(segmenter_conf_t* conf, uint64_t duration_millis); typedef vod_status_t (*segmenter_get_segment_durations_t)( request_context_t* request_context, segmenter_conf_t* conf, media_set_t* media_set, media_sequence_t* sequence, uint32_t media_type, segment_durations_t* result); struct segmenter_conf_s { // config fields uintptr_t segment_duration; vod_array_t* bootstrap_segments; // array of vod_str_t bool_t align_to_key_frames; intptr_t live_window_duration; segmenter_get_segment_count_t get_segment_count; // last short / last long / last rounded segmenter_get_segment_durations_t get_segment_durations; // estimate / accurate vod_uint_t manifest_duration_policy; uintptr_t gop_look_behind; uintptr_t gop_look_ahead; // derived fields uint32_t parse_type; uint32_t bootstrap_segments_count; uint32_t* bootstrap_segments_durations; uint32_t max_segment_duration; uint32_t max_bootstrap_segment_duration; uint32_t bootstrap_segments_total_duration; uint32_t* bootstrap_segments_start; uint32_t* bootstrap_segments_mid; uint32_t* bootstrap_segments_end; }; typedef struct { request_context_t* request_context; vod_array_part_t* part; int64_t* cur_pos; int64_t offset; } align_to_key_frames_context_t; // init vod_status_t segmenter_init_config(segmenter_conf_t* conf, vod_pool_t* pool); // get segment count modes uint32_t segmenter_get_segment_count_last_short(segmenter_conf_t* conf, uint64_t duration_millis); uint32_t segmenter_get_segment_count_last_long(segmenter_conf_t* conf, uint64_t duration_millis); uint32_t segmenter_get_segment_count_last_rounded(segmenter_conf_t* conf, uint64_t duration_millis); // key frames int64_t segmenter_align_to_key_frames( align_to_key_frames_context_t* context, int64_t offset, int64_t limit); // live window vod_status_t segmenter_get_live_window( request_context_t* request_context, segmenter_conf_t* conf, media_set_t* media_set, bool_t parse_all_clips, get_clip_ranges_result_t* clip_ranges, uint32_t* base_clip_index); // manifest duration uint64_t segmenter_get_total_duration( segmenter_conf_t* conf, media_set_t* media_set, media_sequence_t* sequence, media_sequence_t* sequences_end, uint32_t media_type); // get segment durations modes vod_status_t segmenter_get_segment_durations_estimate( request_context_t* request_context, segmenter_conf_t* conf, media_set_t* media_set, media_sequence_t* sequence, uint32_t media_type, segment_durations_t* result); vod_status_t segmenter_get_segment_durations_accurate( request_context_t* request_context, segmenter_conf_t* conf, media_set_t* media_set, media_sequence_t* sequence, uint32_t media_type, segment_durations_t* result); // get segment index uint32_t segmenter_get_segment_index_no_discontinuity( segmenter_conf_t* conf, uint64_t time_millis); vod_status_t segmenter_get_segment_index_discontinuity( request_context_t* request_context, segmenter_conf_t* conf, uint32_t initial_segment_index, media_clip_timing_t* timing, uint64_t time_millis, uint32_t* result); // get start end ranges vod_status_t segmenter_get_start_end_ranges_gop( get_clip_ranges_params_t* params, get_clip_ranges_result_t* result); vod_status_t segmenter_get_start_end_ranges_no_discontinuity( get_clip_ranges_params_t* params, get_clip_ranges_result_t* result); vod_status_t segmenter_get_start_end_ranges_discontinuity( get_clip_ranges_params_t* params, get_clip_ranges_result_t* result); #endif // __SEGMENTER_H__
kaltura/nginx-vod-module
vod/segmenter.h
C
agpl-3.0
5,007
/* * dmroom.cpp * Staff functions related to rooms. * ____ _ * | _ \ ___ __ _| |_ __ ___ ___ * | |_) / _ \/ _` | | '_ ` _ \/ __| * | _ < __/ (_| | | | | | | \__ \ * |_| \_\___|\__,_|_|_| |_| |_|___/ * * Permission to use, modify and distribute is granted via the * GNU Affero General Public License v3 or later * * Copyright (C) 2007-2021 Jason Mitchell, Randi Mitchell * Contributions by Tim Callahan, Jonathan Hseu * Based on Mordor (C) Brooke Paul, Brett J. Vickers, John P. Freeman * */ #include <dirent.h> // for opendir, readdir, dirent #include <fmt/format.h> // for format #include <libxml/parser.h> // for xmlDocSetRootElement #include <unistd.h> // for unlink #include <boost/algorithm/string/replace.hpp> // for replace_all #include <boost/iterator/iterator_traits.hpp> // for iterator_value<>::type #include <cstdio> // for sprintf #include <cstdlib> // for atoi, exit #include <cstring> // for strcmp, strlen, strcpy #include <ctime> // for time, ctime, time_t #include <deque> // for _Deque_iterator #include <iomanip> // for operator<<, setw #include <iostream> // for operator<<, char_traits #include <list> // for operator==, list, _Lis... #include <map> // for operator==, map, map<>... #include <string> // for string, operator== #include <string_view> // for operator==, string_view #include <utility> // for pair #include "area.hpp" // for Area, MapMarker, AreaZone #include "async.hpp" // for Async, AsyncExternal #include "catRef.hpp" // for CatRef #include "catRefInfo.hpp" // for CatRefInfo #include "cmd.hpp" // for cmd #include "commands.hpp" // for getFullstrText, cmdNoAuth #include "config.hpp" // for Config, gConfig, Deity... #include "deityData.hpp" // for DeityData #include "dice.hpp" // for Dice #include "dm.hpp" // for dmAddMob, dmAddObj #include "effects.hpp" // for EffectInfo, Effects #include "factions.hpp" // for Faction #include "flags.hpp" // for R_TRAINING_ROOM, R_SHO... #include "free_crt.hpp" // for free_crt #include "global.hpp" // for CreatureClass, Creatur... #include "hooks.hpp" // for Hooks #include "lasttime.hpp" // for crlasttime #include <libxml/xmlstring.h> // for BAD_CAST #include "location.hpp" // for Location #include "monType.hpp" // for getHitdice, getName #include "money.hpp" // for Money, GOLD #include "mudObjects/areaRooms.hpp" // for AreaRoom #include "mudObjects/creatures.hpp" // for Creature #include "mudObjects/exits.hpp" // for Exit, getDir, getDirName #include "mudObjects/monsters.hpp" // for Monster #include "mudObjects/objects.hpp" // for Object #include "mudObjects/players.hpp" // for Player #include "mudObjects/rooms.hpp" // for BaseRoom, ExitList #include "mudObjects/uniqueRooms.hpp" // for UniqueRoom #include "os.hpp" // for merror #include "paths.hpp" // for checkDirExists, AreaRoom #include "proc.hpp" // for ChildType, ChildType::... #include "property.hpp" // for Property #include "proto.hpp" // for log_immort, low, needU... #include "raceData.hpp" // for RaceData #include "range.hpp" // for Range #include "server.hpp" // for Server, gServer #include "size.hpp" // for getSizeName, getSize #include "startlocs.hpp" // for StartLoc #include "stats.hpp" // for Stat #include "swap.hpp" // for SwapRoom #include "track.hpp" // for Track #include "traps.hpp" // for TRAP_ACID, TRAP_ALARM #include "utils.hpp" // for MAX, MIN #include "wanderInfo.hpp" // for WanderInfo #include "xml.hpp" // for loadRoom, loadMonster //********************************************************************* // checkTeleportRange //********************************************************************* void checkTeleportRange(const Player* player, const CatRef& cr) { // No warning for the test range if(cr.isArea("test")) return; const CatRefInfo* cri = gConfig->getCatRefInfo(cr.area); if(!cri) { player->printColor("^yNo CatRefInfo zone found for this room's area. Contact a dungeonmaster to fix this.\n"); return; } if(cr.id > cri->getTeleportWeight()) { player->printColor("^yThis room is outside the CatRefInfo zone's teleport range.\n"); return; } } //********************************************************************* // isCardinal //********************************************************************* bool isCardinal(std::string_view xname) { return( xname == "north" || xname == "east" || xname == "south" || xname == "west" || xname == "northeast" || xname == "northwest" || xname == "southeast" || xname == "southwest" ); } //********************************************************************* // wrapText //********************************************************************* std::string wrapText(std::string_view text, int wrap) { if(text.empty()) return(""); std::string wrapped = ""; int len = text.length(), i=0, sp=0, spLast=0, spLen=0; char ch, chLast; // find our starting position while(text.at(i) == ' ' || text.at(i) == '\n' || text.at(i) == '\r') i++; for(; i < len; i++) { ch = text.at(i); // convert linebreaks to spaces if(ch == '\r') ch = ' '; if(ch == '\n') ch = ' '; // skiping 2x spacing (or greater) if(ch == ' ' && chLast == ' ') { do { i++; } while(i+1 < len && (text.at(i+1) == ' ' || text.at(i+1) == '\n' || text.at(i+1) == '\r')); if(i < len) ch = text.at(i); } // don't add trailing spaces if(ch != ' ' || i+1 < len) { // If there is color in the room description, the color characters // shouldn't count toward string length. if(ch == '^') spLen += 2; // wrap if(ch == ' ') { // We went over! spLast points to the last non-overboard space. if(wrap <= (sp - spLen)) { wrapped.replace(spLast, 1, "\n"); spLen = spLast; } spLast = sp; } wrapped += ch; sp++; chLast = ch; } } return(wrapped); } //********************************************************************* // expand_exit_name //********************************************************************* std::string expand_exit_name(const std::string &name) { if(name == "n") return("north"); if(name == "s") return("south"); if(name == "e") return("east"); if(name == "w") return("west"); if(name == "sw") return("southwest"); if(name == "nw") return("northwest"); if(name == "se") return("southeast"); if(name == "ne") return("northeast"); if(name == "d") return("door"); if(name == "o") return("out"); if(name == "p") return("passage"); if(name == "t") return("trap door"); if(name == "a") return("arch"); if(name == "g") return("gate"); if(name == "st") return("stairs"); return(name); } //********************************************************************* // opposite_exit_name //********************************************************************* std::string opposite_exit_name(const std::string &name) { if(name == "south") return("north"); if(name == "north") return("south"); if(name == "west") return("east"); if(name == "east") return("west"); if(name == "northeast") return("southwest"); if(name == "southeast") return("northwest"); if(name == "northwest") return("southeast"); if(name == "southwest") return("northeast"); if(name == "up") return("down"); if(name == "down") return("up"); return(name); } //********************************************************************* // dmPurge //********************************************************************* // This function allows staff to purge a room of all its objects and // monsters. int dmPurge(Player* player, cmd* cmnd) { BaseRoom* room = player->getRoomParent(); if(!player->canBuildMonsters() && !player->canBuildObjects()) return(cmdNoAuth(player)); if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Error: this room is out of your range; you cannot *purge here.\n"); return(0); } room->purge(false); player->print("Purged.\n"); if(!player->isDm()) log_immort(false,player, "%s purged room %s.\n", player->getCName(), player->getRoomParent()->fullName().c_str()); return(0); } //********************************************************************* // dmEcho //********************************************************************* // This function allows a staff specified by the socket descriptor in // the first parameter to echo the rest of their command line to all // the other people in the room. int dmEcho(Player* player, cmd* cmnd) { if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Error: room number not in any of your allotted ranges.\n"); return(0); } std::string text = getFullstrText(cmnd->fullstr, 1); if(text.empty() || Pueblo::is(text)) { player->print("Echo what?\n"); return(0); } if(!player->isCt()) broadcast(isStaff, "^G*** %s (%s) echoed: %s", player->getCName(), player->getRoomParent()->fullName().c_str(), text.c_str()); broadcast(nullptr, player->getRoomParent(), "%s", text.c_str()); return(0); } //********************************************************************* // dmReloadRoom //********************************************************************* // This function allows a staff to reload a room from disk. int dmReloadRoom(Player* player, cmd* cmnd) { if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Error: this room is out of your range; you cannot reload this room.\n"); return(0); } if(gServer->reloadRoom(player->getRoomParent())) player->print("Ok.\n"); else player->print("Reload failed.\n"); return(0); } //********************************************************************* // resetPerms //********************************************************************* // This function allows a staff to reset perm timeouts in the room int dmResetPerms(Player* player, cmd* cmnd) { std::map<int, crlasttime>::iterator it; crlasttime* crtm=nullptr; std::map<int, long> tempMonsters; std::map<int, long> tempObjects; UniqueRoom *room = player->getUniqueRoomParent(); //long temp_obj[10], temp_mon[10]; if(!needUniqueRoom(player)) return(0); if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Error: this room is out of your range; you cannot reload this room.\n"); return(0); } for(it = room->permMonsters.begin(); it != room->permMonsters.end() ; it++) { crtm = &(*it).second; tempMonsters[(*it).first] = crtm->interval; crtm->ltime = time(nullptr); crtm->interval = 0; } for(it = room->permObjects.begin(); it != room->permObjects.end() ; it++) { crtm = &(*it).second; tempObjects[(*it).first] = crtm->interval; crtm->ltime = time(nullptr); crtm->interval = 0; } player->print("Permanent object and creature timeouts reset.\n"); room->addPermCrt(); for(it = room->permMonsters.begin(); it != room->permMonsters.end() ; it++) { crtm = &(*it).second; crtm->interval = tempMonsters[(*it).first]; crtm->ltime = time(nullptr); } for(it = room->permObjects.begin(); it != room->permObjects.end() ; it++) { crtm = &(*it).second; crtm->interval = tempObjects[(*it).first]; crtm->ltime = time(nullptr); } log_immort(true, player, "%s reset perm timeouts in room %s\n", player->getCName(), player->getRoomParent()->fullName().c_str()); if(gServer->resaveRoom(room->info) < 0) player->print("Room fail saved.\n"); else player->print("Room saved.\n"); return(0); } //********************************************************************* // stat_rom_exits //********************************************************************* // Display information on room given to staff. void stat_rom_exits(Creature* player, BaseRoom* room) { char str[1024], temp[25], tempstr[32]; int i=0, flagcount=0; UniqueRoom* uRoom = room->getAsUniqueRoom(); if(room->exits.empty()) return; player->print("Exits:\n"); for(Exit* exit : room->exits) { if(!exit->getLevel()) player->print(" %s: ", exit->getCName()); else player->print(" %s(L%d): ", exit->getCName(), exit->getLevel()); if(!exit->target.mapmarker.getArea()) player->printColor("%s ", exit->target.room.str(uRoom ? uRoom->info.area : "", 'y').c_str()); else player->print(" A:%d X:%d Y:%d Z:%d ", exit->target.mapmarker.getArea(), exit->target.mapmarker.getX(), exit->target.mapmarker.getY(), exit->target.mapmarker.getZ()); *str = 0; strcpy(str, "Flags: "); for(i=0; i<MAX_EXIT_FLAGS; i++) { if(exit->flagIsSet(i)) { sprintf(tempstr, "%s(%d), ", gConfig->getXFlag(i).c_str(), i+1); strcat(str, tempstr); flagcount++; } } if(flagcount) { str[strlen(str) - 2] = '.'; str[strlen(str) - 1] = 0; } if(flagcount) player->print("%s", str); if(exit->flagIsSet(X_LOCKABLE)) { player->print(" Key#: %d ", exit->getKey()); if(!exit->getKeyArea().empty()) player->printColor(" Area: ^y%s^x ", exit->getKeyArea().c_str()); } if(exit->flagIsSet(X_TOLL_TO_PASS)) player->print(" Toll: %d ", exit->getToll()); player->print("\n"); if(!exit->getDescription().empty()) player->print(" Description: \"%s\"\n", exit->getDescription().c_str()); if( (exit->flagIsSet(X_CAN_LOOK) || exit->flagIsSet(X_LOOK_ONLY)) && exit->flagIsSet(X_NO_SCOUT) ) player->printColor("^rExit is flagged as no-scout, but it flagged as lookable.\n"); if(exit->flagIsSet(X_PLEDGE_ONLY)) { for(i=1; i<15; i++) if(exit->flagIsSet(i+40)) { sprintf(temp, "Clan: %d, ",i); strcat(str, temp); } player->print(" Clan: %s\n", temp); } if(exit->flagIsSet(X_PORTAL)) { player->printColor(" Owner: ^c%s^x Uses: ^c%d^x\n", exit->getPassPhrase().c_str(), exit->getKey()); } else if(!exit->getPassPhrase().empty()) { player->print(" Passphrase: \"%s\"\n", exit->getPassPhrase().c_str()); if(exit->getPassLanguage()) player->print(" Passlang: %s\n", get_language_adj(exit->getPassLanguage())); } if(!exit->getEnter().empty()) player->print(" OnEnter: \"%s\"\n", exit->getEnter().c_str()); if(!exit->getOpen().empty()) player->print(" OnOpen: \"%s\"\n", exit->getOpen().c_str()); if(exit->getSize() || exit->getDirection()) { if(exit->getSize()) player->print(" Size: %s", getSizeName(exit->getSize()).c_str()); if(exit->getDirection()) { player->print(" Direction: %s", getDirName(exit->getDirection()).c_str()); if(getDir(exit->getName()) != NoDirection) player->printColor("\n^rThis exit has a direction set, but the exit is a cardinal exit."); } player->print("\n"); } if(!exit->effects.effectList.empty()) player->printColor(" Effects:\n%s", exit->effects.getEffectsString(player).c_str()); player->printColor("%s", exit->hooks.display().c_str()); } } //********************************************************************* // trainingFlagSet //********************************************************************* bool trainingFlagSet(const BaseRoom* room, const TileInfo *tile, const AreaZone *zone, int flag) { return( (room && room->flagIsSet(flag)) || (tile && tile->flagIsSet(flag)) || (zone && zone->flagIsSet(flag)) ); } //********************************************************************* // whatTraining //********************************************************************* // determines what class can train here int whatTraining(const BaseRoom* room, const TileInfo *tile, const AreaZone *zone, int extra) { int i = 0; if(R_TRAINING_ROOM - 1 == extra || trainingFlagSet(room, tile, zone, R_TRAINING_ROOM - 1)) i += 16; if(R_TRAINING_ROOM == extra || trainingFlagSet(room, tile, zone, R_TRAINING_ROOM)) i += 8; if(R_TRAINING_ROOM + 1 == extra || trainingFlagSet(room, tile, zone, R_TRAINING_ROOM + 1)) i += 4; if(R_TRAINING_ROOM + 2 == extra || trainingFlagSet(room, tile, zone, R_TRAINING_ROOM + 2)) i += 2; if(R_TRAINING_ROOM + 3 == extra || trainingFlagSet(room, tile, zone, R_TRAINING_ROOM + 3)) i += 1; return(i > static_cast<int>(CreatureClass::CLASS_COUNT) - 1 ? 0 : i); } bool BaseRoom::hasTraining() const { return(whatTraining() != CreatureClass::NONE); } CreatureClass BaseRoom::whatTraining(int extra) const { return(static_cast<CreatureClass>(::whatTraining(this, (const TileInfo*)nullptr, (const AreaZone*)nullptr, extra))); } //********************************************************************* // showRoomFlags //********************************************************************* void showRoomFlags(const Player* player, const BaseRoom* room, const TileInfo *tile, const AreaZone *zone) { bool flags=false; int i=0; std::ostringstream oStr; oStr << "^@Flags set: "; for(; i<MAX_ROOM_FLAGS; i++) { if(i >=2 && i <= 6) // skips training flags continue; if( (room && room->flagIsSet(i)) || (tile && tile->flagIsSet(i)) || (zone && zone->flagIsSet(i)) ) { if(flags) oStr << ", "; flags = true; oStr << gConfig->getRFlag(i) << "(" << (int)(i+1) << ")"; } } if(!flags) oStr << "None"; oStr << ".^x\n"; i = whatTraining(room, tile, zone, 0); if(i) oStr << "^@Training: " << get_class_string(i) << "^x\n"; player->printColor("%s", oStr.str().c_str()); // inform user of redundant flags if(room && room->getAsConstUniqueRoom()) { bool hasTraining = room->hasTraining(); bool limboOrCoven = room->flagIsSet(R_LIMBO) || room->flagIsSet(R_VAMPIRE_COVEN); if(room->flagIsSet(R_NO_TELEPORT)) { if( limboOrCoven || room->flagIsSet(R_JAIL) || room->flagIsSet(R_ETHEREAL_PLANE) || hasTraining ) player->printColor("^rThis room does not need flag 13-No Teleport set.\n"); } if(room->flagIsSet(R_NO_SUMMON_OUT)) { if( room->flagIsSet(R_IS_STORAGE_ROOM) || room->flagIsSet(R_LIMBO) ) player->printColor("^rThis room does not need flag 29-No Summon Out set.\n"); } if(room->flagIsSet(R_NO_LOGIN)) { if( room->flagIsSet(R_LOG_INTO_TRAP_ROOM) || hasTraining ) player->printColor("^rThis room does not need flag 34-No Log set.\n"); } if(room->flagIsSet(R_NO_CLAIR_ROOM)) { if(limboOrCoven) player->printColor("^rThis room does not need flag 43-No Clair set.\n"); } if(room->flagIsSet(R_NO_TRACK_TO)) { if( limboOrCoven || room->flagIsSet(R_IS_STORAGE_ROOM) || room->flagIsSet(R_NO_TELEPORT) || hasTraining ) player->printColor("^rThis room does not need flag 52-No Track To set.\n"); } if(room->flagIsSet(R_NO_SUMMON_TO)) { if( limboOrCoven || room->flagIsSet(R_NO_TELEPORT) || room->flagIsSet(R_ONE_PERSON_ONLY) || hasTraining ) player->printColor("^rThis room does not need flag 54-No Summon To set.\n"); } if(room->flagIsSet(R_NO_TRACK_OUT)) { if( room->flagIsSet(R_LIMBO) || room->flagIsSet(R_ETHEREAL_PLANE) ) player->printColor("^rThis room does not need flag 54-No Summon To set.\n"); } if(room->flagIsSet(R_OUTLAW_SAFE)) { if( limboOrCoven || hasTraining ) player->printColor("^rThis room does not need flag 57-Outlaw Safe set.\n"); } if(room->flagIsSet(R_LOG_INTO_TRAP_ROOM)) { if(hasTraining) player->printColor("^rThis room does not need flag 63-Log To Trap Exit set.\n"); } if(room->flagIsSet(R_LIMBO)) { if(room->flagIsSet(R_POST_OFFICE)) player->printColor("^rThis room does not need flag 11-Post Office set.\n"); if(room->flagIsSet(R_FAST_HEAL)) player->printColor("^rThis room does not need flag 14-Fast Heal set.\n"); if(room->flagIsSet(R_NO_POTION)) player->printColor("^rThis room does not need flag 32-No Potion set.\n"); if(room->flagIsSet(R_NO_CAST_TELEPORT)) player->printColor("^rThis room does not need flag 38-No Cast Teleport set.\n"); if(room->flagIsSet(R_NO_FLEE)) player->printColor("^rThis room does not need flag 44-No Flee set.\n"); if(room->flagIsSet(R_BANK)) player->printColor("^rThis room does not need flag 58-Bank set.\n"); if(room->flagIsSet(R_MAGIC_MONEY_MACHINE)) player->printColor("^rThis room does not need flag 59-Magic Money Machine set.\n"); } } } //********************************************************************* // stat_rom //********************************************************************* int stat_rom(Player* player, AreaRoom* room) { std::list<AreaZone*>::iterator it; AreaZone* zone=nullptr; TileInfo* tile=nullptr; if(!player->checkBuilder(nullptr)) return(0); if(player->getClass() == CreatureClass::CARETAKER) log_immort(false,player, "%s statted room %s.\n", player->getCName(), player->getRoomParent()->fullName().c_str()); player->print("Room: %s %s\n\n", room->area->name.c_str(), room->fullName().c_str()); tile = room->area->getTile(room->area->getTerrain(nullptr, &room->mapmarker, 0, 0, 0, true), false); for(it = room->area->zones.begin() ; it != room->area->zones.end() ; it++) { zone = (*it); if(zone->inside(room->area, &room->mapmarker)) { player->printColor("^yZone:^x %s\n", zone->name.c_str()); if(zone->wander.getTraffic()) { zone->wander.show(player); } else { player->print(" No monsters come in this zone.\n"); } player->print("\n"); } } if(room->getSize()) player->printColor("Size: ^y%s\n", getSizeName(room->getSize()).c_str()); if(tile->wander.getTraffic()) tile->wander.show(player); player->print("Terrain: %c\n", tile->getDisplay()); if(room->isWater()) player->printColor("Water: ^gyes\n"); if(room->isRoad()) player->printColor("Road: ^gyes\n"); player->printColor("Generic Room: %s\n", room->canSave() ? "^rNo" : "^gYes"); if(room->unique.id) { player->printColor("Links to unique room ^y%s^x.\n", room->unique.str().c_str()); player->printColor("needsCompass: %s^x decCompass: %s", room->getNeedsCompass() ? "^gYes" : "^rNo", room->getDecCompass() ? "^gYes" : "^rNo"); } player->print("\n"); showRoomFlags(player, room, nullptr, nullptr); if(!room->effects.effectList.empty()) player->printColor("Effects:\n%s", room->effects.getEffectsString(player).c_str()); player->printColor("%s", room->hooks.display().c_str()); stat_rom_exits(player, room); return(0); } //********************************************************************* // validateShop //********************************************************************* void validateShop(const Player* player, const UniqueRoom* shop, const UniqueRoom* storage) { // basic checks if(!shop) { player->printColor("^rThe shop associated with this storage room does not exist.\n"); return; } if(!storage) { player->printColor("^rThe storage room associated with this shop does not exist.\n"); return; } if(shop->info == storage->info) { player->printColor("^rThe shop and the storage room cannot be the same room. Set the shop's trap exit appropriately.\n"); return; } CatRef cr = shopStorageRoom(shop); if(shop->info == cr) { player->printColor("^rThe shop and the storage room cannot be the same room. Set the shop's trap exit appropriately.\n"); return; } std::string name = "Storage: "; name += shop->getName(); if(cr != storage->info) player->printColor("^rThe shop's storage room of %s does not match the storage room %s.\n", cr.str().c_str(), storage->info.str().c_str()); if(storage->getTrapExit() != shop->info) player->printColor("^yThe storage room's trap exit of %s does not match the shop room %s.\n", storage->info.str().c_str(), shop->info.str().c_str()); if(!shop->flagIsSet(R_SHOP)) player->printColor("^rThe shop's flag 1-Shoppe is not set.\n"); if(!storage->flagIsSet(R_SHOP_STORAGE)) player->printColor("^rThe storage room's flag 97-Shop Storage is not set.\n"); // what DOESN'T the storage room need? if(storage->flagIsSet(R_NO_LOGIN)) player->printColor("^rThe storage room does not need flag 34-No Log set.\n"); if(storage->flagIsSet(R_LOG_INTO_TRAP_ROOM)) player->printColor("^rThe storage room does not need flag 63-Log To Trap Exit set.\n"); if(storage->flagIsSet(R_NO_TELEPORT)) player->printColor("^rThe storage room does not need flag 13-No Teleport set.\n"); if(storage->flagIsSet(R_NO_SUMMON_TO)) player->printColor("^rThe storage room does not need flag 54-No Summon To set.\n"); if(storage->flagIsSet(R_NO_TRACK_TO)) player->printColor("^rThe storage room does not need flag 52-No Track To set.\n"); if(storage->flagIsSet(R_NO_CLAIR_ROOM)) player->printColor("^rThe storage room does not need flag 43-No Clair set.\n"); if(storage->exits.empty()) { player->printColor("^yThe storage room does not have an out exit pointing to the shop.\n"); } else { const Exit* exit = storage->exits.front(); if( exit->target.room != shop->info || exit->getName() != "out") player->printColor("^yThe storage room does not have an out exit pointing to the shop.\n"); else if(storage->exits.size() > 1) player->printColor("^yThe storage room has more than one exit - it only needs one out exit pointing to the shop.\n"); } } //********************************************************************* // stat_rom //********************************************************************* int stat_rom(Player* player, UniqueRoom* room) { std::map<int, crlasttime>::iterator it; crlasttime* crtm=nullptr; CatRef cr; Monster* monster=nullptr; Object* object=nullptr; UniqueRoom* shop=nullptr; time_t t = time(nullptr); if(!player->checkBuilder(room)) return(0); if(player->getClass() == CreatureClass::CARETAKER) log_immort(false,player, "%s statted room %s.\n", player->getCName(), player->getRoomParent()->fullName().c_str()); player->printColor("Room: %s", room->info.str("", 'y').c_str()); if(gConfig->inSwapQueue(room->info, SwapRoom, true)) player->printColor(" ^eThis room is being swapped."); player->print("\nTimes People have entered this room: %d\n", room->getBeenHere()); player->print("Name: %s\n", room->getCName()); Property *p = gConfig->getProperty(room->info); if(p) { player->printColor("Property Belongs To: ^y%s^x\nProperty Type: ^y%s\n", p->getOwner().c_str(), p->getTypeStr().c_str()); } if(player->isCt()) { if(room->last_mod[0]) player->printColor("^cLast modified by: %s on %s\n", room->last_mod, stripLineFeeds(room->lastModTime)); if(room->lastPly[0]) player->printColor("^cLast player here: %s on %s\n", room->lastPly, stripLineFeeds(room->lastPlyTime)); } else player->print("\n"); if(room->getSize()) player->printColor("Size: ^y%s\n", getSizeName(room->getSize()).c_str()); if(room->getRoomExperience()) player->print("Experience for entering this room: %d\n", room->getRoomExperience()); if(!room->getFaction().empty()) player->printColor("Faction: ^g%s^x\n", room->getFaction().c_str()); if(!room->getFishingStr().empty()) player->printColor("Fishing: ^g%s^x\n", room->getFishingStr().c_str()); if(room->getMaxMobs() > 0) player->print("Max mob allowance: %d\n", room->getMaxMobs()); room->wander.show(player, room->info.area); player->print("\n"); player->print("Perm Objects:\n"); for(it = room->permObjects.begin(); it != room->permObjects.end() ; it++) { crtm = &(*it).second; loadObject((*it).second.cr, &object); player->printColor("^y%2d) ^x%14s ^y::^x %-30s ^yInterval:^x %-5d ^yTime Until Spawn:^x %-5d", (*it).first+1, crtm->cr.str("", 'y').c_str(), object ? object->getCName() : "", crtm->interval, MAX<long>(0, crtm->ltime + crtm->interval-t)); if(room->flagIsSet(R_SHOP_STORAGE) && object) player->printColor(" ^yCost:^x %s", object->value.str().c_str()); player->print("\n"); // warning about deeds in improper areas if(object && object->deed.low.id && !object->deed.isArea(room->info.area)) player->printColor(" ^YCaution:^x this object's deed area does not match the room's area.\n"); if(object) { delete object; object = nullptr; } } player->print("\n"); player->print("Perm Monsters:\n"); for(it = room->permMonsters.begin(); it != room->permMonsters.end() ; it++) { crtm = &(*it).second; loadMonster((*it).second.cr, &monster); player->printColor("^m%2d) ^x%14s ^m::^x %-30s ^mInterval:^x %d ^yTime until Spawn:^x %-5d\n", (*it).first+1, crtm->cr.str("", 'm').c_str(), monster ? monster->getCName() : "", crtm->interval, MAX<long>(0, crtm->ltime + crtm->interval-t)); if(monster) { free_crt(monster); monster = nullptr; } } player->print("\n"); if(!room->track.getDirection().empty() && room->flagIsSet(R_PERMENANT_TRACKS)) player->print("Perm Tracks: %s.\n", room->track.getDirection().c_str()); if(room->getLowLevel() || room->getHighLevel()) { player->print("Level Boundary: "); if(room->getLowLevel()) player->print("%d+ level ", room->getLowLevel()); if(room->getHighLevel()) player->print("%d- level ", room->getHighLevel()); player->print("\n"); } if( room->flagIsSet(R_LOG_INTO_TRAP_ROOM) || room->flagIsSet(R_SHOP_STORAGE) || room->hasTraining() ) { if(room->getTrapExit().id) player->print("Players will relog into room %s from here.\n", room->getTrapExit().str(room->info.area).c_str()); else player->printColor("^rTrap exit needs to be set to %s room number.\n", room->flagIsSet(R_SHOP_STORAGE) ? "shop" : "relog"); } if( room->getSize() == NO_SIZE && ( room->flagIsSet(R_INDOORS) || room->flagIsSet(R_UNDERGROUND) ) ) player->printColor("^yThis room does not have a size set.\n"); checkTeleportRange(player, room->info); // isShopValid if(room->flagIsSet(R_SHOP)) { cr = shopStorageRoom(room); player->print("Shop storage room: %s (%s)\n", cr.str().c_str(), cr.id == room->info.id+1 && cr.isArea(room->info.area) ? "default" : "trapexit"); if(room->getFaction().empty() && room->info.area != "shop") player->printColor("^yThis shop does not have a faction set.\n"); loadRoom(cr, &shop); validateShop(player, room, shop); } else if(room->flagIsSet(R_PAWN_SHOP)) { if(room->getFaction().empty()) player->printColor("^yThis pawn shop does not have a faction set.\n"); } if(room->flagIsSet(R_SHOP_STORAGE)) { loadRoom(room->getTrapExit(), &shop); validateShop(player, shop, room); } if(room->getTrap()) { if(room->getTrapWeight()) player->print("Trap weight: %d/%d lbs\n", room->getWeight(), room->getTrapWeight()); player->print("Trap type: "); switch(room->getTrap()) { case TRAP_PIT: player->print("Pit Trap (exit rm %s)\n", room->getTrapExit().str(room->info.area).c_str()); break; case TRAP_DART: player->print("Poison Dart Trap\n"); break; case TRAP_BLOCK: player->print("Falling Block Trap\n"); break; case TRAP_MPDAM: player->print("MP Damage Trap\n"); break; case TRAP_RMSPL: player->print("Negate Spell Trap\n"); break; case TRAP_NAKED: player->print("Naked Trap\n"); break; case TRAP_TPORT: player->print("Teleport Trap\n"); break; case TRAP_ARROW: player->print("Arrow Trap\n"); break; case TRAP_SPIKED_PIT: player->print("Spiked Pit Trap (exit rm %s)\n", room->getTrapExit().str(room->info.area).c_str()); break; case TRAP_WORD: player->print("Word of Recall Trap\n"); break; case TRAP_FIRE: player->print("Fire Trap\n"); break; case TRAP_FROST: player->print("Frost Trap\n"); break; case TRAP_ELEC: player->print("Electricity Trap\n"); break; case TRAP_ACID: player->print("Acid Trap\n"); break; case TRAP_ROCKS: player->print("Rockslide Trap\n"); break; case TRAP_ICE: player->print("Icicle Trap\n"); break; case TRAP_SPEAR: player->print("Spear Trap\n"); break; case TRAP_CROSSBOW: player->print("Crossbow Trap\n"); break; case TRAP_GASP: player->print("Poison Gas Trap\n"); break; case TRAP_GASB: player->print("Blinding Gas Trap\n"); break; case TRAP_GASS: player->print("Stun Gas Trap\n"); break; case TRAP_MUD: player->print("Mud Trap\n"); break; case TRAP_DISP: player->print("Room Displacement Trap (exit rm %s)\n", room->getTrapExit().str(room->info.area).c_str()); break; case TRAP_FALL: player->print("Deadly Fall Trap (exit rm %s)\n", room->getTrapExit().str(room->info.area).c_str()); break; case TRAP_CHUTE: player->print("Chute Trap (exit rm %s)\n", room->getTrapExit().str(room->info.area).c_str()); break; case TRAP_ALARM: player->print("Alarm Trap (guard rm %s)\n", room->getTrapExit().str(room->info.area).c_str()); break; case TRAP_BONEAV: player->print("Bone Avalanche Trap (exit rm %s)\n", room->getTrapExit().str(room->info.area).c_str()); break; case TRAP_PIERCER: player->print("Piercer trap (%d piercers)\n", room->getTrapStrength()); break; case TRAP_ETHEREAL_TRAVEL: player->print("Ethereal travel trap.\n"); break; case TRAP_WEB: player->print("Sticky spider web trap.\n"); break; default: player->print("Invalid trap #\n"); break; } } if(room->flagIsSet(R_CAN_SHOPLIFT)) player->print("Store guardroom: rm %s\n", cr.str(room->info.area).c_str()); showRoomFlags(player, room, nullptr, nullptr); if(!room->effects.effectList.empty()) player->printColor("Effects:\n%s", room->effects.getEffectsString(player).c_str()); player->printColor("%s", room->hooks.display().c_str()); stat_rom_exits(player, room); return(0); } //********************************************************************* // dmAddRoom //********************************************************************* // This function allows staff to add a new, empty room to the current // database of rooms. int dmAddRoom(Player* player, cmd* cmnd) { UniqueRoom *newRoom=nullptr; char file[80]; int i=1; if(!strcmp(cmnd->str[1], "c") && (cmnd->num > 1)) { dmAddMob(player, cmnd); return(0); } if(!strcmp(cmnd->str[1], "o") && (cmnd->num > 1)) { dmAddObj(player, cmnd); return(0); } CatRef cr; bool extra = !strcmp(cmnd->str[1], "r"); getCatRef(getFullstrText(cmnd->fullstr, extra ? 2 : 1), &cr, player); if(cr.id < 1) { player->print("Index error: please specify room number.\n"); return(0); } if(!player->checkBuilder(cr, false)) { player->print("Error: Room number not inside any of your alotted ranges.\n"); return(0); } if(gConfig->moveRoomRestrictedArea(cr.area)) { player->print("Error: ""%s"" is a restricted range. You cannot create unique rooms in that area.\n"); return(0); } Path::checkDirExists(cr.area, roomPath); if(!strcmp(cmnd->str[extra ? 3 : 2], "loop")) i = MAX(1, MIN(100, (int)cmnd->val[extra ? 3 : 2])); for(; i; i--) { if(!player->checkBuilder(cr, false)) { player->print("Error: Room number not inside any of your alotted ranges.\n"); return(0); } sprintf(file, "%s", roomPath(cr)); if(file_exists(file)) { player->print("Room already exists.\n"); return(0); } newRoom = new UniqueRoom; if(!newRoom) merror("dmAddRoom", FATAL); newRoom->info = cr; newRoom->setFlag(R_CONSTRUCTION); newRoom->setName("New Room"); if(newRoom->saveToFile(0) < 0) { player->print("Write failed.\n"); return(0); } delete newRoom; log_immort(true, player, "%s created room %s.\n", player->getCName(), cr.str().c_str()); player->print("Room %s created.\n", cr.str().c_str()); checkTeleportRange(player, cr); cr.id++; } return(0); } //********************************************************************* // dmSetRoom //********************************************************************* // This function allows staff to set a characteristic of a room. int dmSetRoom(Player* player, cmd* cmnd) { BaseRoom *room = player->getRoomParent(); int a=0, num=0; CatRef cr; if(cmnd->num < 3) { player->print("Syntax: *set r [option] [<value>]\n"); return(0); } if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Error: Room number not inside any of your alotted ranges.\n"); return(0); } switch(low(cmnd->str[2][0])) { case 'b': if(!player->inUniqueRoom()) { player->print("Error: You need to be in a unique room to do that.\n"); return(0); } if(low(cmnd->str[2][1]) == 'l') { player->getUniqueRoomParent()->setLowLevel(cmnd->val[2]); player->print("Low level boundary %d\n", player->getUniqueRoomParent()->getLowLevel()); } else if(low(cmnd->str[2][1]) == 'h') { player->getUniqueRoomParent()->setHighLevel(cmnd->val[2]); player->print("Upper level boundary %d\n", player->getUniqueRoomParent()->getHighLevel()); } break; case 'd': if(!player->inAreaRoom()) { player->print("Error: You need to be in an area room to do that.\n"); return(0); } if(!player->getAreaRoomParent()->unique.id) { player->print("Error: The area room must have the unique field set [*set r unique #].\n"); return(0); } player->getAreaRoomParent()->setDecCompass(!player->getAreaRoomParent()->getDecCompass()); player->printColor("DecCompass toggled, set to %s^x.\n", player->getAreaRoomParent()->getDecCompass() ? "^gYes" : "^rNo"); log_immort(true, player, "%s set decCompass to %s in room %s.\n", player->getCName(), player->getAreaRoomParent()->getDecCompass() ? "true" : "false", room->fullName().c_str()); break; case 'e': if(cmnd->str[2][1] == 'f') { if(cmnd->num < 4) { player->print("Set what effect to what?\n"); return(0); } long duration = -1; int strength = 1; std::string txt = getFullstrText(cmnd->fullstr, 4); if(!txt.empty()) duration = atoi(txt.c_str()); txt = getFullstrText(cmnd->fullstr, 5); if(!txt.empty()) strength = atoi(txt.c_str()); if(duration > EFFECT_MAX_DURATION || duration < -1) { player->print("Duration must be between -1 and %d.\n", EFFECT_MAX_DURATION); return(0); } if(strength < 0 || strength > EFFECT_MAX_STRENGTH) { player->print("Strength must be between 0 and %d.\n", EFFECT_MAX_STRENGTH); return(0); } std::string effectStr = cmnd->str[3]; EffectInfo* toSet = nullptr; if((toSet = room->getExactEffect(effectStr))) { // We have an existing effect we're modifying if(duration == 0) { // Duration is 0, so remove it room->removeEffect(toSet, true); player->print("Effect '%s' (room) removed.\n", effectStr.c_str()); } else { // Otherwise modify as appropriate toSet->setDuration(duration); if(strength != -1) toSet->setStrength(strength); player->print("Effect '%s' (room) set to duration %d and strength %d.\n", effectStr.c_str(), toSet->getDuration(), toSet->getStrength()); } break; } else { // No existing effect, add a new one if(strength == -1) strength = 1; if(room->addEffect(effectStr, duration, strength, nullptr, true) != nullptr){ player->print("Effect '%s' (room) added with duration %d and strength %d.\n", effectStr.c_str(), duration, strength); } else { player->print("Unable to add effect '%s' (room)\n", effectStr.c_str()); } break; } } else if(cmnd->str[2][1] == 'x') { if(!player->inUniqueRoom()) { player->print("Error: You need to be in a unique room to do that.\n"); return(0); } player->getUniqueRoomParent()->setRoomExperience(cmnd->val[2]); player->print("Room experience set to %d.\n", player->getUniqueRoomParent()->getRoomExperience()); log_immort(true, player, "%s set roomExp to %d in room %s.\n", player->getCName(), player->getUniqueRoomParent()->getRoomExperience(), room->fullName().c_str()); } else { player->print("Invalid option.\n"); return(0); } break; case 'f': if(low(cmnd->str[2][1]) == 'i') { if(!strcmp(cmnd->str[3], "")) { player->getUniqueRoomParent()->setFishing(""); player->print("Fishing list cleared.\n"); log_immort(true, player, "%s cleared fishing list in room %s.\n", player->getCName(), room->fullName().c_str()); } else { const Fishing* list = gConfig->getFishing(cmnd->str[3]); if(!list) { player->print("Fishing list \"%s\" does not exist!\n", cmnd->str[3]); return(0); } player->getUniqueRoomParent()->setFishing(cmnd->str[3]); player->print("Fishing list set to %s.\n", player->getUniqueRoomParent()->getFishingStr().c_str()); log_immort(true, player, "%s set fishing list to %s in room %s.\n", player->getCName(), player->getUniqueRoomParent()->getFishingStr().c_str(), room->fullName().c_str()); } } else if(low(cmnd->str[2][1]) == 'a') { if(!player->inUniqueRoom()) { player->print("Error: You need to be in a unique room to do that.\n"); return(0); } if(cmnd->num < 3) { player->print("Set faction to what?\n"); return(0); } else if(cmnd->num == 3) { player->getUniqueRoomParent()->setFaction(""); player->print("Faction cleared.\n"); log_immort(true, player, "%s cleared faction in room %s.\n", player->getCName(), room->fullName().c_str()); return(0); } Property* p = gConfig->getProperty(player->getUniqueRoomParent()->info); if(p && p->getType() == PROP_SHOP) { player->print("You can't set room faction on player shops!\n"); return(0); } const Faction* faction = gConfig->getFaction(cmnd->str[3]); if(!faction) { player->print("'%s' is an invalid faction.\n", cmnd->str[3]); return(0); } player->getUniqueRoomParent()->setFaction(faction->getName()); player->print("Faction set to %s.\n", player->getUniqueRoomParent()->getFaction().c_str()); log_immort(true, player, "%s set faction to %s in room %s.\n", player->getCName(), player->getUniqueRoomParent()->getFaction().c_str(), room->fullName().c_str()); break; } else { if(!player->inUniqueRoom()) { player->print("Error: You need to be in a unique room to do that.\n"); return(0); } num = cmnd->val[2]; if(num < 1 || num > MAX_ROOM_FLAGS) { player->print("Error: outside of range.\n"); return(0); } if(!player->isCt() && num == R_CONSTRUCTION+1) { player->print("Error: you cannot set/clear that flag.\n"); return(0); } if(!strcmp(cmnd->str[3], "del")) { for(a=0;a<MAX_ROOM_FLAGS;a++) player->getUniqueRoomParent()->clearFlag(a); player->print("All room flags cleared.\n"); log_immort(true, player, "%s cleared all flags in room %s.\n", player->getCName(), room->fullName().c_str()); break; } if(player->getUniqueRoomParent()->flagIsSet(num - 1)) { player->getUniqueRoomParent()->clearFlag(num - 1); player->print("Room flag #%d(%s) off.\n", num, gConfig->getRFlag(num-1).c_str()); log_immort(true, player, "%s cleared flag #%d(%s) in room %s.\n", player->getCName(), num, gConfig->getRFlag(num-1).c_str(), room->fullName().c_str()); } else { if(num >= R_TRAINING_ROOM && num - 4 <= R_TRAINING_ROOM) { // setting a training flag - do we let them? if(player->getUniqueRoomParent()->whatTraining(num-1) == CreatureClass::NONE) { player->print("You are setting training for a class that does not exist.\n"); return(0); } } player->getUniqueRoomParent()->setFlag(num - 1); player->print("Room flag #%d(%s) on.\n", num, gConfig->getRFlag(num-1).c_str()); log_immort(true, player, "%s set flag #%d(%s) in room %s.\n", player->getCName(), num, gConfig->getRFlag(num-1).c_str(), room->fullName().c_str()); if(num-1 == R_SHOP) player->printColor("^YNote:^x you must set the Shop Storage (97) to use this room as a shop.\n"); if((num-1 == R_INDOORS || num-1 == R_VAMPIRE_COVEN || num-1 == R_UNDERGROUND) && player->getUniqueRoomParent()->getSize() == NO_SIZE) player->printColor("^YNote:^x don't forget to set the size for this room.\n"); } // try and be smart if( num-1 == R_SHOP_STORAGE && player->getUniqueRoomParent()->getName() == "New Room" && player->getUniqueRoomParent()->exits.empty()) { cr = player->getUniqueRoomParent()->info; UniqueRoom* shop=nullptr; std::string storageName = "Storage: "; cr.id--; if(loadRoom(cr, &shop)) { if( shop->flagIsSet(R_SHOP) && (!shop->getTrapExit().id || shop->getTrapExit() == cr) ) { player->printColor("^ySetting up this storage room for you...\n"); player->printColor("^y * ^xSetting the trap exit to %s...\n", cr.str().c_str()); player->getUniqueRoomParent()->setTrapExit(cr); player->printColor("^y * ^xCreating exit ""out"" to %s...\n", cr.str().c_str()); link_rom(player->getUniqueRoomParent(), cr, "out"); player->getUniqueRoomParent()->setTrapExit(cr); player->printColor("^y * ^xNaming this room...\n"); storageName += shop->getName(); player->getUniqueRoomParent()->setName(storageName); player->print("Done!\n"); } } } } break; case 'l': if(!player->inUniqueRoom()) { player->print("Error: You need to be in a unique room to do that.\n"); return(0); } if(strcmp(cmnd->str[3], "clear") != 0) { player->print("Are you sure?\nType \"*set r last clear\" to clear last-arrived info.\n"); return(0); } strcpy(player->getUniqueRoomParent()->lastPly, ""); strcpy(player->getUniqueRoomParent()->lastPlyTime, ""); player->print("Last-arrived info cleared.\n"); break; case 'm': if(!player->inUniqueRoom()) { player->print("Error: You need to be in a unique room to do that.\n"); return(0); } player->getUniqueRoomParent()->setMaxMobs(cmnd->val[2]); if(!player->getUniqueRoomParent()->getMaxMobs()) player->print("The limit on the number of creatures that can be here has been removed.\n"); else player->print("Only %d creature%s can now be in here at a time.\n", player->getUniqueRoomParent()->getMaxMobs(), player->getUniqueRoomParent()->getMaxMobs() != 1 ? "s" : ""); log_immort(true, player, "%s set max %d mobs in room %s.\n", player->getCName(), player->getUniqueRoomParent()->getMaxMobs(), room->fullName().c_str()); break; case 'n': if(!player->inAreaRoom()) { player->print("Error: You need to be in an area room to do that.\n"); return(0); } if(!player->getAreaRoomParent()->unique.id) { player->print("Error: The area room must have the unique field set [*set r unique #].\n"); return(0); } player->getAreaRoomParent()->setNeedsCompass(!player->getAreaRoomParent()->getNeedsCompass()); player->printColor("NeedsCompass toggled, set to %s^x.\n", player->getAreaRoomParent()->getNeedsCompass() ? "^gYes" : "^rNo"); log_immort(true, player, "%s set needsCompass to %s in room %s.\n", player->getCName(), player->getAreaRoomParent()->getNeedsCompass() ? "true" : "false", room->fullName().c_str()); break; case 'r': if(!player->inUniqueRoom()) { player->print("Error: You need to be in a unique room to do that.\n"); return(0); } num = atoi(&cmnd->str[2][1]); if(num < 1 || num > NUM_RANDOM_SLOTS) { player->print("Error: outside of range.\n"); return(PROMPT); } getCatRef(getFullstrText(cmnd->fullstr, 3), &cr, player); if(!cr.id) { player->getUniqueRoomParent()->wander.random.erase(num-1); player->print("Random #%d has been cleared.\n", num); } else { player->getUniqueRoomParent()->wander.random[num-1] = cr; player->print("Random #%d is now %s.\n", num, cr.str().c_str()); } log_immort(false,player, "%s set mob slot %d to mob %s in room %s.\n", player->getCName(), num, cr.str().c_str(), room->fullName().c_str()); break; case 's': if(!player->inUniqueRoom()) { player->print("Error: You need to be in a unique room to do that.\n"); return(0); } player->getUniqueRoomParent()->setSize(getSize(cmnd->str[3])); player->print("Size set to %s.\n", getSizeName(player->getUniqueRoomParent()->getSize()).c_str()); log_immort(true, player, "%s set room %s's %s to %s.\n", player->getCName(), room->fullName().c_str(), "Size", getSizeName(player->getUniqueRoomParent()->getSize()).c_str()); break; case 't': if(!player->inUniqueRoom()) { player->print("Error: You need to be in a unique room to do that.\n"); return(0); } player->getUniqueRoomParent()->wander.setTraffic(cmnd->val[2]); log_immort(true, player, "%s set room %s's traffic to %ld.\n", player->getCName(), player->getUniqueRoomParent()->info.str().c_str(), player->getUniqueRoomParent()->wander.getTraffic()); player->print("Traffic is now %d%%.\n", player->getUniqueRoomParent()->wander.getTraffic()); break; case 'x': if(!player->inUniqueRoom()) { player->print("Error: You need to be in a unique room to do that.\n"); return(0); } if(low(cmnd->str[2][1]) == 'x') { getCatRef(getFullstrText(cmnd->fullstr, 3), &cr, player); if(!player->checkBuilder(cr)) { player->print("Trap's exit must be within an assigned range.\n"); return(0); } player->getUniqueRoomParent()->setTrapExit(cr); player->print("Room's trap exit is now %s.\n", player->getUniqueRoomParent()->getTrapExit().str().c_str()); log_immort(true, player, "%s set trapexit to %s in room %s.\n", player->getCName(), player->getUniqueRoomParent()->getTrapExit().str().c_str(), room->fullName().c_str()); } else if(low(cmnd->str[2][1]) == 'w') { num = (int)cmnd->val[2]; if(num < 0 || num > 5000) { player->print("Trap weight cannot be less than 0 or greater than 5000.\n"); return(0); } player->getUniqueRoomParent()->setTrapWeight(num); player->print("Room's trap weight is now %d.\n", player->getUniqueRoomParent()->getTrapWeight()); log_immort(true, player, "%s set trapweight to %d in room %s.\n", player->getCName(), player->getUniqueRoomParent()->getTrapWeight(), room->fullName().c_str()); } else if(low(cmnd->str[2][1]) == 's') { num = (int)cmnd->val[2]; if(num < 0 || num > 5000) { player->print("Trap strength cannot be less than 0 or greater than 5000.\n"); return(0); } player->getUniqueRoomParent()->setTrapStrength(num); player->print("Room's trap strength is now %d.\n", player->getUniqueRoomParent()->getTrapStrength()); log_immort(true, player, "%s set trapstrength to %d in room %s.\n", player->getCName(), player->getUniqueRoomParent()->getTrapStrength(), room->fullName().c_str()); } else { player->getUniqueRoomParent()->setTrap(cmnd->val[2]); player->print("Room has trap #%d set.\n", player->getUniqueRoomParent()->getTrap()); log_immort(true, player, "%s set trap #%d in room %s.\n", player->getCName(), player->getUniqueRoomParent()->getTrap(), room->fullName().c_str()); } break; case 'u': if(!player->inAreaRoom()) { player->print("Error: You need to be in an area room to do that.\n"); return(0); } getCatRef(getFullstrText(cmnd->fullstr, 3), &cr, player); player->getAreaRoomParent()->unique = cr; player->print("Unique room set to %s.\n", player->getAreaRoomParent()->unique.str().c_str()); if(player->getAreaRoomParent()->unique.id) player->print("You'll need to use *teleport to get to this room in the future.\n"); log_immort(true, player, "%s set unique room to %s in room %s.\n", player->getCName(), player->getAreaRoomParent()->unique.str().c_str(), room->fullName().c_str()); break; default: player->print("Invalid option.\n"); return(0); } if(player->inUniqueRoom()) player->getUniqueRoomParent()->escapeText(); room_track(player); return(0); } //********************************************************************* // dmSetExit //********************************************************************* // This function allows staff to set a characteristic of an exit. int dmSetExit(Player* player, cmd* cmnd) { BaseRoom* room = player->getRoomParent(); int num=0; //char orig_exit[30]; short n=0; if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Error: Room number not inside any of your alotted ranges.\n"); return(0); } // setting something on the exit if(cmnd->str[1][1]) { if(cmnd->num < 3) { player->print("Invalid syntax.\n"); return(0); } Exit* exit = findExit(player, cmnd->str[2], 1); if(!exit) { player->print("Exit not found.\n"); return(0); } switch(cmnd->str[1][1]) { case 'd': { if(cmnd->str[1][2] == 'i') { Direction dir = getDir(cmnd->str[3]); if(getDir(exit->getName()) != NoDirection && dir != NoDirection) { player->print("This exit does not need a direction set on it.\n"); return(0); } exit->setDirection(dir); player->printColor("%s^x's %s set to %s.\n", exit->getCName(), "Direction", getDirName(exit->getDirection()).c_str()); log_immort(true, player, "%s set %s %s^g's %s to %s.\n", player->getCName(), "exit", exit->getCName(), "Direction", getDirName(exit->getDirection()).c_str()); } else if(cmnd->str[1][2] == 'e') { std::string desc = getFullstrText(cmnd->fullstr, 3); boost::replace_all(desc, "*CR*", "\n"); exit->setDescription(desc); if(exit->getDescription().empty()) { player->print("Description cleared.\n"); log_immort(true, player, "%s cleared %s^g's %s.\n", player->getCName(), exit->getCName(), "Description"); } else { player->print("Description set to \"%s\".\n", exit->getDescription().c_str()); log_immort(true, player, "%s set %s^g's %s to \"%s\".\n", player->getCName(), exit->getCName(), "Description", exit->getDescription().c_str()); } } else { player->print("Description or direction?\n"); return(0); } break; } case 'e': if(cmnd->str[1][2] == 'f') { if(cmnd->num < 4) { player->print("Set what effect to what?\n"); return(0); } long duration = -1; int strength = 1; std::string txt = getFullstrText(cmnd->fullstr, 4); if(!txt.empty()) duration = atoi(txt.c_str()); txt = getFullstrText(cmnd->fullstr, 5); if(!txt.empty()) strength = atoi(txt.c_str()); if(duration > EFFECT_MAX_DURATION || duration < -1) { player->print("Duration must be between -1 and %d.\n", EFFECT_MAX_DURATION); return(0); } if(strength < 0 || strength > EFFECT_MAX_STRENGTH) { player->print("Strength must be between 0 and %d.\n", EFFECT_MAX_STRENGTH); return(0); } std::string effectStr = cmnd->str[3]; EffectInfo* toSet = nullptr; if((toSet = exit->getExactEffect(effectStr))) { // We have an existing effect we're modifying if(duration == 0) { // Duration is 0, so remove it exit->removeEffect(toSet, true); player->print("Effect '%s' (exit) removed.\n", effectStr.c_str()); } else { // Otherwise modify as appropriate toSet->setDuration(duration); if(strength != -1) toSet->setStrength(strength); player->print("Effect '%s' (exit) set to duration %d and strength %d.\n", effectStr.c_str(), toSet->getDuration(), toSet->getStrength()); } } else { // No existing effect, add a new one if(strength == -1) strength = 1; if(exit->addEffect(effectStr, duration, strength, nullptr, true) != nullptr) { player->print("Effect '%s' (exit) added with duration %d and strength %d.\n", effectStr.c_str(), duration, strength); } else { player->print("Unable to add effect '%s' (exit)\n", effectStr.c_str()); } } break; } else { exit->setEnter(getFullstrText(cmnd->fullstr, 3)); if(exit->getEnter().empty() || Pueblo::is(exit->getEnter())) { exit->setEnter(""); player->print("OnEnter cleared.\n"); log_immort(true, player, "%s cleared %s^g's %s.\n", player->getCName(), exit->getCName(), "OnEnter"); } else { player->print("OnEnter set to \"%s\".\n", exit->getEnter().c_str()); log_immort(true, player, "%s set %s^g's %s to \"%s\".\n", player->getCName(), exit->getCName(), "OnEnter", exit->getEnter().c_str()); } } break; case 'f': num = cmnd->val[2]; if(num < 1 || num > MAX_EXIT_FLAGS) { player->print("Error: flag out of range.\n"); return(PROMPT); } if(exit->flagIsSet(num - 1)) { exit->clearFlag(num - 1); player->printColor("%s^x exit flag #%d off.\n", exit->getCName(), num); log_immort(true, player, "%s cleared %s^g exit flag #%d(%s) in room %s.\n", player->getCName(), exit->getCName(), num, gConfig->getXFlag(num-1).c_str(), room->fullName().c_str()); } else { exit->setFlag(num - 1); player->printColor("%s^x exit flag #%d on.\n", exit->getCName(), num); log_immort(true, player, "%s turned on %s^g exit flag #%d(%s) in room %s.\n", player->getCName(), exit->getCName(), num, gConfig->getXFlag(num-1).c_str(), room->fullName().c_str()); } break; case 'k': if(cmnd->str[1][2] == 'a') { exit->setKeyArea(cmnd->str[3]); if(exit->getKeyArea().empty()) { player->print("Key Area cleared.\n"); log_immort(true, player, "%s cleared %s^g's %s.\n", player->getCName(), exit->getCName(), "Key Area"); } else { player->print("Key Area set to \"%s\".\n", exit->getKeyArea().c_str()); log_immort(true, player, "%s set %s^g's %s to \"%s\".\n", player->getCName(), exit->getCName(), "Key Area", exit->getKeyArea().c_str()); } } else { if(cmnd->val[2] > 255 || cmnd->val[2] < 0) { player->print("Error: key out of range.\n"); return(0); } exit->setKey(cmnd->val[2]); player->printColor("Exit %s^x key set to %d.\n", exit->getCName(), exit->getKey()); log_immort(true, player, "%s set %s^g's %s to %ld.\n", player->getCName(), exit->getCName(), "Key", exit->getKey()); } break; case 'l': if(cmnd->val[2] > MAXALVL || cmnd->val[2] < 0) { player->print("Level must be from 0 to %d.\n", MAXALVL); return(0); } exit->setLevel(cmnd->val[2]); player->printColor("Exit %s^x's level is now set to %d.\n", exit->getCName(), exit->getLevel()); log_immort(true, player, "%s set %s^g's %s to %ld.\n", player->getCName(), exit->getCName(), "Pick Level", exit->getLevel()); break; case 'o': exit->setOpen(getFullstrText(cmnd->fullstr, 3)); if(exit->getOpen().empty() || Pueblo::is(exit->getOpen())) { exit->setOpen(""); player->print("OnOpen cleared.\n"); log_immort(true, player, "%s cleared %s^g's %s.\n", player->getCName(), exit->getCName(), "OnOpen"); } else { player->print("OnOpen set to \"%s\".\n", exit->getOpen().c_str()); log_immort(true, player, "%s set %s^g's %s to \"%s\".\n", player->getCName(), exit->getCName(), "OnOpen", exit->getOpen().c_str()); } break; case 'p': if(low(cmnd->str[1][2]) == 'p') { exit->setPassPhrase(getFullstrText(cmnd->fullstr, 3)); if(exit->getPassPhrase().empty()) { player->print("Passphrase cleared.\n"); log_immort(true, player, "%s cleared %s^g's %s.\n", player->getCName(), exit->getCName(), "Passphrase"); } else { player->print("Passphrase set to \"%s\".\n", exit->getPassPhrase().c_str()); log_immort(true, player, "%s set %s^g's %s to \"%s\".\n", player->getCName(), exit->getCName(), "Passphrase", exit->getPassPhrase().c_str()); } } else if(low(cmnd->str[1][2]) == 'l') { n = cmnd->val[2]; if(n < 0 || n > LANGUAGE_COUNT) { player->print("Error: pass language out of range.\n"); return(0); } n--; if(n < 0) n = 0; exit->setPassLanguage(n); player->print("Pass language %s.\n", n ? "set" : "cleared"); log_immort(true, player, "%s set %s^g's %s to %s(%ld).\n", player->getCName(), exit->getCName(), "Passlang", n ? get_language_adj(n) : "Nothing", n+1); } else { player->print("Passphrase (xpp) or passlang (xpl)?\n"); return(0); } break; case 's': exit->setSize(getSize(cmnd->str[3])); player->printColor("%s^x's %s set to %s.\n", exit->getCName(), "Size", getSizeName(exit->getSize()).c_str()); log_immort(true, player, "%s set %s %s^g's %s to %s.\n", player->getCName(), "exit", exit->getCName(), "Size", getSizeName(exit->getSize()).c_str()); break; case 't': n = (short)cmnd->val[2]; if(n > 30000 || n < 0) { player->print("Must be between 0-30000.\n"); return(0); } exit->setToll(n); player->printColor("Exit %s^x's toll is now set to %d.\n", exit->getCName(), exit->getToll()); log_immort(true, player, "%s set %s^g's %s to %ld.\n", player->getCName(), exit->getCName(), "Toll", exit->getToll()); break; default: player->print("Invalid syntax.\n"); return(0); } if(player->inUniqueRoom()) player->getUniqueRoomParent()->escapeText(); room_track(player); return(0); } // otherwise, we have other plans for this function if(cmnd->num < 3) { player->print("Syntax: *set x <name> <#> [. or name]\n"); return(0); } // we need more variables to continue our work MapMarker mapmarker; BaseRoom* room2=nullptr; AreaRoom* aRoom=nullptr; UniqueRoom *uRoom=nullptr; Area *area=nullptr; CatRef cr; std::string returnExit = getFullstrText(cmnd->fullstr, 4); getDestination(getFullstrText(cmnd->fullstr, 3).c_str(), &mapmarker, &cr, player); if(!mapmarker.getArea() && !cr.id) { // if the expanded exit wasnt found // and the exit was expanded, check to delete the original if(room->delExit(cmnd->str[2])) player->print("Exit %s deleted.\n", cmnd->str[2]); else player->print("Exit %s not found.\n", cmnd->str[2]); return(0); } if(cr.id) { if(!player->checkBuilder(cr)) return(0); if(!loadRoom(cr, &uRoom)) { player->print("Room %s does not exist.\n", cr.str().c_str()); return(0); } room2 = uRoom; } else { if(player->getClass() == CreatureClass::BUILDER) { player->print("Sorry, builders cannot link exits to the overland.\n"); return(0); } area = gServer->getArea(mapmarker.getArea()); if(!area) { player->print("Area does not exist.\n"); return(0); } aRoom = area->loadRoom(nullptr, &mapmarker, false); room2 = aRoom; } std::string newName = getFullstrText(cmnd->fullstr, 2, ' ', false, true); if(newName.length() > 20) { player->print("Exit names must be 20 characters or less in length.\n"); return(0); } newName = expand_exit_name(newName); if(!returnExit.empty()) { if(returnExit == ".") returnExit = opposite_exit_name(newName); if(cr.id) { link_rom(room, cr, newName); if(player->inUniqueRoom()) link_rom(uRoom, player->getUniqueRoomParent()->info, returnExit); else link_rom(uRoom, &player->getAreaRoomParent()->mapmarker, returnExit); gServer->resaveRoom(cr); } else { link_rom(room, &mapmarker, newName); if(player->inUniqueRoom()) link_rom(aRoom, player->getUniqueRoomParent()->info, returnExit); else link_rom(aRoom, &player->getAreaRoomParent()->mapmarker, returnExit); aRoom->save(); } log_immort(true, player, "%s linked room %s to room %s in %s^g direction, both ways.\n", player->getCName(), room->fullName().c_str(), room2->fullName().c_str(), newName.c_str()); player->printColor("Room %s linked to room %s in %s^x direction, both ways.\n", room->fullName().c_str(), room2->fullName().c_str(), newName.c_str()); } else { if(cr.id) link_rom(room, cr, newName); else link_rom(room, &mapmarker, newName); player->printColor("Room %s linked to room %s in %s^x direction.\n", room->fullName().c_str(), room2->fullName().c_str(), newName.c_str()); log_immort(true, player, "%s linked room %s to room %s in %s^g direction.\n", player->getCName(), room->fullName().c_str(), room2->fullName().c_str(), newName.c_str()); } if(player->inUniqueRoom()) gServer->resaveRoom(player->getUniqueRoomParent()->info); if(aRoom && aRoom->canDelete()) area->remove(aRoom); room_track(player); return(0); } //********************************************************************* // room_track //********************************************************************* int room_track(Creature* player) { long t = time(nullptr); if(player->isMonster() || !player->inUniqueRoom()) return(0); strcpy(player->getUniqueRoomParent()->last_mod, player->getCName()); strcpy(player->getUniqueRoomParent()->lastModTime, ctime(&t)); return(0); } //********************************************************************* // dmReplace //********************************************************************* // this command lets staff replace words or phrases in a room description int dmReplace(Player* player, cmd* cmnd) { UniqueRoom *room = player->getUniqueRoomParent(); int n=0, skip=0, skPos=0; std::string::size_type i=0, pos=0; char delim = ' '; bool sdesc=false, ldesc=false; std::string search = "", temp = ""; if(!needUniqueRoom(player)) return(0); if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Room is not in any of your alotted room ranges.\n"); return(0); } if(cmnd->num < 3) { player->print("syntax: *replace [-SL#<num>] <search> <replace>\n"); return(0); } // we have flags! // let's find out what they are if(cmnd->str[1][0] == '-') { i=1; while(i < strlen(cmnd->str[1])) { switch(cmnd->str[1][i]) { case 'l': ldesc = true; break; case 's': sdesc = true; break; case '#': skip = atoi(&cmnd->str[1][++i]); break; default: break; } i++; } } // we need to get fullstr into a nicer format i = strlen(cmnd->str[0]); if(ldesc || sdesc || skip) i += strlen(cmnd->str[1]) + 1; // which deliminator should we use? if(cmnd->fullstr[i+1] == '\'' || cmnd->fullstr[i+1] == '"' || cmnd->fullstr[i+1] == '*') { delim = cmnd->fullstr[i+1]; i++; } // fullstr is now our search text and replace text seperated by a space cmnd->fullstr = cmnd->fullstr.substr(i+1); //strcpy(cmnd->fullstr, &cmnd->fullstr[i+1]); // we search until we find the deliminator we're looking for pos=0; i = cmnd->fullstr.length(); while(pos < i) { if(cmnd->fullstr[pos] == delim) break; pos++; } if(pos == i) { if(delim != ' ') player->print("Deliminator not found.\n"); else player->print("No replace text found.\n"); return(0); } // cut the string apart cmnd->fullstr[pos] = 0; search = cmnd->fullstr; // if it's not a space, we need to add 2 to get rid of the space and // next deliminator if(delim != ' ') { pos += 2; // although we don't have to, we're enforcing that the deliminators // equal each other so people are consistent with the usage of this function if(cmnd->fullstr[pos] != delim) { player->print("Deliminators do not match up.\n"); return(0); } } // fullstr now has our replace text //strcpy(cmnd->fullstr, &cmnd->fullstr[pos+1]); cmnd->fullstr = cmnd->fullstr.substr(pos+1); if(delim != ' ') { if(cmnd->fullstr[cmnd->fullstr.length()-1] != delim) { player->print("Deliminators do not match up.\n"); return(0); } cmnd->fullstr[cmnd->fullstr.length()-1] = 0; } // the text we are searching for is in "search" // the text we are replacing it with is in "fullstr" // we will use i to help us reuse code // 0 = sdesc, 1 = ldesc i = 0; // if only long desc, skip short desc if(ldesc && !sdesc) i++; // loop for the short and long desc do { // loop for skip do { if(!i) n = room->getShortDescription().find(search.c_str(), skPos); else n = room->getLongDescription().find(search.c_str(), skPos); if(n >= 0) { if(--skip > 0) skPos = n + 1; else { if(!i) { temp = room->getShortDescription().substr(0, n); temp += cmnd->fullstr; temp += room->getShortDescription().substr(n + search.length(), room->getShortDescription().length()); room->setShortDescription(temp); } else { temp = room->getLongDescription().substr(0, n); temp += cmnd->fullstr; temp += room->getLongDescription().substr(n + search.length(), room->getLongDescription().length()); room->setLongDescription(temp); } player->print("Replaced.\n"); room->escapeText(); return(0); } } } while(n >= 0 && skip); // if we're on long desc (i=1), we'll stop after this, so no worries // if we're on short desc and not doing long desc, we need to stop if(sdesc && !ldesc) i++; i++; } while(i<2); player->print("Pattern not found.\n"); return(0); } //********************************************************************* // dmDelete //********************************************************************* // Allows staff to delete some/all of the room description int dmDelete(Player* player, cmd* cmnd) { UniqueRoom *room = player->getUniqueRoomParent(); int pos=0; int unsigned i=0; bool sdesc=false, ldesc=false, phrase=false, after=false; if(!needUniqueRoom(player)) return(0); if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Room is not in any of your alotted room ranges.\n"); return(0); } if(cmnd->num < 2) { player->print("syntax: *delete [-ASLPE] <delete_word>\n"); return(0); } // take care of the easy one if(!strcmp(cmnd->str[1], "-a")) { room->setShortDescription(""); room->setLongDescription(""); } else { // determine our flags i=1; while(i < strlen(cmnd->str[1])) { switch(cmnd->str[1][i]) { case 'l': ldesc = true; break; case 's': sdesc = true; break; case 'p': phrase = true; break; case 'e': after = true; break; default: break; } i++; } // a simple delete operation if(!phrase && !after) { if(sdesc) room->setShortDescription(""); if(ldesc) room->setLongDescription(""); if(!sdesc && !ldesc) { player->print("Invalid syntax.\n"); return(0); } } else { // we need to figure out what our phrase is // turn fullstr into what we want to delete i = strlen(cmnd->str[0]) + strlen(cmnd->str[1]) + 1; if( i >= cmnd->fullstr.length() ) { player->print("Pattern not found.\n"); return(0); } // fullstr is now our phrase cmnd->fullstr = cmnd->fullstr.substr(i+1); // we will use i to help us reuse code // 0 = sdesc, 1 = ldesc i = 0; // if only long desc, skip short desc if(ldesc && !sdesc) i++; // loop! do { if(!i) pos = room->getShortDescription().find(cmnd->fullstr); else pos = room->getLongDescription().find(cmnd->fullstr); if(pos >= 0) break; // if we're on long desc (i=1), we'll stop after this, so no worries // if we're on short desc and not doing long desc, we need to stop if(sdesc && !ldesc) i++; i++; } while(i<2); // did we find it? if(pos < 0) { player->print("Pattern not found.\n"); return(0); } // we delete everything after the phrase if(after) { if(!phrase) pos += cmnd->fullstr.length(); // if it's in the short desc, and they wanted to delete // from both short and long, then delete all of long if(!i && !(sdesc ^ ldesc)) room->setLongDescription(""); if(!i) room->setShortDescription(room->getShortDescription().substr(0, pos)); else room->setLongDescription(room->getLongDescription().substr(0, pos)); // only delete the phrase } else { if(!i) room->setShortDescription(room->getShortDescription().substr(0, pos) + room->getShortDescription().substr(pos + cmnd->fullstr.length(), room->getShortDescription().length())); else room->setLongDescription(room->getLongDescription().substr(0, pos) + room->getLongDescription().substr(pos + cmnd->fullstr.length(), room->getLongDescription().length())); } } // phrase && after } // *del -A log_immort(true, player, "%s deleted description in room %s.\n", player->getCName(), player->getUniqueRoomParent()->info.str().c_str()); player->print("Deleted.\n"); return(0); } //********************************************************************* // dmNameRoom //********************************************************************* int dmNameRoom(Player* player, cmd* cmnd) { if(!needUniqueRoom(player)) return(0); if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Room is not in any of your alotted room ranges.\n"); return(0); } std::string name = getFullstrText(cmnd->fullstr, 1); if(name.empty() || Pueblo::is(name)) { player->print("Rename room to what?\n"); return(0); } if(name.length() > 79) name = name.substr(0, 79); player->getUniqueRoomParent()->setName(name); log_immort(true, player, "%s renamed room %s.\n", player->getCName(), player->getRoomParent()->fullName().c_str()); player->print("Done.\n"); return(0); } //********************************************************************* // dmDescription //********************************************************************* // Allows a staff to add the given text to the room description. int dmDescription(Player* player, cmd* cmnd, bool append) { UniqueRoom *room = player->getUniqueRoomParent(); int unsigned i=0; bool sdesc=false, newline=false; if(!needUniqueRoom(player)) return(0); if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Room is not in any of your alotted room ranges.\n"); return(0); } if(cmnd->num < 2) { player->print("syntax: *%s [-sn] <text>\n", append ? "append" : "prepend"); return(0); } // turn fullstr into what we want to append i = strlen(cmnd->str[0]); sdesc = cmnd->str[1][0] == '-' && (cmnd->str[1][1] == 's' || cmnd->str[1][2] == 's'); newline = !(cmnd->str[1][0] == '-' && (cmnd->str[1][1] == 'n' || cmnd->str[1][2] == 'n')); // keep chopping if(sdesc || !newline) i += strlen(cmnd->str[1]) + 1; cmnd->fullstr = cmnd->fullstr.substr(i+1); // strcpy(cmnd->fullstr, &cmnd->fullstr[i+1]); if(cmnd->fullstr.find(" ") != std::string::npos) player->printColor("Do not use double spaces in room descriptions! Use ^W*wrap^x to fix this.\n"); if(sdesc) { // short descriptions newline = newline && !room->getShortDescription().empty(); if(append) { room->appendShortDescription(newline ? "\n" : ""); room->appendShortDescription(cmnd->fullstr); } else { if(newline) cmnd->fullstr += "\n"; room->setShortDescription(cmnd->fullstr + room->getShortDescription()); } player->print("Short description %s.\n", append ? "appended" : "prepended"); } else { // long descriptions newline = newline && !room->getLongDescription().empty(); if(append) { room->appendLongDescription(newline ? "\n" : ""); room->appendLongDescription(cmnd->fullstr); } else { if(newline) cmnd->fullstr += "\n"; room->setLongDescription(cmnd->fullstr + room->getLongDescription()); } player->print("Long description %s.\n", append ? "appended" : "prepended"); } player->getUniqueRoomParent()->escapeText(); log_immort(true, player, "%s descripted in room %s.\n", player->getCName(), player->getUniqueRoomParent()->info.str().c_str()); return(0); } //********************************************************************* // dmAppend //********************************************************************* int dmAppend(Player* player, cmd* cmnd) { return(dmDescription(player, cmnd, true)); } //********************************************************************* // dmPrepend //********************************************************************* int dmPrepend(Player* player, cmd* cmnd) { return(dmDescription(player, cmnd, false)); } //********************************************************************* // dmMobList //********************************************************************* // Display information about what mobs will randomly spawn. void showMobList(Player* player, WanderInfo *wander, std::string_view type) { std::map<int, CatRef>::iterator it; Monster *monster=nullptr; bool found=false, maybeAggro=false; std::ostringstream oStr; for(it = wander->random.begin(); it != wander->random.end() ; it++) { if(!found) oStr << "^cTraffic = " << wander->getTraffic() << "\n"; found=true; if(!(*it).second.id) continue; if(!loadMonster((*it).second, &monster)) continue; if(monster->flagIsSet(M_AGGRESSIVE)) oStr << "^r"; else { maybeAggro = monster->flagIsSet(M_AGGRESSIVE_EVIL) || monster->flagIsSet(M_AGGRESSIVE_GOOD) || monster->flagIsSet(M_AGGRESSIVE_AFTER_TALK) || monster->flagIsSet(M_CLASS_AGGRO_INVERT) || monster->flagIsSet(M_RACE_AGGRO_INVERT) || monster->flagIsSet(M_DEITY_AGGRO_INVERT); if(!maybeAggro) { RaceDataMap::iterator rIt; for(rIt = gConfig->races.begin() ; rIt != gConfig->races.end() ; rIt++) { if(monster->isRaceAggro((*rIt).second->getId(), false)) { maybeAggro = true; break; } } } if(!maybeAggro) { for(int n=1; n<static_cast<int>(STAFF); n++) { if(monster->isClassAggro(n, false)) { maybeAggro = true; break; } } } if(!maybeAggro) { DeityDataMap::iterator dIt; for(dIt = gConfig->deities.begin() ; dIt != gConfig->deities.end() ; dIt++) { if(monster->isDeityAggro((*dIt).second->getId(), false)) { maybeAggro = true; break; } } } if(maybeAggro) oStr << "^y"; else oStr << "^g"; } oStr << "Slot " << std::setw(2) << (*it).first+1 << ": " << monster->getName() << " " << "[" << monType::getName(monster->getType()) << ":" << monType::getHitdice(monster->getType()) << "HD]\n" << " ^x[I:" << monster->info.str() << " L:" << monster->getLevel() << " X:" << monster->getExperience() << " G:" << monster->coins[GOLD] << " H:" << monster->hp.getMax() << " M:" << monster->mp.getMax() << " N:" << (monster->getNumWander() ? monster->getNumWander() : 1) << (monster->getAlignment() > 0 ? "^g" : "") << (monster->getAlignment() < 0 ? "^r" : "") << " A:" << monster->getAlignment() << "^x D:" << monster->damage.average() << "]\n"; free_crt(monster); } if(!found) oStr << " No random monsters currently come in this " << type << "."; player->printColor("%s\n", oStr.str().c_str()); } int dmMobList(Player* player, cmd* cmnd) { if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Error: Room number not inside any of your alotted ranges.\n"); return(0); } player->print("Random monsters which come in this room:\n"); if(player->inUniqueRoom()) showMobList(player, &player->getUniqueRoomParent()->wander, "room"); else if(player->inAreaRoom()) { Area* area = player->getAreaRoomParent()->area; std::list<AreaZone*>::iterator it; AreaZone *zone=nullptr; for(it = area->zones.begin() ; it != area->zones.end() ; it++) { zone = (*it); if(zone->inside(area, &player->getAreaRoomParent()->mapmarker)) { player->print("Zone: %s\n", zone->name.c_str()); showMobList(player, &zone->wander, "zone"); } } TileInfo* tile = area->getTile(area->getTerrain(nullptr, &player->getAreaRoomParent()->mapmarker, 0, 0, 0, true), area->getSeasonFlags(&player->getAreaRoomParent()->mapmarker)); if(tile && tile->wander.getTraffic()) { player->print("Tile: %s\n", tile->getName().c_str()); showMobList(player, &tile->wander, "tile"); } } return(0); } //********************************************************************* // dmWrap //********************************************************************* // dmWrap will either wrap the short or long desc of a room to the // specified length, for sanity, a range of 60 - 78 chars is the limit. int dmWrap(Player* player, cmd* cmnd) { UniqueRoom *room = player->getUniqueRoomParent(); int wrap=0; bool err=false, which=false; std::string text = ""; if(!needUniqueRoom(player)) return(0); if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Room is not in any of your alotted room ranges.\n"); return(0); } // parse the input command for syntax/range problems if(cmnd->num < 2) err = true; else { switch(cmnd->str[1][0]) { case 'l': which = true; text = room->getLongDescription(); break; case 's': which = false; text = room->getShortDescription(); break; default: err = true; break; } if(!err) { wrap = cmnd->val[1]; if(wrap < 60 || wrap > 78) err = true; } } if(err) { player->print("*wrap <s | l> <len> where len is between 60 and 78 >\n"); return(0); } if((!which && room->getShortDescription().empty()) || (which && room->getLongDescription().empty())) { player->print("No text to wrap!\n"); return(0); } // adjust! wrap++; // replace! if(!which) room->setShortDescription(wrapText(room->getShortDescription(), wrap)); else room->setLongDescription(wrapText(room->getLongDescription(), wrap)); player->print("Text wrapped.\n"); player->getUniqueRoomParent()->escapeText(); log_immort(false, player, "%s wrapped the description in room %s.\n", player->getCName(), player->getRoomParent()->fullName().c_str()); return(0); } //********************************************************************* // dmDeleteAllExits //********************************************************************* int dmDeleteAllExits(Player* player, cmd* cmnd) { if(player->getRoomParent()->exits.empty()) { player->print("No exits to delete.\n"); return(0); } player->getRoomParent()->clearExits(); // sorry, can't delete exits in overland if(player->inAreaRoom()) player->getAreaRoomParent()->updateExits(); player->print("All exits deleted.\n"); log_immort(true, player, "%s deleted all exits in room %s.\n", player->getCName(), player->getRoomParent()->fullName().c_str()); room_track(player); return(0); } //********************************************************************* // exit_ordering //********************************************************************* // 1 mean exit2 goes in front of exit1 // 0 means keep looking int exit_ordering(const char *exit1, const char *exit2) { // always skip if they're the same name if(!strcmp(exit1, exit2)) return(0); // north east south west if(!strcmp(exit1, "north")) return(0); if(!strcmp(exit2, "north")) return(1); if(!strcmp(exit1, "east")) return(0); if(!strcmp(exit2, "east")) return(1); if(!strcmp(exit1, "south")) return(0); if(!strcmp(exit2, "south")) return(1); if(!strcmp(exit1, "west")) return(0); if(!strcmp(exit2, "west")) return(1); // northeast northwest southeast southwest if(!strcmp(exit1, "northeast")) return(0); if(!strcmp(exit2, "northeast")) return(1); if(!strcmp(exit1, "northwest")) return(0); if(!strcmp(exit2, "northwest")) return(1); if(!strcmp(exit1, "southeast")) return(0); if(!strcmp(exit2, "southeast")) return(1); if(!strcmp(exit1, "southwest")) return(0); if(!strcmp(exit2, "southwest")) return(1); if(!strcmp(exit1, "up")) return(0); if(!strcmp(exit2, "up")) return(1); if(!strcmp(exit1, "down")) return(0); if(!strcmp(exit2, "down")) return(1); // alphabetic return strcmp(exit1, exit2) > 0 ? 1 : 0; } //********************************************************************* // dmArrangeExits //********************************************************************* bool exitCompare( const Exit* left, const Exit* right ){ return(!exit_ordering(left->getCName(), right->getCName())); } void BaseRoom::arrangeExits(Player* player) { if(exits.size() <= 1) { if(player) player->print("No exits to rearrange!\n"); return; } exits.sort(exitCompare); if(player) player->print("Exits rearranged!\n"); } int dmArrangeExits(Player* player, cmd* cmnd) { if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Error: Room number not inside any of your alotted ranges.\n"); return(0); } player->getRoomParent()->arrangeExits(player); return(0); } //********************************************************************* // link_rom //********************************************************************* // from this room to unique room void link_rom(BaseRoom* room, const Location& l, std::string_view str) { for(Exit* ext : room->exits) { if(ext->getName() == str) { ext->target = l; return; } } Exit* exit = new Exit; exit->setRoom(room); exit->setName(str); exit->target = l; room->exits.push_back(exit); } void link_rom(BaseRoom* room, short tonum, std::string_view str) { Location l; l.room.id = tonum; link_rom(room, l, str); } void link_rom(BaseRoom* room, const CatRef& cr, std::string_view str) { Location l; l.room = cr; link_rom(room, l, str); } void link_rom(BaseRoom* room, MapMarker *mapmarker, std::string_view str) { Location l; l.mapmarker = *mapmarker; link_rom(room, l, str); } //********************************************************************* // dmFix //********************************************************************* int dmFix(Player* player, cmd* cmnd, std::string_view name, char find, char replace) { Exit *exit=nullptr; int i=0; bool fixed=false; if(cmnd->num < 2) { player->bPrint(fmt::format("Syntax: *{}up <exit>\n", name)); return(0); } exit = findExit(player, cmnd); if(!exit) { player->print("You don't see that exit.\n"); return(0); } std::string newName = exit->getName(); for(i=newName.length(); i>0; i--) { if(newName[i] == find) { newName[i] = replace; fixed = true; } } if(fixed) { exit->setName(newName); log_immort(true, player, fmt::format("{} {}ed the exit '{}' in room {}.\n", player->getName(), name, exit->getName(), player->getRoomParent()->fullName()).c_str()); player->print("Done.\n"); } else player->print("Couldn't find any underscores.\n"); return(0); } //********************************************************************* // dmUnfixExit //********************************************************************* int dmUnfixExit(Player* player, cmd* cmnd) { return(dmFix(player, cmnd, "unfix", ' ', '_')); } //********************************************************************* // dmFixExit //********************************************************************* int dmFixExit(Player* player, cmd* cmnd) { return(dmFix(player, cmnd, "fix", '_', ' ')); } //********************************************************************* // dmRenameExit //********************************************************************* int dmRenameExit(Player* player, cmd* cmnd) { Exit *exit=nullptr; if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Room is not in any of your alotted room ranges.\n"); return(0); } if(cmnd->num < 3) { player->print("Syntax: *xrename <old exit>[#] <new exit>\n"); return(0); } exit = findExit(player, cmnd); if(!exit) { player->print("There is no exit here by that name.\n"); return(0); } std::string newName = getFullstrText(cmnd->fullstr, 2); if(newName.length() > 20) { player->print("New exit name must be 20 characters or less in length.\n"); return(0); } player->printColor("Exit \"%s^x\" renamed to \"%s^x\".\n", exit->getCName(), newName.c_str()); log_immort(false, player, "%s renamed exit %s^g to %s^g in room %s.\n", player->getCName(), exit->getCName(), newName.c_str(), player->getRoomParent()->fullName().c_str()); room_track(player); if(getDir(newName) != NoDirection) exit->setDirection(NoDirection); exit->setName( newName.c_str()); return(0); } //********************************************************************* // dmDestroyRoom //********************************************************************* int dmDestroyRoom(Player* player, cmd* cmnd) { if(!player->inUniqueRoom()) { player->print("Error: You need to be in a unique room to do that.\n"); return(0); } if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Room is not in any of your alotted room ranges.\n"); return(0); } if( player->getUniqueRoomParent()->info.isArea("test") && player->getUniqueRoomParent()->info.id == 1 ) { player->print("Sorry, you cannot destroy this room.\n"); player->print("It is the Builder Waiting Room.\n"); return(0); } if(player->bound.room == player->currentLocation.room) { player->print("Sorry, you cannot destroy this room.\n"); player->print("It is your bound room.\n"); return(0); } std::map<std::string, StartLoc*>::iterator sIt; for(sIt = gConfig->start.begin() ; sIt != gConfig->start.end() ; sIt++) { if( player->getUniqueRoomParent()->info == (*sIt).second->getBind().room || player->getUniqueRoomParent()->info == (*sIt).second->getRequired().room ) { player->print("Sorry, you cannot destroy this room.\n"); player->print("It is important to starting locations.\n"); return(0); } } std::list<CatRefInfo*>::const_iterator crIt; for(crIt = gConfig->catRefInfo.begin() ; crIt != gConfig->catRefInfo.end() ; crIt++) { if(player->getUniqueRoomParent()->info.isArea((*crIt)->getArea())) { if((*crIt)->getLimbo() == player->getUniqueRoomParent()->info.id) { player->print("Sorry, you cannot destroy this room.\n"); player->print("It is a Limbo room.\n"); return(0); } if((*crIt)->getRecall() == player->getUniqueRoomParent()->info.id) { player->print("Sorry, you cannot destroy this room.\n"); player->print("It is a recall room.\n"); return(0); } } } log_immort(true, player, "%s destroyed room %s.\n", player->getCName(), player->getRoomParent()->fullName().c_str()); player->getUniqueRoomParent()->destroy(); return(0); } //********************************************************************* // findRoomsWithFlag //********************************************************************* void findRoomsWithFlag(const Player* player, const Range& range, int flag) { Async async; if(async.branch(player, ChildType::PRINT) == AsyncExternal) { std::ostringstream oStr; bool found = false; if(range.low.id <= range.high) { UniqueRoom* room=nullptr; CatRef cr; int high = range.high; cr.setArea(range.low.area); cr.id = range.low.id; if(range.low.id == -1 && range.high == -1) { cr.id = 1; high = RMAX; } for(; cr.id < high; cr.id++) { if(!loadRoom(cr, &room)) continue; if(room->flagIsSet(flag)) { if(player->isStaff()) oStr << room->info.rstr() << " - "; oStr << room->getName() << "^x\n"; found = true; } } } std::cout << "^YLocations found:^x\n"; if(!found) { std::cout << "No available locations were found."; } else { std::cout << oStr.str(); } exit(0); } } void findRoomsWithFlag(const Player* player, CatRef area, int flag) { Async async; if(async.branch(player, ChildType::PRINT) == AsyncExternal) { struct dirent *dirp=nullptr; DIR *dir=nullptr; std::ostringstream oStr; bool found = false; char filename[250]; UniqueRoom *room=nullptr; // This tells us just to get the path, not the file, // and tells loadRoomFromFile to ignore the CatRef area.id = -1; std::string path = roomPath(area); if((dir = opendir(path.c_str())) != nullptr) { while((dirp = readdir(dir)) != nullptr) { // is this a room file? if(dirp->d_name[0] == '.') continue; sprintf(filename, "%s/%s", path.c_str(), dirp->d_name); if(!loadRoomFromFile(area, &room, filename)) continue; if(room->flagIsSet(flag)) { if(player->isStaff()) oStr << room->info.rstr() << " - "; oStr << room->getName() << "^x\n"; found = true; } // TODO: Memleak (even though it is forked), room is not deleted } } std::cout << "^YLocations found:^x\n"; if(!found) { std::cout << "No available locations were found."; } else { std::cout << oStr.str(); } exit(0); } } //********************************************************************* // dmFind //********************************************************************* int dmFind(Player* player, cmd* cmnd) { std::string type = getFullstrText(cmnd->fullstr, 1); CatRef cr; if(player->inUniqueRoom()) cr = player->getUniqueRoomParent()->info; else cr.setArea("area"); if(type == "r") type = "room"; else if(type == "o") type = "object"; else if(type == "m") type = "monster"; if(type.empty() || (type != "room" && type != "object" && type != "monster")) { if(!type.empty()) player->print("\"%s\" is not a valid type.\n", type.c_str()); player->print("Search for next available of the following: room, object, monster.\n"); return(0); } if(!player->checkBuilder(cr)) { player->print("Error: this area is out of your range; you cannot *find here.\n"); return(0); } if(type == "monster" && !player->canBuildMonsters()) { player->print("Error: you cannot work with monsters.\n"); return(0); } if(type == "object" && !player->canBuildObjects()) { player->print("Error: you cannot work with objects.\n"); return(0); } Async async; if(async.branch(player, ChildType::PRINT) == AsyncExternal) { cr = findNextEmpty(type, cr.area); std::cout << "^YNext available " << type << " in area " << cr.area << "^x\n"; if(cr.id == -1) std::cout << "No empty %ss found.", type.c_str(); else { std::cout << cr.rstr(); } exit(0); } else { player->printColor("Searching for next available %s in ^W%s^x.\n", type.c_str(), cr.area.c_str()); } return(0); } //********************************************************************* // findNextEmpty //********************************************************************* // searches for the next empty room/object/monster in the area CatRef findNextEmpty(const std::string &type, const std::string &area) { CatRef cr; cr.setArea(area); if(type == "room") { UniqueRoom* room=nullptr; for(cr.id = 1; cr.id < RMAX; cr.id++) if(!loadRoom(cr, &room)) return(cr); } else if(type == "object") { Object *object=nullptr; for(cr.id = 1; cr.id < OMAX; cr.id++) { if(!loadObject(cr, &object)) return(cr); else delete object; } } else if(type == "monster") { Monster *monster=nullptr; for(cr.id = 1; cr.id < MMAX; cr.id++) { if(!loadMonster(cr, &monster)) return(cr); else free_crt(monster); } } // -1 indicates failure cr.id = -1; return(cr); } //********************************************************************* // save //********************************************************************* void AreaRoom::save(Player* player) const { char filename[256]; sprintf(filename, "%s/%d/", Path::AreaRoom, area->id); Path::checkDirExists(filename); strcat(filename, mapmarker.filename().c_str()); if(!canSave()) { if(file_exists(filename)) { if(player) player->print("Restoring this room to generic status.\n"); unlink(filename); } else { if(player) player->print("There is no reason to save this room!\n\n"); } return; } // record rooms saved during swap if(gConfig->swapIsInteresting(this)) gConfig->swapLog((std::string)"a" + mapmarker.str(), false); xmlDocPtr xmlDoc; xmlNodePtr rootNode, curNode; xmlDoc = xmlNewDoc(BAD_CAST "1.0"); rootNode = xmlNewDocNode(xmlDoc, nullptr, BAD_CAST "AreaRoom", nullptr); xmlDocSetRootElement(xmlDoc, rootNode); unique.save(rootNode, "Unique", false); xml::saveNonZeroNum(rootNode, "NeedsCompass", needsCompass); xml::saveNonZeroNum(rootNode, "DecCompass", decCompass); effects.save(rootNode, "Effects"); hooks.save(rootNode, "Hooks"); curNode = xml::newStringChild(rootNode, "MapMarker"); mapmarker.save(curNode); curNode = xml::newStringChild(rootNode, "Exits"); saveExitsXml(curNode); xml::saveFile(filename, xmlDoc); xmlFreeDoc(xmlDoc); if(player) player->print("Room saved.\n"); }
RealmsMud/RealmsCode
staff/dmroom.cpp
C++
agpl-3.0
114,289
mod actor_state; mod character; mod openable; mod respawnable; mod stats_item; pub use actor_state::*; pub use character::*; pub use openable::*; pub use respawnable::*; pub use stats_item::*;
arendjr/PlainText
src/entity/components/mod.rs
Rust
agpl-3.0
194
import React from 'react'; import { Card } from 'bm-kit'; import './_pillar.schedule.source.scss'; const friday = [ { start: '6:00 PM', name: '📋 Check in begins' }, { start: '8:00 PM', name: '🎤 Opening Ceremonies' }, { start: '9:00 PM', name: '🤝 Team assembly' }, { start: '9:30 PM', name: '🌮 Dinner' }, { start: '10:00 PM', name: '💻 Hacking Begins' }, { start: '10:00 PM', name: '🤖 Fundamentals of AI with Intel' }, { start: '12:00 AM', name: '🥋 Ninja' } ]; let saturday = [ { start: '3:00 AM', name: '🍿 Late Night Snack' }, { start: '8:00 AM', name: '🥓 Breakfast' }, { start: '9:00 AM', name: '🏗 Workshop' }, { start: '12:30 PM', name: '🍝 Lunch' }, { start: '1:00 PM', name: '👪 Facebook Tech Talk' }, { start: '2:00 PM', name: '🐶 Doggos/Woofers' }, { start: '2:30 PM', name: '✈️ Rockwell Collins Talk' }, { start: '3:00 PM', name: '🍿 Snack' }, { start: '3:00 PM', name: '🚣🏽 Activity' }, { start: '4:00 PM', name: '📈 Startups with T.A. MaCann' }, { start: '6:00 PM', name: '🍕 Dinner' }, { start: '9:00 PM', name: '🥤 Cup stacking with MLH' }, { start: '10:00 PM', name: '🍩 Donuts and Kona Ice' }, { start: '10:00 PM', name: '🏗️ Jenga' } ]; let sunday = [ { start: '1:00 AM', name: '🍿 Late Night Snack' }, { start: '8:00 AM', name: '🍳 Breakfast' }, { start: '9:30 AM', name: '🛑 Hacking Ends' }, { start: '10:00 AM', name: '📔 Expo Begins' }, { start: '11:30 AM', name: '🍞 Lunch' }, { start: '1:00 PM', name: '🎭 Closing Ceremonies' }, { start: '2:30 PM', name: '🚌 Buses Depart' } ]; const ScheduleDay = ({ dayData, title }) => ( <Card className="p-schedule__day"> <h3 className="text-center">{title}</h3> {dayData.map(item => ( <div className="p-schedule__item" key={item.name + item.start}> <div className="p-schedule__item_about"> <span className="p-schedule__item_time">{item.start}</span> <span className="p-schedule__item_title">{item.name}</span> </div> <div className="p-schedule__item_info">{item.info}</div> </div> ))} </Card> ); const Schedule = ({ small }) => ( <div className="p-schedule"> {small ? <h3 style={{ marginTop: 0 }}>Schedule</h3> : <h1>Schedule</h1>} <div className="p-schedule__days"> <ScheduleDay dayData={friday} title="Friday (10/19)" /> <ScheduleDay dayData={saturday} title="Saturday (10/20)" /> <ScheduleDay dayData={sunday} title="Sunday (10/21)" /> </div> </div> ); export default Schedule;
BoilerMake/frontend
src/components/Schedule/index.js
JavaScript
agpl-3.0
2,859
// // Copyright (C) 2015-2016 University of Amsterdam // // 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, see <http://www.gnu.org/licenses/>. // #ifndef INTEGERINFORECORD_H #define INTEGERINFORECORD_H #include "datainforecord.h" namespace spss { /** * @brief The IntegerInfoRecord class * * Associated with record type rectype_value_labels = rectype_meta_data = 7, sub type recsubtype_integer = 3, */ class IntegerInfoRecord : public DataInfoRecord<recsubtype_integer> { public: /** * @brief IntegerInfoRecord default Ctor */ IntegerInfoRecord(); /** * @brief IntegerInfoRecord Ctor * @param Converters fixer Fixes endainness. * @param fileSubType The record subtype value, as found in the file. * @param fileType The record type value, as found in the file. * @param fromStream The file to read from. * * NB This constructor will modify the contents of fixer! */ IntegerInfoRecord(NumericConverter &fixer, RecordSubTypes fileSubType, RecordTypes fileType, SPSSStream &fromStream); virtual ~IntegerInfoRecord(); /* * Data! */ SPSSIMPORTER_READ_ATTRIB(int32_t, version_major) SPSSIMPORTER_READ_ATTRIB(int32_t, version_minor) SPSSIMPORTER_READ_ATTRIB(int32_t, version_revision) SPSSIMPORTER_READ_ATTRIB(int32_t, machine_code) SPSSIMPORTER_READ_ATTRIB(int32_t, floating_point_rep) SPSSIMPORTER_READ_ATTRIB(int32_t, compression_code) SPSSIMPORTER_READ_ATTRIB(int32_t, endianness) SPSSIMPORTER_READ_ATTRIB(int32_t, character_code) /** * @brief process Manipulates columns by adding the contents of thie record. * @param columns * * Implematations should examine columns to determine the record history. */ virtual void process(SPSSColumns & columns); }; } #endif // INTEGERINFORECORD_H
raviselker/jasp-desktop
JASP-Desktop/importers/spss/integerinforecord.h
C
agpl-3.0
2,308
window.addEventListener("DOMContentLoaded", () => { let watchers = {}; new DOM('@Dialog').forEach((dialog) => { dialogPolyfill.registerDialog(dialog); if (dialog.querySelector('Button[Data-Action="Dialog_Submit"]')) { dialog.addEventListener("keydown", (event) => { if (event.ctrlKey && event.keyCode == 13) dialog.querySelector('Button[Data-Action="Dialog_Submit"]').click(); }); } dialog.querySelectorAll('Dialog *[Required]').forEach((input) => { input.addEventListener("input", () => { let result = true; dialog.querySelectorAll('Dialog *[Required]').forEach(requiredField => { if (requiredField.value.replace(/\s/g, "").length == 0) { result = false; return; } }); if (result) { dialog.querySelector('Button[Data-Action="Dialog_Submit"]').classList.remove("mdl-button--disabled"); } else { dialog.querySelector('Button[Data-Action="Dialog_Submit"]').classList.add("mdl-button--disabled"); } }); }); dialog.querySelectorAll('Dialog Button[Data-Action="Dialog_Close"]').forEach((btn) => { btn.addEventListener("click", () => { btn.offsetParent.close(); }); }); }); new DOM("#Dialogs_Profile_DeleteConfirmer_Content_Email-Input").addEventListener("input", () => { if (new DOM("#Dialogs_Profile_DeleteConfirmer_Content_Email-Input").value == base.user.email) { new DOM("#Dialogs_Profile_DeleteConfirmer_Btns_Yes").classList.remove("mdl-button--disabled"); } else { new DOM("#Dialogs_Profile_DeleteConfirmer_Btns_Yes").classList.add("mdl-button--disabled"); } }); new DOM("#Dialogs_Profile_DeleteConfirmer_Btns_Yes").addEventListener("click", (event) => { if (new DOM("#Dialogs_Profile_DeleteConfirmer_Content_Email-Input").value == base.user.email) { base.delete(); } else { new DOM("#Dialogs_Profile_DeleteConfirmer_Content_Email").classList.add("is-invalid"); } }); watchers["Dialogs_Profile_InfoViewer_UID"] = { valueObj: { value: "" }, watcher: null }; watchers["Dialogs_Profile_InfoViewer_UID"].watcher = new DOM.Watcher({ target: watchers["Dialogs_Profile_InfoViewer_UID"].valueObj, onGet: () => { watchers["Dialogs_Profile_InfoViewer_UID"].valueObj.value = new DOM("#Dialogs_Profile_InfoViewer_UID").value }, onChange: (watcher) => { base.Database.get(base.Database.ONCE, `users/${watcher.newValue}`, (res) => { new DOM("#Dialogs_Profile_InfoViewer_Content_Photo").dataset.uid = watcher.newValue, new DOM("#Dialogs_Profile_InfoViewer_Content_Info_Name").textContent = res.userName, new DOM("#Dialogs_Profile_InfoViewer_Content_Info_Detail").textContent = res.detail; while (new DOM("#Dialogs_Profile_InfoViewer_Content_Info_Links").childNodes.length > 0) new DOM("#Dialogs_Profile_InfoViewer_Content_Info_Links").childNodes[0].remove(); if (res.links) { for (let i = 0; i < res.links.length; i++) { let link = new Component.Dialogs.Profile.InfoViewer.Links.Link(res.links[i].name, res.links[i].url); new DOM("#Dialogs_Profile_InfoViewer_Content_Info_Links").appendChild(link); } } }); } }); new DOM("#Dialogs_Thread_DeleteConfirmer_Btns_Yes").addEventListener("click", () => { base.Database.delete(`threads/${new DOM("#Dialogs_Thread_DeleteConfirmer_TID").value}/`); parent.document.querySelector("IFrame.mdl-layout__content").contentWindow.postMessage({ code: "Code-Refresh" }, "*"); new DOM("#Dialogs_Thread_EditNotify").showModal(); }); new DOM("@#Dialogs_Thread_InfoInputter *[Required]").forEach((input) => { input.addEventListener("input", () => { let result = true; let list = [ new DOM("#Dialogs_Thread_InfoInputter_Content_Name-Input"), new DOM("#Dialogs_Thread_InfoInputter_Content_Overview-Input") ]; if (new DOM("#Dialogs_Thread_InfoInputter_Content_Secured-Input").checked) list.push(new DOM("#Dialogs_Thread_InfoInputter_Content_Password-Input")); list.forEach(requiredField => { if (requiredField.value.replace(/\s/g, "").length == 0) { result = false; return; } }); if (result) { new DOM("#Dialogs_Thread_InfoInputter").querySelectorAll('Button[Data-Action="Dialog_Submit"]').forEach(btn => { btn.classList.remove("mdl-button--disabled"); }); } else { new DOM("#Dialogs_Thread_InfoInputter").querySelectorAll('Button[Data-Action="Dialog_Submit"]').forEach(btn => { btn.classList.add("mdl-button--disabled"); }); } }); }); new DOM("#Dialogs_Thread_InfoInputter_Content_Secured-Input").addEventListener("change", (event) => { let result = true; switch (event.target.checked) { case true: new DOM("#Dialogs_Thread_InfoInputter_Content_Password").classList.remove("mdl-switch__child-hide"); [new DOM("#Dialogs_Thread_InfoInputter_Content_Name-Input"), new DOM("#Dialogs_Thread_InfoInputter_Content_Overview-Input"), new DOM("#Dialogs_Thread_InfoInputter_Content_Password-Input")].forEach(requiredField => { if (requiredField.value.replace(/\s/g, "").length == 0) { result = false; return; } }); break; case false: new DOM("#Dialogs_Thread_InfoInputter_Content_Password").classList.add("mdl-switch__child-hide"); [new DOM("#Dialogs_Thread_InfoInputter_Content_Name-Input"), new DOM("#Dialogs_Thread_InfoInputter_Content_Overview-Input")].forEach(requiredField => { if (requiredField.value.replace(/\s/g, "").length == 0) { result = false; return; } }); break; } if (result) { new DOM("#Dialogs_Thread_InfoInputter").querySelectorAll('Button[Data-Action="Dialog_Submit"]').forEach(btn => { btn.classList.remove("mdl-button--disabled"); }); } else { new DOM("#Dialogs_Thread_InfoInputter").querySelectorAll('Button[Data-Action="Dialog_Submit"]').forEach(btn => { btn.classList.add("mdl-button--disabled"); }); } }); new DOM("#Dialogs_Thread_InfoInputter_Btns_Create").addEventListener("click", (event) => { base.Database.transaction("threads", (res) => { let now = new Date().getTime(); base.Database.set("threads/" + res.length, { title: new DOM("#Dialogs_Thread_InfoInputter_Content_Name-Input").value, overview: new DOM("#Dialogs_Thread_InfoInputter_Content_Overview-Input").value, detail: new DOM("#Dialogs_Thread_InfoInputter_Content_Detail-Input").value, jobs: { Owner: (() => { let owner = {}; owner[base.user.uid] = ""; return owner; })(), Admin: { } }, createdAt: now, data: [ { uid: "!SYSTEM_INFO", content: new DOM("#Dialogs_Thread_InfoInputter_Content_Name-Input").value, createdAt: now } ], password: new DOM("#Dialogs_Thread_InfoInputter_Content_Secured-Input").checked ? Encrypter.encrypt(new DOM("#Dialogs_Thread_InfoInputter_Content_Password-Input").value) : "" }); new DOM("#Dialogs_Thread_InfoInputter").close(); parent.document.querySelector("IFrame.mdl-layout__content").src = "Thread/Viewer/?tid=" + res.length; }); }); new DOM("#Dialogs_Thread_InfoInputter_Btns_Edit").addEventListener("click", (event) => { base.Database.update(`threads/${new DOM("#Dialogs_Thread_InfoInputter_TID").value}/`, { title: new DOM("#Dialogs_Thread_InfoInputter_Content_Name-Input").value, overview: new DOM("#Dialogs_Thread_InfoInputter_Content_Overview-Input").value, detail: new DOM("#Dialogs_Thread_InfoInputter_Content_Detail-Input").value, password: new DOM("#Dialogs_Thread_InfoInputter_Content_Secured-Input").checked ? Encrypter.encrypt(new DOM("#Dialogs_Thread_InfoInputter_Content_Password-Input").value) : "" }); new DOM("#Dialogs_Thread_InfoInputter").close(); new DOM("#Dialogs_Thread_EditNotify").showModal(); }); new DOM("#Dialogs_Thread_PasswordConfirmer_Btns_OK").addEventListener("click", (event) => { if (Encrypter.encrypt(new DOM("#Dialogs_Thread_PasswordConfirmer_Content_Password-Input").value) == new DOM("#Dialogs_Thread_PasswordConfirmer_Password").value) { sessionStorage.setItem("com.GenbuProject.SimpleThread.currentPassword", new DOM("#Dialogs_Thread_PasswordConfirmer_Content_Password-Input").value); new DOM("$IFrame.mdl-layout__content").src = new DOM("#Dialogs_Thread_PasswordConfirmer_Link").value; new DOM("#Dialogs_Thread_PasswordConfirmer_Link").value = "", new DOM("#Dialogs_Thread_PasswordConfirmer_Password").value = ""; } else { new DOM("#Dialogs_Thread_PasswordConfirmer_Content_Password").classList.add("is-invalid"); } }); new DOM("#Dialogs_Thread_PasswordConfirmer_Btns_Cancel").addEventListener("click", (event) => { new DOM("$IFrame.mdl-layout__content").src = "/SimpleThread/Thread/"; }); watchers["Dialogs_Thread_InfoViewer_TID"] = { valueObj: { value: "0" }, watcher: null }; watchers["Dialogs_Thread_InfoViewer_TID"].watcher = new DOM.Watcher({ target: watchers["Dialogs_Thread_InfoViewer_TID"].valueObj, onGet: () => { watchers["Dialogs_Thread_InfoViewer_TID"].valueObj.value = new DOM("#Dialogs_Thread_InfoViewer_TID").value }, onChange: (watcher) => { base.Database.get(base.Database.ONCE, `threads/${watcher.newValue}`, (res) => { new DOM("#Dialogs_Thread_InfoViewer_Content_Name").textContent = res.title, new DOM("#Dialogs_Thread_InfoViewer_Content_Overview").textContent = res.overview, new DOM("#Dialogs_Thread_InfoViewer_Content_Detail").textContent = res.detail; URL.filter(new DOM("#Dialogs_Thread_InfoViewer_Content_Overview").textContent).forEach((urlString) => { new DOM("#Dialogs_Thread_InfoViewer_Content_Overview").innerHTML = new DOM("#Dialogs_Thread_InfoViewer_Content_Overview").innerHTML.replace(urlString, `<A Href = "${urlString}" Target = "_blank">${urlString}</A>`); }); URL.filter(new DOM("#Dialogs_Thread_InfoViewer_Content_Detail").textContent).forEach((urlString) => { new DOM("#Dialogs_Thread_InfoViewer_Content_Detail").innerHTML = new DOM("#Dialogs_Thread_InfoViewer_Content_Detail").innerHTML.replace(urlString, `<A Href = "${urlString}" Target = "_blank">${urlString}</A>`); }); }); } }); new DOM("#Dialogs_Thread_Poster_Menu_MenuItem-EmbedLink").addEventListener("click", () => { new DOM("#Dialogs_Thread_Poster_LinkEmbedder").showModal(); }); new DOM("#Dialogs_Thread_Poster_Menu_MenuItem-EmbedImage").addEventListener("click", () => { new DOM("#Dialogs_Thread_Poster").close(); let picker = new Picker.PhotoPicker(data => { console.log(data); switch (data[google.picker.Response.ACTION]) { case google.picker.Action.CANCEL: case google.picker.Action.PICKED: new DOM("#Dialogs_Thread_Poster").showModal(); break; } }); picker.show(); }); new DOM("#Dialogs_Thread_Poster_Menu_MenuItem-EmbedFile").addEventListener("click", () => { new DOM("#Dialogs_Thread_Poster").close(); let picker = new Picker.FilePicker(data => { console.log(data); switch (data[google.picker.Response.ACTION]) { case google.picker.Action.CANCEL: case google.picker.Action.PICKED: new DOM("#Dialogs_Thread_Poster").showModal(); break; } }); picker.show(); }); new DOM("#Dialogs_Thread_Poster_Content_Text-Input").addEventListener("keydown", (event) => { let inputter = event.target; let selectionStart = inputter.selectionStart, selectionEnd = inputter.selectionEnd; switch (event.keyCode) { case 9: event.preventDefault(); inputter.value = `${inputter.value.slice(0, selectionStart)}\t${inputter.value.slice(selectionEnd)}`; inputter.setSelectionRange(selectionStart + 1, selectionStart + 1); new DOM("#Dialogs_Thread_Poster_Content_Text").classList.add("is-dirty"); break; } }); new DOM("#Dialogs_Thread_Poster_Btns_OK").addEventListener("click", (event) => { base.Database.transaction("threads/" + new DOM("#Dialogs_Thread_Poster_TID").value + "/data", (res) => { base.Database.set("threads/" + new DOM("#Dialogs_Thread_Poster_TID").value + "/data/" + res.length, { uid: base.user.uid, content: new DOM("#Dialogs_Thread_Poster_Content_Text-Input").value, createdAt: new Date().getTime() }); new DOM("#Dialogs_Thread_Poster_Btns_OK").classList.add("mdl-button--disabled"), new DOM("#Dialogs_Thread_Poster_Content_Text").classList.remove("is-dirty"), new DOM("#Dialogs_Thread_Poster_Content_Text-Input").value = ""; new DOM("#Page").contentDocument.querySelector("#FlowPanel_Btns_CreatePost").removeAttribute("Disabled"); new DOM("#Dialogs_Thread_Poster").close(); }); }); new DOM("#Dialogs_Thread_Poster_Btns_Cancel").addEventListener("click", () => { new DOM("#Dialogs_Thread_Poster_Btns_OK").classList.add("mdl-button--disabled"), new DOM("#Dialogs_Thread_Poster_Content_Text").classList.remove("is-dirty"), new DOM("#Dialogs_Thread_Poster_Content_Text-Input").value = ""; new DOM("#Page").contentDocument.querySelector("#FlowPanel_Btns_CreatePost").removeAttribute("Disabled"); }); for (let watcherName in watchers) DOM.Watcher.addWatcher(watchers[watcherName].watcher); });
GenbuProject/SimpleThread
Dialog.js
JavaScript
agpl-3.0
13,060
{% extends "happyapp/base.html" %} {% load i18n %} {% block title %}{% trans "Good for you, continue beeing happy :D" %}{% endblock %} {% block content %} <h1 class="ok"> {% blocktrans %} Good for you, continue beeing happy, you are doing it ok. {% endblocktrans %} </h1> {% include "happyapp/makead.html" %} {% endblock %}
danigm/happy
happy/happyapp/templates/happyapp/good_for_you.html
HTML
agpl-3.0
330
package com.simplyian.superplots.actions; import static org.mockito.Matchers.contains; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.when; import java.util.Arrays; import java.util.List; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.simplyian.superplots.EconHook; import com.simplyian.superplots.SPSettings; import com.simplyian.superplots.SuperPlotsPlugin; import com.simplyian.superplots.plot.Plot; import com.simplyian.superplots.plot.PlotManager; public class ActionWithdrawTest { private SuperPlotsPlugin main; private ActionWithdraw action; private PlotManager plotManager; private Player player; private EconHook econ; @Before public void setup() { main = mock(SuperPlotsPlugin.class); action = new ActionWithdraw(main); econ = mock(EconHook.class); when(main.getEconomy()).thenReturn(econ); plotManager = mock(PlotManager.class); when(main.getPlotManager()).thenReturn(plotManager); SPSettings settings = mock(SPSettings.class); when(main.getSettings()).thenReturn(settings); when(settings.getInfluenceMultiplier()).thenReturn(1.5); when(settings.getInitialPlotSize()).thenReturn(10); player = mock(Player.class); when(player.getName()).thenReturn("albireox"); } @After public void tearDown() { main = null; action = null; plotManager = null; player = null; } @Test public void test_perform_notInPlot() { World world = mock(World.class); Location playerLoc = new Location(world, 0, 0, 0); when(plotManager.getPlotAt(playerLoc)).thenReturn(null); List<String> args = Arrays.asList("asdf"); action.perform(player, args); verify(player).sendMessage(contains("not in a plot")); } @Test public void test_perform_mustBeAdministrator() { World world = mock(World.class); Location playerLoc = new Location(world, 0, 0, 0); when(player.getLocation()).thenReturn(playerLoc); Plot plot = mock(Plot.class); when(plotManager.getPlotAt(playerLoc)).thenReturn(plot); when(plot.isAdministrator("albireox")).thenReturn(false); when(player.getName()).thenReturn("albireox"); List<String> args = Arrays.asList(); action.perform(player, args); verify(player).sendMessage(contains("must be an administrator")); } @Test public void test_perform_noAmount() { World world = mock(World.class); Location playerLoc = new Location(world, 0, 0, 0); when(player.getLocation()).thenReturn(playerLoc); Plot plot = mock(Plot.class); when(plotManager.getPlotAt(playerLoc)).thenReturn(plot); when(plot.isAdministrator("albireox")).thenReturn(true); when(player.getName()).thenReturn("albireox"); List<String> args = Arrays.asList(); action.perform(player, args); verify(player).sendMessage(contains("did not specify")); } @Test public void test_perform_notANumber() { World world = mock(World.class); Location playerLoc = new Location(world, 0, 0, 0); when(player.getLocation()).thenReturn(playerLoc); Plot plot = mock(Plot.class); when(plotManager.getPlotAt(playerLoc)).thenReturn(plot); when(plot.isAdministrator("albireox")).thenReturn(true); when(player.getName()).thenReturn("albireox"); when(econ.getBalance("albireox")).thenReturn(200.0); List<String> args = Arrays.asList("400x"); action.perform(player, args); verify(player).sendMessage(contains("not a valid amount")); } @Test public void test_perform_notEnoughMoney() { World world = mock(World.class); Location playerLoc = new Location(world, 0, 0, 0); when(player.getLocation()).thenReturn(playerLoc); Plot plot = mock(Plot.class); when(plotManager.getPlotAt(playerLoc)).thenReturn(plot); when(plot.isAdministrator("albireox")).thenReturn(true); when(player.getName()).thenReturn("albireox"); when(plot.getFunds()).thenReturn(200); List<String> args = Arrays.asList("400"); action.perform(player, args); verify(player).sendMessage(contains("doesn't have that much money")); } @Test public void test_perform_success() { World world = mock(World.class); Location playerLoc = new Location(world, 0, 0, 0); when(player.getLocation()).thenReturn(playerLoc); Plot plot = mock(Plot.class); when(plotManager.getPlotAt(playerLoc)).thenReturn(plot); when(plot.isAdministrator("albireox")).thenReturn(true); when(player.getName()).thenReturn("albireox"); when(plot.getFunds()).thenReturn(400); List<String> args = Arrays.asList("400"); action.perform(player, args); verify(player).sendMessage(contains("has been withdrawn")); verify(plot).subtractFunds(400); verify(econ).addBalance("albireox", 400); } }
simplyianm/SuperPlots
src/test/java/com/simplyian/superplots/actions/ActionWithdrawTest.java
Java
agpl-3.0
5,323
# -*- encoding: utf-8 -*- from . import res_partner_bank from . import account_bank_statement_import
StefanRijnhart/bank-statement-import
account_bank_statement_import/__init__.py
Python
agpl-3.0
102
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Struct template basic_stream</title> <link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../../index.html" title="Chapter&#160;1.&#160;Boost.Convert 2.0"> <link rel="up" href="../../header/boost/convert/stream_hpp.html" title="Header &lt;boost/convert/stream.hpp&gt;"> <link rel="prev" href="../../header/boost/convert/stream_hpp.html" title="Header &lt;boost/convert/stream.hpp&gt;"> <link rel="next" href="basic_stream/ibuffer_type.html" title="Struct ibuffer_type"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../../header/boost/convert/stream_hpp.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../header/boost/convert/stream_hpp.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="basic_stream/ibuffer_type.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.cnv.basic_stream"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Struct template basic_stream</span></h2> <p>boost::cnv::basic_stream</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../header/boost/convert/stream_hpp.html" title="Header &lt;boost/convert/stream.hpp&gt;">boost/convert/stream.hpp</a>&gt; </span><span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> Char<span class="special">&gt;</span> <span class="keyword">struct</span> <a class="link" href="basic_stream.html" title="Struct template basic_stream">basic_stream</a> <span class="special">:</span> <span class="keyword">public</span> <span class="identifier">noncopyable</span> <span class="special">{</span> <span class="comment">// types</span> <span class="keyword">typedef</span> <span class="identifier">Char</span> <a name="boost.cnv.basic_stream.char_type"></a><span class="identifier">char_type</span><span class="special">;</span> <span class="keyword">typedef</span> <a class="link" href="basic_stream.html" title="Struct template basic_stream">boost::cnv::basic_stream</a><span class="special">&lt;</span> <span class="identifier">char_type</span> <span class="special">&gt;</span> <a name="boost.cnv.basic_stream.this_type"></a><span class="identifier">this_type</span><span class="special">;</span> <span class="keyword">typedef</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_stringstream</span><span class="special">&lt;</span> <span class="identifier">char_type</span> <span class="special">&gt;</span> <a name="boost.cnv.basic_stream.stream_type"></a><span class="identifier">stream_type</span><span class="special">;</span> <span class="keyword">typedef</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_istream</span><span class="special">&lt;</span> <span class="identifier">char_type</span> <span class="special">&gt;</span> <a name="boost.cnv.basic_stream.istream_type"></a><span class="identifier">istream_type</span><span class="special">;</span> <span class="keyword">typedef</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_streambuf</span><span class="special">&lt;</span> <span class="identifier">char_type</span> <span class="special">&gt;</span> <a name="boost.cnv.basic_stream.buffer_type"></a><span class="identifier">buffer_type</span><span class="special">;</span> <span class="keyword">typedef</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_string</span><span class="special">&lt;</span> <span class="identifier">char_type</span> <span class="special">&gt;</span> <a name="boost.cnv.basic_stream.stdstr_type"></a><span class="identifier">stdstr_type</span><span class="special">;</span> <span class="keyword">typedef</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">ios_base</span> <span class="special">&amp;</span><span class="special">(</span><span class="special">*</span> <a name="boost.cnv.basic_stream.manipulator_type"></a><span class="identifier">manipulator_type</span><span class="special">;</span> <span class="comment">// member classes/structs/unions</span> <span class="keyword">struct</span> <a class="link" href="basic_stream/ibuffer_type.html" title="Struct ibuffer_type">ibuffer_type</a> <span class="special">:</span> <span class="keyword">public</span> <span class="identifier">buffer_type</span> <span class="special">{</span> <span class="comment">// <a class="link" href="basic_stream/ibuffer_type.html#boost.cnv.basic_stream.ibuffer_typeconstruct-copy-destruct">construct/copy/destruct</a></span> <a class="link" href="basic_stream/ibuffer_type.html#idp35843504-bb"><span class="identifier">ibuffer_type</span></a><span class="special">(</span><span class="identifier">char_type</span> <span class="keyword">const</span> <span class="special">*</span><span class="special">,</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span><span class="special">)</span><span class="special">;</span> <span class="special">}</span><span class="special">;</span> <span class="keyword">struct</span> <a class="link" href="basic_stream/obuffer_type.html" title="Struct obuffer_type">obuffer_type</a> <span class="special">:</span> <span class="keyword">public</span> <span class="identifier">buffer_type</span> <span class="special">{</span> <span class="special">}</span><span class="special">;</span> <span class="comment">// <a class="link" href="basic_stream.html#boost.cnv.basic_streamconstruct-copy-destruct">construct/copy/destruct</a></span> <a class="link" href="basic_stream.html#idp35899760-bb"><span class="identifier">basic_stream</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span> <a class="link" href="basic_stream.html#idp35900048-bb"><span class="identifier">basic_stream</span></a><span class="special">(</span><a class="link" href="basic_stream.html#boost.cnv.basic_stream.this_type">this_type</a> <span class="special">&amp;&amp;</span><span class="special">)</span><span class="special">;</span> <span class="comment">// <a class="link" href="basic_stream.html#idp35852432-bb">public member functions</a></span> <a class="link" href="basic_stream.html#idp35852992-bb"><span class="identifier">BOOST_CNV_STRING_ENABLE</span></a><span class="special">(</span><span class="identifier">type</span> <span class="keyword">const</span> <span class="special">&amp;</span><span class="special">,</span> <span class="identifier">optional</span><span class="special">&lt;</span> <span class="identifier">string_type</span> <span class="special">&gt;</span> <span class="special">&amp;</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span> <a class="link" href="basic_stream.html#idp35855344-bb"><span class="identifier">BOOST_CNV_STRING_ENABLE</span></a><span class="special">(</span><span class="identifier">string_type</span> <span class="keyword">const</span> <span class="special">&amp;</span><span class="special">,</span> <span class="identifier">optional</span><span class="special">&lt;</span> <span class="identifier">type</span> <span class="special">&gt;</span> <span class="special">&amp;</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span> <span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> type<span class="special">&gt;</span> <span class="keyword">void</span> <a class="link" href="basic_stream.html#idp35857680-bb"><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span></a><span class="special">(</span><span class="identifier">char_type</span> <span class="keyword">const</span> <span class="special">*</span><span class="special">,</span> <span class="identifier">optional</span><span class="special">&lt;</span> <span class="identifier">type</span> <span class="special">&gt;</span> <span class="special">&amp;</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span> <span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> type<span class="special">&gt;</span> <span class="keyword">void</span> <a class="link" href="basic_stream.html#idp35861024-bb"><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span></a><span class="special">(</span><span class="identifier">stdstr_type</span> <span class="keyword">const</span> <span class="special">&amp;</span><span class="special">,</span> <span class="identifier">optional</span><span class="special">&lt;</span> <span class="identifier">type</span> <span class="special">&gt;</span> <span class="special">&amp;</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span> <span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> manipulator<span class="special">&gt;</span> <a class="link" href="basic_stream.html#boost.cnv.basic_stream.this_type">this_type</a> <span class="special">&amp;</span> <a class="link" href="basic_stream.html#idp35864368-bb"><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span></a><span class="special">(</span><span class="identifier">manipulator</span><span class="special">)</span><span class="special">;</span> <a class="link" href="basic_stream.html#boost.cnv.basic_stream.this_type">this_type</a> <span class="special">&amp;</span> <a class="link" href="basic_stream.html#idp35867040-bb"><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span></a><span class="special">(</span><span class="identifier">manipulator_type</span><span class="special">)</span><span class="special">;</span> <a class="link" href="basic_stream.html#boost.cnv.basic_stream.this_type">this_type</a> <span class="special">&amp;</span> <a class="link" href="basic_stream.html#idp35868864-bb"><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span></a><span class="special">(</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">locale</span> <span class="keyword">const</span> <span class="special">&amp;</span><span class="special">)</span><span class="special">;</span> <a class="link" href="basic_stream.html#idp35870688-bb"><span class="identifier">BOOST_CNV_PARAM</span></a><span class="special">(</span><span class="identifier">locale</span><span class="special">,</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">locale</span><span class="special">)</span><span class="special">;</span> <a class="link" href="basic_stream.html#idp35872752-bb"><span class="identifier">BOOST_CNV_PARAM</span></a><span class="special">(</span><span class="identifier">precision</span><span class="special">,</span> <span class="keyword">int</span><span class="special">)</span><span class="special">;</span> <a class="link" href="basic_stream.html#idp35874816-bb"><span class="identifier">BOOST_CNV_PARAM</span></a><span class="special">(</span><span class="identifier">precision</span><span class="special">,</span> <span class="keyword">int</span><span class="special">)</span><span class="special">;</span> <a class="link" href="basic_stream.html#idp35876880-bb"><span class="identifier">BOOST_CNV_PARAM</span></a><span class="special">(</span><span class="identifier">width</span><span class="special">,</span> <span class="keyword">int</span><span class="special">)</span><span class="special">;</span> <a class="link" href="basic_stream.html#idp35878944-bb"><span class="identifier">BOOST_CNV_PARAM</span></a><span class="special">(</span><span class="identifier">fill</span><span class="special">,</span> <span class="keyword">char</span><span class="special">)</span><span class="special">;</span> <a class="link" href="basic_stream.html#idp35881008-bb"><span class="identifier">BOOST_CNV_PARAM</span></a><span class="special">(</span><span class="identifier">uppercase</span><span class="special">,</span> <span class="keyword">bool</span><span class="special">)</span><span class="special">;</span> <a class="link" href="basic_stream.html#idp35883072-bb"><span class="identifier">BOOST_CNV_PARAM</span></a><span class="special">(</span><span class="identifier">skipws</span><span class="special">,</span> <span class="keyword">bool</span><span class="special">)</span><span class="special">;</span> <a class="link" href="basic_stream.html#idp35885136-bb"><span class="identifier">BOOST_CNV_PARAM</span></a><span class="special">(</span><a class="link" href="adjust.html" title="Struct adjust">adjust</a><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">cnv</span><span class="special">::</span><span class="identifier">adjust</span><span class="special">::</span><span class="identifier">type</span><span class="special">)</span><span class="special">;</span> <a class="link" href="basic_stream.html#idp35887344-bb"><span class="identifier">BOOST_CNV_PARAM</span></a><span class="special">(</span><a class="link" href="base.html" title="Struct base">base</a><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">cnv</span><span class="special">::</span><span class="identifier">base</span><span class="special">::</span><span class="identifier">type</span><span class="special">)</span><span class="special">;</span> <a class="link" href="basic_stream.html#idp35889536-bb"><span class="identifier">BOOST_CNV_PARAM</span></a><span class="special">(</span><a class="link" href="notation.html" title="Struct notation">notation</a><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">cnv</span><span class="special">::</span><span class="identifier">notation</span><span class="special">::</span><span class="identifier">type</span><span class="special">)</span><span class="special">;</span> <span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> string_type<span class="special">,</span> <span class="keyword">typename</span> in_type<span class="special">&gt;</span> <span class="keyword">void</span> <a class="link" href="basic_stream.html#idp35891744-bb"><span class="identifier">to_str</span></a><span class="special">(</span><span class="identifier">in_type</span> <span class="keyword">const</span> <span class="special">&amp;</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">optional</span><span class="special">&lt;</span> <span class="identifier">string_type</span> <span class="special">&gt;</span> <span class="special">&amp;</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span> <span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> string_type<span class="special">,</span> <span class="keyword">typename</span> out_type<span class="special">&gt;</span> <span class="keyword">void</span> <a class="link" href="basic_stream.html#idp35895664-bb"><span class="identifier">str_to</span></a><span class="special">(</span><span class="identifier">boost</span><span class="special">::</span><span class="identifier">cnv</span><span class="special">::</span><span class="identifier">range</span><span class="special">&lt;</span> <span class="identifier">string_type</span> <span class="special">&gt;</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">optional</span><span class="special">&lt;</span> <span class="identifier">out_type</span> <span class="special">&gt;</span> <span class="special">&amp;</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span> <span class="comment">// <a class="link" href="basic_stream.html#idp35901312-bb">private member functions</a></span> <span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> string_type<span class="special">,</span> <span class="keyword">typename</span> out_type<span class="special">&gt;</span> <span class="keyword">void</span> <a class="link" href="basic_stream.html#idp35901888-bb"><span class="identifier">str_to</span></a><span class="special">(</span><span class="identifier">cnv</span><span class="special">::</span><span class="identifier">range</span><span class="special">&lt;</span> <span class="identifier">string_type</span> <span class="special">&gt;</span><span class="special">,</span> <span class="identifier">optional</span><span class="special">&lt;</span> <span class="identifier">out_type</span> <span class="special">&gt;</span> <span class="special">&amp;</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span> <span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> string_type<span class="special">,</span> <span class="keyword">typename</span> in_type<span class="special">&gt;</span> <span class="keyword">void</span> <a class="link" href="basic_stream.html#idp35905808-bb"><span class="identifier">to_str</span></a><span class="special">(</span><span class="identifier">in_type</span> <span class="keyword">const</span> <span class="special">&amp;</span><span class="special">,</span> <span class="identifier">optional</span><span class="special">&lt;</span> <span class="identifier">string_type</span> <span class="special">&gt;</span> <span class="special">&amp;</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span> <span class="special">}</span><span class="special">;</span></pre></div> <div class="refsect1"> <a name="idp102043712"></a><h2>Description</h2> <div class="refsect2"> <a name="idp102044128"></a><h3> <a name="boost.cnv.basic_streamconstruct-copy-destruct"></a><code class="computeroutput">basic_stream</code> public construct/copy/destruct</h3> <div class="orderedlist"><ol class="orderedlist" type="1"> <li class="listitem"><pre class="literallayout"><a name="idp35899760-bb"></a><span class="identifier">basic_stream</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"><a name="idp35900048-bb"></a><span class="identifier">basic_stream</span><span class="special">(</span><a class="link" href="basic_stream.html#boost.cnv.basic_stream.this_type">this_type</a> <span class="special">&amp;&amp;</span> other<span class="special">)</span><span class="special">;</span></pre></li> </ol></div> </div> <div class="refsect2"> <a name="idp102055104"></a><h3> <a name="idp35852432-bb"></a><code class="computeroutput">basic_stream</code> public member functions</h3> <div class="orderedlist"><ol class="orderedlist" type="1"> <li class="listitem"><pre class="literallayout"> <a name="idp35852992-bb"></a><span class="identifier">BOOST_CNV_STRING_ENABLE</span><span class="special">(</span><span class="identifier">type</span> <span class="keyword">const</span> <span class="special">&amp;</span> v<span class="special">,</span> <span class="identifier">optional</span><span class="special">&lt;</span> <span class="identifier">string_type</span> <span class="special">&gt;</span> <span class="special">&amp;</span> s<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"> <a name="idp35855344-bb"></a><span class="identifier">BOOST_CNV_STRING_ENABLE</span><span class="special">(</span><span class="identifier">string_type</span> <span class="keyword">const</span> <span class="special">&amp;</span> s<span class="special">,</span> <span class="identifier">optional</span><span class="special">&lt;</span> <span class="identifier">type</span> <span class="special">&gt;</span> <span class="special">&amp;</span> r<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"><span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> type<span class="special">&gt;</span> <span class="keyword">void</span> <a name="idp35857680-bb"></a><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span><span class="special">(</span><span class="identifier">char_type</span> <span class="keyword">const</span> <span class="special">*</span> s<span class="special">,</span> <span class="identifier">optional</span><span class="special">&lt;</span> <span class="identifier">type</span> <span class="special">&gt;</span> <span class="special">&amp;</span> r<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"><span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> type<span class="special">&gt;</span> <span class="keyword">void</span> <a name="idp35861024-bb"></a><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span><span class="special">(</span><span class="identifier">stdstr_type</span> <span class="keyword">const</span> <span class="special">&amp;</span> s<span class="special">,</span> <span class="identifier">optional</span><span class="special">&lt;</span> <span class="identifier">type</span> <span class="special">&gt;</span> <span class="special">&amp;</span> r<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"><span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> manipulator<span class="special">&gt;</span> <a class="link" href="basic_stream.html#boost.cnv.basic_stream.this_type">this_type</a> <span class="special">&amp;</span> <a name="idp35864368-bb"></a><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span><span class="special">(</span><span class="identifier">manipulator</span> m<span class="special">)</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"><a class="link" href="basic_stream.html#boost.cnv.basic_stream.this_type">this_type</a> <span class="special">&amp;</span> <a name="idp35867040-bb"></a><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span><span class="special">(</span><span class="identifier">manipulator_type</span> m<span class="special">)</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"><a class="link" href="basic_stream.html#boost.cnv.basic_stream.this_type">this_type</a> <span class="special">&amp;</span> <a name="idp35868864-bb"></a><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span><span class="special">(</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">locale</span> <span class="keyword">const</span> <span class="special">&amp;</span> l<span class="special">)</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"> <a name="idp35870688-bb"></a><span class="identifier">BOOST_CNV_PARAM</span><span class="special">(</span><span class="identifier">locale</span><span class="special">,</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">locale</span> const<span class="special">)</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"> <a name="idp35872752-bb"></a><span class="identifier">BOOST_CNV_PARAM</span><span class="special">(</span><span class="identifier">precision</span><span class="special">,</span> <span class="keyword">int</span> const<span class="special">)</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"> <a name="idp35874816-bb"></a><span class="identifier">BOOST_CNV_PARAM</span><span class="special">(</span><span class="identifier">precision</span><span class="special">,</span> <span class="keyword">int</span><span class="special">)</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"> <a name="idp35876880-bb"></a><span class="identifier">BOOST_CNV_PARAM</span><span class="special">(</span><span class="identifier">width</span><span class="special">,</span> <span class="keyword">int</span> const<span class="special">)</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"> <a name="idp35878944-bb"></a><span class="identifier">BOOST_CNV_PARAM</span><span class="special">(</span><span class="identifier">fill</span><span class="special">,</span> <span class="keyword">char</span> const<span class="special">)</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"> <a name="idp35881008-bb"></a><span class="identifier">BOOST_CNV_PARAM</span><span class="special">(</span><span class="identifier">uppercase</span><span class="special">,</span> <span class="keyword">bool</span> const<span class="special">)</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"> <a name="idp35883072-bb"></a><span class="identifier">BOOST_CNV_PARAM</span><span class="special">(</span><span class="identifier">skipws</span><span class="special">,</span> <span class="keyword">bool</span> const<span class="special">)</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"> <a name="idp35885136-bb"></a><span class="identifier">BOOST_CNV_PARAM</span><span class="special">(</span><a class="link" href="adjust.html" title="Struct adjust">adjust</a><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">cnv</span><span class="special">::</span><span class="identifier">adjust</span><span class="special">::</span><span class="identifier">type</span> const<span class="special">)</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"> <a name="idp35887344-bb"></a><span class="identifier">BOOST_CNV_PARAM</span><span class="special">(</span><a class="link" href="base.html" title="Struct base">base</a><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">cnv</span><span class="special">::</span><span class="identifier">base</span><span class="special">::</span><span class="identifier">type</span> const<span class="special">)</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"> <a name="idp35889536-bb"></a><span class="identifier">BOOST_CNV_PARAM</span><span class="special">(</span><a class="link" href="notation.html" title="Struct notation">notation</a><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">cnv</span><span class="special">::</span><span class="identifier">notation</span><span class="special">::</span><span class="identifier">type</span> const<span class="special">)</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"><span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> string_type<span class="special">,</span> <span class="keyword">typename</span> in_type<span class="special">&gt;</span> <span class="keyword">void</span> <a name="idp35891744-bb"></a><span class="identifier">to_str</span><span class="special">(</span><span class="identifier">in_type</span> <span class="keyword">const</span> <span class="special">&amp;</span> value_in<span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">optional</span><span class="special">&lt;</span> <span class="identifier">string_type</span> <span class="special">&gt;</span> <span class="special">&amp;</span> string_out<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"><span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> string_type<span class="special">,</span> <span class="keyword">typename</span> out_type<span class="special">&gt;</span> <span class="keyword">void</span> <a name="idp35895664-bb"></a><span class="identifier">str_to</span><span class="special">(</span><span class="identifier">boost</span><span class="special">::</span><span class="identifier">cnv</span><span class="special">::</span><span class="identifier">range</span><span class="special">&lt;</span> <span class="identifier">string_type</span> <span class="special">&gt;</span> string_in<span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">optional</span><span class="special">&lt;</span> <span class="identifier">out_type</span> <span class="special">&gt;</span> <span class="special">&amp;</span> result_out<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li> </ol></div> </div> <div class="refsect2"> <a name="idp102235440"></a><h3> <a name="idp35901312-bb"></a><code class="computeroutput">basic_stream</code> private member functions</h3> <div class="orderedlist"><ol class="orderedlist" type="1"> <li class="listitem"><pre class="literallayout"><span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> string_type<span class="special">,</span> <span class="keyword">typename</span> out_type<span class="special">&gt;</span> <span class="keyword">void</span> <a name="idp35901888-bb"></a><span class="identifier">str_to</span><span class="special">(</span><span class="identifier">cnv</span><span class="special">::</span><span class="identifier">range</span><span class="special">&lt;</span> <span class="identifier">string_type</span> <span class="special">&gt;</span><span class="special">,</span> <span class="identifier">optional</span><span class="special">&lt;</span> <span class="identifier">out_type</span> <span class="special">&gt;</span> <span class="special">&amp;</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"><span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> string_type<span class="special">,</span> <span class="keyword">typename</span> in_type<span class="special">&gt;</span> <span class="keyword">void</span> <a name="idp35905808-bb"></a><span class="identifier">to_str</span><span class="special">(</span><span class="identifier">in_type</span> <span class="keyword">const</span> <span class="special">&amp;</span><span class="special">,</span> <span class="identifier">optional</span><span class="special">&lt;</span> <span class="identifier">string_type</span> <span class="special">&gt;</span> <span class="special">&amp;</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li> </ol></div> </div> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2009-2016 Vladimir Batov<p> Distributed under the Boost Software License, Version 1.0. See copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>. </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../../header/boost/convert/stream_hpp.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../header/boost/convert/stream_hpp.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="basic_stream/ibuffer_type.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
cris-iisc/mpc-primitives
crislib/libscapi/lib/boost_1_64_0/libs/convert/doc/html/boost/cnv/basic_stream.html
HTML
agpl-3.0
34,555
import {login, signup} from '../../src/app/actions/authActions'; import ActionsConstants from '../../src/common/constants/actionsConstants'; describe('auth actions', () => { describe('if we create a login action', () => { let userId = 'TestUser'; it('should generate action with payload', () => { expect(login(userId)).toEqual({ type: ActionsConstants.Login, payload: userId }); }); }); describe('if we create a login action without a userId', () => { const error = new TypeError('not a string'); it('should fail', () => { expect(login(error)).toEqual({ type: ActionsConstants.Login, payload: error, error: true }); }); }); describe('if we create a signup action', () => { it('should generate action with payload', () => { expect(signup()).toEqual({ type: ActionsConstants.SignUp }); }); }); });
bernatmv/thegame
client/__tests__/actions/authActions.spec.ts
TypeScript
agpl-3.0
1,057
""" Tests course_creators.admin.py. """ from django.test import TestCase from django.contrib.auth.models import User from django.contrib.admin.sites import AdminSite from django.http import HttpRequest import mock from course_creators.admin import CourseCreatorAdmin from course_creators.models import CourseCreator from django.core import mail from student.roles import CourseCreatorRole from student import auth def mock_render_to_string(template_name, context): """Return a string that encodes template_name and context""" return str((template_name, context)) class CourseCreatorAdminTest(TestCase): """ Tests for course creator admin. """ def setUp(self): """ Test case setup """ super(CourseCreatorAdminTest, self).setUp() self.user = User.objects.create_user('test_user', '[email protected]', 'foo') self.table_entry = CourseCreator(user=self.user) self.table_entry.save() self.admin = User.objects.create_user('Mark', '[email protected]', 'foo') self.admin.is_staff = True self.request = HttpRequest() self.request.user = self.admin self.creator_admin = CourseCreatorAdmin(self.table_entry, AdminSite()) self.studio_request_email = '[email protected]' self.enable_creator_group_patch = { "ENABLE_CREATOR_GROUP": True, "STUDIO_REQUEST_EMAIL": self.studio_request_email } @mock.patch('course_creators.admin.render_to_string', mock.Mock(side_effect=mock_render_to_string, autospec=True)) @mock.patch('django.contrib.auth.models.User.email_user') def test_change_status(self, email_user): """ Tests that updates to state impact the creator group maintained in authz.py and that e-mails are sent. """ def change_state_and_verify_email(state, is_creator): """ Changes user state, verifies creator status, and verifies e-mail is sent based on transition """ self._change_state(state) self.assertEqual(is_creator, auth.user_has_role(self.user, CourseCreatorRole())) context = {'studio_request_email': self.studio_request_email} if state == CourseCreator.GRANTED: template = 'emails/course_creator_granted.txt' elif state == CourseCreator.DENIED: template = 'emails/course_creator_denied.txt' else: template = 'emails/course_creator_revoked.txt' email_user.assert_called_with( mock_render_to_string('emails/course_creator_subject.txt', context), mock_render_to_string(template, context), self.studio_request_email ) with mock.patch.dict('django.conf.settings.FEATURES', self.enable_creator_group_patch): # User is initially unrequested. self.assertFalse(auth.user_has_role(self.user, CourseCreatorRole())) change_state_and_verify_email(CourseCreator.GRANTED, True) change_state_and_verify_email(CourseCreator.DENIED, False) change_state_and_verify_email(CourseCreator.GRANTED, True) change_state_and_verify_email(CourseCreator.PENDING, False) change_state_and_verify_email(CourseCreator.GRANTED, True) change_state_and_verify_email(CourseCreator.UNREQUESTED, False) change_state_and_verify_email(CourseCreator.DENIED, False) @mock.patch('course_creators.admin.render_to_string', mock.Mock(side_effect=mock_render_to_string, autospec=True)) def test_mail_admin_on_pending(self): """ Tests that the admin account is notified when a user is in the 'pending' state. """ def check_admin_message_state(state, expect_sent_to_admin, expect_sent_to_user): """ Changes user state and verifies e-mail sent to admin address only when pending. """ mail.outbox = [] self._change_state(state) # If a message is sent to the user about course creator status change, it will be the first # message sent. Admin message will follow. base_num_emails = 1 if expect_sent_to_user else 0 if expect_sent_to_admin: context = {'user_name': "test_user", 'user_email': u'[email protected]'} self.assertEquals(base_num_emails + 1, len(mail.outbox), 'Expected admin message to be sent') sent_mail = mail.outbox[base_num_emails] self.assertEquals( mock_render_to_string('emails/course_creator_admin_subject.txt', context), sent_mail.subject ) self.assertEquals( mock_render_to_string('emails/course_creator_admin_user_pending.txt', context), sent_mail.body ) self.assertEquals(self.studio_request_email, sent_mail.from_email) self.assertEqual([self.studio_request_email], sent_mail.to) else: self.assertEquals(base_num_emails, len(mail.outbox)) with mock.patch.dict('django.conf.settings.FEATURES', self.enable_creator_group_patch): # E-mail message should be sent to admin only when new state is PENDING, regardless of what # previous state was (unless previous state was already PENDING). # E-mail message sent to user only on transition into and out of GRANTED state. check_admin_message_state(CourseCreator.UNREQUESTED, expect_sent_to_admin=False, expect_sent_to_user=False) check_admin_message_state(CourseCreator.PENDING, expect_sent_to_admin=True, expect_sent_to_user=False) check_admin_message_state(CourseCreator.GRANTED, expect_sent_to_admin=False, expect_sent_to_user=True) check_admin_message_state(CourseCreator.DENIED, expect_sent_to_admin=False, expect_sent_to_user=True) check_admin_message_state(CourseCreator.GRANTED, expect_sent_to_admin=False, expect_sent_to_user=True) check_admin_message_state(CourseCreator.PENDING, expect_sent_to_admin=True, expect_sent_to_user=True) check_admin_message_state(CourseCreator.PENDING, expect_sent_to_admin=False, expect_sent_to_user=False) check_admin_message_state(CourseCreator.DENIED, expect_sent_to_admin=False, expect_sent_to_user=True) def _change_state(self, state): """ Helper method for changing state """ self.table_entry.state = state self.creator_admin.save_model(self.request, self.table_entry, None, True) def test_add_permission(self): """ Tests that staff cannot add entries """ self.assertFalse(self.creator_admin.has_add_permission(self.request)) def test_delete_permission(self): """ Tests that staff cannot delete entries """ self.assertFalse(self.creator_admin.has_delete_permission(self.request)) def test_change_permission(self): """ Tests that only staff can change entries """ self.assertTrue(self.creator_admin.has_change_permission(self.request)) self.request.user = self.user self.assertFalse(self.creator_admin.has_change_permission(self.request))
nttks/edx-platform
cms/djangoapps/course_creators/tests/test_admin.py
Python
agpl-3.0
7,332
# quium crowdference's WUI
crowdference/quium
README.md
Markdown
agpl-3.0
27
<?php $mod_strings = array_merge($mod_strings, array( 'LBL_LIST_NONINHERITABLE' => "Não Herdável", ) ); ?>
yonkon/nedvig
custom/Extension/modules/Users/Ext/Language/pt_br.SecurityGroups.php
PHP
agpl-3.0
115
DELETE FROM `weenie` WHERE `class_Id` = 14030; INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`) VALUES (14030, 'housecottage2338', 53, '2019-02-10 00:00:00') /* House */; INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`) VALUES (14030, 1, 128) /* ItemType - Misc */ , (14030, 5, 10) /* EncumbranceVal */ , (14030, 16, 1) /* ItemUseable - No */ , (14030, 93, 52) /* PhysicsState - Ethereal, IgnoreCollisions, NoDraw */ , (14030, 155, 1) /* HouseType - Cottage */ , (14030, 8041, 101) /* PCAPRecordedPlacement - Resting */; INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`) VALUES (14030, 1, True ) /* Stuck */ , (14030, 24, True ) /* UiHidden */; INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`) VALUES (14030, 39, 0.1) /* DefaultScale */; INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`) VALUES (14030, 1, 'Cottage') /* Name */; INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`) VALUES (14030, 1, 0x02000A42) /* Setup */ , (14030, 8, 0x06002181) /* Icon */ , (14030, 30, 152) /* PhysicsScript - RestrictionEffectBlue */ , (14030, 8001, 203423760) /* PCAPRecordedWeenieHeader - Usable, Burden, HouseRestrictions, PScript */ , (14030, 8003, 148) /* PCAPRecordedObjectDesc - Stuck, Attackable, UiHidden */ , (14030, 8005, 163969) /* PCAPRecordedPhysicsDesc - CSetup, ObjScale, Position, AnimationFrame */; INSERT INTO `weenie_properties_position` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`) VALUES (14030, 8040, 0x6B8E0112, 33.9241, 135.967, 17.9995, -0.66963, 0, 0, -0.742695) /* PCAPRecordedLocation */ /* @teleloc 0x6B8E0112 [33.924100 135.967000 17.999500] -0.669630 0.000000 0.000000 -0.742695 */; INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`) VALUES (14030, 8000, 0x76B8E1A2) /* PCAPRecordedObjectIID */;
ACEmulator/ACE-World
Database/3-Core/9 WeenieDefaults/SQL/House/Cottage/14030 Cottage.sql
SQL
agpl-3.0
2,087
<?php /** * Validation. * * @author Fabio Alessandro Locati <[email protected]> * @author Wenzel Pünter <[email protected]> * @author Daniel Mejta <[email protected]> * * @version 2.0.0 */ namespace Isbn; /** * Validation. */ class Validation { /** * Check Instance. * * @var Check */ private $check; /** * Hyphens Instance. * * @var Hyphens */ private $hyphens; /** * Constructor. * * @param Check $check * @param Hyphens $hyphens */ public function __construct(Check $check, Hyphens $hyphens) { $this->check = $check; $this->hyphens = $hyphens; } /** * Validate the ISBN $isbn. * * @param string $isbn * * @return bool */ public function isbn($isbn) { if ($this->check->is13($isbn)) { return $this->isbn13($isbn); } if ($this->check->is10($isbn)) { return $this->isbn10($isbn); } return false; } /** * Validate the ISBN-10 $isbn. * * @param string $isbn * * @throws Exception * * @return bool */ public function isbn10($isbn) { if (\is_string($isbn) === false) { throw new Exception('Invalid parameter type.'); } //Verify ISBN-10 scheme $isbn = $this->hyphens->removeHyphens($isbn); if (\strlen($isbn) != 10) { return false; } if (\preg_match('/\d{9}[0-9xX]/i', $isbn) == false) { return false; } //Verify checksum $check = 0; for ($i = 0; $i < 10; $i++) { if (\strtoupper($isbn[$i]) === 'X') { $check += 10 * \intval(10 - $i); } else { $check += \intval($isbn[$i]) * \intval(10 - $i); } } return $check % 11 === 0; } /** * Validate the ISBN-13 $isbn. * * @param string $isbn * * @throws Exception * * @return bool */ public function isbn13($isbn) { if (\is_string($isbn) === false) { throw new Exception('Invalid parameter type.'); } //Verify ISBN-13 scheme $isbn = $this->hyphens->removeHyphens($isbn); if (\strlen($isbn) != 13) { return false; } if (\preg_match('/\d{13}/i', $isbn) == false) { return false; } //Verify checksum $check = 0; for ($i = 0; $i < 13; $i += 2) { $check += \substr($isbn, $i, 1); } for ($i = 1; $i < 12; $i += 2) { $check += 3 * \substr($isbn, $i, 1); } return $check % 10 === 0; } }
Fale/isbn
src/Isbn/Validation.php
PHP
agpl-3.0
2,769
import unittest from app import read_config class ConfigFileReaderTest(unittest.TestCase): def test_read(self): config = read_config('config') self.assertEqual(config['cmus_host'], 'raspberry') self.assertEqual(config['cmus_passwd'], 'PaSsWd') self.assertEqual(config['app_host'], 'localhost') self.assertEqual(config['app_port'], '8080') if __name__ == '__main__': unittest.main()
jboynyc/cmus_app
tests.py
Python
agpl-3.0
433
/** * ownCloud - News * * This file is licensed under the Affero General Public License version 3 or * later. See the COPYING file. * * @author Bernhard Posselt <[email protected]> * @copyright Bernhard Posselt 2014 */ #global-loading { width: 100%; height: 100%; } #undo-container { position: fixed; top: 0px; width: 100%; text-align: center; z-index: 101; line-height: 1.2; } #undo { z-index:101; background-color:#fc4; border:0; padding:0 .7em .3em; display:none; position: relative; top:0; border-bottom-left-radius:1em; border-bottom-right-radius:1em; } #undo a { font-weight: bold; } #undo a:hover { text-decoration: underline; }
Xefir/news
css/app.css
CSS
agpl-3.0
755
/** * Copyright (C) 2000 - 2011 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://repository.silverpeas.com/legal/licensing" * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.stratelia.webactiv.beans.admin; import java.util.ArrayList; import java.util.List; import com.silverpeas.scheduler.Scheduler; import com.silverpeas.scheduler.SchedulerEvent; import com.silverpeas.scheduler.SchedulerEventListener; import com.silverpeas.scheduler.SchedulerFactory; import com.silverpeas.scheduler.trigger.JobTrigger; import com.stratelia.silverpeas.silvertrace.SilverTrace; public class SynchroDomainScheduler implements SchedulerEventListener { public static final String ADMINSYNCHRODOMAIN_JOB_NAME = "AdminSynchroDomainJob"; private List<String> domainIds = null; public void initialize(String cron, List<String> domainIds) { try { this.domainIds = domainIds; SchedulerFactory schedulerFactory = SchedulerFactory.getFactory(); Scheduler scheduler = schedulerFactory.getScheduler(); scheduler.unscheduleJob(ADMINSYNCHRODOMAIN_JOB_NAME); JobTrigger trigger = JobTrigger.triggerAt(cron); scheduler.scheduleJob(ADMINSYNCHRODOMAIN_JOB_NAME, trigger, this); } catch (Exception e) { SilverTrace.error("admin", "SynchroDomainScheduler.initialize()", "admin.CANT_INIT_DOMAINS_SYNCHRO", e); } } public void addDomain(String id) { if (domainIds == null) { domainIds = new ArrayList<String>(); } domainIds.add(id); } public void removeDomain(String id) { if (domainIds != null) { domainIds.remove(id); } } public void doSynchro() { SilverTrace.info("admin", "SynchroDomainScheduler.doSynchro()", "root.MSG_GEN_ENTER_METHOD"); if (domainIds != null) { for (String domainId : domainIds) { try { AdminReference.getAdminService().synchronizeSilverpeasWithDomain(domainId, true); } catch (Exception e) { SilverTrace.error("admin", "SynchroDomainScheduler.doSynchro()", "admin.MSG_ERR_SYNCHRONIZE_DOMAIN", e); } } } SilverTrace.info("admin", "SynchroDomainScheduler.doSynchro()", "root.MSG_GEN_EXIT_METHOD"); } @Override public void triggerFired(SchedulerEvent anEvent) { String jobName = anEvent.getJobExecutionContext().getJobName(); SilverTrace.debug("admin", "SynchroDomainScheduler.triggerFired()", "The job '" + jobName + "' is executed"); doSynchro(); } @Override public void jobSucceeded(SchedulerEvent anEvent) { String jobName = anEvent.getJobExecutionContext().getJobName(); SilverTrace.debug("admin", "SynchroDomainScheduler.jobSucceeded()", "The job '" + jobName + "' was successfull"); } @Override public void jobFailed(SchedulerEvent anEvent) { String jobName = anEvent.getJobExecutionContext().getJobName(); SilverTrace.error("admin", "SynchroDomainScheduler.jobFailed", "The job '" + jobName + "' was not successfull"); } }
stephaneperry/Silverpeas-Core
lib-core/src/main/java/com/stratelia/webactiv/beans/admin/SynchroDomainScheduler.java
Java
agpl-3.0
3,969
chunker_bully = Creature:new { objectName = "@mob/creature_names:chunker_bully", randomNameType = NAME_GENERIC_TAG, socialGroup = "chunker", faction = "thug", level = 10, chanceHit = 0.280000, damageMin = 90, damageMax = 110, baseXp = 356, baseHAM = 810, baseHAMmax = 990, armor = 0, resists = {0,0,0,0,0,0,0,-1,-1}, meatType = "", meatAmount = 0, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0.000000, ferocity = 0, pvpBitmask = ATTACKABLE, creatureBitmask = PACK + STALKER, diet = HERBIVORE, templates = {"object/mobile/dressed_mugger.iff", "object/mobile/dressed_robber_human_male_01.iff", "object/mobile/dressed_criminal_thug_zabrak_female_01.iff", "object/mobile/dressed_criminal_thug_aqualish_female_02.iff", "object/mobile/dressed_criminal_thug_aqualish_male_02.iff", "object/mobile/dressed_desperado_bith_female_01.iff", "object/mobile/dressed_criminal_thug_human_female_01.iff", "object/mobile/dressed_goon_twk_female_01.iff", "object/mobile/dressed_criminal_thug_human_male_01.iff", "object/mobile/dressed_robber_twk_female_01.iff", "object/mobile/dressed_villain_trandoshan_male_01.iff", "object/mobile/dressed_desperado_bith_male_01.iff", "object/mobile/dressed_mugger.iff"}, lootGroups = { { groups = { {group = "junk", chance = 1200000}, {group = "rifles", chance = 700000}, {group = "melee_knife", chance = 700000}, {group = "pistols", chance = 700000}, {group = "carbines", chance = 700000}, {group = "chunker_common", chance = 6000000}, } } }, weapons = {"ranged_weapons"}, reactionStf = "@npc_reaction/slang", attacks = merge(marksmannovice,brawlernovice) } CreatureTemplates:addCreatureTemplate(chunker_bully, "chunker_bully")
lasko2112/legend-of-hondo
MMOCoreORB/bin/scripts/mobile/talus/chunker_bully.lua
Lua
agpl-3.0
1,779
# frozen_string_literal: true require 'ffaker' FactoryBot.define do sequence(:random_string) { FFaker::Lorem.sentence } sequence(:random_description) { FFaker::Lorem.paragraphs(Kernel.rand(1..5)).join("\n") } sequence(:random_email) { FFaker::Internet.email } factory :classification, class: Spree::Classification do end factory :exchange, class: Exchange do incoming { false } order_cycle { OrderCycle.first || FactoryBot.create(:simple_order_cycle) } sender { incoming ? FactoryBot.create(:enterprise) : order_cycle.coordinator } receiver { incoming ? order_cycle.coordinator : FactoryBot.create(:enterprise) } end factory :schedule, class: Schedule do sequence(:name) { |n| "Schedule #{n}" } transient do order_cycles { [OrderCycle.first || create(:simple_order_cycle)] } end before(:create) do |schedule, evaluator| evaluator.order_cycles.each do |order_cycle| order_cycle.schedules << schedule end end end factory :proxy_order, class: ProxyOrder do subscription order_cycle { subscription.order_cycles.first } before(:create) do |proxy_order, _proxy| proxy_order.order&.update_attribute(:order_cycle_id, proxy_order.order_cycle_id) end end factory :variant_override, class: VariantOverride do price { 77.77 } on_demand { false } count_on_hand { 11_111 } default_stock { 2000 } resettable { false } trait :on_demand do on_demand { true } count_on_hand { nil } end trait :use_producer_stock_settings do on_demand { nil } count_on_hand { nil } end end factory :inventory_item, class: InventoryItem do enterprise variant visible { true } end factory :enterprise_relationship do end factory :enterprise_role do end factory :enterprise_group, class: EnterpriseGroup do name { 'Enterprise group' } sequence(:permalink) { |n| "group#{n}" } description { 'this is a group' } on_front_page { false } address { FactoryBot.build(:address) } end factory :enterprise_fee, class: EnterpriseFee do transient { amount { nil } } sequence(:name) { |n| "Enterprise fee #{n}" } sequence(:fee_type) { |n| EnterpriseFee::FEE_TYPES[n % EnterpriseFee::FEE_TYPES.count] } enterprise { Enterprise.first || FactoryBot.create(:supplier_enterprise) } calculator { build(:calculator_per_item, preferred_amount: amount) } after(:create) { |ef| ef.calculator.save! } trait :flat_rate do transient { amount { 1 } } calculator { build(:calculator_flat_rate, preferred_amount: amount) } end trait :per_item do transient { amount { 1 } } calculator { build(:calculator_per_item, preferred_amount: amount) } end end factory :adjustment_metadata, class: AdjustmentMetadata do adjustment { FactoryBot.create(:adjustment) } enterprise { FactoryBot.create(:distributor_enterprise) } fee_name { 'fee' } fee_type { 'packing' } enterprise_role { 'distributor' } end factory :producer_property, class: ProducerProperty do value { 'abc123' } producer { create(:supplier_enterprise) } property end factory :stripe_account do enterprise { FactoryBot.create(:distributor_enterprise) } stripe_user_id { "abc123" } stripe_publishable_key { "xyz456" } end end
openfoodfoundation/openfoodnetwork
spec/factories.rb
Ruby
agpl-3.0
3,400
module CC::Exporter::Epub module Exportable def content_cartridge self.attachment end def convert_to_epub(opts={}) exporter = CC::Exporter::Epub::Exporter.new(content_cartridge.open, opts[:sort_by_content]) epub = CC::Exporter::Epub::Book.new(exporter.templates) epub.create end end end
AndranikMarkosyan/lms
lib/cc/exporter/epub/exportable.rb
Ruby
agpl-3.0
332
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>File: scan_rules_reader.rb</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <meta http-equiv="Content-Script-Type" content="text/javascript" /> <link rel="stylesheet" href="../.././rdoc-style.css" type="text/css" media="screen" /> <script type="text/javascript"> // <![CDATA[ function popupCode( url ) { window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400") } function toggleCode( id ) { if ( document.getElementById ) elem = document.getElementById( id ); else if ( document.all ) elem = eval( "document.all." + id ); else return false; elemStyle = elem.style; if ( elemStyle.display != "block" ) { elemStyle.display = "block" } else { elemStyle.display = "none" } return true; } // Make codeblocks hidden by default document.writeln( "<style type=\"text/css\">div.method-source-code { display: none }</style>" ) // ]]> </script> </head> <body> <div id="fileHeader"> <h1>scan_rules_reader.rb</h1> <table class="header-table"> <tr class="top-aligned-row"> <td><strong>Path:</strong></td> <td>lib/scan_rules_reader.rb </td> </tr> <tr class="top-aligned-row"> <td><strong>Last Update:</strong></td> <td>Wed Dec 05 10:33:50 -0700 2007</td> </tr> </table> </div> <!-- banner header --> <div id="bodyContent"> <div id="contextContent"> <div id="description"> <p> scan_rules_reader.rb </p> <p> LEGAL NOTICE </p> <hr size="10"></hr><p> OSS Discovery is a tool that finds installed open source software. </p> <pre> Copyright (C) 2007-2009 OpenLogic, Inc. </pre> <p> OSS Discovery is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3 as published by the Free Software Foundation. </p> <p> 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 Affero General Public License version 3 (discovery2-client/license/OSSDiscoveryLicense.txt) for more details. </p> <p> You should have received a copy of the GNU Affero General Public License along with this program. If not, see <a href="http://www.gnu.org/licenses">www.gnu.org/licenses</a>/ </p> <p> You can learn more about OSSDiscovery, report bugs and get the latest versions at <a href="http://www.ossdiscovery.org">www.ossdiscovery.org</a>. You can contact the OSS Discovery team at [email protected]. You can contact OpenLogic at [email protected]. </p> </div> <div id="requires-list"> <h3 class="section-bar">Required files</h3> <div class="name-list"> set&nbsp;&nbsp; find&nbsp;&nbsp; rexml/document&nbsp;&nbsp; eval_rule&nbsp;&nbsp; expression&nbsp;&nbsp; project_rule&nbsp;&nbsp; match_rule_set&nbsp;&nbsp; matchrules/binary_match_rule&nbsp;&nbsp; matchrules/filename_match_rule&nbsp;&nbsp; matchrules/filename_version_match_rule&nbsp;&nbsp; matchrules/md5_match_rule&nbsp;&nbsp; </div> </div> </div> </div> <!-- if includes --> <div id="includes"> <h3 class="section-bar">Included Modules</h3> <div id="includes-list"> <span class="include-name">REXML</span> </div> </div> <div id="section"> <!-- if method_list --> </div> <div id="validator-badges"> <p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p> </div> </body> </html>
openlogic/ossdiscovery
doc/files/lib/scan_rules_reader_rb.html
HTML
agpl-3.0
3,939
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Netto-Lohn</title> <meta name="viewport" content="user-scalable=no"> <link rel="stylesheet" href="../shared/css/export-email.css"> <script src="../shared/config.js" defer></script> <script src="../dojotoolkit/dojo/dojo.js" defer></script> <script src="export-email.js" defer></script> </head> <body> </body> </html>
ohaz/amos-ss15-proj1
FlaskWebProject/static/scripts/rechner-brutto-netto/export-email.html
HTML
agpl-3.0
394
/* * (c) Copyright Ascensio System SIA 2010-2019 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha * street, Riga, Latvia, EU, LV-1050. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ #ifndef _BUILD_BASE64_CROSSPLATFORM_DEFINE #define _BUILD_BASE64_CROSSPLATFORM_DEFINE #include <stdio.h> #include <limits.h> #include "Types.h" #include "../../Common/kernel_config.h" namespace NSBase64 { const int B64_BASE64_FLAG_NONE = 0; const int B64_BASE64_FLAG_NOPAD = 1; const int B64_BASE64_FLAG_NOCRLF = 2; #define _BASE64_INT_MAX 2147483647 KERNEL_DECL int Base64EncodeGetRequiredLength(int nSrcLen, DWORD dwFlags = B64_BASE64_FLAG_NONE); KERNEL_DECL int Base64DecodeGetRequiredLength(int nSrcLen); KERNEL_DECL int Base64Encode(const BYTE *pbSrcData, int nSrcLen, BYTE* szDest, int *pnDestLen, DWORD dwFlags = B64_BASE64_FLAG_NONE); KERNEL_DECL int DecodeBase64Char(unsigned int ch); KERNEL_DECL int Base64Decode(const char* szSrc, int nSrcLen, BYTE *pbDest, int *pnDestLen); } #endif//_BUILD_BASE64_CROSSPLATFORM_DEFINE
ONLYOFFICE/core
DesktopEditor/common/Base64.h
C
agpl-3.0
2,486
/* * AscEmu Framework based on ArcEmu MMORPG Server * Copyright (c) 2014-2021 AscEmu Team <http://www.ascemu.org> * Copyright (C) 2005-2011 MaNGOS <http://getmangos.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 * 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/>. */ #ifndef WDTFILE_H #define WDTFILE_H #include "mpq_libmpq04.h" #include <string> class ADTFile; class WDTFile { public: WDTFile(char* file_name, char* file_name1); ~WDTFile(void); bool init(char* map_id, unsigned int mapID); ADTFile* GetMap(int x, int z); std::string* gWmoInstansName; int gnWMO; private: MPQFile WDT; std::string filename; }; #endif //WDTFILE_H
Appled/AscEmu
src/tools/vmap_tools/vmap4_extractor/wdtfile.h
C
agpl-3.0
1,211
from django.conf.urls.defaults import * import frontend.views as frontend_views import codewiki.views import codewiki.viewsuml from django.contrib.syndication.views import feed as feed_view from django.views.generic import date_based, list_detail from django.views.generic.simple import direct_to_template from django.contrib import admin import django.contrib.auth.views as auth_views from django.conf import settings from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect from django.contrib import admin admin.autodiscover() # Need to move this somewhere more useful and try to make it less hacky but # seems to be the easiest way unfortunately. from django.contrib.auth.models import User User._meta.ordering = ['username'] from frontend.feeds import LatestCodeObjects, LatestCodeObjectsBySearchTerm, LatestCodeObjectsByTag, LatestViewObjects, LatestScraperObjects feeds = { 'all_code_objects': LatestCodeObjects, 'all_scrapers': LatestScraperObjects, 'all_views': LatestViewObjects, 'latest_code_objects_by_search_term': LatestCodeObjectsBySearchTerm, 'latest_code_objects_by_tag': LatestCodeObjectsByTag, } urlpatterns = patterns('', url(r'^$', frontend_views.frontpage, name="frontpage"), # redirects from old version (would clashes if you happen to have a scraper whose name is list!) (r'^scrapers/list/$', lambda request: HttpResponseRedirect(reverse('scraper_list_wiki_type', args=['scraper']))), url(r'^', include('codewiki.urls')), url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name="logout"), url(r'^accounts/', include('registration.urls')), url(r'^accounts/resend_activation_email/', frontend_views.resend_activation_email, name="resend_activation_email"), url(r'^captcha/', include('captcha.urls')), url(r'^attachauth', codewiki.views.attachauth), # allows direct viewing of the django tables url(r'^admin/', include(admin.site.urls)), # favicon (r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', {'url': '/media/images/favicon.ico'}), # RSS feeds url(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}, name='feeds'), # API (r'^api/', include('api.urls', namespace='foo', app_name='api')), # Status url(r'^status/$', codewiki.viewsuml.status, name='status'), # Documentation (r'^docs/', include('documentation.urls')), # Robots.txt (r'^robots.txt$', direct_to_template, {'template': 'robots.txt', 'mimetype': 'text/plain'}), # pdf cropper technology (r'^cropper/', include('cropper.urls')), # froth (r'^froth/', include('froth.urls')), # static media server for the dev sites / local dev url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_DIR, 'show_indexes':True}), url(r'^media-admin/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ADMIN_DIR, 'show_indexes':True}), #Rest of the site url(r'^', include('frontend.urls')), # redirects from old version (r'^editor/$', lambda request: HttpResponseRedirect('/scrapers/new/python?template=tutorial_python_trivial')), (r'^scrapers/show/(?P<short_name>[\w_\-]+)/(?:data/|map-only/)?$', lambda request, short_name: HttpResponseRedirect(reverse('code_overview', args=['scraper', short_name]))), )
rossjones/ScraperWikiX
web/urls.py
Python
agpl-3.0
3,556
function timenow(){ var timenow1 = Date.getHours(); return timenow1; }
trynothingy/JQSchProj
assets/js/func.js
JavaScript
agpl-3.0
78
<!-- | FUNCTION show page to edit account --> <?php function $$$showEditAccount () { global $TSunic; // activate template $data = array('User' => $TSunic->Usr); $TSunic->Tmpl->activate('$$$showEditAccount', '$system$content', $data); $TSunic->Tmpl->activate('$system$html', false, array('title' => '{SHOWEDITACCOUNT__TITLE}')); return true; } ?>
nfrickler/tsunic
data/source/modules/usersystem/functions/showEditAccount.func.php
PHP
agpl-3.0
372
package cz.plichtanet.honza; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import javax.sql.DataSource; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private DataSource dataSource; @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/robots.txt", "/index.jsp", "/.well-known/**", "/static/**").permitAll() .antMatchers("/downloadPdf/**").hasRole("PDF_USER") .antMatchers("/dir/**", "/setPassword", "/addUser").hasRole("ADMIN") .antMatchers("/helloagain").hasRole("ADMIN") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll() .and() .exceptionHandling() .accessDeniedPage("/403") .and() .csrf(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { /* // pro lokalni testovani bez databaze auth .inMemoryAuthentication() .withUser("jenda").password("604321192").roles("USER","PDF_USER","ADMIN"); */ PasswordEncoder encoder = passwordEncoder(); auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(encoder) /* .withUser("petra").password(encoder.encode("737438719")).roles("USER") .and() .withUser("kuba").password(encoder.encode("737438719")).roles("USER") .and() .withUser("jenda").password(encoder.encode("604321192")).roles("USER","ADMIN") */ ; } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
plichjan/pdfDriveWebApp
src/main/java/cz/plichtanet/honza/WebSecurityConfig.java
Java
agpl-3.0
2,624
'use strict'; angular.module('cheeperApp') .controller('AuthCtrl', function ($scope, $http) { $scope.signin = function() { $http .post('http://127.0.0.1:8000/auth-token/', $scope.credentials) .success(function(data, status, headers, config) { $scope.token = data.token; }) .error(function(data, status, headers, config) { console.log(data); }); }; });
hnarayanan/cheeper
app/scripts/controllers/auth.js
JavaScript
agpl-3.0
430
<?php //Harvie's PHP HTTP-Auth script (2oo7-2o1o) //CopyLefted4U ;) ///SETTINGS////////////////////////////////////////////////////////////////////////////////////////////////////// //Login /*$realm = 'music'; //This is used by browser to identify protected area and saving passwords (one_site+one_realm==one_user+one_password) $users = array( //You can specify multiple users in this array 'music' => 'passw' );*/ //Misc $require_login = true; //Require login? (if false, no login needed) - WARNING!!! $location = '401'; //Location after logout - 401 = default logout page (can be overridden by ?logout=[LOCATION]) //CopyLeft $ver = '2o1o-3.9'; $link = '<a href="https://blog.harvie.cz/">blog.harvie.cz</a>'; $banner = "Harvie's PHP HTTP-Auth script (v$ver)"; $hbanner = "<hr /><i>$banner\n-\n$link</i>\n"; $cbanner = "<!-- $banner -->\n"; //Config file @include('./_config.php'); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// //MANUAL///////////////////////////////////////////////////////////////////////////////////////////////////////// /* HOWTO * To each file, you want to lock add this line (at begin of first line - Header-safe): * <?php require_once('http_auth.php'); ?> //Password Protection 8') * Protected file have to be php script (if it's html, simply rename it to .php) * Server needs to have PHP as module (not CGI). * You need HTTP Basic auth enabled on server and php. */ ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////CODE///////////////////////////////////////////////////////////////////////////////////////////////////////// function send_auth_headers($realm='') { Header('WWW-Authenticate: Basic realm="'.$realm.'"'); Header('HTTP/1.0 401 Unauthorized'); } function check_auth($PHP_AUTH_USER, $PHP_AUTH_PW) { //Check if login is succesfull (U can modify this to use DB, or anything else) return (isset($GLOBALS['users'][$PHP_AUTH_USER]) && ($GLOBALS['users'][$PHP_AUTH_USER] == $PHP_AUTH_PW)); } function unauth() { //Do this when login fails $cbanner = $GLOBALS['cbanner']; $hbanner = $GLOBALS['hbanner']; die("$cbanner<title>401 - Forbidden</title>\n<h1>401 - Forbidden</h1>\n<a href=\"?\">Login...</a>\n$hbanner"); //Show warning and die die(); //Don't forget!!! } //Backward compatibility if(isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_PW'] != '') $PHP_AUTH_USER = $_SERVER['PHP_AUTH_USER']; if(isset($_SERVER['PHP_AUTH_PW']) && $_SERVER['PHP_AUTH_PW'] != '') $PHP_AUTH_PW = $_SERVER['PHP_AUTH_PW']; //Logout if(isset($_GET['logout'])) { //script.php?logout if(isset($PHP_AUTH_USER) || isset($PHP_AUTH_PW)) { Header('WWW-Authenticate: Basic realm="'.$realm.'"'); Header('HTTP/1.0 401 Unauthorized'); } else { if($_GET['logout'] != '') $location = $_GET['logout']; if(trim($location) != '401') Header('Location: '.$location); die("$cbanner<title>401 - Log out successfull</title>\n<h1>401 - Log out successfull</h1>\n<a href=\"?\">Continue...</a>\n$hbanner"); } } if($require_login) { if(!isset($PHP_AUTH_USER)) { //Storno or first visit of page send_auth_headers($realm); unauth(); } else { //Login sent if (check_auth($PHP_AUTH_USER, $PHP_AUTH_PW)) { //Login succesfull - probably do nothing } else { //Bad login send_auth_headers($realm); unauth(); } } } //Rest of file will be displayed only if login is correct
Kyberia/Kyberia-bloodline
wwwroot/inc/http_auth.php
PHP
agpl-3.0
3,525
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>buffers_iterator::operator++ (1 of 2 overloads)</title> <link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../../../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../operator_plus__plus_.html" title="buffers_iterator::operator++"> <link rel="prev" href="../operator_plus__plus_.html" title="buffers_iterator::operator++"> <link rel="next" href="overload2.html" title="buffers_iterator::operator++ (2 of 2 overloads)"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../operator_plus__plus_.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../operator_plus__plus_.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h5 class="title"> <a name="boost_asio.reference.buffers_iterator.operator_plus__plus_.overload1"></a><a class="link" href="overload1.html" title="buffers_iterator::operator++ (1 of 2 overloads)">buffers_iterator::operator++ (1 of 2 overloads)</a> </h5></div></div></div> <p> Increment operator (prefix). </p> <pre class="programlisting"><span class="identifier">buffers_iterator</span> <span class="special">&amp;</span> <span class="keyword">operator</span><span class="special">++();</span> </pre> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2017 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../operator_plus__plus_.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../operator_plus__plus_.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
cris-iisc/mpc-primitives
crislib/libscapi/lib/boost_1_64_0/doc/html/boost_asio/reference/buffers_iterator/operator_plus__plus_/overload1.html
HTML
agpl-3.0
3,401
############################################################################### # # Package: NaturalDocs::Parser::Native # ############################################################################### # # A package that converts comments from Natural Docs' native format into <NaturalDocs::Parser::ParsedTopic> objects. # Unlike most second-level packages, these are packages and not object classes. # ############################################################################### # This file is part of Natural Docs, which is Copyright © 2003-2010 Greg Valure # Natural Docs is licensed under version 3 of the GNU Affero General Public License (AGPL) # Refer to License.txt for the complete details use strict; use integer; package NaturalDocs::Parser::Native; ############################################################################### # Group: Variables # Return values of TagType(). Not documented here. use constant POSSIBLE_OPENING_TAG => 1; use constant POSSIBLE_CLOSING_TAG => 2; use constant NOT_A_TAG => 3; # # var: package # # A <SymbolString> representing the package normal topics will be a part of at the current point in the file. This is a package variable # because it needs to be reserved between function calls. # my $package; # # hash: functionListIgnoredHeadings # # An existence hash of all the headings that prevent the parser from creating function list symbols. Whenever one of # these headings are used in a function list topic, symbols are not created from definition lists until the next heading. The keys # are in all lowercase. # my %functionListIgnoredHeadings = ( 'parameters' => 1, 'parameter' => 1, 'params' => 1, 'param' => 1, 'arguments' => 1, 'argument' => 1, 'args' => 1, 'arg' => 1 ); ############################################################################### # Group: Interface Functions # # Function: Start # # This will be called whenever a file is about to be parsed. It allows the package to reset its internal state. # sub Start { my ($self) = @_; $package = undef; }; # # Function: IsMine # # Examines the comment and returns whether it is *definitely* Natural Docs content, i.e. it is owned by this package. Note # that a comment can fail this function and still be interpreted as a Natural Docs content, for example a JavaDoc-styled comment # that doesn't have header lines but no JavaDoc tags either. # # Parameters: # # commentLines - An arrayref of the comment lines. Must have been run through <NaturalDocs::Parser->CleanComment()>. # isJavaDoc - Whether the comment was JavaDoc-styled. # # Returns: # # Whether the comment is *definitely* Natural Docs content. # sub IsMine #(string[] commentLines, bool isJavaDoc) { my ($self, $commentLines, $isJavaDoc) = @_; # Skip to the first line with content. my $line = 0; while ($line < scalar @$commentLines && !length $commentLines->[$line]) { $line++; }; return $self->ParseHeaderLine($commentLines->[$line]); }; # # Function: ParseComment # # This will be called whenever a comment capable of containing Natural Docs content is found. # # Parameters: # # commentLines - An arrayref of the comment lines. Must have been run through <NaturalDocs::Parser->CleanComment()>. # *The original memory will be changed.* # isJavaDoc - Whether the comment is JavaDoc styled. # lineNumber - The line number of the first of the comment lines. # parsedTopics - A reference to the array where any new <NaturalDocs::Parser::ParsedTopics> should be placed. # # Returns: # # The number of parsed topics added to the array, or zero if none. # sub ParseComment #(commentLines, isJavaDoc, lineNumber, parsedTopics) { my ($self, $commentLines, $isJavaDoc, $lineNumber, $parsedTopics) = @_; my $topicCount = 0; my $prevLineBlank = 1; my $inCodeSection = 0; my ($type, $scope, $isPlural, $title, $symbol); #my $package; # package variable. my ($newKeyword, $newTitle); my $index = 0; my $bodyStart = 0; my $bodyEnd = 0; # Not inclusive. while ($index < scalar @$commentLines) { # Everything but leading whitespace was removed beforehand. # If we're in a code section... if ($inCodeSection) { if ($commentLines->[$index] =~ /^ *\( *(?:end|finish|done)(?: +(?:table|code|example|diagram))? *\)$/i) { $inCodeSection = undef; }; $prevLineBlank = 0; $bodyEnd++; } # If the line is empty... elsif (!length($commentLines->[$index])) { $prevLineBlank = 1; if ($topicCount) { $bodyEnd++; }; } # If the line has a recognized header and the previous line is blank... elsif ($prevLineBlank && (($newKeyword, $newTitle) = $self->ParseHeaderLine($commentLines->[$index])) ) { # Process the previous one, if any. if ($topicCount) { if ($scope == ::SCOPE_START() || $scope == ::SCOPE_END()) { $package = undef; }; my $body = $self->FormatBody($commentLines, $bodyStart, $bodyEnd, $type, $isPlural); my $newTopic = $self->MakeParsedTopic($type, $title, $package, $body, $lineNumber + $bodyStart - 1, $isPlural); push @$parsedTopics, $newTopic; $package = $newTopic->Package(); }; $title = $newTitle; my $typeInfo; ($type, $typeInfo, $isPlural) = NaturalDocs::Topics->KeywordInfo($newKeyword); $scope = $typeInfo->Scope(); $bodyStart = $index + 1; $bodyEnd = $index + 1; $topicCount++; $prevLineBlank = 0; } # If we're on a non-empty, non-header line of a JavaDoc-styled comment and we haven't started a topic yet... elsif ($isJavaDoc && !$topicCount) { $type = undef; $scope = ::SCOPE_NORMAL(); # The scope repair and topic merging processes will handle if this is a class topic. $isPlural = undef; $title = undef; $symbol = undef; $bodyStart = $index; $bodyEnd = $index + 1; $topicCount++; $prevLineBlank = undef; } # If we're on a normal content line within a topic elsif ($topicCount) { $prevLineBlank = 0; $bodyEnd++; if ($commentLines->[$index] =~ /^ *\( *(?:(?:start|begin)? +)?(?:table|code|example|diagram) *\)$/i) { $inCodeSection = 1; }; }; $index++; }; # Last one, if any. This is the only one that gets the prototypes. if ($topicCount) { if ($scope == ::SCOPE_START() || $scope == ::SCOPE_END()) { $package = undef; }; my $body = $self->FormatBody($commentLines, $bodyStart, $bodyEnd, $type, $isPlural); my $newTopic = $self->MakeParsedTopic($type, $title, $package, $body, $lineNumber + $bodyStart - 1, $isPlural); push @$parsedTopics, $newTopic; $topicCount++; $package = $newTopic->Package(); }; return $topicCount; }; # # Function: ParseHeaderLine # # If the passed line is a topic header, returns the array ( keyword, title ). Otherwise returns an empty array. # sub ParseHeaderLine #(line) { my ($self, $line) = @_; if ($line =~ /^ *([a-z0-9 ]*[a-z0-9]): +(.*)$/i) { my ($keyword, $title) = ($1, $2); # We need to do it this way because if you do "if (ND:T->KeywordInfo($keyword)" and the last element of the array it # returns is false, the statement is false. That is really retarded, but there it is. my ($type, undef, undef) = NaturalDocs::Topics->KeywordInfo($keyword); if ($type) { return ($keyword, $title); } else { return ( ); }; } else { return ( ); }; }; ############################################################################### # Group: Support Functions # # Function: MakeParsedTopic # # Creates a <NaturalDocs::Parser::ParsedTopic> object for the passed parameters. Scope is gotten from # the package variable <package> instead of from the parameters. The summary is generated from the body. # # Parameters: # # type - The <TopicType>. May be undef for headerless topics. # title - The title of the topic. May be undef for headerless topics. # package - The package <SymbolString> the topic appears in. # body - The topic's body in <NDMarkup>. # lineNumber - The topic's line number. # isList - Whether the topic is a list. # # Returns: # # The <NaturalDocs::Parser::ParsedTopic> object. # sub MakeParsedTopic #(type, title, package, body, lineNumber, isList) { my ($self, $type, $title, $package, $body, $lineNumber, $isList) = @_; my $summary; if (defined $body) { $summary = NaturalDocs::Parser->GetSummaryFromBody($body); }; return NaturalDocs::Parser::ParsedTopic->New($type, $title, $package, undef, undef, $summary, $body, $lineNumber, $isList); }; # # Function: FormatBody # # Converts the section body to <NDMarkup>. # # Parameters: # # commentLines - The arrayref of comment lines. # startingIndex - The starting index of the body to format. # endingIndex - The ending index of the body to format, *not* inclusive. # type - The type of the section. May be undef for headerless comments. # isList - Whether it's a list topic. # # Returns: # # The body formatted in <NDMarkup>. # sub FormatBody #(commentLines, startingIndex, endingIndex, type, isList) { my ($self, $commentLines, $startingIndex, $endingIndex, $type, $isList) = @_; use constant TAG_NONE => 1; use constant TAG_PARAGRAPH => 2; use constant TAG_BULLETLIST => 3; use constant TAG_DESCRIPTIONLIST => 4; use constant TAG_HEADING => 5; use constant TAG_PREFIXCODE => 6; use constant TAG_TAGCODE => 7; my %tagEnders = ( TAG_NONE() => '', TAG_PARAGRAPH() => '</p>', TAG_BULLETLIST() => '</li></ul>', TAG_DESCRIPTIONLIST() => '</dd></dl>', TAG_HEADING() => '</h>', TAG_PREFIXCODE() => '</code>', TAG_TAGCODE() => '</code>' ); my $topLevelTag = TAG_NONE; my $output; my $textBlock; my $prevLineBlank = 1; my $codeBlock; my $removedCodeSpaces; my $ignoreListSymbols; my $index = $startingIndex; while ($index < $endingIndex) { # If we're in a tagged code section... if ($topLevelTag == TAG_TAGCODE) { if ($commentLines->[$index] =~ /^ *\( *(?:end|finish|done)(?: +(?:table|code|example|diagram))? *\)$/i) { $codeBlock =~ s/\n+$//; $output .= NaturalDocs::NDMarkup->ConvertAmpChars($codeBlock) . '</code>'; $codeBlock = undef; $topLevelTag = TAG_NONE; $prevLineBlank = undef; } else { $self->AddToCodeBlock($commentLines->[$index], \$codeBlock, \$removedCodeSpaces); }; } # If the line starts with a code designator... elsif ($commentLines->[$index] =~ /^ *[>:|](.*)$/) { my $code = $1; if ($topLevelTag == TAG_PREFIXCODE) { $self->AddToCodeBlock($code, \$codeBlock, \$removedCodeSpaces); } else # $topLevelTag != TAG_PREFIXCODE { if (defined $textBlock) { $output .= $self->RichFormatTextBlock($textBlock) . $tagEnders{$topLevelTag}; $textBlock = undef; }; $topLevelTag = TAG_PREFIXCODE; $output .= '<code type="anonymous">'; $self->AddToCodeBlock($code, \$codeBlock, \$removedCodeSpaces); }; } # If we're not in either code style... else { # Strip any leading whitespace. $commentLines->[$index] =~ s/^ +//; # If we were in a prefixed code section... if ($topLevelTag == TAG_PREFIXCODE) { $codeBlock =~ s/\n+$//; $output .= NaturalDocs::NDMarkup->ConvertAmpChars($codeBlock) . '</code>'; $codeBlock = undef; $topLevelTag = TAG_NONE; $prevLineBlank = undef; }; # If the line is blank... if (!length($commentLines->[$index])) { # End a paragraph. Everything else ignores it for now. if ($topLevelTag == TAG_PARAGRAPH) { $output .= $self->RichFormatTextBlock($textBlock) . '</p>'; $textBlock = undef; $topLevelTag = TAG_NONE; }; $prevLineBlank = 1; } # If the line starts with a bullet... elsif ($commentLines->[$index] =~ /^[-\*o+] +([^ ].*)$/ && substr($1, 0, 2) ne '- ') # Make sure "o - Something" is a definition, not a bullet. { my $bulletedText = $1; if (defined $textBlock) { $output .= $self->RichFormatTextBlock($textBlock); }; if ($topLevelTag == TAG_BULLETLIST) { $output .= '</li><li>'; } else #($topLevelTag != TAG_BULLETLIST) { $output .= $tagEnders{$topLevelTag} . '<ul><li>'; $topLevelTag = TAG_BULLETLIST; }; $textBlock = $bulletedText; $prevLineBlank = undef; } # If the line looks like a description list entry... elsif ($commentLines->[$index] =~ /^(.+?) +- +([^ ].*)$/ && $topLevelTag != TAG_PARAGRAPH) { my $entry = $1; my $description = $2; if (defined $textBlock) { $output .= $self->RichFormatTextBlock($textBlock); }; if ($topLevelTag == TAG_DESCRIPTIONLIST) { $output .= '</dd>'; } else #($topLevelTag != TAG_DESCRIPTIONLIST) { $output .= $tagEnders{$topLevelTag} . '<dl>'; $topLevelTag = TAG_DESCRIPTIONLIST; }; if (($isList && !$ignoreListSymbols) || $type eq ::TOPIC_ENUMERATION()) { $output .= '<ds>' . NaturalDocs::NDMarkup->ConvertAmpChars($entry) . '</ds><dd>'; } else { $output .= '<de>' . NaturalDocs::NDMarkup->ConvertAmpChars($entry) . '</de><dd>'; }; $textBlock = $description; $prevLineBlank = undef; } # If the line could be a header... elsif ($prevLineBlank && $commentLines->[$index] =~ /^(.*)([^ ]):$/) { my $headerText = $1 . $2; if (defined $textBlock) { $output .= $self->RichFormatTextBlock($textBlock); $textBlock = undef; } $output .= $tagEnders{$topLevelTag}; $topLevelTag = TAG_NONE; $output .= '<h>' . $self->RichFormatTextBlock($headerText) . '</h>'; if ($type eq ::TOPIC_FUNCTION() && $isList) { $ignoreListSymbols = exists $functionListIgnoredHeadings{lc($headerText)}; }; $prevLineBlank = undef; } # If the line looks like a code tag... elsif ($commentLines->[$index] =~ /^\( *(?:(?:start|begin)? +)?(table|code|example|diagram) *\)$/i) { my $codeType = lc($1); if (defined $textBlock) { $output .= $self->RichFormatTextBlock($textBlock); $textBlock = undef; }; if ($codeType eq 'example') { $codeType = 'anonymous'; } elsif ($codeType eq 'table' || $codeType eq 'diagram') { $codeType = 'text'; } # else leave it 'code' $output .= $tagEnders{$topLevelTag} . '<code type="' . $codeType . '">'; $topLevelTag = TAG_TAGCODE; } # If the line looks like an inline image... elsif ($commentLines->[$index] =~ /^(\( *see +)([^\)]+?)( *\))$/i) { if (defined $textBlock) { $output .= $self->RichFormatTextBlock($textBlock); $textBlock = undef; }; $output .= $tagEnders{$topLevelTag}; $topLevelTag = TAG_NONE; $output .= '<img mode="inline" target="' . NaturalDocs::NDMarkup->ConvertAmpChars($2) . '" ' . 'original="' . NaturalDocs::NDMarkup->ConvertAmpChars($1 . $2 . $3) . '">'; $prevLineBlank = undef; } # If the line isn't any of those, we consider it normal text. else { # A blank line followed by normal text ends lists. We don't handle this when we detect if the line's blank because # we don't want blank lines between list items to break the list. if ($prevLineBlank && ($topLevelTag == TAG_BULLETLIST || $topLevelTag == TAG_DESCRIPTIONLIST)) { $output .= $self->RichFormatTextBlock($textBlock) . $tagEnders{$topLevelTag} . '<p>'; $topLevelTag = TAG_PARAGRAPH; $textBlock = undef; } elsif ($topLevelTag == TAG_NONE) { $output .= '<p>'; $topLevelTag = TAG_PARAGRAPH; # textBlock will already be undef. }; if (defined $textBlock) { $textBlock .= ' '; }; $textBlock .= $commentLines->[$index]; $prevLineBlank = undef; }; }; $index++; }; # Clean up anything left dangling. if (defined $textBlock) { $output .= $self->RichFormatTextBlock($textBlock) . $tagEnders{$topLevelTag}; } elsif (defined $codeBlock) { $codeBlock =~ s/\n+$//; $output .= NaturalDocs::NDMarkup->ConvertAmpChars($codeBlock) . '</code>'; }; return $output; }; # # Function: AddToCodeBlock # # Adds a line of text to a code block, handling all the indentation processing required. # # Parameters: # # line - The line of text to add. # codeBlockRef - A reference to the code block to add it to. # removedSpacesRef - A reference to a variable to hold the number of spaces removed. It needs to be stored between calls. # It will reset itself automatically when the code block codeBlockRef points to is undef. # sub AddToCodeBlock #(line, codeBlockRef, removedSpacesRef) { my ($self, $line, $codeBlockRef, $removedSpacesRef) = @_; $line =~ /^( *)(.*)$/; my ($spaces, $code) = ($1, $2); if (!defined $$codeBlockRef) { if (length($code)) { $$codeBlockRef = $code . "\n"; $$removedSpacesRef = length($spaces); }; # else ignore leading line breaks. } elsif (length $code) { # Make sure we have the minimum amount of spaces to the left possible. if (length($spaces) != $$removedSpacesRef) { my $spaceDifference = abs( length($spaces) - $$removedSpacesRef ); my $spacesToAdd = ' ' x $spaceDifference; if (length($spaces) > $$removedSpacesRef) { $$codeBlockRef .= $spacesToAdd; } else { $$codeBlockRef =~ s/^(.)/$spacesToAdd . $1/gme; $$removedSpacesRef = length($spaces); }; }; $$codeBlockRef .= $code . "\n"; } else # (!length $code) { $$codeBlockRef .= "\n"; }; }; # # Function: RichFormatTextBlock # # Applies rich <NDMarkup> formatting to a chunk of text. This includes both amp chars, formatting tags, and link tags. # # Parameters: # # text - The block of text to format. # # Returns: # # The formatted text block. # sub RichFormatTextBlock #(text) { my ($self, $text) = @_; my $output; # First find bare urls, e-mail addresses, and images. We have to do this before the split because they may contain underscores, # asterisks, bacquotes, hyphens or tildas. We have to mark the tags with \x1E and \x1F so they don't get confused with angle # brackets from the comment. We can't convert the amp chars beforehand because we need lookbehinds in the regexps below # and they need to be constant length. Sucks, huh? $text =~ s{ # The previous character can't be an alphanumeric or an opening angle bracket. (?<! [a-z0-9<] ) # Optional mailto:. Ignored in output. (?:mailto\:)? # Begin capture ( # The user portion. Alphanumeric and - _. Dots can appear between, but not at the edges or more than # one in a row. (?: [a-z0-9\-_]+ \. )* [a-z0-9\-_]+ @ # The domain. Alphanumeric and -. Dots same as above, however, there must be at least two sections # and the last one must be two to four alphanumeric characters (.com, .uk, .info, .203 for IP addresses) (?: [a-z0-9\-]+ \. )+ [a-z]{2,4} # End capture. ) # The next character can't be an alphanumeric, which should prevent .abcde from matching the two to # four character requirement, or a closing angle bracket. (?! [a-z0-9>] ) } {"\x1E" . 'email target="' . NaturalDocs::NDMarkup->ConvertAmpChars($1) . '" ' . 'name="' . NaturalDocs::NDMarkup->ConvertAmpChars($1) . '"' . "\x1F"}igxe; $text =~ s{ # The previous character can't be an alphanumeric or an opening angle bracket. (?<! [a-z0-9<] ) # Begin capture. ( # URL must start with one of the acceptable protocols. (?:http|https|ftp|news|file)\: # The acceptable URL characters as far as I know. [a-z0-9\-\=\~\@\#\%\&\_\+\/\;\:\?\*\.\,]* # The URL characters minus period and comma. If it ends on them, they're probably intended as # punctuation. [a-z0-9\-\=\~\@\#\%\&\_\+\/\;\:\?\*] # End capture. ) # The next character must not be an acceptable character or a closing angle bracket. It must also not be a # dot and then an acceptable character. These will prevent the URL from ending early just to get a match. (?! \.?[a-z0-9\-\=\~\@\#\%\&\_\+\/\;\:\?\*\>] ) } {"\x1E" . 'url target="' . NaturalDocs::NDMarkup->ConvertAmpChars($1) . '" ' . 'name="' . NaturalDocs::NDMarkup->ConvertAmpChars($1) . '"' . "\x1F"}igxe; # Find image links. Inline images should already be pulled out by now. $text =~ s{(\( *see +)([^\)\<\>]+?)( *\))} {"\x1E" . 'img mode="link" target="' . NaturalDocs::NDMarkup->ConvertAmpChars($2) . '" ' . 'original="' . NaturalDocs::NDMarkup->ConvertAmpChars($1 . $2 . $3) . '"' . "\x1F"}gie; # Split the text from the potential tags. my @tempTextBlocks = split(/([\*_\~\+\`<>\x1E\x1F])/, $text); # Since the symbols are considered dividers, empty strings could appear between two in a row or at the beginning/end of the # array. This could seriously screw up TagType(), so we need to get rid of them. my @textBlocks; while (scalar @tempTextBlocks) { my $tempTextBlock = shift @tempTextBlocks; if (length $tempTextBlock) { push @textBlocks, $tempTextBlock; }; }; my $bold; my $underline; my $underlineHasWhitespace; my $strikethrough; my $strikethroughHasWhitespace; my $italic; my $monotype; my $index = 0; while ($index < scalar @textBlocks) { if ($textBlocks[$index] eq "\x1E") { $output .= '<'; $index++; while ($textBlocks[$index] ne "\x1F") { $output .= $textBlocks[$index]; $index++; }; $output .= '>'; } elsif ($textBlocks[$index] eq '<' && $self->TagType(\@textBlocks, $index) == POSSIBLE_OPENING_TAG) { my $endingIndex = $self->ClosingTag(\@textBlocks, $index, undef); if ($endingIndex != -1) { my $linkText; $index++; while ($index < $endingIndex) { $linkText .= $textBlocks[$index]; $index++; }; # Index will be incremented again at the end of the loop. $linkText = NaturalDocs::NDMarkup->ConvertAmpChars($linkText); if ($linkText =~ /^(?:mailto\:)?((?:[a-z0-9\-_]+\.)*[a-z0-9\-_]+@(?:[a-z0-9\-]+\.)+[a-z]{2,4})$/i) { $output .= '<email target="' . $1 . '" name="' . $1 . '">'; } elsif ($linkText =~ /^(.+?) at (?:mailto\:)?((?:[a-z0-9\-_]+\.)*[a-z0-9\-_]+@(?:[a-z0-9\-]+\.)+[a-z]{2,4})$/i) { $output .= '<email target="' . $2 . '" name="' . $1 . '">'; } elsif ($linkText =~ /^(?:http|https|ftp|news|file)\:/i) { $output .= '<url target="' . $linkText . '" name="' . $linkText . '">'; } elsif ($linkText =~ /^(.+?) at ((?:http|https|ftp|news|file)\:.+)/i) { $output .= '<url target="' . $2 . '" name="' . $1 . '">'; } else { $output .= '<link target="' . $linkText . '" name="' . $linkText . '" original="&lt;' . $linkText . '&gt;">'; }; } else # it's not a link. { $output .= '&lt;'; }; } elsif ($textBlocks[$index] eq '*') { my $tagType = $self->TagType(\@textBlocks, $index); if ($tagType == POSSIBLE_OPENING_TAG && $self->ClosingTag(\@textBlocks, $index, undef) != -1) { # ClosingTag() makes sure tags aren't opened multiple times in a row. $bold = 1; $output .= '<b>'; } elsif ($bold && $tagType == POSSIBLE_CLOSING_TAG) { $bold = undef; $output .= '</b>'; } else { $output .= '*'; }; } elsif ($textBlocks[$index] eq '_') { my $tagType = $self->TagType(\@textBlocks, $index); if ($tagType == POSSIBLE_OPENING_TAG && $self->ClosingTag(\@textBlocks, $index, \$underlineHasWhitespace) != -1) { # ClosingTag() makes sure tags aren't opened multiple times in a row. $underline = 1; #underlineHasWhitespace is set by ClosingTag(). $output .= '<u>'; } elsif ($underline && $tagType == POSSIBLE_CLOSING_TAG) { $underline = undef; #underlineHasWhitespace will be reset by the next opening underline. $output .= '</u>'; } elsif ($underline && !$underlineHasWhitespace) { # If there's no whitespace between underline tags, all underscores are replaced by spaces so # _some_underlined_text_ becomes <u>some underlined text</u>. The standard _some underlined text_ # will work too. $output .= ' '; } else { $output .= '_'; }; } elsif ($textBlocks[$index] eq '~') { my $tagType = $self->TagType(\@textBlocks, $index); if ($tagType == POSSIBLE_OPENING_TAG && $self->ClosingTag(\@textBlocks, $index, \$strikethroughHasWhitespace) != -1) { # ClosingTag() makes sure tags aren't opened multiple times in a row. $strikethrough = 1; #strikethroughHasWhitespace is set by ClosingTag(). $output .= '<s>'; } elsif ($strikethrough && $tagType == POSSIBLE_CLOSING_TAG) { $strikethrough = undef; #strikethroughHasWhitespace will be reset by the next opening strikethrough. $output .= '</s>'; } elsif ($strikethrough && !$strikethroughHasWhitespace) { # If there's no whitespace between strikethrough tags, all hyphens are replaced # by spaces so -some-struck-through-text- becomes <s>some struck through text</s>. # The standard -some struck-through text- will work too. $output .= ' '; } else { $output .= '~'; }; } elsif ($textBlocks[$index] eq '+') { my $tagType = $self->TagType(\@textBlocks, $index); if ($tagType == POSSIBLE_OPENING_TAG && $self->ClosingTag(\@textBlocks, $index, undef) != -1) { # ClosingTag() makes sure tags aren't opened multiple times in a row. $italic = 1; $output .= '<i>'; } elsif ($italic && $tagType == POSSIBLE_CLOSING_TAG) { $italic = undef; $output .= '</i>'; } else { $output .= '+'; }; } elsif ($textBlocks[$index] eq '`') { my $tagType = $self->TagType(\@textBlocks, $index); if ($tagType == POSSIBLE_OPENING_TAG && $self->ClosingTag(\@textBlocks, $index, undef) != -1) { # ClosingTag() makes sure tags aren't opened multiple times in a row. $monotype = 1; $output .= '<tt>'; } elsif ($monotype && $tagType == POSSIBLE_CLOSING_TAG) { $monotype = undef; $output .= '</tt>'; } else { $output .= '`'; }; } else # plain text or a > that isn't part of a link { $output .= NaturalDocs::NDMarkup->ConvertAmpChars($textBlocks[$index]); }; $index++; }; return $output; }; # # Function: TagType # # Returns whether the tag is a possible opening or closing tag, or neither. "Possible" because it doesn't check if an opening tag is # closed or a closing tag is opened, just whether the surrounding characters allow it to be a candidate for a tag. For example, in # "A _B" the underscore is a possible opening underline tag, but in "A_B" it is not. Support function for <RichFormatTextBlock()>. # # Parameters: # # textBlocks - A reference to an array of text blocks. # index - The index of the tag. # # Returns: # # POSSIBLE_OPENING_TAG, POSSIBLE_CLOSING_TAG, or NOT_A_TAG. # sub TagType #(textBlocks, index) { my ($self, $textBlocks, $index) = @_; # Possible opening tags if ( ( $textBlocks->[$index] =~ /^[\*_\~\+\`<]$/ ) && # Before it must be whitespace, the beginning of the text, or ({["'-/*_~+`. ( $index == 0 || $textBlocks->[$index-1] =~ /[\ \t\n\(\{\[\"\'\-\/\*\_\~\+\`]$/ ) && # Notes for 2.0: Include Spanish upside down ! and ? as well as opening quotes (66) and apostrophes (6). Look into # Unicode character classes as well. # After it must be non-whitespace. ( $index + 1 < scalar @$textBlocks && $textBlocks->[$index+1] !~ /^[\ \t\n]/) && # Make sure we don't accept <<, <=, <-, or *= as opening tags. ( $textBlocks->[$index] ne '<' || $textBlocks->[$index+1] !~ /^[<=-]/ ) && ( $textBlocks->[$index] ne '*' || $textBlocks->[$index+1] !~ /^[\=\*]/ ) && # Make sure we don't accept *, _, ~, + or ` before it unless it's <. ( $textBlocks->[$index] eq '<' || $index == 0 || $textBlocks->[$index-1] !~ /[\*\_\~\+\`]$/) ) { return POSSIBLE_OPENING_TAG; } # Possible closing tags elsif ( ( $textBlocks->[$index] =~ /^[\*_\~\+\`>]$/) && # After it must be whitespace, the end of the text, or )}].,!?"';:-/*_~+`. ( $index + 1 == scalar @$textBlocks || $textBlocks->[$index+1] =~ /^[ \t\n\)\]\}\.\,\!\?\"\'\;\:\-\/\*\_\~\+\`]/ || # Links also get plurals, like <link>s, <linx>es, <link>'s, and <links>'. ( $textBlocks->[$index] eq '>' && $textBlocks->[$index+1] =~ /^(?:es|s|\')/ ) ) && # Notes for 2.0: Include closing quotes (99) and apostrophes (9). Look into Unicode character classes as well. # Before it must be non-whitespace. ( $index != 0 && $textBlocks->[$index-1] !~ /[ \t\n]$/ ) && # Make sure we don't accept >>, ->, or => as closing tags. >= is already taken care of. ( $textBlocks->[$index] ne '>' || $textBlocks->[$index-1] !~ /[>=-]$/ ) && # Make sure we don't accept *, _, ~, + or ` after it unless it's >. ( $textBlocks->[$index] eq '>' || $textBlocks->[$index+1] !~ /[\*\_\~\+\`]$/) ) { return POSSIBLE_CLOSING_TAG; } else { return NOT_A_TAG; }; }; # # Function: ClosingTag # # Returns whether a tag is closed or not, where it's closed if it is, and optionally whether there is any whitespace between the # tags. Support function for <RichFormatTextBlock()>. # # The results of this function are in full context, meaning that if it says a tag is closed, it can be interpreted as that tag in the # final output. It takes into account any spoiling factors, like there being two opening tags in a row. # # Parameters: # # textBlocks - A reference to an array of text blocks. # index - The index of the opening tag. # hasWhitespaceRef - A reference to the variable that will hold whether there is whitespace between the tags or not. If # undef, the function will not check. If the tag is not closed, the variable will not be changed. # # Returns: # # If the tag is closed, it returns the index of the closing tag and puts whether there was whitespace between the tags in # hasWhitespaceRef if it was specified. If the tag is not closed, it returns -1 and doesn't touch the variable pointed to by # hasWhitespaceRef. # sub ClosingTag #(textBlocks, index, hasWhitespace) { my ($self, $textBlocks, $index, $hasWhitespaceRef) = @_; my $hasWhitespace; my $closingTag; if ($textBlocks->[$index] eq '*' || $textBlocks->[$index] eq '_' || $textBlocks->[$index] eq '~' || $textBlocks->[$index] eq '+' || $textBlocks->[$index] eq '`') { $closingTag = $textBlocks->[$index]; } elsif ($textBlocks->[$index] eq '<') { $closingTag = '>'; } else { return -1; }; my $beginningIndex = $index; $index++; while ($index < scalar @$textBlocks) { if ($textBlocks->[$index] eq '<' && $self->TagType($textBlocks, $index) == POSSIBLE_OPENING_TAG) { # If we hit a < and we're checking whether a link is closed, it's not. The first < becomes literal and the second one # becomes the new link opening. if ($closingTag eq '>') { return -1; } # If we're not searching for the end of a link, we have to skip the link because formatting tags cannot appear within # them. That's of course provided it's closed. else { my $linkHasWhitespace; my $endIndex = $self->ClosingTag($textBlocks, $index, ($hasWhitespaceRef && !$hasWhitespace ? \$linkHasWhitespace : undef) ); if ($endIndex != -1) { if ($linkHasWhitespace) { $hasWhitespace = 1; }; # index will be incremented again at the end of the loop, which will bring us past the link's >. $index = $endIndex; }; }; } elsif ($textBlocks->[$index] eq $closingTag) { my $tagType = $self->TagType($textBlocks, $index); if ($tagType == POSSIBLE_CLOSING_TAG) { # There needs to be something between the tags for them to count. if ($index == $beginningIndex + 1) { return -1; } else { # Success! if ($hasWhitespaceRef) { $$hasWhitespaceRef = $hasWhitespace; }; return $index; }; } # If there are two opening tags of the same type, the first becomes literal and the next becomes part of a tag. elsif ($tagType == POSSIBLE_OPENING_TAG) { return -1; } } elsif ($hasWhitespaceRef && !$hasWhitespace) { if ($textBlocks->[$index] =~ /[ \t\n]/) { $hasWhitespace = 1; }; }; $index++; }; # Hit the end of the text blocks if we're here. return -1; }; 1;
prantlf/NaturalDocs
Modules/NaturalDocs/Parser/Native.pm
Perl
agpl-3.0
40,495
/* $OpenBSD: bcrypt_pbkdf.c,v 1.4 2013/07/29 00:55:53 tedu Exp $ */ /* * Copyright (c) 2013 Ted Unangst <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef HAVE_BCRYPT_PBKDF #include "libssh2_priv.h" #include <stdlib.h> #include <sys/types.h> #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif #include "blf.h" #define MINIMUM(a,b) (((a) < (b)) ? (a) : (b)) /* * pkcs #5 pbkdf2 implementation using the "bcrypt" hash * * The bcrypt hash function is derived from the bcrypt password hashing * function with the following modifications: * 1. The input password and salt are preprocessed with SHA512. * 2. The output length is expanded to 256 bits. * 3. Subsequently the magic string to be encrypted is lengthened and modified * to "OxychromaticBlowfishSwatDynamite" * 4. The hash function is defined to perform 64 rounds of initial state * expansion. (More rounds are performed by iterating the hash.) * * Note that this implementation pulls the SHA512 operations into the caller * as a performance optimization. * * One modification from official pbkdf2. Instead of outputting key material * linearly, we mix it. pbkdf2 has a known weakness where if one uses it to * generate (i.e.) 512 bits of key material for use as two 256 bit keys, an * attacker can merely run once through the outer loop below, but the user * always runs it twice. Shuffling output bytes requires computing the * entirety of the key material to assemble any subkey. This is something a * wise caller could do; we just do it for you. */ #define BCRYPT_BLOCKS 8 #define BCRYPT_HASHSIZE (BCRYPT_BLOCKS * 4) static void bcrypt_hash(uint8_t *sha2pass, uint8_t *sha2salt, uint8_t *out) { blf_ctx state; uint8_t ciphertext[BCRYPT_HASHSIZE] = "OxychromaticBlowfishSwatDynamite"; uint32_t cdata[BCRYPT_BLOCKS]; int i; uint16_t j; size_t shalen = SHA512_DIGEST_LENGTH; /* key expansion */ Blowfish_initstate(&state); Blowfish_expandstate(&state, sha2salt, shalen, sha2pass, shalen); for(i = 0; i < 64; i++) { Blowfish_expand0state(&state, sha2salt, shalen); Blowfish_expand0state(&state, sha2pass, shalen); } /* encryption */ j = 0; for(i = 0; i < BCRYPT_BLOCKS; i++) cdata[i] = Blowfish_stream2word(ciphertext, sizeof(ciphertext), &j); for(i = 0; i < 64; i++) blf_enc(&state, cdata, sizeof(cdata) / sizeof(uint64_t)); /* copy out */ for(i = 0; i < BCRYPT_BLOCKS; i++) { out[4 * i + 3] = (cdata[i] >> 24) & 0xff; out[4 * i + 2] = (cdata[i] >> 16) & 0xff; out[4 * i + 1] = (cdata[i] >> 8) & 0xff; out[4 * i + 0] = cdata[i] & 0xff; } /* zap */ _libssh2_explicit_zero(ciphertext, sizeof(ciphertext)); _libssh2_explicit_zero(cdata, sizeof(cdata)); _libssh2_explicit_zero(&state, sizeof(state)); } int bcrypt_pbkdf(const char *pass, size_t passlen, const uint8_t *salt, size_t saltlen, uint8_t *key, size_t keylen, unsigned int rounds) { uint8_t sha2pass[SHA512_DIGEST_LENGTH]; uint8_t sha2salt[SHA512_DIGEST_LENGTH]; uint8_t out[BCRYPT_HASHSIZE]; uint8_t tmpout[BCRYPT_HASHSIZE]; uint8_t *countsalt; size_t i, j, amt, stride; uint32_t count; size_t origkeylen = keylen; libssh2_sha512_ctx ctx; /* nothing crazy */ if(rounds < 1) return -1; if(passlen == 0 || saltlen == 0 || keylen == 0 || keylen > sizeof(out) * sizeof(out) || saltlen > 1<<20) return -1; countsalt = calloc(1, saltlen + 4); if(countsalt == NULL) return -1; stride = (keylen + sizeof(out) - 1) / sizeof(out); amt = (keylen + stride - 1) / stride; memcpy(countsalt, salt, saltlen); /* collapse password */ libssh2_sha512_init(&ctx); libssh2_sha512_update(ctx, pass, passlen); libssh2_sha512_final(ctx, sha2pass); /* generate key, sizeof(out) at a time */ for(count = 1; keylen > 0; count++) { countsalt[saltlen + 0] = (count >> 24) & 0xff; countsalt[saltlen + 1] = (count >> 16) & 0xff; countsalt[saltlen + 2] = (count >> 8) & 0xff; countsalt[saltlen + 3] = count & 0xff; /* first round, salt is salt */ libssh2_sha512_init(&ctx); libssh2_sha512_update(ctx, countsalt, saltlen + 4); libssh2_sha512_final(ctx, sha2salt); bcrypt_hash(sha2pass, sha2salt, tmpout); memcpy(out, tmpout, sizeof(out)); for(i = 1; i < rounds; i++) { /* subsequent rounds, salt is previous output */ libssh2_sha512_init(&ctx); libssh2_sha512_update(ctx, tmpout, sizeof(tmpout)); libssh2_sha512_final(ctx, sha2salt); bcrypt_hash(sha2pass, sha2salt, tmpout); for(j = 0; j < sizeof(out); j++) out[j] ^= tmpout[j]; } /* * pbkdf2 deviation: output the key material non-linearly. */ amt = MINIMUM(amt, keylen); for(i = 0; i < amt; i++) { size_t dest = i * stride + (count - 1); if(dest >= origkeylen) { break; } key[dest] = out[i]; } keylen -= i; } /* zap */ _libssh2_explicit_zero(out, sizeof(out)); free(countsalt); return 0; } #endif /* HAVE_BCRYPT_PBKDF */
FriendSoftwareLabs/friendup
libs-ext/libssh2/src/bcrypt_pbkdf.c
C
agpl-3.0
6,092
/* * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/evp.h> #include <openssl/core_names.h> #include "internal/provider_util.h" void ossl_prov_cipher_reset(PROV_CIPHER *pc) { EVP_CIPHER_free(pc->alloc_cipher); pc->alloc_cipher = NULL; pc->cipher = NULL; pc->engine = NULL; } int ossl_prov_cipher_copy(PROV_CIPHER *dst, const PROV_CIPHER *src) { if (src->alloc_cipher != NULL && !EVP_CIPHER_up_ref(src->alloc_cipher)) return 0; dst->engine = src->engine; dst->cipher = src->cipher; dst->alloc_cipher = src->alloc_cipher; return 1; } static int load_common(const OSSL_PARAM params[], const char **propquery, ENGINE **engine) { const OSSL_PARAM *p; *propquery = NULL; p = OSSL_PARAM_locate_const(params, OSSL_ALG_PARAM_PROPERTIES); if (p != NULL) { if (p->data_type != OSSL_PARAM_UTF8_STRING) return 0; *propquery = p->data; } *engine = NULL; /* TODO legacy stuff, to be removed */ /* Inside the FIPS module, we don't support legacy ciphers */ #if !defined(FIPS_MODE) && !defined(OPENSSL_NO_ENGINE) p = OSSL_PARAM_locate_const(params, "engine"); if (p != NULL) { if (p->data_type != OSSL_PARAM_UTF8_STRING) return 0; ENGINE_finish(*engine); *engine = ENGINE_by_id(p->data); if (*engine == NULL) return 0; } #endif return 1; } int ossl_prov_cipher_load_from_params(PROV_CIPHER *pc, const OSSL_PARAM params[], OPENSSL_CTX *ctx) { const OSSL_PARAM *p; const char *propquery; if (!load_common(params, &propquery, &pc->engine)) return 0; p = OSSL_PARAM_locate_const(params, OSSL_ALG_PARAM_CIPHER); if (p == NULL) return 1; if (p->data_type != OSSL_PARAM_UTF8_STRING) return 0; EVP_CIPHER_free(pc->alloc_cipher); pc->cipher = pc->alloc_cipher = EVP_CIPHER_fetch(ctx, p->data, propquery); /* TODO legacy stuff, to be removed */ #ifndef FIPS_MODE /* Inside the FIPS module, we don't support legacy ciphers */ if (pc->cipher == NULL) pc->cipher = EVP_get_cipherbyname(p->data); #endif return pc->cipher != NULL; } const EVP_CIPHER *ossl_prov_cipher_cipher(const PROV_CIPHER *pc) { return pc->cipher; } ENGINE *ossl_prov_cipher_engine(const PROV_CIPHER *pc) { return pc->engine; } void ossl_prov_digest_reset(PROV_DIGEST *pd) { EVP_MD_free(pd->alloc_md); pd->alloc_md = NULL; pd->md = NULL; pd->engine = NULL; } int ossl_prov_digest_copy(PROV_DIGEST *dst, const PROV_DIGEST *src) { if (src->alloc_md != NULL && !EVP_MD_up_ref(src->alloc_md)) return 0; dst->engine = src->engine; dst->md = src->md; dst->alloc_md = src->alloc_md; return 1; } int ossl_prov_digest_load_from_params(PROV_DIGEST *pd, const OSSL_PARAM params[], OPENSSL_CTX *ctx) { const OSSL_PARAM *p; const char *propquery; if (!load_common(params, &propquery, &pd->engine)) return 0; p = OSSL_PARAM_locate_const(params, OSSL_ALG_PARAM_DIGEST); if (p == NULL) return 1; if (p->data_type != OSSL_PARAM_UTF8_STRING) return 0; EVP_MD_free(pd->alloc_md); pd->md = pd->alloc_md = EVP_MD_fetch(ctx, p->data, propquery); /* TODO legacy stuff, to be removed */ #ifndef FIPS_MODE /* Inside the FIPS module, we don't support legacy digests */ if (pd->md == NULL) pd->md = EVP_get_digestbyname(p->data); #endif return pd->md != NULL; } const EVP_MD *ossl_prov_digest_md(const PROV_DIGEST *pd) { return pd->md; } ENGINE *ossl_prov_digest_engine(const PROV_DIGEST *pd) { return pd->engine; } int ossl_prov_macctx_load_from_params(EVP_MAC_CTX **macctx, const OSSL_PARAM params[], const char *macname, const char *ciphername, const char *mdname, OPENSSL_CTX *libctx) { const OSSL_PARAM *p; OSSL_PARAM mac_params[5], *mp = mac_params; const char *properties = NULL; if (macname == NULL && (p = OSSL_PARAM_locate_const(params, OSSL_ALG_PARAM_MAC)) != NULL) { if (p->data_type != OSSL_PARAM_UTF8_STRING) return 0; macname = p->data; } if ((p = OSSL_PARAM_locate_const(params, OSSL_ALG_PARAM_PROPERTIES)) != NULL) { if (p->data_type != OSSL_PARAM_UTF8_STRING) return 0; properties = p->data; } /* If we got a new mac name, we make a new EVP_MAC_CTX */ if (macname != NULL) { EVP_MAC *mac = EVP_MAC_fetch(libctx, macname, properties); EVP_MAC_CTX_free(*macctx); *macctx = mac == NULL ? NULL : EVP_MAC_CTX_new(mac); /* The context holds on to the MAC */ EVP_MAC_free(mac); if (*macctx == NULL) return 0; } /* * If there is no MAC yet (and therefore, no MAC context), we ignore * all other parameters. */ if (*macctx == NULL) return 1; if (mdname == NULL) { if ((p = OSSL_PARAM_locate_const(params, OSSL_ALG_PARAM_DIGEST)) != NULL) { if (p->data_type != OSSL_PARAM_UTF8_STRING) return 0; mdname = p->data; } } if (ciphername == NULL) { if ((p = OSSL_PARAM_locate_const(params, OSSL_ALG_PARAM_CIPHER)) != NULL) { if (p->data_type != OSSL_PARAM_UTF8_STRING) return 0; ciphername = p->data; } } if (mdname != NULL) *mp++ = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, (char *)mdname, 0); if (ciphername != NULL) *mp++ = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, (char *)ciphername, 0); if (properties != NULL) *mp++ = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_PROPERTIES, (char *)properties, 0); #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODE) if ((p = OSSL_PARAM_locate_const(params, "engine")) != NULL) { if (p->data_type != OSSL_PARAM_UTF8_STRING) return 0; *mp++ = OSSL_PARAM_construct_utf8_string("engine", p->data, p->data_size); } #endif *mp = OSSL_PARAM_construct_end(); if (EVP_MAC_CTX_set_params(*macctx, mac_params)) return 1; EVP_MAC_CTX_free(*macctx); *macctx = NULL; return 0; }
FriendSoftwareLabs/friendup
libs-ext/openssl/providers/common/provider_util.c
C
agpl-3.0
7,174
//////////////////////////////////////////////////////////////// // // Copyright (C) 2008 Affymetrix, Inc. // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License // (version 2.1) as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License // for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, write to the Free Software Foundation, Inc., // 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //////////////////////////////////////////////////////////////// #ifndef _FamilialMultiDataData_HEADER_ #define _FamilialMultiDataData_HEADER_ /*! \file FamilialMultiDataData.h This file provides types to store results for a familial file. */ // #include "calvin_files/parameter/src/ParameterNameValueType.h" #include "calvin_files/portability/src/AffymetrixBaseTypes.h" // #include <cstring> #include <sstream> #include <string> #include <vector> // namespace affymetrix_calvin_data { /*! Stores the segment overlap from a familial file. */ typedef struct _FamilialSegmentOverlap { /*! The type of segment; the name of the data set in which the segment appears in the CYCHP file. */ std::string segmentType; /*! The key identifying the sample from the Samples data set. */ u_int32_t referenceSampleKey; /*! The ID of the segment of the reference sample. */ std::string referenceSegmentID; /*! The key identifying the sample from the Samples data set. */ u_int32_t familialSampleKey; /*! The ID of the segment of the compare sample. */ std::string familialSegmentID; } FamilialSegmentOverlap; /*! Stores information about the sample for a familial file. */ typedef struct _FamilialSample { /*! Local arbitrary unique sample identifier used within the file. */ u_int32_t sampleKey; /*! The identifier of the ARR file associated with the sample. If no ARR file was used in generating the associated CYCHP files, this value will be the empty string. */ std::string arrID; /*! The identifier of the CYCHP file containing the sample data. */ std::string chpID; /*! The filename (not the complete path) of the CYCHP file containing the sample data. */ std::wstring chpFilename; /*! The role of the identified sample, such as “index”, “mother”, or “father”. */ std::string role; /*! The call of whether the assigned role is correct. */ bool roleValidity; /*! The confidence that the assigned role is correct */ float roleConfidence; } FamilialSample; } #endif
einon/affymetrix-power-tools
sdk/calvin_files/data/src/FamilialMultiDataData.h
C
lgpl-2.1
2,816
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This 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 Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #ifndef SOFA_CONTACT_LISTENER_H #define SOFA_CONTACT_LISTENER_H #include "config.h" #include <sofa/core/objectmodel/BaseObject.h> #include <sofa/core/collision/Contact.h> //#include <sofa/core/collision/DetectionOutput.h> #include <sofa/helper/vector.h> //#include <sofa/core/CollisionModel.h> namespace sofa { namespace core { // forward declaration class CollisionModel; namespace collision { // forward declaration class NarrowPhaseDetection; class SOFA_BASE_COLLISION_API ContactListener : public virtual core::objectmodel::BaseObject { public: SOFA_CLASS(ContactListener, core::objectmodel::BaseObject); protected: ContactListener( CollisionModel* collModel1 = NULL, CollisionModel* collModel2 = NULL ); virtual ~ContactListener(); // DetectionOutput iterators typedef helper::vector<const helper::vector<DetectionOutput>* >::const_iterator ContactVectorsIterator; typedef helper::vector<DetectionOutput>::const_iterator ContactsIterator; virtual void beginContact(const helper::vector<const helper::vector<DetectionOutput>* >& ) {} virtual void endContact(void*) {} protected: const CollisionModel* mCollisionModel1; const CollisionModel* mCollisionModel2; //// are these SingleLinks necessary ? they are used only in canCreate(...) and create functions(...) //SingleLink<ContactListener, CollisionModel, BaseLink::FLAG_STOREPATH|BaseLink::FLAG_STRONGLINK> mLinkCollisionModel1; ///// Pointer to the next (finer / lower / child level) CollisionModel in the hierarchy. //SingleLink<ContactListener, CollisionModel, BaseLink::FLAG_STOREPATH|BaseLink::FLAG_STRONGLINK> mLinkCollisionModel2; private: helper::vector<const helper::vector<DetectionOutput>* > mContactsVector; core::collision::NarrowPhaseDetection* mNarrowPhase; public: virtual void init(void) override; virtual void handleEvent( core::objectmodel::Event* event ) override; template<class T> static bool canCreate(T*& obj, core::objectmodel::BaseContext* context, core::objectmodel::BaseObjectDescription* arg) { core::CollisionModel* collModel1 = NULL; core::CollisionModel* collModel2 = NULL; std::string collModelPath1; std::string collModelPath2; if (arg->getAttribute("collisionModel1")) collModelPath1 = arg->getAttribute("collisionModel1"); else collModelPath1 = ""; context->findLinkDest(collModel1, collModelPath1, NULL); if (arg->getAttribute("collisionModel2")) collModelPath2 = arg->getAttribute("collisionModel2"); else collModelPath2 = ""; context->findLinkDest(collModel2, collModelPath2, NULL); if (collModel1 == NULL && collModel2 == NULL ) { context->serr << "Creation of " << className(obj) << " CollisonListener failed because no Collision Model links are found: \"" << collModelPath1 << "\" and \"" << collModelPath2 << "\" " << context->sendl; return false; } return BaseObject::canCreate(obj, context, arg); } template<class T> static typename T::SPtr create(T* , core::objectmodel::BaseContext* context, core::objectmodel::BaseObjectDescription* arg) { CollisionModel* collModel1 = NULL; CollisionModel* collModel2 = NULL; std::string collModelPath1; std::string collModelPath2; if(arg) { collModelPath1 = arg->getAttribute(std::string("collisionModel1"), NULL ); collModelPath2 = arg->getAttribute(std::string("collisionModel2"), NULL ); // now 3 cases if ( strcmp( collModelPath1.c_str(),"" ) != 0 ) { context->findLinkDest(collModel1, collModelPath1, NULL); if ( strcmp( collModelPath2.c_str(),"" ) != 0 ) { context->findLinkDest(collModel2, collModelPath2, NULL); } } else { context->findLinkDest(collModel1, collModelPath2, NULL); } } typename T::SPtr obj = sofa::core::objectmodel::New<T>( collModel1, collModel2 ); //if ( obj ) //{ // obj->mLinkCollisionModel1.setPath( collModelPath1 ); // obj->mLinkCollisionModel2.setPath( collModelPath2 ); //} if (context) { context->addObject(obj); } if (arg) { obj->parse(arg); } return obj; } }; } // namespace collision } // namespace core } // namespace sofa #endif // SOFA_CONTACT_LISTENER_H
FabienPean/sofa
SofaKernel/modules/SofaBaseCollision/ContactListener.h
C
lgpl-2.1
6,198
/* Copyright 2009 Will Stephenson <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #ifndef KNM_INTERNALS_UNCONFIGUREDINTERFACE_H #define KNM_INTERNALS_UNCONFIGUREDINTERFACE_H #include "activatable.h" namespace Knm { class UnconfiguredInterface : public Activatable { Q_OBJECT public: UnconfiguredInterface(const QString &deviceUni, QObject *parent); virtual ~UnconfiguredInterface(); }; } #endif // KNM_INTERNALS_UNCONFIGUREDINTERFACE_H
zballina/nm-applet-qt
libs/internals/unconfiguredinterface.h
C
lgpl-2.1
1,300
#ifndef HIGHSCORE_HPP #define HIGHSCORE_HPP #include <cassert> #include <sstream> #include "framework.hpp" #include "./config.hpp" #include "./media.hpp" class Highscore { public: Highscore(); ~Highscore(); /* Load/Save */ void load(); void save(); /* Access particular difficulties */ util::Highscore &getHighscore(LEVEL_DIFFICULTY difficulty); /* Draw */ void draw(); private: /* Data */ util::Timer timer; util::Highscore highscore[LEVEL_DIFFICULTY_END]; double offset; int haltstart; int difficulty; bool shifting; struct { font::TtfLabel difficulty[LEVEL_DIFFICULTY_END]; font::TtfLabel place[3/*HIGHSCORE_PLACECOUNT*/]; font::TtfLabel score[LEVEL_DIFFICULTY_END][3/*HIGHSCORE_PLACECOUNT*/]; font::TtfLabel prescore[LEVEL_DIFFICULTY_END][3/*HIGHSCORE_PLACECOUNT*/]; }label; }; #endif // HIGHSCORE_HPP
mrzzzrm/shootet
src/Highscore.hpp
C++
lgpl-2.1
1,080
/* table.h - Iterative table interface. * Copyright (C) 2006 g10 Code GmbH * * This file is part of Scute. * * Scute is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Scute is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see <https://gnu.org/licenses/>. * SPDX-License-Identifier: LGPL-2.1-or-later */ #ifndef TABLE_H #define TABLE_H 1 #include <stdbool.h> #include <gpg-error.h> /* The indexed list type. */ struct scute_table; typedef struct scute_table *scute_table_t; /* TABLE interface. */ /* A table entry allocator function callback. Should return the new table entry in DATA_R. */ typedef gpg_error_t (*scute_table_alloc_cb_t) (void **data_r, void *hook); /* A table entry deallocator function callback. */ typedef void (*scute_table_dealloc_cb_t) (void *data); /* Allocate a new table and return it in TABLE_R. */ gpg_error_t scute_table_create (scute_table_t *table_r, scute_table_alloc_cb_t alloc, scute_table_dealloc_cb_t dealloc); /* Destroy the indexed list TABLE. This also calls the deallocator on all entries. */ void scute_table_destroy (scute_table_t table); /* Allocate a new table entry with a free index. Returns the index pointing to the new list entry in INDEX_R. This calls the allocator on the new entry before returning. Also returns the table entry in *DATA_R if this is not NULL. */ gpg_error_t scute_table_alloc (scute_table_t table, int *index_r, void **data_r, void *hook); /* Deallocate the list entry index. Afterwards, INDEX points to the following entry. This calls the deallocator on the entry before returning. */ void scute_table_dealloc (scute_table_t table, int *index); /* Return the index for the beginning of the list TABLE. */ int scute_table_first (scute_table_t table); /* Return the index following INDEX. If INDEX is the last element in the list, return 0. */ int scute_table_next (scute_table_t table, int index); /* Return true iff INDEX is the end-of-list marker. */ bool scute_table_last (scute_table_t table, int index); /* Return the user data associated with INDEX. Return NULL if INDEX is the end-of-list marker. */ void *scute_table_data (scute_table_t table, int index); /* Return the number of entries in the table TABLE. */ int scute_table_used (scute_table_t table); #endif /* !TABLE_H */
gpg/scute
src/table.h
C
lgpl-2.1
2,851
// CC0 Public Domain: http://creativecommons.org/publicdomain/zero/1.0/ #include "bsefilter.hh" #include <sfi/sfi.hh> using namespace Bse; const gchar* bse_iir_filter_kind_string (BseIIRFilterKind fkind) { switch (fkind) { case BSE_IIR_FILTER_BUTTERWORTH: return "Butterworth"; case BSE_IIR_FILTER_BESSEL: return "Bessel"; case BSE_IIR_FILTER_CHEBYSHEV1: return "Chebyshev1"; case BSE_IIR_FILTER_CHEBYSHEV2: return "Chebyshev2"; case BSE_IIR_FILTER_ELLIPTIC: return "Elliptic"; default: return "?unknown?"; } } const gchar* bse_iir_filter_type_string (BseIIRFilterType ftype) { switch (ftype) { case BSE_IIR_FILTER_LOW_PASS: return "Low-pass"; case BSE_IIR_FILTER_BAND_PASS: return "Band-pass"; case BSE_IIR_FILTER_HIGH_PASS: return "High-pass"; case BSE_IIR_FILTER_BAND_STOP: return "Band-stop"; default: return "?unknown?"; } } gchar* bse_iir_filter_request_string (const BseIIRFilterRequest *ifr) { String s; s += bse_iir_filter_kind_string (ifr->kind); s += " "; s += bse_iir_filter_type_string (ifr->type); s += " order=" + string_from_int (ifr->order); s += " sample-rate=" + string_from_float (ifr->sampling_frequency); if (ifr->kind == BSE_IIR_FILTER_CHEBYSHEV1 || ifr->kind == BSE_IIR_FILTER_ELLIPTIC) s += " passband-ripple-db=" + string_from_float (ifr->passband_ripple_db); s += " passband-edge=" + string_from_float (ifr->passband_edge); if (ifr->type == BSE_IIR_FILTER_BAND_PASS || ifr->type == BSE_IIR_FILTER_BAND_STOP) s += " passband-edge2=" + string_from_float (ifr->passband_edge2); if (ifr->kind == BSE_IIR_FILTER_ELLIPTIC && ifr->stopband_db < 0) s += " stopband-db=" + string_from_float (ifr->stopband_db); if (ifr->kind == BSE_IIR_FILTER_ELLIPTIC && ifr->stopband_edge > 0) s += " stopband-edge=" + string_from_float (ifr->stopband_edge); return g_strdup (s.c_str()); } gchar* bse_iir_filter_design_string (const BseIIRFilterDesign *fid) { String s; s += "order=" + string_from_int (fid->order); s += " sampling-frequency=" + string_from_float (fid->sampling_frequency); s += " center-frequency=" + string_from_float (fid->center_frequency); s += " gain=" + string_from_double (fid->gain); s += " n_zeros=" + string_from_int (fid->n_zeros); s += " n_poles=" + string_from_int (fid->n_poles); for (uint i = 0; i < fid->n_zeros; i++) { String u ("Zero:"); u += " " + string_from_double (fid->zz[i].re); u += " + " + string_from_double (fid->zz[i].im) + "*i"; s += "\n" + u; } for (uint i = 0; i < fid->n_poles; i++) { String u ("Pole:"); u += " " + string_from_double (fid->zp[i].re); u += " + " + string_from_double (fid->zp[i].im) + "*i"; s += "\n" + u; } String u; #if 0 uint o = fid->order; u = string_from_double (fid->zn[o]); while (o--) u = "(" + u + ") * z + " + string_from_double (fid->zn[o]); s += "\nNominator: " + u; o = fid->order; u = string_from_double (fid->zd[o]); while (o--) u = "(" + u + ") * z + " + string_from_double (fid->zd[o]); s += "\nDenominator: " + u; #endif return g_strdup (s.c_str()); } bool bse_iir_filter_design (const BseIIRFilterRequest *filter_request, BseIIRFilterDesign *filter_design) { if (filter_request->kind == BSE_IIR_FILTER_BUTTERWORTH || filter_request->kind == BSE_IIR_FILTER_CHEBYSHEV1 || filter_request->kind == BSE_IIR_FILTER_ELLIPTIC) return _bse_filter_design_ellf (filter_request, filter_design); return false; }
GNOME/beast
bse/bsefilter.cc
C++
lgpl-2.1
3,662
#include <stdio.h> #include <QtDebug> #include "cguitreedomdocument.h" CGuiTreeDomDocument::CGuiTreeDomDocument() { QDomImplementation impl; impl.setInvalidDataPolicy(QDomImplementation::ReturnNullNode); } /** * Get first "guiObject" located in "guiRoot". * * @return Node element of first guiObject or an empty element node if there is none. **/ CGuiTreeDomElement CGuiTreeDomDocument::getFirstGuiObjectElement() { CGuiTreeDomElement domElmGuiTree; domElmGuiTree = this->firstChildElement("guiRoot"); if(domElmGuiTree.isNull()) return(domElmGuiTree); return(domElmGuiTree.firstChildElement("guiObject")); }
stevedorries/DFM2QT4UI
cguitreedomdocument.cpp
C++
lgpl-2.1
651