repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
acappellamaniac/eva_website
sites/all/modules/civicrm/CRM/Admin/Page/MessageTemplates.php
10277
<?php /* +--------------------------------------------------------------------+ | CiviCRM version 4.6 | +--------------------------------------------------------------------+ | Copyright CiviCRM LLC (c) 2004-2015 | +--------------------------------------------------------------------+ | This file is a part of CiviCRM. | | | | CiviCRM is free software; you can copy, modify, and distribute it | | under the terms of the GNU Affero General Public License | | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. | | | | CiviCRM 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 and the CiviCRM Licensing Exception along | | with this program; if not, contact CiviCRM LLC | | at info[AT]civicrm[DOT]org. If you have questions about the | | GNU Affero General Public License or the licensing of CiviCRM, | | see the CiviCRM license FAQ at http://civicrm.org/licensing | +--------------------------------------------------------------------+ */ /** * * @package CRM * @copyright CiviCRM LLC (c) 2004-2015 * $Id$ * */ /** * Page for displaying list of message templates */ class CRM_Admin_Page_MessageTemplates extends CRM_Core_Page_Basic { /** * The action links that we need to display for the browse screen. * * @var array */ static $_links = NULL; // ids of templates which diverted from the default ones and can be reverted protected $_revertible = array(); // set to the id that we’re reverting at the given moment (if we are) protected $_revertedId; /** * @param null $title * @param null $mode */ public function __construct($title = NULL, $mode = NULL) { parent::__construct($title, $mode); // fetch the ids of templates which diverted from defaults and can be reverted – // these templates have the same workflow_id as the defaults; defaults are reserved $sql = ' SELECT diverted.id, orig.id orig_id FROM civicrm_msg_template diverted JOIN civicrm_msg_template orig ON ( diverted.workflow_id = orig.workflow_id AND orig.is_reserved = 1 AND ( diverted.msg_subject != orig.msg_subject OR diverted.msg_text != orig.msg_text OR diverted.msg_html != orig.msg_html ) ) '; $dao = CRM_Core_DAO::executeQuery($sql); while ($dao->fetch()) { $this->_revertible[$dao->id] = $dao->orig_id; } } /** * Get BAO Name. * * @return string * Classname of BAO. */ public function getBAOName() { return 'CRM_Core_BAO_MessageTemplate'; } /** * Get action Links. * * @return array * (reference) of action links */ public function &links() { if (!(self::$_links)) { $confirm = ts('Are you sure you want to revert this template to the default for this workflow? You will lose any customizations you have made.', array('escape' => 'js')) . '\n\n' . ts('We recommend that you save a copy of the your customized Text and HTML message content to a text file before reverting so you can combine your changes with the system default messages as needed.', array('escape' => 'js')); self::$_links = array( CRM_Core_Action::UPDATE => array( 'name' => ts('Edit'), 'url' => 'civicrm/admin/messageTemplates/add', 'qs' => 'action=update&id=%%id%%&reset=1', 'title' => ts('Edit this message template'), ), CRM_Core_Action::DISABLE => array( 'name' => ts('Disable'), 'ref' => 'crm-enable-disable', 'title' => ts('Disable this message template'), ), CRM_Core_Action::ENABLE => array( 'name' => ts('Enable'), 'ref' => 'crm-enable-disable', 'title' => ts('Enable this message template'), ), CRM_Core_Action::DELETE => array( 'name' => ts('Delete'), 'url' => 'civicrm/admin/messageTemplates', 'qs' => 'action=delete&id=%%id%%', 'title' => ts('Delete this message template'), ), CRM_Core_Action::REVERT => array( 'name' => ts('Revert to Default'), 'extra' => "onclick = 'return confirm(\"$confirm\");'", 'url' => 'civicrm/admin/messageTemplates', 'qs' => 'action=revert&id=%%id%%&selectedChild=workflow', 'title' => ts('Revert this workflow message template to the system default'), ), CRM_Core_Action::VIEW => array( 'name' => ts('View Default'), 'url' => 'civicrm/admin/messageTemplates', 'qs' => 'action=view&id=%%orig_id%%&reset=1', 'title' => ts('View the system default for this workflow message template'), ), ); } return self::$_links; } /** * @param CRM_Core_DAO $object * @param int $action * @param array $values * @param array $links * @param string $permission * @param bool $forceAction */ public function action(&$object, $action, &$values, &$links, $permission, $forceAction = FALSE) { if ($object->workflow_id) { // do not expose action link for reverting to default if the template did not diverge or we just reverted it now if (!in_array($object->id, array_keys($this->_revertible)) or ($this->_action & CRM_Core_Action::REVERT and $object->id == $this->_revertedId) ) { $action &= ~CRM_Core_Action::REVERT; $action &= ~CRM_Core_Action::VIEW; } // default workflow templates shouldn’t be deletable // workflow templates shouldn’t have disable/enable actions (at least for CiviCRM 3.1) if ($object->workflow_id) { $action &= ~CRM_Core_Action::DISABLE; $action &= ~CRM_Core_Action::DELETE; } // rebuild the action links HTML, as we need to handle %%orig_id%% for revertible templates $values['action'] = CRM_Core_Action::formLink($links, $action, array( 'id' => $object->id, 'orig_id' => CRM_Utils_Array::value($object->id, $this->_revertible), ), ts('more'), FALSE, 'messageTemplate.manage.action', 'MessageTemplate', $object->id ); } else { $action &= ~CRM_Core_Action::REVERT; $action &= ~CRM_Core_Action::VIEW; parent::action($object, $action, $values, $links, $permission); } } /** * @param null $args * @param null $pageArgs * @param null $sort * * @throws Exception */ public function run($args = NULL, $pageArgs = NULL, $sort = NULL) { // handle the revert action and offload the rest to parent if (CRM_Utils_Request::retrieve('action', 'String', $this) & CRM_Core_Action::REVERT) { $id = CRM_Utils_Request::retrieve('id', 'Positive', $this); if (!$this->checkPermission($id, NULL)) { CRM_Core_Error::fatal(ts('You do not have permission to revert this template.')); } $this->_revertedId = $id; CRM_Core_BAO_MessageTemplate::revert($id); } $this->assign('selectedChild', CRM_Utils_Request::retrieve('selectedChild', 'String', $this)); return parent::run($args, $pageArgs, $sort); } /** * Get name of edit form. * * @return string * Classname of edit form. */ public function editForm() { return 'CRM_Admin_Form_MessageTemplates'; } /** * Get edit form name. * * @return string * name of this page. */ public function editName() { return ts('Message Template'); } /** * Get user context. * * @param null $mode * * @return string * user context. */ public function userContext($mode = NULL) { return 'civicrm/admin/messageTemplates'; } /** * Browse all entities. * * @return void */ public function browse() { $action = func_num_args() ? func_get_arg(0) : NULL; if ($this->_action & CRM_Core_Action::ADD) { return; } $links = $this->links(); if ($action == NULL) { if (!empty($links)) { $action = array_sum(array_keys($links)); } } if ($action & CRM_Core_Action::DISABLE) { $action -= CRM_Core_Action::DISABLE; } if ($action & CRM_Core_Action::ENABLE) { $action -= CRM_Core_Action::ENABLE; } $messageTemplate = new CRM_Core_BAO_MessageTemplate(); $messageTemplate->orderBy('msg_title' . ' asc'); $userTemplates = array(); $workflowTemplates = array(); // find all objects $messageTemplate->find(); while ($messageTemplate->fetch()) { $values[$messageTemplate->id] = array(); CRM_Core_DAO::storeValues($messageTemplate, $values[$messageTemplate->id]); // populate action links $this->action($messageTemplate, $action, $values[$messageTemplate->id], $links, CRM_Core_Permission::EDIT); if (!$messageTemplate->workflow_id) { $userTemplates[$messageTemplate->id] = $values[$messageTemplate->id]; } elseif (!$messageTemplate->is_reserved) { $workflowTemplates[$messageTemplate->id] = $values[$messageTemplate->id]; } } $rows = array( 'userTemplates' => $userTemplates, 'workflowTemplates' => $workflowTemplates, ); $this->assign('rows', $rows); } }
gpl-2.0
IEEE-CS-UWM/OrgWeb
resource/views/member/login.php
647
<?php if (isset($_POST["member_uwmemail"]) && isset($_POST["member_password"])){ require "./resource/controllers/member/search.php"; //I set up for true because it means there is value. if ( $member == true) { $row = mysqli_fetch_array($member); session_start(); $_SESSION["member_id"] = $row["member_id"]; $message = "<p class=\"message success\">Logged in! Returning to main page.</p>"; } else { $message = "<p class=\"warning\">This email and password combination is not recognized. Please try again.</p>"; } } else { $message = "<p class=\"message error\">ERROR: Email and password were not provided</p>"; } ?>
gpl-2.0
MayGo/tockler
client/src/components/SearchResults/SearchResults.tsx
2013
import { IconButton, Tooltip } from '@chakra-ui/react'; import moment from 'moment'; import React, { memo } from 'react'; import { AiOutlineUnorderedList } from 'react-icons/ai'; import { useHistory } from 'react-router'; import { useStoreActions } from '../../store/easyPeasy'; import { ItemsTable } from '../TrackItemTable/ItemsTable'; const ActionCell = ({ cell }) => { const { beginDate, endDate } = cell.row.original; const loadTimerange = useStoreActions((state) => state.loadTimerange); const setVisibleTimerange = useStoreActions((state) => state.setVisibleTimerange); const history = useHistory(); const goToTimelinePage = (record) => { loadTimerange([moment(record.beginDate).startOf('day'), moment(record.beginDate).endOf('day')]); setVisibleTimerange([ moment(record.beginDate).subtract(15, 'minutes'), moment(record.endDate).add(15, 'minutes'), ]); history.push('/app/timeline'); }; return ( <Tooltip placement="left" label="Select date and go to timeline view"> <IconButton variant="ghost" aria-label="Go to timeline" icon={<AiOutlineUnorderedList />} onClick={() => goToTimelinePage({ beginDate, endDate })} /> </Tooltip> ); }; const extraColumns = [ { Cell: ActionCell, id: 'actions', accessor: 'title', width: 20, minWidth: 20, maxWidth: 20, }, ]; const SearchResultsPlain = ({ searchResult, fetchData, pageIndex, total }) => { return ( <ItemsTable data={searchResult.results || []} isOneDay={false} isSearchTable fetchData={fetchData} pageCount={searchResult.total} pageIndex={pageIndex} extraColumns={extraColumns} total={total} manualSortBy /> ); }; export const SearchResults = memo(SearchResultsPlain);
gpl-2.0
AlexanderDolgan/ojahuri
wp-content/plugins/quick-restaurant-menu/includes/admin/metabox.php
5165
<?php /** * Metabox Functions * * @package ERM * @subpackage Admin * @copyright Copyright (c) 2015, Alejandro Pascual * @license http://opensource.org/licenses/gpl-2.0.php GNU Public License * @since 1.0 */ // Exit if accessed directly if ( ! defined( 'ABSPATH' ) ) exit; /** * Register metabox for Menu * * @since 1.0 * @updated 1.1 * @return void */ function erm_add_menu_meta_box() { $post_types = apply_filters( 'erm_menu_metabox_post_types' , array( 'erm_menu' ) ); foreach ( $post_types as $post_type ) { add_meta_box( 'erm_menu_items', __( 'Menu Items', 'erm' ), 'erm_render_menu_meta_box', $post_type, 'normal', 'high' ); add_meta_box( 'erm_footer_item', __( 'Footer Menu', 'erm' ), 'erm_render_footer_meta_box', $post_type, 'normal', 'high' ); add_meta_box( 'erm_menu_shortcode', __( 'Shortcode', 'erm' ), 'erm_render_shortcode_meta_box', $post_type, 'side' ); } $post_types = apply_filters( 'erm_menu_week_post_types', array( 'erm_menu_week' ) ); foreach( $post_types as $post_type ) { add_meta_box( 'erm_menu_weekly', __( 'Weekly menu rules', 'erm' ), 'erm_render_menu_week_meta_box', $post_type, 'normal', 'high' ); add_meta_box( 'erm_menu_weekly_shortcode', __( 'Shortcode', 'erm' ), 'erm_render_menu_week_shortcode_meta_box', $post_type, 'side' ); } } add_action( 'add_meta_boxes', 'erm_add_menu_meta_box' ); /** * Menu Items metabox * * @since 1.0 * @return void */ function erm_render_menu_meta_box() { global $post; /* * Output list of Menu Items */ do_action( 'erm_meta_box_menu_items', $post->ID ); } /** * Render Menu Items inside metabox * * @since 1.0 * @param $post_id */ function erm_render_menu_items( $post_id ) { include ERM_PLUGIN_DIR.'/templates/metabox-menu-items.php'; } add_action( 'erm_meta_box_menu_items', 'erm_render_menu_items', 10 ); /** * Footer Menu metabox * * @since 1.0 * @return void */ function erm_render_footer_meta_box() { global $post; do_action( 'erm_meta_box_footer', $post->ID ); } /** * Render Menu Footer * * @since 1.0 * @param $post_id */ function erm_render_footer_item( $post_id ) { $content = get_post_meta( $post_id, '_erm_footer_menu', true ); wp_editor( $content, '_erm_footer_menu', array( 'wpautop' => true, 'media_buttons' => false, //'textarea_name' => 'meta_biography', 'textarea_rows' => 10, 'teeny' => true ) ); wp_nonce_field( 'erm_footer_metabox_nonce', 'erm_footer_metabox_nonce' ); } add_action( 'erm_meta_box_footer', 'erm_render_footer_item', 10); /** * Save Footer menu * * @since 1.0 * @param $post_id */ function erm_save_footer_item( $post_id ){ // Check if our nonce is set. if ( ! isset( $_POST['erm_footer_metabox_nonce'] ) ) { return; } // Verify that the nonce is valid. if ( ! wp_verify_nonce( $_POST['erm_footer_metabox_nonce'], 'erm_footer_metabox_nonce' ) ) { return; } // If this is an autosave, our form has not been submitted, so we don't want to do anything. if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } // Check the user's permissions. if ( isset( $_POST['post_type'] ) && 'erm_menu' == $_POST['post_type'] ) { if ( ! current_user_can( 'edit_post', $post_id ) ) { return; } } else { if ( ! current_user_can( 'edit_post', $post_id ) ) { return; } } // Make sure that it is set. if ( ! isset( $_POST['_erm_footer_menu'] ) ) { return; } // Sanitize user input. //$my_data = sanitize_text_field( $_POST['_erm_footer_menu'] ); $my_data = $_POST['_erm_footer_menu']; // Update the meta field in the database. update_post_meta( $post_id, '_erm_footer_menu', $my_data ); } add_action( 'save_post', 'erm_save_footer_item' ); /** * Shortcode Menu metabox * * @since 1.0 * @return void */ function erm_render_shortcode_meta_box() { global $post; $sc = '[erm_menu id='.$post->ID.']'; echo '<p>'.__('Insert this shortcode to display Menu in Front end','erm').'</p>'; echo '<div style="background-color: #F1F1F1;padding: 10px;font-size: 20px;">'; print_r( $sc ); echo '</div>'; } /** * Menu Weekly metabox * * @since 1.0 * @return void */ function erm_render_menu_week_meta_box() { global $post; do_action( 'erm_render_menu_week_meta_box', $post->ID ); } /** * Render Menu Week metabox * * @since 1.1 * @param $post_id */ function erm_render_menu_week_rules( $post_id ){ include ERM_PLUGIN_DIR.'/templates/metabox-menu-week.php'; } add_action('erm_render_menu_week_meta_box','erm_render_menu_week_rules'); /** * Render Menu Week shortcode metabox * * @since 1.1 */ function erm_render_menu_week_shortcode_meta_box(){ global $post; $sc = '[erm_menu_week id='.$post->ID.']'; echo '<p>'.__('Insert this shortcode to display Menu in Front end','erm').'</p>'; echo '<div style="background-color: #F1F1F1;padding: 10px;font-size: 16px;">'; print_r( $sc ); echo '</div>'; }
gpl-2.0
latproc/clockwork
modbus/src/mbmon.cpp
19195
#include <iostream> #include <zmq.hpp> #include <modbus.h> #include <unistd.h> #include <stdlib.h> #include <boost/thread.hpp> #include <map> #include <set> #include "modbus_helpers.h" #include "buffer_monitor.h" #include "plc_interface.h" #include <string.h> #include "monitor.h" #include <zmq.hpp> #include <value.h> #include <MessageEncoding.h> #include <MessagingInterface.h> #include "cJSON.h" #include "MessagingInterface.h" #include "SocketMonitor.h" #include "ConnectionManager.h" #include "symboltable.h" #include <fstream> #include <libgen.h> #include <sys/time.h> #include <Logger.h> #include "options.h" bool iod_connected = false; bool update_status = true; //const char *program_name; /* void getTimeString(char *buf, size_t buf_size) { struct timeval now_tv; gettimeofday(&now_tv,0); struct tm now_tm; localtime_r(&now_tv.tv_sec, &now_tm); uint32_t msec = now_tv.tv_usec / 1000L; snprintf(buf, 50,"%04d-%02d-%02d %02d:%02d:%02d.%03d ", now_tm.tm_year+1900, now_tm.tm_mon+1, now_tm.tm_mday, now_tm.tm_hour, now_tm.tm_min, now_tm.tm_sec, msec); } */ struct UserData { }; Options options; /* Clockwork interface */ void sendMessage(zmq::socket_t &socket, const char *message) { safeSend(socket, message, strlen(message)); } std::list<Value> params; char *send_command(zmq::socket_t &sock, std::list<Value> &params) { if (params.size() == 0) return 0; Value cmd_val = params.front(); params.pop_front(); std::string cmd = cmd_val.asString(); char *msg = MessageEncoding::encodeCommand(cmd, &params); if (options.verbose) std::cerr << " sending: " << msg << "\n"; sendMessage(sock, msg); size_t size = strlen(msg); free(msg); zmq::message_t reply; if (sock.recv(&reply)) { size = reply.size(); char *data = (char *)malloc(size+1); memcpy(data, reply.data(), size); data[size] = 0; return data; } return 0; } void process_command(zmq::socket_t &sock, std::list<Value> &params) { char * data = send_command(sock, params); if (data) { if (options.verbose) std::cerr << data << "\n"; free(data); } } void sendStatus(const char *s) { zmq::socket_t sock(*MessagingInterface::getContext(), ZMQ_REQ); sock.connect("tcp://localhost:5555"); {FileLogger fl(program_name); fl.f() << "reporting status " << s << "\n"; } if (options.status_machine.length()) { std::list<Value>cmd; cmd.push_back("PROPERTY"); cmd.push_back(options.status_machine.c_str()); cmd.push_back(options.status_property.c_str()); cmd.push_back(s); process_command(sock, cmd); } else {FileLogger fl(program_name); fl.f() << "no status machine" << "\n"; } } /* #if 0 class ClockworkClientThread { public: ClockworkClientThread(): finished(false) { int linger = 0; // do not wait at socket close time socket = new zmq::socket_t(*MessagingInterface::getContext(), ZMQ_REQ); socket->setsockopt(ZMQ_LINGER, &linger, sizeof(linger)); psocket = socket; socket->connect("tcp://localhost:5555"); } void operator()() { while (!finished) { usleep(500000); } } zmq::socket_t *socket; bool finished; }; */ std::map<int, UserData *> active_addresses; std::map<int, UserData *> ro_bits; std::map<int, UserData *> inputs; //std::map<int, UserData *> registers; void sendStateUpdate(zmq::socket_t *sock, ModbusMonitor *mm, bool which) { std::list<Value> cmd; cmd.push_back("SET"); cmd.push_back(mm->name().c_str()); cmd.push_back("TO"); if (which) cmd.push_back("on"); else cmd.push_back("off"); process_command(*sock, cmd); } void sendPropertyUpdate(zmq::socket_t *sock, ModbusMonitor *mm) { std::list<Value> cmd; long value = 0; cmd.push_back("PROPERTY"); char buf[100]; snprintf(buf, 100, "%s", mm->name().c_str()); char *p = strrchr(buf, '.'); if (p) { *p++ = 0; cmd.push_back(buf); cmd.push_back(p); } else { cmd.push_back(buf); cmd.push_back("VALUE"); } // note: the monitor address is in the global range grp<<16 + offset // this method is only using the addresses in the local range //mm->set(buffer_addr + ( (mm->address() & 0xffff)) ); if (mm->length() == 1 && mm->format() == "SignedInt") { value = *( (int16_t*)mm->value->getWordData() ); cmd.push_back( value ); } else if (mm->length() == 1) { value = *( (uint16_t*)mm->value->getWordData() ); cmd.push_back( value ); } else if (mm->length() == 2 && mm->format() == "Float") { uint16_t *xx = (uint16_t*)mm->value->getWordData(); Value vv(*((float*)xx)); cmd.push_back( *( (float*)xx )); } else if (mm->length() == 2 && mm->format() == "SignedInt") { uint16_t modbus_value[2]; modbus_value[0] = (mm->value->getWordData())[0]; modbus_value[1] = (mm->value->getWordData())[1]; value = MODBUS_GET_INT32_FROM_INT16(modbus_value, 0); cmd.push_back( (int32_t)value ); } else if (mm->length() == 2) { uint16_t modbus_value[2]; modbus_value[0] = (mm->value->getWordData())[0]; modbus_value[1] = (mm->value->getWordData())[1]; value = MODBUS_GET_INT32_FROM_INT16(modbus_value, 0); cmd.push_back( (uint32_t)value ); } else { cmd.push_back(0); // TBD } process_command(*sock, cmd); } void displayChanges(zmq::socket_t *sock, std::set<ModbusMonitor*> &changes, uint8_t *buffer_addr) { if (changes.size()) { if (options.verbose) std::cerr << changes.size() << " changes\n"; std::set<ModbusMonitor*>::iterator iter = changes.begin(); while (iter != changes.end()) { ModbusMonitor *mm = *iter++; // note: the monitor address is in the global range grp<<16 + offset // this method is only using the addresses in the local range uint8_t *val = buffer_addr + ( (mm->address() & 0xffff)); if (options.verbose) std::cerr << mm->name() << " "; mm->set( val, options.verbose ); if (sock && (mm->group() == 0 || mm->group() == 1) && mm->length()==1) { sendStateUpdate(sock, mm, (bool)*val); } } } } void displayChanges(zmq::socket_t *sock, std::set<ModbusMonitor*> &changes, uint16_t *buffer_addr) { if (changes.size()) { if (options.verbose) std::cerr << changes.size() << " changes\n"; std::set<ModbusMonitor*>::iterator iter = changes.begin(); while (iter != changes.end()) { ModbusMonitor *mm = *iter++; uint16_t *val = buffer_addr + ( (mm->address() & 0xffff)) ; if (options.verbose) std::cerr << mm->name() << " "; mm->set( val, options.verbose ); if (mm->readOnly() && sock) { // INPUTREGISTER sendPropertyUpdate(sock, mm); } } } } #include "modbus_client_thread.cpp" ModbusClientThread *mb = 0; class SetupDisconnectMonitor : public EventResponder { public: void operator()(const zmq_event_t &event_, const char* addr_) { iod_connected = false; exit(0); } }; static bool need_refresh = false; class SetupConnectMonitor : public EventResponder { public: void operator()(const zmq_event_t &event_, const char* addr_) { iod_connected = true; need_refresh = true; } }; void loadRemoteConfiguration(zmq::socket_t &iod, std::string &chn_instance_name, PLCInterface &plc, MonitorConfiguration &mc) { std::list<Value>cmd; cmd.push_back("REFRESH"); cmd.push_back(chn_instance_name.c_str()); cJSON *obj = nullptr; { char *response = send_command(iod, cmd); if (options.verbose) std::cerr << response << "\n"; obj = cJSON_Parse(response); free(response); } if (obj) { iod_connected = true; if (obj->type != cJSON_Array) { std::cerr << "error. clock response is not an array"; char *item = cJSON_Print(obj); std::cerr << item << "\n"; free(item); } cJSON *item = obj->child; while (item) { cJSON *name_js = cJSON_GetObjectItem(item, "name"); cJSON *addr_js = cJSON_GetObjectItem(item, "address"); cJSON *length_js = cJSON_GetObjectItem(item, "length"); cJSON *type_js = cJSON_GetObjectItem(item, "type"); cJSON *format_js = cJSON_GetObjectItem(item, "format"); std::string name; if (name_js && name_js->type == cJSON_String) { name = name_js->valuestring; } int length = length_js->valueint; std::string type; if (type_js && type_js->type == cJSON_String) { type = type_js->valuestring; } int group = 1; bool readonly = true; if (type == "INPUTBIT") group = 1; else if (type == "OUTPUTBIT") { group = 0; readonly = false; } else if (type == "INPUTREGISTER") group = 3; else if (type == "OUTPUTREGISTER") { group = 4; readonly = false; } std::string format; if (format_js && type_js->type == cJSON_String) { format = format_js->valuestring; } else if (group == 1 || group == 0) format = "BIT"; else if (group == 3 || group == 4) format = "SignedInt"; else format = "WORD"; int addr = 0; std::string addr_str; if (addr_js && addr_js->type == cJSON_String) { addr_str = addr_js->valuestring; std::pair<int, int> plc_addr = plc.decode(addr_str.c_str()); if (plc_addr.first >= 0) group = plc_addr.first; if (plc_addr.second >= 0) addr = plc_addr.second; } ModbusMonitor *mm = new ModbusMonitor(name, group, addr, length, format, readonly); mc.monitors.insert(std::make_pair(name, *mm) ); mm->add(); item = item->next; } cJSON_Delete(obj); } } void setupMonitoring(MonitorConfiguration &mc) { std::map<std::string, ModbusMonitor>::const_iterator iter = mc.monitors.begin(); while (iter != mc.monitors.end()) { const std::pair<std::string, ModbusMonitor> &item = *iter++; if (item.second.group() == 0) { for (unsigned int i=0; i<item.second.length(); ++i) { if (options.verbose) std::cerr << "monitoring: " << item.second.group() << ":" << (item.second.address()+i) <<" " << item.second.name() << "\n"; active_addresses[item.second.address()+i] = 0; } } else if (item.second.group() == 1) { for (unsigned int i=0; i<item.second.length(); ++i) { if (options.verbose) std::cerr << "monitoring: " << item.second.group() << ":" << (item.second.address()+i) <<" " << item.second.name() << "\n"; ro_bits[item.second.address()+i] = 0; } } else if (item.second.group() >= 3) { for (unsigned int i=0; i<item.second.length(); ++i) { if (options.verbose) std::cerr << "monitoring: " << item.second.group() << ":" << (item.second.address()+i) <<" " << item.second.name() << "\n"; inputs[item.second.address()+i] = 0; } } } } size_t parseIncomingMessage(const char *data, std::vector<Value> &params) // fillin params { size_t count =0; std::list<Value> parts; std::string ds; std::list<Value> *param_list = 0; if (MessageEncoding::getCommand(data, ds, &param_list)) { params.push_back(ds); if (param_list) { std::list<Value>::const_iterator iter = param_list->begin(); while (iter != param_list->end()) { const Value &v = *iter++; params.push_back(v); } } count = params.size(); delete param_list; } else { std::istringstream iss(data); while (iss >> ds) { if (options.verbose) std::cerr << ds << "\n"; parts.push_back(ds.c_str()); ++count; } std::copy(parts.begin(), parts.end(), std::back_inserter(params)); } return count; } using namespace std; int main(int argc, const char *argv[]) { program_name = strdup(basename((char*)argv[0])); zmq::context_t context; MessagingInterface::setContext(&context); std::cerr << "Modbus version (compile time): " << LIBMODBUS_VERSION_STRING << " "; std::cerr << "(linked): " << libmodbus_version_major << "." << libmodbus_version_minor << "." << libmodbus_version_micro << "\n"; if (!options.parseArgs(argc, argv)) { options.usage(program_name); } const ModbusSettings *ms = options.settings(); if (!ms) { exit(1); } PLCInterface plc; if (!plc.load("modbus_addressing.conf")) { std::cerr << "Failed to load plc mapping configuration\n"; exit(1); } {FileLogger fl(program_name); fl.f() << "----- starting -----\n"; } std::string chn_instance_name; MonitorConfiguration mc; if (options.configFileName()) { if (!mc.load(options.configFileName())) { cerr << "Failed to load modbus mappings to be monitored\n"; exit(1); } } else { int linger = 0; // do not wait at socket close time zmq::socket_t iod(*MessagingInterface::getContext(), ZMQ_REQ); iod.setsockopt(ZMQ_LINGER, &linger, sizeof(linger)); iod.connect("tcp://localhost:5555"); std::list<Value>cmd; cmd.push_back("CHANNEL"); cmd.push_back(options.channelName()); cJSON *obj = nullptr; { char *response = send_command(iod, cmd); if ( !response ) { FileLogger fl(program_name); fl.f() << "null response to channel request. exiting\n"; sleep(2); exit(1); } else if (!*response) { FileLogger fl(program_name); fl.f() << "empty response to channel request. exiting\n"; sleep(2); exit(2); } if (options.verbose) std::cerr << response << "\n"; obj = cJSON_Parse(response); free(response); } if (obj) { cJSON *name_js = cJSON_GetObjectItem(obj, "name"); if (name_js) { chn_instance_name = name_js->valuestring; } else { char *resp_str = cJSON_PrintUnformatted(obj); std::cerr << "configuration error, expected to find a field 'name' in " << resp_str << "\n"; free(resp_str); } cJSON_Delete(obj); obj = 0; if (!name_js) { exit(3); } } else { } if (options.verbose) std::cerr << chn_instance_name << "\n"; sendStatus("initialising"); update_status = true; loadRemoteConfiguration(iod, chn_instance_name, plc, mc); } if (options.simulatorName()) { mc.createSimulator(options.simulatorName()); exit(0); } setupMonitoring(mc); if (options.configFileName()) { // standalone execution ModbusClientThread modbus_interface(*ms, mc); mb = &modbus_interface; boost::thread monitor_modbus(boost::ref(modbus_interface)); while (true) { usleep(100000); } exit(0); } // running along with clockwork // the local command channel accepts commands from the modbus thread and relays them to iod. const char *local_commands = "inproc://local_cmds"; zmq::socket_t iosh_cmd(*MessagingInterface::getContext(), ZMQ_REP); iosh_cmd.bind(local_commands); SubscriptionManager subscription_manager(chn_instance_name.c_str(), eCLOCKWORK, "localhost", 5555); SetupDisconnectMonitor disconnect_responder; SetupConnectMonitor connect_responder; subscription_manager.monit_setup->addResponder(ZMQ_EVENT_DISCONNECTED, &disconnect_responder); subscription_manager.monit_setup->addResponder(ZMQ_EVENT_CONNECTED, &connect_responder); subscription_manager.setupConnections(); ModbusClientThread modbus_interface(*ms, mc, local_commands); mb = &modbus_interface; boost::thread monitor_modbus(boost::ref(modbus_interface)); enum ProgramState { s_initialising, s_running, // polling for io changes from clockwork s_finished,// about to exit } program_state = s_initialising; int exception_count = 0; int error_count = 0; while (program_state != s_finished) { zmq::pollitem_t items[] = { { subscription_manager.setup(), 0, ZMQ_POLLIN, 0 }, { subscription_manager.subscriber(), 0, ZMQ_POLLIN, 0 }, { iosh_cmd, 0, ZMQ_POLLIN, 0 } }; try { if (!subscription_manager.checkConnections(items, 3, iosh_cmd)) { if (options.verbose) std::cerr << "no connection to iod\n"; usleep(1000000); exception_count = 0; continue; } exception_count = 0; } catch (std::exception ex) { std::cerr << "polling connections: " << ex.what() << "\n"; {FileLogger fl(program_name); fl.f() << "exception when polling connections " << ex.what()<< "\n"; } if (++exception_count <= 5 && program_state != s_finished) { usleep(400000); continue; } exit(0); } if ( !(items[1].revents & ZMQ_POLLIN) ) { usleep(50); continue; } zmq::message_t update; if (!subscription_manager.subscriber().recv(&update, ZMQ_DONTWAIT)) { if (errno == EAGAIN) { usleep(50); continue; } if (errno == EFSM) exit(1); if (errno == ENOTSOCK) exit(1); std::cerr << "subscriber recv: " << zmq_strerror(zmq_errno()) << "\n"; if (++error_count > 5) exit(1); continue; } error_count = 0; long len = update.size(); char *data = (char *)malloc(len+1); memcpy(data, update.data(), len); data[len] = 0; std::cerr << "received: " << data << " (len == " <<len << " from clockwork\n"; std::vector<Value> params(0); parseIncomingMessage(data, params); free(data); data = 0; std::string cmd = "Unknown"; if (params.size() > 0) { cmd = params[0].asString(); } else { std::cerr << "unexpected data received\n"; } if (cmd == "STATE") { try { ModbusMonitor &m = mc.monitors.at(params[1].asString()); if (options.verbose) std::cerr << m.name() << " " << ( (m.readOnly()) ? "READONLY" : "" ) << "\n"; if (!m.readOnly()) { if (params[2].asString() == "on") mb->requestUpdate(m.address(), true); else mb->requestUpdate(m.address(), false); } //sendStateUpdate(&iosh_cmd, &m, *(m.value->getWordData()) ); } catch (std::exception ex) { std::cerr << "Exception when processing STATE command: " << ex.what() << "\n"; } } else if (cmd == "PROPERTY" && params.size() >= 4) { try { std::map<std::string, ModbusMonitor>::iterator found = mc.monitors.find(params[1].asString()); if (found == mc.monitors.end()) { std::cerr << "Error: not monitoring property " << params[1] << "\n"; continue; } ModbusMonitor &m = (*found).second; //mc.monitors.at(params[0].asString()); if (options.verbose) std::cerr << m.name() << " " << ( (m.readOnly()) ? "READONLY" : "" ) << "\n"; if (!m.readOnly() && m.group() == 4) { if (options.verbose) std::cerr << "setting " << m.name() << " (" << m.format() << ")\n"; if (params[2].asString() == "VALUE") { if (m.format() == "Float") { double dval; if (params[3].asFloat(dval)) { uint16_t value[2]; float fval = dval; if (options.verbose) std::cerr << "setting float value " << fval << " for address" << std::hex << "0x" << m.address() << std::dec << "\n"; modbus_set_float_badc(fval, value); if (m.length() == 2) { m.setRaw(value, 2); mb->requestRegisterUpdates(m.address(), value, 2); } else { std::cerr << "Error: cannot set float value for " << params[1] << " into a field of length " << m.length() << "\n"; } } else { std::cerr << "Error: could not convert '" << params[3] << "' to a float\n"; } } else { long value; if (params[2].asString() == "VALUE" && params[3].asInteger(value)) { if (m.length() == 1) { m.setRaw( (uint16_t) value); mb->requestRegisterUpdate(m.address(), (uint16_t)value); } else if (m.length() == 2) { uint16_t modbus_value[2]; MODBUS_SET_INT32_TO_INT16(modbus_value, 0, (uint32_t)(value & 0xffffffff)); m.setRaw( modbus_value ,2 ); mb->requestRegisterUpdates(m.address(), (uint16_t*)&modbus_value, 2); } } } } } //sendPropertyUpdate(&iosh_cmd, &m); // dont' send the property value back } catch (std::exception ex) { std::cerr << "Exception when processing PROPERTY command: " << ex.what() << "\n"; } } } }
gpl-2.0
evilsephiroth/plugin.program.hyperspin
resources/lib/hyperspin_plugin.py
2315
""" Plugin for Launching HyperSpin """ import sys import os import fnmatch import xbmc import xbmcgui import xbmcplugin import xbmcaddon import time import re import urllib import subprocess_hack import xml.dom.minidom import socket import exceptions import random from traceback import print_exc import shutil from xbmcaddon import Addon class Main: def __init__( self ): addon = xbmcaddon.Addon() icon = addon.getAddonInfo('icon') language = addon.getLocalizedString path = addon.getSetting('hyperspinexe') if path == "": xbmc.executebuiltin("XBMC.Notification(%s,%s,10000,%s)"%(language(30003), language(30002), icon)) addon.openSettings() path = addon.getSetting('hyperspinexe') if path == "": return path2 = addon.getSetting('hyperspinfolder') if path2 == "": xbmc.executebuiltin("XBMC.Notification(%s,%s,10000,%s)"%(language(30003), language(30002), icon)) addon.openSettings() path2 = addon.getSetting('hyperspinfolder') if path2 == "": return if ( xbmc.Player().isPlaying() ): xbmc.executebuiltin('PlayerControl(Play)') xbmc.sleep(400) info = None ap = path arguments = "-quick" apppath = path2 startproc = subprocess_hack.Popen(r'%s %s' % (ap, arguments), cwd=apppath, startupinfo=info) startproc.wait() xbmc.sleep(200) systemLabel = xbmc.getInfoLabel("System.BuildVersion") majorVersion = int(systemLabel[:2]) if(majorVersion > 13): ap = xbmc.translatePath("special://xbmc") + "\\xbmc.exe" else: ap = xbmc.translatePath("special://xbmc") + "\\kodi.exe" arguments = "" apppath = xbmc.translatePath("special://xbmc") startproc = subprocess_hack.Popen(r'%s %s' % (ap, arguments), cwd=apppath, startupinfo=info) # startproc.wait() xbmc.sleep(200) xbmc.executebuiltin('PlayerControl(Play)') xbmc.sleep(400) xbmc.executebuiltin('ActivateWindow(home)')
gpl-2.0
overplumbum/pgfouine
tests/simpletest/test/shell_tester_test.php
1360
<?php // $Id: shell_tester_test.php,v 1.1 2005/11/09 23:41:18 gsmet Exp $ Mock::generate('SimpleShell'); class TestOfShellTestCase extends ShellTestCase { var $_mock_shell = false; function &_getShell() { return $this->_mock_shell; } function testExitCode() { $this->_mock_shell = &new MockSimpleShell($this); $this->_mock_shell->setReturnValue('execute', 0); $this->_mock_shell->expectOnce('execute', array('ls')); $this->assertTrue($this->execute('ls')); $this->assertExitCode(0); $this->_mock_shell->tally(); } function testOutput() { $this->_mock_shell = &new MockSimpleShell($this); $this->_mock_shell->setReturnValue('execute', 0); $this->_mock_shell->setReturnValue('getOutput', "Line 1\nLine 2\n"); $this->assertOutput("Line 1\nLine 2\n"); } function testOutputPatterns() { $this->_mock_shell = &new MockSimpleShell($this); $this->_mock_shell->setReturnValue('execute', 0); $this->_mock_shell->setReturnValue('getOutput', "Line 1\nLine 2\n"); $this->assertOutputPattern('/line/i'); $this->assertNoOutputPattern('/line 2/'); } } ?>
gpl-2.0
merego/scrippa
C++/NRinC302/legacy/nr2/CPP_211/examples/xstifbs.cpp
1090
#include <iostream> #include <iomanip> #include "nr.h" using namespace std; // Driver for routine stifbs int kmax,kount; // defining declarations DP dxsav; Vec_DP *xp_p; Mat_DP *yp_p; int main(void) { int nbad,nok; DP eps,hstart,x1=0.0,x2=50.0; Vec_DP y(3); cout << fixed << setprecision(6); for (;;) { cout << endl << "Enter eps,hstart (or eps=0 to end)" << endl; cin >> eps >> hstart; if (eps == 0.0) break; kmax=0; y[0]=y[1]=1.0; y[2]=0.0; NR::odeint(y,x1,x2,eps,hstart,0.0,nok,nbad,NR::derivs_s,NR::stifbs); cout << fixed << setprecision(6); cout << endl << "successful steps:" << setw(14) << " "; cout << setw(4) << nok << endl; cout << "bad steps:" << setw(21) << " " << setw(4) << nbad << endl; cout << "y(end) = " << setw(12) << y[0] << setw(12) << y[1]; cout << setw(12) << y[2] << endl; } cout << "Normal completion" << endl; return 0; }
gpl-2.0
carlosway89/testshop
user_classes/overloads/_samples/AdminApplicationBottomExtenderComponent/SampleExtender.inc.php
678
<?php /* -------------------------------------------------------------- SampleExtender.inc.php 2014-01-01 gm Gambio GmbH http://www.gambio.de Copyright (c) 2014 Gambio GmbH Released under the GNU General Public License (Version 2) [http://www.gnu.org/licenses/gpl-2.0.html] -------------------------------------------------------------- */ class SampleExtender extends SampleExtender_parent { function proceed() { parent::proceed(); // PHP Code // {...} // HTML Output echo '<div style="background: #fff; margin: 0 auto 20px auto; width: 1000px; line-height: 50px; text-align: center;">Gambio ApplicationBottomExtenderComponent</div>'; } }
gpl-2.0
taconaut/ums-mlx
core/src/main/java/net/pms/formats/RAW.java
3225
package net.pms.formats; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.List; import net.coobird.thumbnailator.Thumbnails; import net.pms.PMS; import net.pms.configuration.PmsConfiguration; import net.pms.configuration.RendererConfiguration; import net.pms.dlna.DLNAMediaInfo; import net.pms.dlna.InputFile; import net.pms.encoders.RAWThumbnailer; import net.pms.io.OutputParams; import net.pms.io.ProcessWrapperImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RAW extends JPG { private static final Logger LOGGER = LoggerFactory.getLogger(RAW.class); /** * {@inheritDoc} */ @Override public Identifier getIdentifier() { return Identifier.RAW; } /** * {@inheritDoc} */ @Override public String[] getSupportedExtensions() { return new String[] { "3fr", "ari", "arw", "bay", "cap", "cr2", "crw", "dcr", "dcs", "dng", "drf", "eip", "erf", "fff", "iiq", "k25", "kdc", "mdc", "mef", "mos", "mrw", "nef", "nrw", "obm", "orf", "pef", "ptx", "pxn", "r3d", "raf", "raw", "rw2", "rwl", "rwz", "sr2", "srf", "srw", "x3f" }; } @Override public boolean transcodable() { return true; } @Override public void parse(DLNAMediaInfo media, InputFile file, int type, RendererConfiguration renderer) { PmsConfiguration configuration = PMS.getConfiguration(renderer); try { OutputParams params = new OutputParams(configuration); params.waitbeforestart = 1; params.minBufferSize = 1; params.maxBufferSize = 6; params.hidebuffer = true; String cmdArray[] = new String[4]; cmdArray[0] = configuration.getDCRawPath(); cmdArray[1] = "-i"; cmdArray[2] = "-v"; if (file.getFile() != null) { cmdArray[3] = file.getFile().getAbsolutePath(); } params.log = true; ProcessWrapperImpl pw = new ProcessWrapperImpl(cmdArray, params, true, false); pw.runInSameThread(); List<String> list = pw.getOtherResults(); for (String s : list) { if (s.startsWith("Thumb size: ")) { String sz = s.substring(13); media.setWidth(Integer.parseInt(sz.substring(0, sz.indexOf('x')).trim())); media.setHeight(Integer.parseInt(sz.substring(sz.indexOf('x') + 1).trim())); break; } } if (media.getWidth() > 0) { byte[] image = RAWThumbnailer.getThumbnail(params, file.getFile().getAbsolutePath()); media.setSize(image.length); // XXX why the image size is set to thumbnail size and the codecV and container is set to RAW when thumbnail is in the JPEG format media.setCodecV("raw"); media.setContainer("raw"); if (configuration.getImageThumbnailsEnabled()) { // Resize the thumbnail image using the Thumbnailator library ByteArrayOutputStream out = new ByteArrayOutputStream(); Thumbnails.of(new ByteArrayInputStream(image)) .size(320, 180) .outputFormat("JPEG") .outputQuality(1.0f) .toOutputStream(out); media.setThumb(out.toByteArray()); } } media.finalize(type, file); media.setMediaparsed(true); } catch (Exception e) { LOGGER.debug("Caught exception", e); } } }
gpl-2.0
julianangel/EmotionBot
ROS/theatrebot_action_modulation/src/platform_action_execution/AbstractPlatformExecution.cpp
338
/* * AbstractPlatformExecution.cpp * * Created on: Jul 8, 2014 * Author: julian */ #include "AbstractPlatformExecution.h" AbstractPlatformExecution::AbstractPlatformExecution() { // TODO Auto-generated constructor stub } AbstractPlatformExecution::~AbstractPlatformExecution() { // TODO Auto-generated destructor stub }
gpl-2.0
rakeybulhasan/IAPP
wp-content/themes/centum/map-meta-box.php
6072
<?php /** * Adds a box to the main column on the Post and Page edit screens. */ function map_marker_add_custom_box() { $screens = array( 'post', 'page' ); foreach ( $screens as $screen ) { add_meta_box( 'map_marker_metabox', __( 'Map Options' ), 'map_marker_inner_section', $screen ); } } add_action( 'add_meta_boxes', 'map_marker_add_custom_box' ); /** * Prints the box content. * * @param WP_Post $post The object for the current post/page. */ function map_marker_inner_section( $post ) { // Add an nonce field so we can check for it later. wp_nonce_field( 'map_marker_inner_section', 'map_marker_inner_section_nonce' ); /* * Use get_post_meta() to retrieve an existing value * from the database and use the value for the form. */ $data = json_decode(get_post_meta( $post->ID, '_map_config', true ), true); $showMap = $data[ 'mapShow' ]; $type = $data[ 'type' ]; $layerId = $data[ 'layerId' ]; $markerId = $data[ 'markerId' ]; $layers = getLayersList(); $markers = getMarkersList(); ?> <p> <label for="map_marker_show"><?php _e( 'Show map in sidebar?' ); ?></label> <select id="map_marker_show" name="map_marker_show"> <option value="no"<?php if($showMap == 'no') echo 'selected="selected"' ?>>No</option> <option value="yes"<?php if($showMap == 'yes') echo 'selected="selected"' ?>>Yes</option> </select> </p> <div id="map_marker_option_container" style="display: none"> <p> <label for="map_marker_type"><?php _e( 'Type:' ); ?></label> <select id="map_marker_type" name="map_marker_type"> <option value="layer"<?php if($type == 'layer') echo 'selected="selected"' ?>>Layer</option> <option value="marker"<?php if($type == 'marker') echo 'selected="selected"' ?>>Marker</option> </select> </p> <p id="layer_list"> <label for="map_marker_layer_id"><?php _e( 'Layer:' ); ?></label> <select id="map_marker_layer_id" name="map_marker_layer_id"> <?php foreach ($layers as $id => $name) { $selected = ($layerId == $id) ? 'selected="selected"' : '' ?> <option value="<?php echo $id?>" <?php echo $selected ?>><?php echo $name?></option> <?php } ?> </select> </p> <p id="marker_list"> <label for="map_marker_marker_id"><?php _e( 'Marker:' ); ?></label> <select id="map_marker_marker_id" name="map_marker_marker_id"> <?php foreach ($markers as $id => $name) { $selected = ($markerId == $id) ? 'selected="selected"' : '' ?> <option value="<?php echo $id?>" <?php echo $selected ?>><?php echo $name?></option> <?php } ?> </select> </p> </div> <script> jQuery(document).ready(function(){ jQuery('#map_marker_show').change(function(){ if (jQuery(this).val() == 'no') { jQuery('#map_marker_option_container').hide(); } else { jQuery('#map_marker_option_container').slideDown(); } }).trigger('change'); jQuery('#map_marker_type').change(function(){ if (jQuery(this).val() == 'layer') { jQuery('#layer_list').show(); jQuery('#marker_list').hide(); } else { jQuery('#layer_list').hide(); jQuery('#marker_list').show(); } }).trigger('change'); }); </script> <?php } /** * When the post is saved, saves our custom data. * * @param int $post_id The ID of the post being saved. */ function map_marker_save_postdata( $post_id ) { /* * We need to verify this came from the our screen and with proper authorization, * because save_post can be triggered at other times. */ // Check if our nonce is set. if ( ! isset( $_POST['map_marker_inner_section_nonce'] ) ) return $post_id; $nonce = $_POST['map_marker_inner_section_nonce']; // Verify that the nonce is valid. if ( ! wp_verify_nonce( $nonce, 'map_marker_inner_section' ) ) return $post_id; // If this is an autosave, our form has not been submitted, so we don't want to do anything. if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return $post_id; // Check the user's permissions. if ( 'page' == $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_id ) ) return $post_id; } else { if ( ! current_user_can( 'edit_post', $post_id ) ) return $post_id; } /* OK, its safe for us to save the data now. */ // Sanitize user input. $data = json_encode(array( 'mapShow' => sanitize_text_field( $_POST['map_marker_show'] ), 'type' => sanitize_text_field( $_POST['map_marker_type'] ), 'layerId' => sanitize_text_field( $_POST['map_marker_layer_id'] ), 'markerId' => sanitize_text_field( $_POST['map_marker_marker_id'] ), )); // Update the meta field in the database. update_post_meta( $post_id, '_map_config', $data ); } add_action( 'save_post', 'map_marker_save_postdata' ); function getLayersList() { global $wpdb; $sql = "SELECT * FROM wp_leafletmapsmarker_layers WHERE id > 0"; $result = $wpdb->get_results($sql); $layers = array(); foreach ($result as $row) { $layers[$row->id] = $row->name; } return $layers; } function getMarkersList() { global $wpdb; $sql = "SELECT * FROM wp_leafletmapsmarker_markers"; $result = $wpdb->get_results($sql); $markers = array(); foreach ($result as $row) { $markers[$row->id] = $row->markername; } return $markers; } function getLayerShortCode($layerId) { return '[mapsmarker layer="'.$layerId.'"]'; } function getMarkerLayerCode($markerId) { return '[mapsmarker marker="'.$markerId.'"]'; }
gpl-2.0
killermonkey/softgym
src/Forms/IN_Pago_Cliente.java
10224
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Forms; import Utilidades.usadb; import Utilidades.VerticalLabelUI; import Utilidades.SoftGym; import java.awt.Color; import java.util.Date; import javax.swing.JOptionPane; /** * * @author LeticiaRojas */ public class IN_Pago_Cliente extends javax.swing.JInternalFrame { /** * Creates new form PagoClient */ public IN_Pago_Cliente() { initComponents(); jLabel3.setUI(new VerticalLabelUI(false)); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel2 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jDateChooser1 = new com.toedter.calendar.JDateChooser(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jButton2 = new javax.swing.JButton(); jTextField1 = new javax.swing.JTextField(); setClosable(true); setIconifiable(true); setTitle("Mensualidad"); jPanel2.setBackground(SoftGym.fondo); jLabel3.setFont(new java.awt.Font("Agency FB", 1, 24)); // NOI18N jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel3.setText("Pago del cliente"); jLabel3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jPanel1.setBackground(new Color(0,0,0,50)); jButton1.setFont(new java.awt.Font("Agency FB", 0, 18)); // NOI18N jButton1.setText("Aceptar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jDateChooser1.setFont(new java.awt.Font("Agency FB", 0, 14)); // NOI18N jLabel1.setFont(new java.awt.Font("Agency FB", 0, 18)); // NOI18N jLabel1.setText("Proxima fecha corte:"); jLabel2.setFont(new java.awt.Font("Agency FB", 0, 18)); // NOI18N jLabel2.setText("Monto:"); jButton2.setFont(new java.awt.Font("Agency FB", 0, 18)); // NOI18N jButton2.setText("Cancelar"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jDateChooser1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTextField1)))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 33, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jDateChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: usadb db = new usadb(); if (SoftGym.prin.IDCliente != -1) { db.in_ingreso(new Date(), "Mensualidad", "Pago Cliente " + SoftGym.prin.jTextField1.getText(), Double.parseDouble(jTextField1.getText()), SoftGym.nombre);//******* int ultimoingreso = db.ObtenerUltimoIngreso(); db.in_historialClientes(ultimoingreso, SoftGym.prin.IDCliente);//Falta obtener el idcliente db.actualizar("FechaCorte_Clientes", new Object[]{SoftGym.prin.IDCliente, jDateChooser1.getDate()});//Falta obtener el idcliente dispose(); SoftGym.prin.BusquedaCompleta(SoftGym.prin.IDCliente); } else { JOptionPane.showMessageDialog(this, "Se debe loguear un cliente primero"); } }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: dispose(); }//GEN-LAST:event_jButton2ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private com.toedter.calendar.JDateChooser jDateChooser1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables }
gpl-2.0
descent/tvision
examples/tutorial/tvguid16.cc
11567
/*---------------------------------------------------------*/ /* */ /* Turbo Vision 1.0 */ /* TVGUID16 Demo Source File */ /* Copyright (c) 1991 by Borland International */ /* */ /*---------------------------------------------------------*/ /* * Modified by Sergio Sigala <ssigala@globalnet.it> */ /* Taked from the Sergio Sigala <ssigala@globalnet.it> Turbo Vision port to UNIX. LSM: TurboVision for UNIX ftp://sunsite.unc.edu /pub/Linux/devel/lang/c++/tvision-0.6.tar.gz Copying policy: BSD Adapted by Salvador Eduardo Tropea (SET) <set-soft@usa.net>. See how setData/getData transfer information to/from a structure to the objects inserted in the dialog. */ // same as tvguid15 except for saving and restoring dialog contents // modify TMyApp::newDialog #define Uses_stdlib // for exit(), rand() #define Uses_iostream #define Uses_fstream #define Uses_stdio // for puts() etc #define Uses_string // for strlen etc #define Uses_ctype #define Uses_IfStreamGetLine #define Uses_TEventQueue #define Uses_TEvent #define Uses_TProgram #define Uses_TApplication #define Uses_TKeys #define Uses_TRect #define Uses_TMenuBar #define Uses_TSubMenu #define Uses_TMenuItem #define Uses_TStatusLine #define Uses_TStatusItem #define Uses_TStatusDef #define Uses_TDeskTop #define Uses_TView #define Uses_TWindow #define Uses_TFrame #define Uses_TScroller #define Uses_TScrollBar #define Uses_TDialog #define Uses_TButton #define Uses_TSItem #define Uses_TCheckBoxes #define Uses_TRadioButtons #define Uses_TLabel #define Uses_TInputLine #define Uses_TRangeValidator #define Uses_MsgBox #include <tv.h> UsingNamespaceStd const int cmMyFileOpen = 200; // assign new command values const int cmMyNewWin = 201; const int cmNewDialog = 202; struct DialogData { ushort checkBoxData; ushort radioButtonData; char inputLineData[128]; char inputLineRangeData[34]; }; DialogData *demoDialogData; // we'll save dialog box data in above struct /* SS: micro change here */ const char *fileToRead = "tvguid16.cc"; //const char *fileToRead = "tvguid16.cpp"; const int maxLineLength = maxViewWidth+1; const int maxLines = 100; char *lines[maxLines]; int lineCount = 0; static short winNumber = 0; // initialize window number class TMyApp : public TApplication { public: TMyApp(); ~TMyApp(); static TStatusLine *initStatusLine( TRect r ); static TMenuBar *initMenuBar( TRect r ); virtual void handleEvent( TEvent& event); void newWindow(); void newDialog(); }; class TInterior : public TScroller { public: TInterior( const TRect& bounds, TScrollBar *aHScrollBar, TScrollBar *aVScrollBar ); // constructor virtual void draw(); // override TView::draw }; class TDemoWindow : public TWindow // define a new window class { public: TDemoWindow( const TRect& bounds, const char *aTitle, short aNumber ); TInterior *makeInterior( const TRect& r, Boolean left ); virtual void sizeLimits( TPoint& minP, TPoint& maxP ); // override TWindow::sizeLimits private: TInterior *lInterior, *rInterior; }; void readFile( const char *fileName ) { ifstream fileToView( fileName ); if( !fileToView ) { cout << "Invalid file name..." << endl; exit( 1 ); } else { char buf[maxLineLength]; while( lineCount < maxLines && IfStreamGetLine(fileToView,buf,maxLineLength) ) { lines[lineCount] = newStr( buf ); lineCount++; } } } void deleteFile() { for( int i = 0; i < lineCount; i++ ) delete lines[i]; } TInterior::TInterior( const TRect& bounds, TScrollBar *aHScrollBar, TScrollBar *aVScrollBar ) : TScroller( bounds, aHScrollBar, aVScrollBar ) { options = options | ofFramed; setLimit( maxLineLength, lineCount ); } void TInterior::draw() // modified for scroller { ushort color = getColor(0x0301); for( int i = 0; i < size.y; i++ ) // for each line: { TDrawBuffer b; b.moveChar( 0, ' ', color, size.x ); // fill line buffer with spaces int j = delta.y + i; // delta is scroller offset if( j < lineCount && lines[j] != 0 ) { char s[maxLineLength]; if( delta.x > (int)strlen(lines[j] ) ) s[0] = EOS; else { strncpy( s, lines[j]+delta.x, size.x ); s[size.x] = EOS; } b.moveCStr( 0, s, color ); } writeLine( 0, i, size.x, 1, b); } } // modified from tvguid08: TDemoWindow::TDemoWindow( const TRect& bounds, const char *aTitle, short aNumber) : TWindowInit( &TDemoWindow::initFrame ), TWindow( bounds, aTitle, aNumber) { TRect lbounds = getExtent(); TRect r( lbounds.a.x, lbounds.a.y, lbounds.b.x/2+1, lbounds.b.y ); lInterior = makeInterior( r, True ); lInterior->growMode = gfGrowHiY; insert( lInterior ); // creates left-side scrollable interior and inserts into window r = TRect( lbounds.b.x/2, lbounds.a.y, lbounds.b.x, lbounds.b.y ); rInterior = makeInterior( r, False ); rInterior->growMode = gfGrowHiX | gfGrowHiY; insert( rInterior ); // likewise for right-side scroller } TInterior *TDemoWindow::makeInterior( const TRect& bounds, Boolean left ) { TRect r = TRect( bounds.b.x-1, bounds.a.y+1, bounds.b.x, bounds.b.y-1 ); TScrollBar *vScrollBar = new TScrollBar( r ); if( vScrollBar == 0 ) { cout << "vScrollbar init error" << endl; exit(1); } // production code would display error dialog box vScrollBar->options |= ofPostProcess; if( left ) vScrollBar->growMode = gfGrowHiY; insert( vScrollBar ); r = TRect( bounds.a.x+2, bounds.b.y-1, bounds.b.x-2, bounds.b.y ); TScrollBar *hScrollBar = new TScrollBar( r ); if( hScrollBar == 0 ) { cout << "hScrollbar init error" << endl; exit(1); } hScrollBar->options |= ofPostProcess; if( left ) hScrollBar->growMode = (gfGrowHiY | gfGrowLoY); insert( hScrollBar ); r = bounds; r.grow( -1, -1 ); return new TInterior( r, hScrollBar, vScrollBar ); } void TDemoWindow::sizeLimits( TPoint& minP, TPoint& maxP ) { TWindow::sizeLimits( minP, maxP ); minP.x = lInterior->size.x+9; } TMyApp::TMyApp() : TProgInit( &TMyApp::initStatusLine, &TMyApp::initMenuBar, &TMyApp::initDeskTop ) { // new for tvguid16: set up initial dialog data demoDialogData = new DialogData; demoDialogData->checkBoxData = 1; demoDialogData->radioButtonData = 2; strcpy( demoDialogData->inputLineData, "Phone Mum!" ); sprintf( demoDialogData->inputLineRangeData, "%d", 16 ); } TMyApp::~TMyApp() { delete demoDialogData; } void TMyApp::handleEvent(TEvent& event) { TApplication::handleEvent(event); if( event.what == evCommand ) { switch( event.message.command ) { case cmMyNewWin: newWindow(); break; case cmNewDialog: newDialog(); break; default: return; } clearEvent( event ); // clear event after handling } } TMenuBar *TMyApp::initMenuBar( TRect r ) { r.b.y = r.a.y + 1; // set bottom line 1 line below top line return new TMenuBar( r, *new TSubMenu( "~F~ile", kbAltF )+ *new TMenuItem( "~O~pen", cmMyFileOpen, kbF3, hcNoContext, "F3" )+ *new TMenuItem( "~N~ew", cmMyNewWin, kbF4, hcNoContext, "F4" )+ newLine()+ *new TMenuItem( "E~x~it", cmQuit, cmQuit, hcNoContext, "Alt-X" )+ *new TSubMenu( "~W~indow", kbAltW )+ *new TMenuItem( "~N~ext", cmNext, kbF6, hcNoContext, "F6" )+ *new TMenuItem( "~Z~oom", cmZoom, kbF5, hcNoContext, "F5" )+ *new TMenuItem( "~D~ialog", cmNewDialog, kbF2, hcNoContext, "F2" ) // new dialog menu added here ); } TStatusLine *TMyApp::initStatusLine( TRect r ) { r.a.y = r.b.y - 1; // move top to 1 line above bottom return new TStatusLine( r, *new TStatusDef( 0, 0xFFFF ) + // set range of help contexts *new TStatusItem( 0, kbF10, cmMenu ) + // define an item *new TStatusItem( "~Alt-X~ Exit", kbAltX, cmQuit ) + // and another one *new TStatusItem( "~Alt-F3~ Close", kbAltF3, cmClose ) // and another one ); } void TMyApp::newWindow() { TRect r( 0, 0, 45, 13 ); // set initial size and position /* SS: micro change here */ r.move( rand() % 34, rand() % 11 ); // randomly move around screen TDemoWindow *window = new TDemoWindow ( r, "Demo Window", ++winNumber); deskTop->insert(window); // put window into desktop and draw it } // changed from tvguid12: add buttons void TMyApp::newDialog() { TDialog *pd = new TDialog( TRect( 20, 4, 60, 20), "Demo Dialog" ); if( pd ) { TView *b = new TCheckBoxes( TRect( 3, 3, 18, 6), new TSItem( "~H~varti", new TSItem( "~T~ilset", new TSItem( "~J~arlsberg", 0 ) ))); pd->insert( b ); pd->insert( new TLabel( TRect( 2, 2, 10, 3), "Cheeses", b )); b = new TRadioButtons( TRect( 22, 3, 34, 6), new TSItem( "~S~olid", new TSItem( "~R~unny", new TSItem( "~M~elted", 0 ) ))); pd->insert( b ); pd->insert( new TLabel( TRect( 21, 2, 33, 3), "Consistency", b )); // add input line b = new TInputLine( TRect( 3, 8, 37, 9 ), 128 ); pd->insert( b ); pd->insert( new TLabel( TRect( 2, 7, 24, 8 ), "Delivery Instructions", b )); // add input line with range validation TInputLine *inp=new TInputLine( TRect( 3,11, 37,12 ), 32 ); pd->insert( inp ); pd->insert( new TLabel( TRect( 2,10, 26,11 ), "A value from -20 to 590", inp )); TValidator *vld=new TRangeValidator(-20,590); inp->SetValidator( vld ); pd->insert( new TButton( TRect( 15, 13, 25, 15 ), "~O~K", cmOK, bfDefault )); pd->insert( new TButton( TRect( 28, 13, 38, 15 ), "~C~ancel", cmCancel, bfNormal )); // we save the dialog data: pd->setData( demoDialogData ); ushort control = deskTop->execView( pd ); // and read it back when the dialog box is successfully closed if( control != cmCancel ) { char *end; pd->getData( demoDialogData ); // this is a message box with arguments like printf messageBox( mfInformation|mfOKButton, "Deliver: %s value %ld", demoDialogData->inputLineData, strtol(demoDialogData->inputLineRangeData,&end,0) ); } } CLY_destroy( pd ); } int main() { readFile( fileToRead ); TMyApp myApp; myApp.run(); deleteFile(); return 0; }
gpl-2.0
styleflashernewmedia/cjw_newsletter
modules/newsletter/settings.php
1309
<?php /** * File settings.php * * @copyright Copyright (C) 2007-2010 CJW Network - Coolscreen.de, JAC Systeme GmbH, Webmanufaktur. All rights reserved. * @license http://ez.no/licenses/gnu_gpl GNU GPL v2 * @version //autogentag// * @package cjw_newsletter * @subpackage modules * @filesource */ $module = $Params["Module"]; $http = eZHTTPTool::instance(); $viewParameters = array(); $tpl = eZTemplate::factory(); $tpl->setVariable( 'view_parameters', $viewParameters ); //http://admin.eldorado-templin.info.jac400.in-mv.com/settings/view/eldorado-templin_admin/cjw_newsletter.ini $tpl->setVariable( 'current_siteaccess', $viewParameters ); //$tpl->setVariable( 'link_array', $data['result']); //$tpl->setVariable( 'csv_data_not_ok', $invalidLinien ); $currentSiteAccess = $GLOBALS['eZCurrentAccess']; $currentSiteAccessName = $currentSiteAccess['name']; $redirectUri = "/settings/view/$currentSiteAccessName/cjw_newsletter.ini"; return $module->redirectTo( $redirectUri ); /* $Result = array(); $Result['content'] = $tpl->fetch( "design:newsletter/index.tpl" ); $Result['path'] = array( array( 'url' => false, 'text' => 'newsletter' ), array( 'url' => false, 'text' => 'index' ) ); */ ?>
gpl-2.0
Distrotech/wanpipe
api/libsangoma/examples/sample_data_tapping/Sangoma/Code/Sangoma/PortBuffer.cpp
4570
#if defined WIN32 && defined NDEBUG #pragma optimize("gt",on) #endif #include "PortBuffer.h" #include "sangoma_interface.h" #define ERR_PORT_BUFFER if(0)printf("Error:%s():line:%d: ", __FUNCTION__, __LINE__);if(0)printf /////////////////////////////////////////////////////////////////////////////////////////////// /// \fn PortBuffer::PortBuffer(unsigned int buffer_size_in_bytes) /// \brief Structure containing a buffer for the port to read from or write to. The /// size of buffer is indicated so that it can be allocated dynamically. /// /// \param[in] buffer_size_in_bytes - The size of the port buffer in bytes. /// \author David Rokhvarg (davidr@sangoma.com) /// \date 11/13/2007 /////////////////////////////////////////////////////////////////////////////////////////////// PortBuffer::PortBuffer(unsigned int buffer_size_in_bytes) { BufferSize = buffer_size_in_bytes; Buffer = (unsigned char*)malloc(buffer_size_in_bytes); ApiHeader = new wp_api_hdr_t(); memset(ApiHeader, 0x00, sizeof(wp_api_hdr_t)); } PortBuffer::~PortBuffer() { free(Buffer); delete ApiHeader; } /////////////////////////////////////////////////////////////////////////////////////////////// /// \fn PortBuffer::GetPortBuffer() /// \brief Returns pointer to Buffer. /// \return pointer to Buffer. /// \author David Rokhvarg (davidr@sangoma.com) /// \date 11/15/2007 /////////////////////////////////////////////////////////////////////////////////////////////// unsigned char* PortBuffer::GetPortBuffer() { return Buffer; } /////////////////////////////////////////////////////////////////////////////////////////////// /// \fn PortBuffer::GetPortBufferSize() /// \brief Returns the total Buffer size. /// \return Buffer size. /// \author David Rokhvarg (davidr@sangoma.com) /// \date 11/15/2007 /////////////////////////////////////////////////////////////////////////////////////////////// unsigned int PortBuffer::GetPortBufferSize() { return BufferSize; } /////////////////////////////////////////////////////////////////////////////////////////////// /// \fn PortBuffer::GetUserDataBuffer() /// \brief Returns pointer to buffer containng user data. /// When data is recieved, this buffer will hold rx data. /// When data is transmitted, this buffer should contain tx data before Write() is called. /// \return pointer to buffer containing user data. /// \author David Rokhvarg (davidr@sangoma.com) /// \date 11/15/2007 /////////////////////////////////////////////////////////////////////////////////////////////// unsigned char *PortBuffer::GetUserDataBuffer() { return GetPortBuffer(); } /////////////////////////////////////////////////////////////////////////////////////////////// /// \fn PortBuffer::GetMaximumUserDataBufferSize() /// \brief Returns maximum size of user data buffer. This is the maximum length of user data /// which can be transmitted/received in one buffer. /// \return maximum size of user data buffer. /// \author David Rokhvarg (davidr@sangoma.com) /// \date 11/15/2007 /////////////////////////////////////////////////////////////////////////////////////////////// unsigned int PortBuffer::GetMaximumUserDataBufferSize() { return GetPortBufferSize(); } /////////////////////////////////////////////////////////////////////////////////////////////// /// \fn PortBuffer::GetUserDataLength() /// \brief Returns current length of user data at DataBuffer. /// When data is recieved, GetUserDataLength() will return length of rx data. /// \return current length of user data at DataBuffer.. /// \author David Rokhvarg (davidr@sangoma.com) /// \date 11/15/2007 /////////////////////////////////////////////////////////////////////////////////////////////// unsigned int PortBuffer::GetUserDataLength() { return ApiHeader->data_length; } /////////////////////////////////////////////////////////////////////////////////////////////// /// \fn PortBuffer::SetUserDataLength(unsigned int user_data_length) /// \brief Set length of user data at DataBuffer. /// When data is transmitted, SetUserDataLength() will indicate to Sangoma API how many /// should be transmitted. /// \return there is no return value. /// \author David Rokhvarg (davidr@sangoma.com) /// \date 11/15/2007 /////////////////////////////////////////////////////////////////////////////////////////////// void PortBuffer::SetUserDataLength(unsigned int user_data_length) { ApiHeader->data_length = user_data_length; }
gpl-2.0
chuchu/SharpRipLib
DemoApplication/Properties/AssemblyInfo.cs
1412
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SharpRipLib")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SharpRipLib")] [assembly: AssemblyCopyright("Copyright © Chris Hußlack 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("86e9c5ee-0010-445e-b925-6698a2d90ec4")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
gpl-2.0
quantum13/hgh
apps/main/migrations/0011_auto__add_field_unit_battle_target.py
10174
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Unit.battle_target' db.add_column('main_unit', 'battle_target', self.gf('django.db.models.fields.related.ForeignKey')(default=None, to=orm['main.Unit'], null=True), keep_default=False) def backwards(self, orm): # Deleting field 'Unit.battle_target' db.delete_column('main_unit', 'battle_target_id') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'main.battle': { 'Meta': {'object_name': 'Battle'}, 'date': ('django.db.models.fields.DateTimeField', [], {}), 'hero1': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'battles1'", 'to': "orm['main.Hero']"}), 'hero1_moved': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'hero2': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'battles2'", 'to': "orm['main.Hero']"}), 'hero2_moved': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'round': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'}), 'winner': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'winned_battles'", 'null': 'True', 'to': "orm['main.Hero']"}) }, 'main.battlequeue': { 'Meta': {'object_name': 'BattleQueue'}, 'date': ('django.db.models.fields.DateTimeField', [], {}), 'hero': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['main.Hero']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'main.hero': { 'Meta': {'object_name': 'Hero'}, 'army_power': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'attack_github': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'attack_own': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'attentiveness_github': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'attentiveness_own': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'avatar_url': ('django.db.models.fields.URLField', [], {'default': "''", 'max_length': '200'}), 'blog': ('django.db.models.fields.URLField', [], {'default': "''", 'max_length': '200'}), 'charm_github': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'charm_own': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'defence_github': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'defence_own': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'experience': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'followers': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'following': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'hireable': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'html_url': ('django.db.models.fields.URLField', [], {'default': "''", 'max_length': '200'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_update': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2000, 1, 1, 0, 0)'}), 'level': ('django.db.models.fields.IntegerField', [], {'default': '1'}), 'location': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '200'}), 'login': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'losses': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '200'}), 'power': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'public_gists': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'public_repos': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'race': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '100'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'hero'", 'unique': 'True', 'to': "orm['auth.User']"}), 'wins': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'main.spell': { 'Meta': {'object_name': 'Spell'}, 'cnt': ('django.db.models.fields.IntegerField', [], {'default': '1'}), 'hero': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'spells'", 'to': "orm['main.Hero']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'type': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'main.unit': { 'Meta': {'object_name': 'Unit'}, 'attack_github': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'attentiveness_github': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'battle_target': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['main.Unit']", 'null': 'True'}), 'charm_github': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'custom_name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'defence_github': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'forks': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'hero': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'units'", 'to': "orm['main.Hero']"}), 'html_url': ('django.db.models.fields.URLField', [], {'default': "''", 'max_length': '200'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'open_issues': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'race': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '100'}), 'watchers': ('django.db.models.fields.IntegerField', [], {'default': '0'}) } } complete_apps = ['main']
gpl-2.0
sdtorresl/ExeaMusicPlayer
Player/src/player/Player.java
1647
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package player; import java.io.File; import javafx.application.Application; import javafx.concurrent.Task; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; /** * * @author sdtorresl */ public class Player extends Application { @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("Player.fxml")); stage.setTitle("Farmatodo radio (beta)"); stage.setResizable(false); //stage.getIcons().add(new Image("file:icon.png")); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); } @Override public void stop() { Thread t = PlayerController.getThread(); t.stop(); System.out.println("Exit"); try { File audioFile = PlayerController.getAudioFile(); audioFile.delete(); } catch(Exception ioe) { } Task task = PlayerController.getTask(); task.cancel(); } /** * The main() method is ignored in correctly deployed JavaFX application. * main() serves only as fallback in case the application can not be * launched through deployment artifacts, e.g., in IDEs with limited FX * support. NetBeans ignores main(). * * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
gpl-2.0
nfprojects/nfengine
Src/Engine/Common/Memory/Buffer.hpp
1276
/** * @file * @author Witek902 * @brief Buffer class declaration. */ #pragma once #include "../nfCommon.hpp" namespace NFE { namespace Common { /** * Dynamic data buffer */ class NFCOMMON_API Buffer { public: Buffer(); Buffer(const Buffer& src); Buffer(Buffer&& other); Buffer(const void* data, const size_t dataSize, const size_t alignment = 1); Buffer& operator = (const Buffer& src); Buffer& operator = (Buffer&& src); ~Buffer(); NFE_FORCE_INLINE bool Empty() const { return mSize == 0; } NFE_FORCE_INLINE size_t Size() const { return mSize; } NFE_FORCE_INLINE size_t GetAlignment() const { return mAlignment; } NFE_FORCE_INLINE size_t Capacity() const { return mCapacity; } NFE_FORCE_INLINE void* Data() const { return mData; } void Zero(); // Resize bufer and optionaly copy data into it bool Resize(size_t size, const void* data = nullptr, const size_t alignment = 1); // Reserve space bool Reserve(size_t size, bool preserveData = true, const size_t alignment = 1); // Set size to zero void Clear(); // Free memory void Release(); private: void* mData; size_t mSize; size_t mCapacity; size_t mAlignment; }; } // namespace Common } // namespace NFE
gpl-2.0
klst-com/metasfresh
de.metas.handlingunits.client/src/test/java-deprecated/de/metas/handlingunits/client/editor/view/manual/HUEditorManualTestFrame.java
4725
package de.metas.handlingunits.client.editor.view.manual; /* * #%L * de.metas.handlingunits.client * %% * Copyright (C) 2015 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 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/gpl-2.0.html>. * #L% */ import java.awt.Dimension; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JMenuBar; import org.adempiere.ad.trx.api.ITrx; import org.adempiere.ad.wrapper.POJOLookupMap; import org.adempiere.ad.wrapper.POJOWrapper; import org.adempiere.model.PlainContextAware; import org.adempiere.test.AdempiereTestHelper; import org.adempiere.util.Services; import org.compiere.util.Env; import org.junit.Ignore; import de.metas.adempiere.form.IClientUI; import de.metas.adempiere.form.swing.SwingClientUI; import de.metas.handlingunits.HUAssert; import de.metas.handlingunits.allocation.source.impl.TestDataSource; import de.metas.handlingunits.api.IHandlingUnitsBL; import de.metas.handlingunits.api.IHandlingUnitsDAO; import de.metas.handlingunits.client.editor.hu.view.swing.HUEditorPanel; import de.metas.handlingunits.client.form.HUEditorHelper; import de.metas.handlingunits.document.AbstractTestDataSourceBuilder; import de.metas.handlingunits.document.IDataSource; import de.metas.handlingunits.document.MInOutTestDataSourceBuilder; import de.metas.handlingunits.model.I_M_HU; import de.metas.handlingunits.model.I_M_HU_Item; import de.metas.handlingunits.storage.IHUItemStorage; import de.metas.handlingunits.storage.IHUStorageFactory; @Ignore public class HUEditorManualTestFrame { // // Setup static { AdempiereTestHelper.get().init(); Services.registerService(IClientUI.class, new SwingClientUI()); POJOWrapper.setPrintReferencedModels(false); new de.metas.handlingunits.model.validator.Main().registerFactories(); } public static void main(final String[] args) { new HUEditorManualTestFrame().start(); } private AbstractTestDataSourceBuilder<?> dataSourceBuilder; protected HUEditorManualTestFrame() { super(); } protected AbstractTestDataSourceBuilder<?> createDataSourceBuilder() { final IDataSource parentDataSource = new TestDataSource(); POJOLookupMap.get().dumpStatus(); final AbstractTestDataSourceBuilder<?> dataSourceBuilder = new MInOutTestDataSourceBuilder(parentDataSource); // final AbstractTestDataSourceBuilder<?> dataSourceBuilder = new ReceiptScheduleTestDataSourceBuilder(parentDataSource); // final AbstractTestDataSourceBuilder<?> dataSourceBuilder = new HandlingUnitTestDataSourceBuilder(parentDataSource); dataSourceBuilder.setContext(new PlainContextAware(Env.getCtx(), ITrx.TRXNAME_ThreadInherited)); return dataSourceBuilder; } public IDataSource createDataSource() { if (dataSourceBuilder == null) { dataSourceBuilder = createDataSourceBuilder(); } return dataSourceBuilder.createDataSource(); } public void start() { while (true) { final IDataSource dataSource = createDataSource(); showHUEditor(dataSource); validateData(); } } private static void showHUEditor(final IDataSource dataSource) { final HUEditorPanel huEditorPanel = new HUEditorPanel(); huEditorPanel.setDataDource(dataSource); final JDialog frame = new JDialog(); frame.setModal(true); frame.setTitle("HU Editor"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setPreferredSize(new Dimension(1200, 800)); frame.add(huEditorPanel); frame.setJMenuBar(new JMenuBar()); HUEditorHelper.createMenu(frame.getJMenuBar(), huEditorPanel); frame.pack(); frame.setVisible(true); } private static void validateData() { try { validateData0(); } catch (Exception e) { e.printStackTrace(); } } private static void validateData0() { final IHUStorageFactory storageFactory = Services.get(IHandlingUnitsBL.class).getStorageFactory(); for (final I_M_HU hu : POJOLookupMap.get().getRecords(I_M_HU.class)) { for (final I_M_HU_Item huItem : Services.get(IHandlingUnitsDAO.class).retrieveItems(hu)) { final IHUItemStorage itemStorage = storageFactory.getStorage(huItem); HUAssert.assertStorageValid(itemStorage); } } } }
gpl-2.0
identityxx/penrose-server
client/src/java/org/safehaus/penrose/directory/DirectoryClient.java
17511
package org.safehaus.penrose.directory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.safehaus.penrose.util.ClassUtil; import org.safehaus.penrose.util.TextUtil; import org.safehaus.penrose.partition.PartitionClient; import org.safehaus.penrose.partition.PartitionManagerClient; import org.safehaus.penrose.client.BaseClient; import org.safehaus.penrose.client.PenroseClient; import org.safehaus.penrose.ldap.DN; import org.apache.log4j.Level; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.PatternLayout; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.xml.DOMConfigurator; import javax.management.*; import java.util.Collection; import java.util.Iterator; import java.util.ArrayList; import java.util.List; import java.io.File; import gnu.getopt.LongOpt; import gnu.getopt.Getopt; /** * @author Endi Sukma Dewata */ public class DirectoryClient extends BaseClient implements DirectoryServiceMBean { public static Logger log = LoggerFactory.getLogger(DirectoryClient.class); protected String partitionName; public DirectoryClient(PenroseClient client, String partitionName) throws Exception { super(client, "Directory", getStringObjectName(partitionName)); this.partitionName = partitionName; } public DirectoryConfig getDirectoryConfig() throws Exception { return (DirectoryConfig)getAttribute("DirectoryConfig"); } public static String getStringObjectName(String partitionName) { return "Penrose:type=Directory,partition="+partitionName; } public String getPartitionName() { return partitionName; } public void setPartitionName(String partitionName) { this.partitionName = partitionName; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Entries //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public DN getSuffix() throws Exception { return (DN)getAttribute("Suffix"); } public Collection<DN> getSuffixes() throws Exception { return (Collection<DN>)getAttribute("Suffixes"); } public Collection<String> getRootEntryNames() throws Exception { return (Collection<String>)getAttribute("RootEntryNames"); } public Collection<String> getEntryNames() throws Exception { return (Collection<String>)getAttribute("EntryNames"); } public String getParentName(String entryName) throws Exception { return (String)invoke( "getParentName", new Object[] { entryName }, new String[] { String.class.getName() } ); } public List<String> getChildNames(String entryName) throws Exception { return (List<String>)invoke( "getChildNames", new Object[] { entryName }, new String[] { String.class.getName() } ); } public void setChildNames(String entryName, List<String> childNames) throws Exception { invoke( "setChildNames", new Object[] { entryName, childNames }, new String[] { String.class.getName(), List.class.getName() } ); } public EntryClient getEntryClient(String entryName) throws Exception { return new EntryClient(client, partitionName, entryName); } public String getEntryName(DN dn) throws Exception { return (String)invoke( "getEntryName", new Object[] { dn }, new String[] { DN.class.getName() } ); } public DN getEntryDn(String entryName) throws Exception { return (DN)invoke( "getEntryDn", new Object[] { entryName }, new String[] { String.class.getName() } ); } public EntryConfig getEntryConfig(String entryName) throws Exception { return (EntryConfig)invoke( "getEntryConfig", new Object[] { entryName }, new String[] { String.class.getName() } ); } public String createEntry(EntryConfig entryConfig) throws Exception { return (String)invoke( "createEntry", new Object[] { entryConfig }, new String[] { EntryConfig.class.getName() } ); } public void updateEntry(String name, EntryConfig entryConfig) throws Exception { invoke( "updateEntry", new Object[] { name, entryConfig }, new String[] { String.class.getName(), EntryConfig.class.getName() } ); } public void removeEntry(String name) throws Exception { invoke( "removeEntry", new Object[] { name }, new String[] { String.class.getName() } ); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Command Line //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void showEntries(PenroseClient client, String partitionName) throws Exception { PartitionManagerClient partitionManagerClient = client.getPartitionManagerClient(); PartitionClient partitionClient = partitionManagerClient.getPartitionClient(partitionName); DirectoryClient directoryClient = partitionClient.getDirectoryClient(); System.out.print(TextUtil.rightPad("ENTRIES", 10)+" "); System.out.println(TextUtil.rightPad("DN", 50)); System.out.print(TextUtil.repeat("-", 10)+" "); System.out.println(TextUtil.repeat("-", 50)); for (String entryId : directoryClient.getEntryNames()) { EntryClient entryClient = directoryClient.getEntryClient(entryId); DN dn = entryClient.getDn(); System.out.print(TextUtil.rightPad(entryId, 10)+" "); System.out.println(TextUtil.rightPad(dn.toString(), 50)+" "); } } public static void showEntry(PenroseClient client, String partitionName, String entryId) throws Exception { PartitionManagerClient partitionManagerClient = client.getPartitionManagerClient(); PartitionClient partitionClient = partitionManagerClient.getPartitionClient(partitionName); DirectoryClient directoryClient = partitionClient.getDirectoryClient(); EntryClient entryClient = directoryClient.getEntryClient(entryId); EntryConfig entryConfig = entryClient.getEntryConfig(); System.out.println("Name : "+entryConfig.getName()); System.out.println("DN : "+entryConfig.getDn()); String entryClass = entryConfig.getEntryClass(); System.out.println("Class : "+(entryClass == null ? "" : entryClass)); String description = entryConfig.getDescription(); System.out.println("Description : "+(description == null ? "" : description)); System.out.println(); String parentName = entryClient.getParentName(); System.out.println("Parent Name : "+(parentName == null ? "" : parentName)); Collection<String> childNames = entryClient.getChildNames(); System.out.println("Child Names : "+childNames); System.out.println(); System.out.println("Parameters :"); for (String paramName : entryConfig.getParameterNames()) { String value = entryConfig.getParameter(paramName); System.out.println(" - " + paramName + ": " + value); } System.out.println(); System.out.println("Attributes:"); for (MBeanAttributeInfo attributeInfo : entryClient.getAttributes()) { System.out.println(" - "+attributeInfo.getName()+" ("+attributeInfo.getType()+")"); } System.out.println(); System.out.println("Operations:"); for (MBeanOperationInfo operationInfo : entryClient.getOperations()) { Collection<String> paramTypes = new ArrayList<String>(); for (MBeanParameterInfo parameterInfo : operationInfo.getSignature()) { paramTypes.add(parameterInfo.getType()); } String operation = operationInfo.getReturnType()+" "+ ClassUtil.getSignature(operationInfo.getName(), paramTypes); System.out.println(" - "+operation); } } public static void processShowCommand(PenroseClient client, Iterator<String> iterator) throws Exception { String target = iterator.next(); if ("entries".equals(target)) { iterator.next(); // in iterator.next(); // partition String partitionName = iterator.next(); showEntries(client, partitionName); } else if ("entry".equals(target)) { String entryId = iterator.next(); iterator.next(); // in iterator.next(); // partition String partitionName = iterator.next(); showEntry(client, partitionName, entryId); } else { System.out.println("Invalid target: "+target); } } public static void invokeMethod( PenroseClient client, String partitionName, String entryId, String methodName, Object[] paramValues, String[] paramTypes ) throws Exception { PartitionManagerClient partitionManagerClient = client.getPartitionManagerClient(); PartitionClient partitionClient = partitionManagerClient.getPartitionClient(partitionName); DirectoryClient directoryClient = partitionClient.getDirectoryClient(); EntryClient entryClient = directoryClient.getEntryClient(entryId); Object returnValue = entryClient.invoke( methodName, paramValues, paramTypes ); System.out.println("Return value: "+returnValue); } public static void processInvokeCommand(PenroseClient client, Iterator<String> iterator) throws Exception { iterator.next(); // method String methodName = iterator.next(); iterator.next(); // in String target = iterator.next(); if ("entry".equals(target)) { String entryId = iterator.next(); iterator.next(); // in iterator.next(); // partition String partitionName = iterator.next(); Object[] paramValues; String[] paramTypes; if (iterator.hasNext()) { iterator.next(); // with Collection<Object> values = new ArrayList<Object>(); Collection<String> types = new ArrayList<String>(); while (iterator.hasNext()) { String value = iterator.next(); values.add(value); types.add(String.class.getName()); } paramValues = values.toArray(new Object[values.size()]); paramTypes = types.toArray(new String[types.size()]); } else { paramValues = new Object[0]; paramTypes = new String[0]; } invokeMethod(client, partitionName, entryId, methodName, paramValues, paramTypes); } else { System.out.println("Invalid target: "+target); } } public static void execute(PenroseClient client, Collection<String> parameters) throws Exception { Iterator<String> iterator = parameters.iterator(); String command = iterator.next(); log.debug("Executing "+command); if ("show".equals(command)) { processShowCommand(client, iterator); } else if ("invoke".equals(command)) { processInvokeCommand(client, iterator); } else { System.out.println("Invalid command: "+command); } } public static void showUsage() { System.out.println("Usage: org.safehaus.penrose.directory.DirectoryClient [OPTION]... <COMMAND>"); System.out.println(); System.out.println("Options:"); System.out.println(" -?, --help display this help and exit"); System.out.println(" -P protocol Penrose JMX protocol"); System.out.println(" -h host Penrose server"); System.out.println(" -p port Penrose JMX port"); System.out.println(" -D username username"); System.out.println(" -w password password"); System.out.println(" -d run in debug mode"); System.out.println(" -v run in verbose mode"); System.out.println(); System.out.println("Commands:"); System.out.println(); System.out.println(" show entries in partition <partition name>"); System.out.println(" show entry <entry ID> in partition <partition name>>"); } public static void main(String args[]) throws Exception { Level level = Level.WARN; String serverType = PenroseClient.PENROSE; String protocol = PenroseClient.DEFAULT_PROTOCOL; String hostname = "localhost"; int portNumber = PenroseClient.DEFAULT_RMI_PORT; int rmiTransportPort = PenroseClient.DEFAULT_RMI_TRANSPORT_PORT; String bindDn = null; String bindPassword = null; LongOpt[] longopts = new LongOpt[1]; longopts[0] = new LongOpt("help", LongOpt.NO_ARGUMENT, null, '?'); Getopt getopt = new Getopt("ConnectionClient", args, "-:?dvt:h:p:r:P:D:w:", longopts); Collection<String> parameters = new ArrayList<String>(); int c; while ((c = getopt.getopt()) != -1) { switch (c) { case ':': case '?': showUsage(); System.exit(0); break; case 1: parameters.add(getopt.getOptarg()); break; case 'd': level = Level.DEBUG; break; case 'v': level = Level.INFO; break; case 'P': protocol = getopt.getOptarg(); break; case 't': serverType = getopt.getOptarg(); break; case 'h': hostname = getopt.getOptarg(); break; case 'p': portNumber = Integer.parseInt(getopt.getOptarg()); break; case 'r': rmiTransportPort = Integer.parseInt(getopt.getOptarg()); break; case 'D': bindDn = getopt.getOptarg(); break; case 'w': bindPassword = getopt.getOptarg(); } } if (parameters.size() == 0) { showUsage(); System.exit(0); } File serviceHome = new File(System.getProperty("org.safehaus.penrose.client.home")); //Logger rootLogger = Logger.getRootLogger(); //rootLogger.setLevel(Level.OFF); org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("org.safehaus.penrose"); File log4jXml = new File(serviceHome, "conf"+File.separator+"log4j.xml"); if (level.equals(Level.DEBUG)) { logger.setLevel(level); ConsoleAppender appender = new ConsoleAppender(new PatternLayout("%-20C{1} [%4L] %m%n")); BasicConfigurator.configure(appender); } else if (level.equals(Level.INFO)) { logger.setLevel(level); ConsoleAppender appender = new ConsoleAppender(new PatternLayout("[%d{MM/dd/yyyy HH:mm:ss}] %m%n")); BasicConfigurator.configure(appender); } else if (log4jXml.exists()) { DOMConfigurator.configure(log4jXml.getAbsolutePath()); } else { logger.setLevel(level); ConsoleAppender appender = new ConsoleAppender(new PatternLayout("[%d{MM/dd/yyyy HH:mm:ss}] %m%n")); BasicConfigurator.configure(appender); } try { PenroseClient client = new PenroseClient( serverType, protocol, hostname, portNumber, bindDn, bindPassword ); client.setRmiTransportPort(rmiTransportPort); client.connect(); execute(client, parameters); client.close(); } catch (SecurityException e) { log.error(e.getMessage()); } catch (Exception e) { log.error(e.getMessage(), e); } } }
gpl-2.0
felladrin/last-wish
Scripts/Items/Special/Rares/Ingots/DecoSilverIngot.cs
542
namespace Server.Items { public class DecoSilverIngot : Item { [Constructable] public DecoSilverIngot() : base( 0x1BF5 ) { Movable = true; Stackable = true; } public DecoSilverIngot( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } }
gpl-2.0
linnovate/jquery.org.il
sites/all/themes/jqoilo/tpl/block-search-0.tpl.php
413
<?php //removed block subject// ?> <div id="block-<?php print $block->module .'-'. $block->delta; ?>" class="block block-<?php print $block->module ?> <?php print $block_region_placement ?> block-<?php print $block_zebra ?> <?php if ($blocktheme != '') print $blocktheme; if (function_exists(block_class)) print block_class($block); ?>"> <div class="content"> <?php print $block->content ?> </div> </div>
gpl-2.0
ashaury/sanlexb
templates/sanlex/index.php
2537
<?php /* #------------------------------------------------------------------------ JA Purity II for Joomla 1.5 #------------------------------------------------------------------------ #Copyright (C) 2004-2009 J.O.O.M Solutions Co., Ltd. All Rights Reserved. #@license - GNU/GPL, http://www.gnu.org/copyleft/gpl.html #Author: J.O.O.M Solutions Co., Ltd #Websites: http://www.joomlart.com - http://www.joomlancers.com #------------------------------------------------------------------------ */ // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ); include_once (dirname(__FILE__).DS.'libs'.DS.'ja.template.helper.php'); $tmplTools = JATemplateHelper::getInstance($this, array('ui', JA_TOOL_SCREEN, JA_TOOL_MENU, 'main_layout', 'direction')); //Calculate the width of template $tmplWidth = ''; $tmplWrapMin = '100%'; switch ($tmplTools->getParam(JA_TOOL_SCREEN)){ case 'auto': $tmplWidth = '97%'; break; case 'fluid': $tmplWidth = intval($tmplTools->getParam('ja_screen-fluid-fix-ja_screen_width')); $tmplWidth = $tmplWidth ? $tmplWidth.'%' : '90%'; break; case 'fix': $tmplWidth = intval($tmplTools->getParam('ja_screen-fluid-fix-ja_screen_width')); $tmplWrapMin = $tmplWidth ? ($tmplWidth+1).'px' : '771px'; $tmplWidth = $tmplWidth ? $tmplWidth.'px' : '770px'; break; default: $tmplWidth = intval($tmplTools->getParam(JA_TOOL_SCREEN)); $tmplWrapMin = $tmplWidth ? ($tmplWidth+1).'px' : '981px'; $tmplWidth = $tmplWidth ? $tmplWidth.'px' : '980px'; break; } $tmplTools->setParam ('tmplWidth', $tmplWidth); $tmplTools->setParam ('tmplWrapMin', $tmplWrapMin); //Main navigation $ja_menutype = $tmplTools->getMenuType(); $jamenu = null; if ($ja_menutype && $ja_menutype != 'none') { $japarams = new JParameter(''); $japarams->set( 'menutype', $tmplTools->getParam('menutype', 'mainmenu') ); $japarams->set( 'menu_images_align', 'left' ); $japarams->set( 'menupath', $tmplTools->templateurl() .'/ja_menus'); $japarams->set('menu_images', 1); //0: not show image, 1: show image which set in menu item $japarams->set('menu_background', 1); //0: image, 1: background $japarams->set('mega-colwidth', 200); //Megamenu only: Default column width $japarams->set('mega-style', 1); //Megamenu only: Menu style. $japarams->set('rtl',($tmplTools->getParam('direction')=='rtl' || $tmplTools->direction == 'rtl')); $jamenu = $tmplTools->loadMenu($japarams, $ja_menutype); } //End for main navigation $layout = $tmplTools->getLayout (); if ($layout) { $tmplTools->display ($layout); }
gpl-2.0
InuSasha/xbmc
xbmc/interfaces/json-rpc/PlayerOperations.cpp
51122
/* * Copyright (C) 2005-2013 Team XBMC * http://xbmc.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, 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 XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "PlayerOperations.h" #include "Application.h" #include "PlayListPlayer.h" #include "guilib/GUIWindowManager.h" #include "input/Key.h" #include "GUIUserMessages.h" #include "pictures/GUIWindowSlideShow.h" #include "interfaces/builtins/Builtins.h" #include "PartyModeManager.h" #include "messaging/ApplicationMessenger.h" #include "FileItem.h" #include "VideoLibrary.h" #include "video/VideoDatabase.h" #include "AudioLibrary.h" #include "GUIInfoManager.h" #include "epg/EpgInfoTag.h" #include "music/MusicDatabase.h" #include "pvr/PVRManager.h" #include "pvr/channels/PVRChannel.h" #include "pvr/channels/PVRChannelGroupsContainer.h" #include "pvr/recordings/PVRRecordings.h" #include "cores/IPlayer.h" #include "cores/playercorefactory/PlayerCoreFactory.h" #include "utils/SeekHandler.h" #include "utils/Variant.h" using namespace JSONRPC; using namespace PLAYLIST; using namespace PVR; using namespace KODI::MESSAGING; JSONRPC_STATUS CPlayerOperations::GetActivePlayers(const std::string &method, ITransportLayer *transport, IClient *client, const CVariant &parameterObject, CVariant &result) { int activePlayers = GetActivePlayers(); result = CVariant(CVariant::VariantTypeArray); if (activePlayers & Video) { CVariant video = CVariant(CVariant::VariantTypeObject); video["playerid"] = GetPlaylist(Video); video["type"] = "video"; result.append(video); } if (activePlayers & Audio) { CVariant audio = CVariant(CVariant::VariantTypeObject); audio["playerid"] = GetPlaylist(Audio); audio["type"] = "audio"; result.append(audio); } if (activePlayers & Picture) { CVariant picture = CVariant(CVariant::VariantTypeObject); picture["playerid"] = GetPlaylist(Picture); picture["type"] = "picture"; result.append(picture); } return OK; } JSONRPC_STATUS CPlayerOperations::GetPlayers(const std::string &method, ITransportLayer *transport, IClient *client, const CVariant &parameterObject, CVariant &result) { std::string media = parameterObject["media"].asString(); result = CVariant(CVariant::VariantTypeArray); std::vector<std::string> players; if (media == "all") { CPlayerCoreFactory::GetInstance().GetPlayers(players); } else { bool video = false; if (media == "video") video = true; CPlayerCoreFactory::GetInstance().GetPlayers(players, true, video); } for (auto playername: players) { CVariant player(CVariant::VariantTypeObject); player["name"] = playername; player["playsvideo"] = CPlayerCoreFactory::GetInstance().PlaysVideo(playername); player["playsaudio"] = CPlayerCoreFactory::GetInstance().PlaysAudio(playername); player["type"] = CPlayerCoreFactory::GetInstance().GetPlayerType(playername); result.push_back(player); } return OK; } JSONRPC_STATUS CPlayerOperations::GetProperties(const std::string &method, ITransportLayer *transport, IClient *client, const CVariant &parameterObject, CVariant &result) { PlayerType player = GetPlayer(parameterObject["playerid"]); CVariant properties = CVariant(CVariant::VariantTypeObject); for (unsigned int index = 0; index < parameterObject["properties"].size(); index++) { std::string propertyName = parameterObject["properties"][index].asString(); CVariant property; JSONRPC_STATUS ret; if ((ret = GetPropertyValue(player, propertyName, property)) != OK) return ret; properties[propertyName] = property; } result = properties; return OK; } JSONRPC_STATUS CPlayerOperations::GetItem(const std::string &method, ITransportLayer *transport, IClient *client, const CVariant &parameterObject, CVariant &result) { PlayerType player = GetPlayer(parameterObject["playerid"]); CFileItemPtr fileItem; switch (player) { case Video: case Audio: { fileItem = CFileItemPtr(new CFileItem(g_application.CurrentFileItem())); if (IsPVRChannel()) { CPVRChannelPtr currentChannel(g_PVRManager.GetCurrentChannel()); if (currentChannel) fileItem = CFileItemPtr(new CFileItem(currentChannel)); } else if (player == Video) { if (!CVideoLibrary::FillFileItem(g_application.CurrentFile(), fileItem, parameterObject)) { const CVideoInfoTag *currentVideoTag = g_infoManager.GetCurrentMovieTag(); if (currentVideoTag != NULL) { std::string originalLabel = fileItem->GetLabel(); fileItem->SetFromVideoInfoTag(*currentVideoTag); if (fileItem->GetLabel().empty()) fileItem->SetLabel(originalLabel); } fileItem->SetPath(g_application.CurrentFileItem().GetPath()); } } else { if (!CAudioLibrary::FillFileItem(g_application.CurrentFile(), fileItem, parameterObject)) { const MUSIC_INFO::CMusicInfoTag *currentMusicTag = g_infoManager.GetCurrentSongTag(); if (currentMusicTag != NULL) { std::string originalLabel = fileItem->GetLabel(); fileItem->SetFromMusicInfoTag(*currentMusicTag); if (fileItem->GetLabel().empty()) fileItem->SetLabel(originalLabel); } fileItem->SetPath(g_application.CurrentFileItem().GetPath()); } } if (IsPVRChannel()) break; if (player == Video) { bool additionalInfo = false; for (CVariant::const_iterator_array itr = parameterObject["properties"].begin_array(); itr != parameterObject["properties"].end_array(); itr++) { std::string fieldValue = itr->asString(); if (fieldValue == "cast" || fieldValue == "set" || fieldValue == "setid" || fieldValue == "showlink" || fieldValue == "resume" || (fieldValue == "streamdetails" && !fileItem->GetVideoInfoTag()->m_streamDetails.HasItems())) additionalInfo = true; } CVideoDatabase videodatabase; if ((additionalInfo) && videodatabase.Open()) { if (additionalInfo) { switch (fileItem->GetVideoContentType()) { case VIDEODB_CONTENT_MOVIES: videodatabase.GetMovieInfo("", *(fileItem->GetVideoInfoTag()), fileItem->GetVideoInfoTag()->m_iDbId); break; case VIDEODB_CONTENT_MUSICVIDEOS: videodatabase.GetMusicVideoInfo("", *(fileItem->GetVideoInfoTag()), fileItem->GetVideoInfoTag()->m_iDbId); break; case VIDEODB_CONTENT_EPISODES: videodatabase.GetEpisodeInfo("", *(fileItem->GetVideoInfoTag()), fileItem->GetVideoInfoTag()->m_iDbId); break; case VIDEODB_CONTENT_TVSHOWS: case VIDEODB_CONTENT_MOVIE_SETS: default: break; } } videodatabase.Close(); } } else if (player == Audio) { if (fileItem->IsMusicDb()) { CMusicDatabase musicdb; CFileItemList items; items.Add(fileItem); CAudioLibrary::GetAdditionalSongDetails(parameterObject, items, musicdb); } } break; } case Picture: { CGUIWindowSlideShow *slideshow = (CGUIWindowSlideShow*)g_windowManager.GetWindow(WINDOW_SLIDESHOW); if (!slideshow) return FailedToExecute; CFileItemList slides; slideshow->GetSlideShowContents(slides); fileItem = slides[slideshow->CurrentSlide() - 1]; break; } case None: default: return FailedToExecute; } HandleFileItem("id", !IsPVRChannel(), "item", fileItem, parameterObject, parameterObject["properties"], result, false); return OK; } JSONRPC_STATUS CPlayerOperations::PlayPause(const std::string &method, ITransportLayer *transport, IClient *client, const CVariant &parameterObject, CVariant &result) { CGUIWindowSlideShow *slideshow = NULL; switch (GetPlayer(parameterObject["playerid"])) { case Video: case Audio: if (!g_application.m_pPlayer->CanPause()) return FailedToExecute; if (parameterObject["play"].isString()) CBuiltins::GetInstance().Execute("playercontrol(play)"); else { if (parameterObject["play"].asBoolean()) { if (g_application.m_pPlayer->IsPausedPlayback()) CApplicationMessenger::GetInstance().SendMsg(TMSG_MEDIA_PAUSE); else if (g_application.m_pPlayer->GetPlaySpeed() != 1) g_application.m_pPlayer->SetPlaySpeed(1); } else if (!g_application.m_pPlayer->IsPausedPlayback()) CApplicationMessenger::GetInstance().SendMsg(TMSG_MEDIA_PAUSE); } result["speed"] = g_application.m_pPlayer->IsPausedPlayback() ? 0 : (int)lrint(g_application.m_pPlayer->GetPlaySpeed()); return OK; case Picture: slideshow = (CGUIWindowSlideShow*)g_windowManager.GetWindow(WINDOW_SLIDESHOW); if (slideshow && slideshow->IsPlaying() && (parameterObject["play"].isString() || (parameterObject["play"].isBoolean() && parameterObject["play"].asBoolean() == slideshow->IsPaused()))) SendSlideshowAction(ACTION_PAUSE); if (slideshow && slideshow->IsPlaying() && !slideshow->IsPaused()) result["speed"] = slideshow->GetDirection(); else result["speed"] = 0; return OK; case None: default: return FailedToExecute; } } JSONRPC_STATUS CPlayerOperations::Stop(const std::string &method, ITransportLayer *transport, IClient *client, const CVariant &parameterObject, CVariant &result) { switch (GetPlayer(parameterObject["playerid"])) { case Video: case Audio: CApplicationMessenger::GetInstance().SendMsg(TMSG_MEDIA_STOP, static_cast<int>(parameterObject["playerid"].asInteger())); return ACK; case Picture: SendSlideshowAction(ACTION_STOP); return ACK; case None: default: return FailedToExecute; } } JSONRPC_STATUS CPlayerOperations::SetSpeed(const std::string &method, ITransportLayer *transport, IClient *client, const CVariant &parameterObject, CVariant &result) { switch (GetPlayer(parameterObject["playerid"])) { case Video: case Audio: if (parameterObject["speed"].isInteger()) { int speed = (int)parameterObject["speed"].asInteger(); if (speed != 0) { // If the player is paused we first need to unpause if (g_application.m_pPlayer->IsPausedPlayback()) g_application.m_pPlayer->Pause(); g_application.m_pPlayer->SetPlaySpeed(speed); } else g_application.m_pPlayer->Pause(); } else if (parameterObject["speed"].isString()) { if (parameterObject["speed"].asString().compare("increment") == 0) CBuiltins::GetInstance().Execute("playercontrol(forward)"); else CBuiltins::GetInstance().Execute("playercontrol(rewind)"); } else return InvalidParams; result["speed"] = g_application.m_pPlayer->IsPausedPlayback() ? 0 : (int)lrint(g_application.m_pPlayer->GetPlaySpeed()); return OK; case Picture: case None: default: return FailedToExecute; } } JSONRPC_STATUS CPlayerOperations::Seek(const std::string &method, ITransportLayer *transport, IClient *client, const CVariant &parameterObject, CVariant &result) { PlayerType player = GetPlayer(parameterObject["playerid"]); switch (player) { case Video: case Audio: { if (!g_application.m_pPlayer->CanSeek()) return FailedToExecute; const CVariant& value = parameterObject["value"]; if (IsType(value, NumberValue) || (value.isObject() && value.isMember("percentage"))) g_application.SeekPercentage(IsType(value, NumberValue) ? value.asFloat() : value["percentage"].asFloat()); else if (value.isString() || (value.isObject() && value.isMember("step"))) { std::string step = value.isString() ? value.asString() : value["step"].asString(); if (step == "smallforward") CBuiltins::GetInstance().Execute("playercontrol(smallskipforward)"); else if (step == "smallbackward") CBuiltins::GetInstance().Execute("playercontrol(smallskipbackward)"); else if (step == "bigforward") CBuiltins::GetInstance().Execute("playercontrol(bigskipforward)"); else if (step == "bigbackward") CBuiltins::GetInstance().Execute("playercontrol(bigskipbackward)"); else return InvalidParams; } else if (value.isObject() && value.isMember("seconds") && value.size() == 1) CSeekHandler::GetInstance().SeekSeconds(static_cast<int>(value["seconds"].asInteger())); else if (value.isObject()) g_application.SeekTime(ParseTimeInSeconds(value.isMember("time") ? value["time"] : value)); else return InvalidParams; GetPropertyValue(player, "percentage", result["percentage"]); GetPropertyValue(player, "time", result["time"]); GetPropertyValue(player, "totaltime", result["totaltime"]); return OK; } case Picture: case None: default: return FailedToExecute; } } JSONRPC_STATUS CPlayerOperations::Move(const std::string &method, ITransportLayer *transport, IClient *client, const CVariant &parameterObject, CVariant &result) { std::string direction = parameterObject["direction"].asString(); switch (GetPlayer(parameterObject["playerid"])) { case Picture: if (direction == "left") SendSlideshowAction(ACTION_MOVE_LEFT); else if (direction == "right") SendSlideshowAction(ACTION_MOVE_RIGHT); else if (direction == "up") SendSlideshowAction(ACTION_MOVE_UP); else if (direction == "down") SendSlideshowAction(ACTION_MOVE_DOWN); else return InvalidParams; return ACK; case Video: case Audio: if (direction == "left" || direction == "up") CApplicationMessenger::GetInstance().SendMsg(TMSG_GUI_ACTION, WINDOW_INVALID, -1, static_cast<void*>(new CAction(ACTION_PREV_ITEM))); else if (direction == "right" || direction == "down") CApplicationMessenger::GetInstance().SendMsg(TMSG_GUI_ACTION, WINDOW_INVALID, -1, static_cast<void*>(new CAction(ACTION_NEXT_ITEM))); else return InvalidParams; return ACK; case None: default: return FailedToExecute; } } JSONRPC_STATUS CPlayerOperations::Zoom(const std::string &method, ITransportLayer *transport, IClient *client, const CVariant &parameterObject, CVariant &result) { CVariant zoom = parameterObject["zoom"]; switch (GetPlayer(parameterObject["playerid"])) { case Picture: if (zoom.isInteger()) SendSlideshowAction(ACTION_ZOOM_LEVEL_NORMAL + ((int)zoom.asInteger() - 1)); else if (zoom.isString()) { std::string strZoom = zoom.asString(); if (strZoom == "in") SendSlideshowAction(ACTION_ZOOM_IN); else if (strZoom == "out") SendSlideshowAction(ACTION_ZOOM_OUT); else return InvalidParams; } else return InvalidParams; return ACK; case Video: case Audio: case None: default: return FailedToExecute; } } JSONRPC_STATUS CPlayerOperations::Rotate(const std::string &method, ITransportLayer *transport, IClient *client, const CVariant &parameterObject, CVariant &result) { switch (GetPlayer(parameterObject["playerid"])) { case Picture: if (parameterObject["value"].asString().compare("clockwise") == 0) SendSlideshowAction(ACTION_ROTATE_PICTURE_CW); else SendSlideshowAction(ACTION_ROTATE_PICTURE_CCW); return ACK; case Video: case Audio: case None: default: return FailedToExecute; } } JSONRPC_STATUS CPlayerOperations::Open(const std::string &method, ITransportLayer *transport, IClient *client, const CVariant &parameterObject, CVariant &result) { CVariant options = parameterObject["options"]; CVariant optionShuffled = options["shuffled"]; CVariant optionRepeat = options["repeat"]; CVariant optionResume = options["resume"]; CVariant optionPlayer = options["playername"]; if (parameterObject["item"].isObject() && parameterObject["item"].isMember("playlistid")) { int playlistid = (int)parameterObject["item"]["playlistid"].asInteger(); if (playlistid < PLAYLIST_PICTURE) { // Apply the "shuffled" option if available if (optionShuffled.isBoolean()) g_playlistPlayer.SetShuffle(playlistid, optionShuffled.asBoolean(), false); // Apply the "repeat" option if available if (!optionRepeat.isNull()) g_playlistPlayer.SetRepeat(playlistid, (REPEAT_STATE)ParseRepeatState(optionRepeat), false); } int playlistStartPosition = (int)parameterObject["item"]["position"].asInteger(); switch (playlistid) { case PLAYLIST_MUSIC: case PLAYLIST_VIDEO: CApplicationMessenger::GetInstance().SendMsg(TMSG_MEDIA_PLAY, playlistid, playlistStartPosition); OnPlaylistChanged(); break; case PLAYLIST_PICTURE: { std::string firstPicturePath; if (playlistStartPosition > 0) { CGUIWindowSlideShow *slideshow = (CGUIWindowSlideShow*)g_windowManager.GetWindow(WINDOW_SLIDESHOW); if (slideshow != NULL) { CFileItemList list; slideshow->GetSlideShowContents(list); if (playlistStartPosition < list.Size()) firstPicturePath = list.Get(playlistStartPosition)->GetPath(); } } return StartSlideshow("", false, optionShuffled.isBoolean() && optionShuffled.asBoolean(), firstPicturePath); break; } } return ACK; } else if (parameterObject["item"].isObject() && parameterObject["item"].isMember("path")) { bool random = (optionShuffled.isBoolean() && optionShuffled.asBoolean()) || (!optionShuffled.isBoolean() && parameterObject["item"]["random"].asBoolean()); return StartSlideshow(parameterObject["item"]["path"].asString(), parameterObject["item"]["recursive"].asBoolean(), random); } else if (parameterObject["item"].isObject() && parameterObject["item"].isMember("partymode")) { if (g_partyModeManager.IsEnabled()) g_partyModeManager.Disable(); CApplicationMessenger::GetInstance().SendMsg(TMSG_EXECUTE_BUILT_IN, -1, -1, nullptr, "playercontrol(partymode(" + parameterObject["item"]["partymode"].asString() + "))"); return ACK; } else if (parameterObject["item"].isObject() && parameterObject["item"].isMember("channelid")) { if (!g_PVRManager.IsStarted()) return FailedToExecute; CPVRChannelGroupsContainerPtr channelGroupContainer = g_PVRChannelGroups; if (!channelGroupContainer) return FailedToExecute; CPVRChannelPtr channel = channelGroupContainer->GetChannelById((int)parameterObject["item"]["channelid"].asInteger()); if (channel == NULL) return InvalidParams; if ((g_PVRManager.IsPlayingRadio() && channel->IsRadio()) || (g_PVRManager.IsPlayingTV() && !channel->IsRadio())) g_application.m_pPlayer->SwitchChannel(channel); else { CFileItemList *l = new CFileItemList; //don't delete, l->Add(std::make_shared<CFileItem>(channel)); CApplicationMessenger::GetInstance().PostMsg(TMSG_MEDIA_PLAY, -1, -1, static_cast<void*>(l)); } return ACK; } else if (parameterObject["item"].isObject() && parameterObject["item"].isMember("recordingid")) { if (!g_PVRManager.IsStarted()) return FailedToExecute; CPVRRecordingsPtr recordingsContainer = g_PVRRecordings; if (!recordingsContainer) return FailedToExecute; CFileItemPtr fileItem = recordingsContainer->GetById((int)parameterObject["item"]["recordingid"].asInteger()); if (fileItem == NULL) return InvalidParams; CFileItemList *l = new CFileItemList; //don't delete, l->Add(std::make_shared<CFileItem>(*fileItem)); CApplicationMessenger::GetInstance().PostMsg(TMSG_MEDIA_PLAY, -1, -1, static_cast<void*>(l)); return ACK; } else { CFileItemList list; if (FillFileItemList(parameterObject["item"], list) && list.Size() > 0) { bool slideshow = true; for (int index = 0; index < list.Size(); index++) { if (!list[index]->IsPicture()) { slideshow = false; break; } } if (slideshow) { CGUIWindowSlideShow *slideshow = (CGUIWindowSlideShow*)g_windowManager.GetWindow(WINDOW_SLIDESHOW); if (!slideshow) return FailedToExecute; SendSlideshowAction(ACTION_STOP); slideshow->Reset(); for (int index = 0; index < list.Size(); index++) slideshow->Add(list[index].get()); return StartSlideshow("", false, optionShuffled.isBoolean() && optionShuffled.asBoolean()); } else { std::string playername; // Handle the "playerid" option if (!optionPlayer.isNull()) { if (optionPlayer.isString()) { playername = optionPlayer.asString(); if (playername != "default") { // check if the there's actually a player with the given name if (CPlayerCoreFactory::GetInstance().GetPlayerType(playername).empty()) return InvalidParams; // check if the player can handle at least the first item in the list std::vector<std::string> possiblePlayers; CPlayerCoreFactory::GetInstance().GetPlayers(*list.Get(0).get(), possiblePlayers); bool match = false; for (auto entry : possiblePlayers) { if (StringUtils::CompareNoCase(entry, playername)) { match = true; break; } } if (!match) return InvalidParams; } } else return InvalidParams; } // Handle "shuffled" option if (optionShuffled.isBoolean()) list.SetProperty("shuffled", optionShuffled); // Handle "repeat" option if (!optionRepeat.isNull()) list.SetProperty("repeat", ParseRepeatState(optionRepeat)); // Handle "resume" option if (list.Size() == 1) { if (optionResume.isBoolean() && optionResume.asBoolean()) list[0]->m_lStartOffset = STARTOFFSET_RESUME; else if (optionResume.isDouble()) list[0]->SetProperty("StartPercent", optionResume); else if (optionResume.isObject()) list[0]->m_lStartOffset = (int)(ParseTimeInSeconds(optionResume) * 75.0); } auto l = new CFileItemList(); //don't delete l->Copy(list); CApplicationMessenger::GetInstance().SendMsg(TMSG_MEDIA_PLAY, -1, -1, static_cast<void*>(l), playername); } return ACK; } else return InvalidParams; } return InvalidParams; } JSONRPC_STATUS CPlayerOperations::GoTo(const std::string &method, ITransportLayer *transport, IClient *client, const CVariant &parameterObject, CVariant &result) { CVariant to = parameterObject["to"]; switch (GetPlayer(parameterObject["playerid"])) { case Video: case Audio: if (to.isString()) { std::string strTo = to.asString(); int actionID; if (strTo == "previous") actionID = ACTION_PREV_ITEM; else if (strTo == "next") actionID = ACTION_NEXT_ITEM; else return InvalidParams; CApplicationMessenger::GetInstance().SendMsg(TMSG_GUI_ACTION, WINDOW_INVALID, -1, static_cast<void*>(new CAction(actionID))); } else if (to.isInteger()) { if (IsPVRChannel()) CApplicationMessenger::GetInstance().SendMsg(TMSG_GUI_ACTION, WINDOW_INVALID, -1, static_cast<void*>( new CAction(ACTION_CHANNEL_SWITCH, static_cast<float>(to.asInteger())))); else CApplicationMessenger::GetInstance().SendMsg(TMSG_PLAYLISTPLAYER_PLAY, static_cast<int>(to.asInteger())); } else return InvalidParams; break; case Picture: if (to.isString()) { std::string strTo = to.asString(); int actionID; if (strTo == "previous") actionID = ACTION_PREV_PICTURE; else if (strTo == "next") actionID = ACTION_NEXT_PICTURE; else return InvalidParams; SendSlideshowAction(actionID); } else return FailedToExecute; break; case None: default: return FailedToExecute; } OnPlaylistChanged(); return ACK; } JSONRPC_STATUS CPlayerOperations::SetShuffle(const std::string &method, ITransportLayer *transport, IClient *client, const CVariant &parameterObject, CVariant &result) { CGUIWindowSlideShow *slideshow = NULL; CVariant shuffle = parameterObject["shuffle"]; switch (GetPlayer(parameterObject["playerid"])) { case Video: case Audio: { if (IsPVRChannel()) return FailedToExecute; int playlistid = GetPlaylist(GetPlayer(parameterObject["playerid"])); if (g_playlistPlayer.IsShuffled(playlistid)) { if ((shuffle.isBoolean() && !shuffle.asBoolean()) || (shuffle.isString() && shuffle.asString() == "toggle")) { CApplicationMessenger::GetInstance().SendMsg(TMSG_PLAYLISTPLAYER_SHUFFLE, playlistid, 0); OnPlaylistChanged(); } } else { if ((shuffle.isBoolean() && shuffle.asBoolean()) || (shuffle.isString() && shuffle.asString() == "toggle")) { CApplicationMessenger::GetInstance().SendMsg(TMSG_PLAYLISTPLAYER_SHUFFLE, playlistid, 1); OnPlaylistChanged(); } } break; } case Picture: slideshow = (CGUIWindowSlideShow*)g_windowManager.GetWindow(WINDOW_SLIDESHOW); if (slideshow == NULL) return FailedToExecute; if (slideshow->IsShuffled()) { if ((shuffle.isBoolean() && !shuffle.asBoolean()) || (shuffle.isString() && shuffle.asString() == "toggle")) return FailedToExecute; } else { if ((shuffle.isBoolean() && shuffle.asBoolean()) || (shuffle.isString() && shuffle.asString() == "toggle")) slideshow->Shuffle(); } break; default: return FailedToExecute; } return ACK; } JSONRPC_STATUS CPlayerOperations::SetRepeat(const std::string &method, ITransportLayer *transport, IClient *client, const CVariant &parameterObject, CVariant &result) { switch (GetPlayer(parameterObject["playerid"])) { case Video: case Audio: { if (IsPVRChannel()) return FailedToExecute; REPEAT_STATE repeat = REPEAT_NONE; int playlistid = GetPlaylist(GetPlayer(parameterObject["playerid"])); if (parameterObject["repeat"].asString() == "cycle") { REPEAT_STATE repeatPrev = g_playlistPlayer.GetRepeat(playlistid); if (repeatPrev == REPEAT_NONE) repeat = REPEAT_ALL; else if (repeatPrev == REPEAT_ALL) repeat = REPEAT_ONE; else repeat = REPEAT_NONE; } else repeat = (REPEAT_STATE)ParseRepeatState(parameterObject["repeat"]); CApplicationMessenger::GetInstance().SendMsg(TMSG_PLAYLISTPLAYER_REPEAT, playlistid, repeat); OnPlaylistChanged(); break; } case Picture: default: return FailedToExecute; } return ACK; } JSONRPC_STATUS CPlayerOperations::SetPartymode(const std::string &method, ITransportLayer *transport, IClient *client, const CVariant &parameterObject, CVariant &result) { PlayerType player = GetPlayer(parameterObject["playerid"]); switch (player) { case Video: case Audio: { if (IsPVRChannel()) return FailedToExecute; bool change = false; PartyModeContext context = PARTYMODECONTEXT_UNKNOWN; std::string strContext; if (player == Video) { context = PARTYMODECONTEXT_VIDEO; strContext = "video"; } else if (player == Audio) { context = PARTYMODECONTEXT_MUSIC; strContext = "music"; } bool toggle = parameterObject["partymode"].isString(); if (g_partyModeManager.IsEnabled()) { if (g_partyModeManager.GetType() != context) return InvalidParams; if (toggle || parameterObject["partymode"].asBoolean() == false) change = true; } else { if (toggle || parameterObject["partymode"].asBoolean() == true) change = true; } if (change) CApplicationMessenger::GetInstance().SendMsg(TMSG_EXECUTE_BUILT_IN, -1, -1, nullptr, "playercontrol(partymode(" + strContext + "))"); break; } case Picture: default: return FailedToExecute; } return ACK; } JSONRPC_STATUS CPlayerOperations::SetAudioStream(const std::string &method, ITransportLayer *transport, IClient *client, const CVariant &parameterObject, CVariant &result) { switch (GetPlayer(parameterObject["playerid"])) { case Video: if (g_application.m_pPlayer->HasPlayer()) { int index = -1; if (parameterObject["stream"].isString()) { std::string action = parameterObject["stream"].asString(); if (action.compare("previous") == 0) { index = g_application.m_pPlayer->GetAudioStream() - 1; if (index < 0) index = g_application.m_pPlayer->GetAudioStreamCount() - 1; } else if (action.compare("next") == 0) { index = g_application.m_pPlayer->GetAudioStream() + 1; if (index >= g_application.m_pPlayer->GetAudioStreamCount()) index = 0; } else return InvalidParams; } else if (parameterObject["stream"].isInteger()) index = (int)parameterObject["stream"].asInteger(); if (index < 0 || g_application.m_pPlayer->GetAudioStreamCount() <= index) return InvalidParams; g_application.m_pPlayer->SetAudioStream(index); } else return FailedToExecute; break; case Audio: case Picture: default: return FailedToExecute; } return ACK; } JSONRPC_STATUS CPlayerOperations::SetSubtitle(const std::string &method, ITransportLayer *transport, IClient *client, const CVariant &parameterObject, CVariant &result) { switch (GetPlayer(parameterObject["playerid"])) { case Video: if (g_application.m_pPlayer->HasPlayer()) { int index = -1; if (parameterObject["subtitle"].isString()) { std::string action = parameterObject["subtitle"].asString(); if (action.compare("previous") == 0) { index = g_application.m_pPlayer->GetSubtitle() - 1; if (index < 0) index = g_application.m_pPlayer->GetSubtitleCount() - 1; } else if (action.compare("next") == 0) { index = g_application.m_pPlayer->GetSubtitle() + 1; if (index >= g_application.m_pPlayer->GetSubtitleCount()) index = 0; } else if (action.compare("off") == 0) { g_application.m_pPlayer->SetSubtitleVisible(false); return ACK; } else if (action.compare("on") == 0) { g_application.m_pPlayer->SetSubtitleVisible(true); return ACK; } else return InvalidParams; } else if (parameterObject["subtitle"].isInteger()) index = (int)parameterObject["subtitle"].asInteger(); if (index < 0 || g_application.m_pPlayer->GetSubtitleCount() <= index) return InvalidParams; g_application.m_pPlayer->SetSubtitle(index); // Check if we need to enable subtitles to be displayed if (parameterObject["enable"].asBoolean() && !g_application.m_pPlayer->GetSubtitleVisible()) g_application.m_pPlayer->SetSubtitleVisible(true); } else return FailedToExecute; break; case Audio: case Picture: default: return FailedToExecute; } return ACK; } JSONRPC_STATUS CPlayerOperations::SetVideoStream(const std::string &method, ITransportLayer *transport, IClient *client, const CVariant &parameterObject, CVariant &result) { switch (GetPlayer(parameterObject["playerid"])) { case Video: { int streamCount = g_application.m_pPlayer->GetVideoStreamCount(); if (streamCount > 0) { int index = g_application.m_pPlayer->GetVideoStream(); if (parameterObject["stream"].isString()) { std::string action = parameterObject["stream"].asString(); if (action.compare("previous") == 0) { index--; if (index < 0) index = streamCount - 1; } else if (action.compare("next") == 0) { index++; if (index >= streamCount) index = 0; } else return InvalidParams; } else if (parameterObject["stream"].isInteger()) index = (int)parameterObject["stream"].asInteger(); if (index < 0 || streamCount <= index) return InvalidParams; g_application.m_pPlayer->SetVideoStream(index); } else return FailedToExecute; break; } case Audio: case Picture: default: return FailedToExecute; } return ACK; } int CPlayerOperations::GetActivePlayers() { int activePlayers = 0; if (g_application.m_pPlayer->IsPlayingVideo() || g_PVRManager.IsPlayingTV() || g_PVRManager.IsPlayingRecording()) activePlayers |= Video; if (g_application.m_pPlayer->IsPlayingAudio() || g_PVRManager.IsPlayingRadio()) activePlayers |= Audio; if (g_windowManager.IsWindowActive(WINDOW_SLIDESHOW)) activePlayers |= Picture; return activePlayers; } PlayerType CPlayerOperations::GetPlayer(const CVariant &player) { int iPlayer = (int)player.asInteger(); PlayerType playerID; switch (iPlayer) { case PLAYLIST_VIDEO: playerID = Video; break; case PLAYLIST_MUSIC: playerID = Audio; break; case PLAYLIST_PICTURE: playerID = Picture; break; default: playerID = None; break; } if (GetPlaylist(playerID) == iPlayer) return playerID; else return None; } int CPlayerOperations::GetPlaylist(PlayerType player) { int playlist = g_playlistPlayer.GetCurrentPlaylist(); if (playlist == PLAYLIST_NONE) // No active playlist, try guessing playlist = g_application.m_pPlayer->GetPreferredPlaylist(); switch (player) { case Video: return playlist == PLAYLIST_NONE ? PLAYLIST_VIDEO : playlist; case Audio: return playlist == PLAYLIST_NONE ? PLAYLIST_MUSIC : playlist; case Picture: return PLAYLIST_PICTURE; default: return playlist; } } JSONRPC_STATUS CPlayerOperations::StartSlideshow(const std::string& path, bool recursive, bool random, const std::string &firstPicturePath /* = "" */) { int flags = 0; if (recursive) flags |= 1; if (random) flags |= 2; else flags |= 4; std::vector<std::string> params; params.push_back(path); if (!firstPicturePath.empty()) params.push_back(firstPicturePath); // Reset screensaver when started from JSON only to avoid potential conflict with slideshow screensavers g_application.ResetScreenSaver(); g_application.WakeUpScreenSaverAndDPMS(); CGUIMessage msg(GUI_MSG_START_SLIDESHOW, 0, 0, flags); msg.SetStringParams(params); CApplicationMessenger::GetInstance().SendGUIMessage(msg, WINDOW_SLIDESHOW); return ACK; } void CPlayerOperations::SendSlideshowAction(int actionID) { CApplicationMessenger::GetInstance().SendMsg(TMSG_GUI_ACTION, WINDOW_SLIDESHOW, -1, static_cast<void*>(new CAction(actionID))); } void CPlayerOperations::OnPlaylistChanged() { CGUIMessage msg(GUI_MSG_PLAYLIST_CHANGED, 0, 0); g_windowManager.SendThreadMessage(msg); } JSONRPC_STATUS CPlayerOperations::GetPropertyValue(PlayerType player, const std::string &property, CVariant &result) { if (player == None) return FailedToExecute; int playlist = GetPlaylist(player); if (property == "type") { switch (player) { case Video: result = "video"; break; case Audio: result = "audio"; break; case Picture: result = "picture"; break; default: return FailedToExecute; } } else if (property == "partymode") { switch (player) { case Video: case Audio: if (IsPVRChannel()) { result = false; break; } result = g_partyModeManager.IsEnabled(); break; case Picture: result = false; break; default: return FailedToExecute; } } else if (property == "speed") { CGUIWindowSlideShow *slideshow = NULL; switch (player) { case Video: case Audio: result = g_application.m_pPlayer->IsPausedPlayback() ? 0 : (int)lrint(g_application.m_pPlayer->GetPlaySpeed()); break; case Picture: slideshow = (CGUIWindowSlideShow*)g_windowManager.GetWindow(WINDOW_SLIDESHOW); if (slideshow && slideshow->IsPlaying() && !slideshow->IsPaused()) result = slideshow->GetDirection(); else result = 0; break; default: return FailedToExecute; } } else if (property == "time") { switch (player) { case Video: case Audio: { int ms = 0; if (!IsPVRChannel()) ms = (int)(g_application.GetTime() * 1000.0); else { EPG::CEpgInfoTagPtr epg(GetCurrentEpg()); if (epg) ms = epg->Progress() * 1000; } MillisecondsToTimeObject(ms, result); break; } case Picture: MillisecondsToTimeObject(0, result); break; default: return FailedToExecute; } } else if (property == "percentage") { CGUIWindowSlideShow *slideshow = NULL; switch (player) { case Video: case Audio: { if (!IsPVRChannel()) result = g_application.GetPercentage(); else { EPG::CEpgInfoTagPtr epg(GetCurrentEpg()); if (epg) result = epg->ProgressPercentage(); else result = 0; } break; } case Picture: slideshow = (CGUIWindowSlideShow*)g_windowManager.GetWindow(WINDOW_SLIDESHOW); if (slideshow && slideshow->NumSlides() > 0) result = (double)slideshow->CurrentSlide() / slideshow->NumSlides(); else result = 0.0; break; default: return FailedToExecute; } } else if (property == "totaltime") { switch (player) { case Video: case Audio: { int ms = 0; if (!IsPVRChannel()) ms = (int)(g_application.GetTotalTime() * 1000.0); else { EPG::CEpgInfoTagPtr epg(GetCurrentEpg()); if (epg) ms = epg->GetDuration() * 1000; } MillisecondsToTimeObject(ms, result); break; } case Picture: MillisecondsToTimeObject(0, result); break; default: return FailedToExecute; } } else if (property == "playlistid") { result = playlist; } else if (property == "position") { CGUIWindowSlideShow *slideshow = NULL; switch (player) { case Video: case Audio: /* Return the position of current item if there is an active playlist */ if (!IsPVRChannel() && g_playlistPlayer.GetCurrentPlaylist() == playlist) result = g_playlistPlayer.GetCurrentSong(); else result = -1; break; case Picture: slideshow = (CGUIWindowSlideShow*)g_windowManager.GetWindow(WINDOW_SLIDESHOW); if (slideshow && slideshow->IsPlaying()) result = slideshow->CurrentSlide() - 1; else result = -1; break; default: result = -1; break; } } else if (property == "repeat") { switch (player) { case Video: case Audio: if (IsPVRChannel()) { result = "off"; break; } switch (g_playlistPlayer.GetRepeat(playlist)) { case REPEAT_ONE: result = "one"; break; case REPEAT_ALL: result = "all"; break; default: result = "off"; break; } break; case Picture: default: result = "off"; break; } } else if (property == "shuffled") { CGUIWindowSlideShow *slideshow = NULL; switch (player) { case Video: case Audio: if (IsPVRChannel()) { result = false; break; } result = g_playlistPlayer.IsShuffled(playlist); break; case Picture: slideshow = (CGUIWindowSlideShow*)g_windowManager.GetWindow(WINDOW_SLIDESHOW); if (slideshow && slideshow->IsPlaying()) result = slideshow->IsShuffled(); else result = -1; break; default: result = -1; break; } } else if (property == "canseek") { switch (player) { case Video: case Audio: result = g_application.m_pPlayer->CanSeek(); break; case Picture: default: result = false; break; } } else if (property == "canchangespeed") { switch (player) { case Video: case Audio: result = !IsPVRChannel(); break; case Picture: default: result = false; break; } } else if (property == "canmove") { switch (player) { case Picture: result = true; break; case Video: case Audio: default: result = false; break; } } else if (property == "canzoom") { switch (player) { case Picture: result = true; break; case Video: case Audio: default: result = false; break; } } else if (property == "canrotate") { switch (player) { case Picture: result = true; break; case Video: case Audio: default: result = false; break; } } else if (property == "canshuffle") { switch (player) { case Video: case Audio: case Picture: result = !IsPVRChannel(); break; default: result = false; break; } } else if (property == "canrepeat") { switch (player) { case Video: case Audio: result = !IsPVRChannel(); break; case Picture: default: result = false; break; } } else if (property == "currentaudiostream") { switch (player) { case Video: case Audio: if (g_application.m_pPlayer->HasPlayer()) { result = CVariant(CVariant::VariantTypeObject); int index = g_application.m_pPlayer->GetAudioStream(); if (index >= 0) { SPlayerAudioStreamInfo info; g_application.m_pPlayer->GetAudioStreamInfo(index, info); result["index"] = index; result["name"] = info.name; result["language"] = info.language; result["codec"] = info.audioCodecName; result["bitrate"] = info.bitrate; result["channels"] = info.channels; } } else result = CVariant(CVariant::VariantTypeNull); break; case Picture: default: result = CVariant(CVariant::VariantTypeNull); break; } } else if (property == "audiostreams") { result = CVariant(CVariant::VariantTypeArray); switch (player) { case Video: if (g_application.m_pPlayer->HasPlayer()) { for (int index = 0; index < g_application.m_pPlayer->GetAudioStreamCount(); index++) { SPlayerAudioStreamInfo info; g_application.m_pPlayer->GetAudioStreamInfo(index, info); CVariant audioStream(CVariant::VariantTypeObject); audioStream["index"] = index; audioStream["name"] = info.name; audioStream["language"] = info.language; audioStream["codec"] = info.audioCodecName; audioStream["bitrate"] = info.bitrate; audioStream["channels"] = info.channels; result.append(audioStream); } } break; case Audio: case Picture: default: break; } } else if (property == "currentvideostream") { switch (player) { case Video: { int index = g_application.m_pPlayer->GetVideoStream(); if (index >= 0) { result = CVariant(CVariant::VariantTypeObject); SPlayerVideoStreamInfo info; g_application.m_pPlayer->GetVideoStreamInfo(index, info); result["index"] = index; result["name"] = info.name; result["language"] = info.language; result["codec"] = info.videoCodecName; result["width"] = info.width; result["height"] = info.height; } else result = CVariant(CVariant::VariantTypeNull); break; } case Audio: case Picture: default: result = CVariant(CVariant::VariantTypeNull); break; } } else if (property == "videostreams") { result = CVariant(CVariant::VariantTypeArray); switch (player) { case Video: { int streamCount = g_application.m_pPlayer->GetVideoStreamCount(); if (streamCount >= 0) { for (int index = 0; index < streamCount; ++index) { SPlayerVideoStreamInfo info; g_application.m_pPlayer->GetVideoStreamInfo(index, info); CVariant videoStream(CVariant::VariantTypeObject); videoStream["index"] = index; videoStream["name"] = info.name; videoStream["language"] = info.language; videoStream["codec"] = info.videoCodecName; videoStream["width"] = info.width; videoStream["height"] = info.height; result.append(videoStream); } } break; } case Audio: case Picture: default: break; } } else if (property == "subtitleenabled") { switch (player) { case Video: result = g_application.m_pPlayer->GetSubtitleVisible(); break; case Audio: case Picture: default: result = false; break; } } else if (property == "currentsubtitle") { switch (player) { case Video: if (g_application.m_pPlayer->HasPlayer()) { result = CVariant(CVariant::VariantTypeObject); int index = g_application.m_pPlayer->GetSubtitle(); if (index >= 0) { SPlayerSubtitleStreamInfo info; g_application.m_pPlayer->GetSubtitleStreamInfo(index, info); result["index"] = index; result["name"] = info.name; result["language"] = info.language; } } else result = CVariant(CVariant::VariantTypeNull); break; case Audio: case Picture: default: result = CVariant(CVariant::VariantTypeNull); break; } } else if (property == "subtitles") { result = CVariant(CVariant::VariantTypeArray); switch (player) { case Video: if (g_application.m_pPlayer->HasPlayer()) { for (int index = 0; index < g_application.m_pPlayer->GetSubtitleCount(); index++) { SPlayerSubtitleStreamInfo info; g_application.m_pPlayer->GetSubtitleStreamInfo(index, info); CVariant subtitle(CVariant::VariantTypeObject); subtitle["index"] = index; subtitle["name"] = info.name; subtitle["language"] = info.language; result.append(subtitle); } } break; case Audio: case Picture: default: break; } } else if (property == "live") result = IsPVRChannel(); else return InvalidParams; return OK; } int CPlayerOperations::ParseRepeatState(const CVariant &repeat) { REPEAT_STATE state = REPEAT_NONE; std::string strState = repeat.asString(); if (strState.compare("one") == 0) state = REPEAT_ONE; else if (strState.compare("all") == 0) state = REPEAT_ALL; return state; } double CPlayerOperations::ParseTimeInSeconds(const CVariant &time) { double seconds = 0.0; if (time.isObject()) { if (time.isMember("hours")) seconds += time["hours"].asInteger() * 60 * 60; if (time.isMember("minutes")) seconds += time["minutes"].asInteger() * 60; if (time.isMember("seconds")) seconds += time["seconds"].asInteger(); if (time.isMember("milliseconds")) seconds += time["milliseconds"].asDouble() / 1000.0; } return seconds; } bool CPlayerOperations::IsPVRChannel() { return g_PVRManager.IsPlayingTV() || g_PVRManager.IsPlayingRadio(); } EPG::CEpgInfoTagPtr CPlayerOperations::GetCurrentEpg() { if (!g_PVRManager.IsPlayingTV() && !g_PVRManager.IsPlayingRadio()) return EPG::CEpgInfoTagPtr(); CPVRChannelPtr currentChannel(g_PVRManager.GetCurrentChannel()); if (!currentChannel) return EPG::CEpgInfoTagPtr(); return currentChannel->GetEPGNow(); }
gpl-2.0
jpschewe/fll-sw
src/main/java/fll/scheduler/PerformanceRoundsEditor.java
2233
/* * Copyright (c) 2016 High Tech Kids. All rights reserved * HighTechKids is on the web at: http://www.hightechkids.org * This code is released under GPL; see LICENSE.txt for details. */ package fll.scheduler; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.time.LocalTime; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JTable; import org.checkerframework.checker.nullness.qual.Nullable; /** * Edit a list of performance start round limits. */ /* package */ class PerformanceRoundsEditor extends JComponent { private final PerformanceRoundsModel tableModel; private final JTable table; PerformanceRoundsEditor() { super(); setLayout(new BorderLayout()); setBorder(BorderFactory.createTitledBorder("Performance Rounds")); this.setToolTipText("Define the number of rounds and the earliest start time for each round."); tableModel = new PerformanceRoundsModel(); table = new JTable(this.tableModel); table.setDefaultEditor(LocalTime.class, new ScheduleTimeCellEditor(true)); table.setDefaultEditor(Integer.class, new IntegerCellEditor(1, 1000)); final JPanel buttonPanel = new JPanel(new FlowLayout()); final JButton addButton = new JButton("Add Round"); buttonPanel.add(addButton); addButton.addActionListener(e -> { tableModel.addRound(); }); final JButton removeButton = new JButton("Remove Last Round"); buttonPanel.add(removeButton); removeButton.addActionListener(e -> { tableModel.removeLastRound(); }); add(buttonPanel, BorderLayout.SOUTH); add(table, BorderLayout.CENTER); add(table.getTableHeader(), BorderLayout.NORTH); } /** * The rounds for the tournament. * * @param v a list of earliest start times for each round, the indeex * is the round, each value may be null meaning no limit */ public void setRounds(final List<@Nullable LocalTime> v) { this.tableModel.setData(v); } /** * @return unmodifiable map of the limits. */ public List<@Nullable LocalTime> getLimits() { return this.tableModel.getData(); } }
gpl-2.0
heros/LasCore
src/server/scripts/Northrend/isle_of_conquest.cpp
2710
/* * Copyright (C) 2013 LasCore <http://lascore.makeforum.eu/> * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "PassiveAI.h" #include "BattlegroundIC.h" #include "Player.h" // TO-DO: This should be done with SmartAI, but yet it does not correctly support vehicles's AIs. // Even adding ReactState Passive we still have issues using SmartAI. class npc_four_car_garage : public CreatureScript { public: npc_four_car_garage() : CreatureScript("npc_four_car_garage") {} struct npc_four_car_garageAI : public NullCreatureAI { npc_four_car_garageAI(Creature* creature) : NullCreatureAI(creature) { } void PassengerBoarded(Unit* who, int8 /*seatId*/, bool apply) { if (apply) { uint32 spellId = 0; switch (me->GetEntry()) { case NPC_DEMOLISHER: spellId = SPELL_DRIVING_CREDIT_DEMOLISHER; break; case NPC_GLAIVE_THROWER_A: case NPC_GLAIVE_THROWER_H: spellId = SPELL_DRIVING_CREDIT_GLAIVE; break; case NPC_SIEGE_ENGINE_H: case NPC_SIEGE_ENGINE_A: spellId = SPELL_DRIVING_CREDIT_SIEGE; break; case NPC_CATAPULT: spellId = SPELL_DRIVING_CREDIT_CATAPULT; break; default: return; } me->CastSpell(who, spellId, true); } } }; CreatureAI* GetAI(Creature* creature) const { return new npc_four_car_garageAI(creature); } }; void AddSC_isle_of_conquest() { new npc_four_car_garage(); }
gpl-2.0
openjdk/jdk7u
jdk/src/share/classes/sun/security/ec/ECDSAOperations.java
7994
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.security.ec; import sun.security.ec.point.*; import sun.security.util.ArrayUtil; import sun.security.util.Function; import sun.security.util.Optional; import sun.security.util.math.*; import static sun.security.ec.ECOperations.IntermediateValueException; import java.security.ProviderException; import java.security.spec.*; public class ECDSAOperations { public static class Seed { private final byte[] seedValue; public Seed(byte[] seedValue) { this.seedValue = seedValue; } public byte[] getSeedValue() { return seedValue; } } public static class Nonce { private final byte[] nonceValue; public Nonce(byte[] nonceValue) { this.nonceValue = nonceValue; } public byte[] getNonceValue() { return nonceValue; } } private final ECOperations ecOps; private final AffinePoint basePoint; public ECDSAOperations(ECOperations ecOps, ECPoint basePoint) { this.ecOps = ecOps; this.basePoint = toAffinePoint(basePoint, ecOps.getField()); } public ECOperations getEcOperations() { return ecOps; } public AffinePoint basePointMultiply(byte[] scalar) { return ecOps.multiply(basePoint, scalar).asAffine(); } public static AffinePoint toAffinePoint(ECPoint point, IntegerFieldModuloP field) { ImmutableIntegerModuloP affineX = field.getElement(point.getAffineX()); ImmutableIntegerModuloP affineY = field.getElement(point.getAffineY()); return new AffinePoint(affineX, affineY); } public static Optional<ECDSAOperations> forParameters(final ECParameterSpec ecParams) { Optional<ECOperations> curveOps = ECOperations.forParameters(ecParams); return curveOps.map(new Function<ECOperations, ECDSAOperations>() { @Override public ECDSAOperations apply(ECOperations ops) { return new ECDSAOperations(ops, ecParams.getGenerator()); } }); } /** * * Sign a digest using the provided private key and seed. * IMPORTANT: The private key is a scalar represented using a * little-endian byte array. This is backwards from the conventional * representation in ECDSA. The routines that produce and consume this * value uses little-endian, so this deviation from convention removes * the requirement to swap the byte order. The returned signature is in * the conventional byte order. * * @param privateKey the private key scalar as a little-endian byte array * @param digest the digest to be signed * @param seed the seed that will be used to produce the nonce. This object * should contain an array that is at least 64 bits longer than * the number of bits required to represent the group order. * @return the ECDSA signature value * @throws IntermediateValueException if the signature cannot be produced * due to an unacceptable intermediate or final value. If this * exception is thrown, then the caller should discard the nonnce and * try again with an entirely new nonce value. */ public byte[] signDigest(byte[] privateKey, byte[] digest, Seed seed) throws IntermediateValueException { byte[] nonceArr = ecOps.seedToScalar(seed.getSeedValue()); Nonce nonce = new Nonce(nonceArr); return signDigest(privateKey, digest, nonce); } /** * * Sign a digest using the provided private key and nonce. * IMPORTANT: The private key and nonce are scalars represented by a * little-endian byte array. This is backwards from the conventional * representation in ECDSA. The routines that produce and consume these * values use little-endian, so this deviation from convention removes * the requirement to swap the byte order. The returned signature is in * the conventional byte order. * * @param privateKey the private key scalar as a little-endian byte array * @param digest the digest to be signed * @param nonce the nonce object containing a little-endian scalar value. * @return the ECDSA signature value * @throws IntermediateValueException if the signature cannot be produced * due to an unacceptable intermediate or final value. If this * exception is thrown, then the caller should discard the nonnce and * try again with an entirely new nonce value. */ public byte[] signDigest(byte[] privateKey, byte[] digest, Nonce nonce) throws IntermediateValueException { IntegerFieldModuloP orderField = ecOps.getOrderField(); int orderBits = orderField.getSize().bitLength(); if (orderBits % 8 != 0 && orderBits < digest.length * 8) { // This implementation does not support truncating digests to // a length that is not a multiple of 8. throw new ProviderException("Invalid digest length"); } byte[] k = nonce.getNonceValue(); // check nonce length int length = (orderField.getSize().bitLength() + 7) / 8; if (k.length != length) { throw new ProviderException("Incorrect nonce length"); } MutablePoint R = ecOps.multiply(basePoint, k); IntegerModuloP r = R.asAffine().getX(); // put r into the correct field by fully reducing to an array byte[] temp = new byte[length]; r.asByteArray(temp); r = orderField.getElement(temp); // store r in result r.asByteArray(temp); byte[] result = new byte[2 * length]; ArrayUtil.reverse(temp); System.arraycopy(temp, 0, result, 0, length); // compare r to 0 if (ECOperations.allZero(temp)) { throw new IntermediateValueException(); } IntegerModuloP dU = orderField.getElement(privateKey); int lengthE = Math.min(length, digest.length); byte[] E = new byte[lengthE]; System.arraycopy(digest, 0, E, 0, lengthE); ArrayUtil.reverse(E); IntegerModuloP e = orderField.getElement(E); IntegerModuloP kElem = orderField.getElement(k); IntegerModuloP kInv = kElem.multiplicativeInverse(); MutableIntegerModuloP s = r.mutable(); s.setProduct(dU).setSum(e).setProduct(kInv); // store s in result s.asByteArray(temp); ArrayUtil.reverse(temp); System.arraycopy(temp, 0, result, length, length); // compare s to 0 if (ECOperations.allZero(temp)) { throw new IntermediateValueException(); } return result; } }
gpl-2.0
jolay/intelisis3
sites/all/modules/acquia/modules/ac_portfolio/theme/node--portfolio-teaser.tpl.php
1384
<section<?php print drupal_attributes($attributes_array); ?>> <div class='s-i'> <div class="<?php print $media_classes?>"> <?php print $media; ?> </div> <div class="<?php print $desc_classes?>"> <div class="item-i"> <?php if (!empty($title_prefix) || !empty($title_suffix) || !$page): ?> <header> <?php print render($title_prefix); ?> <?php if (!$page): ?> <h3<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>" rel="bookmark"><?php print $title; ?></a></h3> <?php endif; ?> <?php print render($title_suffix); ?> </header> <?php endif; ?> <div class="node-meta"> <div class='meta'> <?php if ($display_submitted && $date): ?> <?php print $date?> <span class='sep'></span> <?php endif; ?> <?php if (isset($content[AC_PORTFOLIO_FIELD])): ?> <?php print render($content[AC_PORTFOLIO_FIELD]) ?> <?php endif; ?> </div> </div> <!--Meta--> <div class="project-excerpt"><?php print render($excerpt);?></div> </div> </div> <?php if (isset($read_more)):?> <div class='meta read_more'> <?php print $read_more?> </div> <?php endif;?> <!--Links--> </div> </section>
gpl-2.0
jamielaff/als_resourcing
tmp/install_55cb054400b98/jsjobs/site/views/employer/tmpl/controlpanel.php
14202
<?php /** * @Copyright Copyright (C) 2009-2011 * @license GNU/GPL http://www.gnu.org/copyleft/gpl.html + Created by: Ahmad Bilal * Company: Buruj Solutions + Contact: www.burujsolutions.com , ahmad@burujsolutions.com * Created on: Jan 11, 2009 ^ + Project: JS Jobs * File Name: views/employer/tmpl/controlpanel.php ^ * Description: template view for control panel ^ * History: NONE ^ */ defined('_JEXEC') or die('Restricted access'); ?> <div id="jsjobs_main"> <div id="js_menu_wrapper"> <?php if (sizeof($this->jobseekerlinks) != 0){ foreach($this->jobseekerlinks as $lnk){ ?> <a class="js_menu_link <?php if($lnk[2] == 'controlpanel') echo 'selected'; ?>" href="<?php echo $lnk[0]; ?>"><?php echo $lnk[1]; ?></a> <?php } } if (sizeof($this->employerlinks) != 0){ foreach($this->employerlinks as $lnk) { ?> <a class="js_menu_link <?php if($lnk[2] == 'controlpanel') echo 'selected'; ?>" href="<?php echo $lnk[0]; ?>"><?php echo $lnk[1]; ?></a> <?php } } ?> </div> <?php if ($this->config['offline'] == '1'){ ?> <div class="js_job_error_messages_wrapper"> <div class="js_job_messages_image_wrapper"> <img class="js_job_messages_image" src="components/com_jsjobs/images/7.png"/> </div> <div class="js_job_messages_data_wrapper"> <span class="js_job_messages_main_text"> <?php echo JText::_('JS_JOBS_OFFLINE_MODE'); ?> </span> <span class="js_job_messages_block_text"> <?php echo $this->config['offline_text']; ?> </span> </div> </div> <?php }else{ ?> <?php $userrole = $this->userrole; $config = $this->config; $emcontrolpanel = $this->emcontrolpanel; if (isset($userrole->rolefor)){ if ($userrole->rolefor == 1) // employer $allowed = true; else $allowed = false; }else { if ($config['visitorview_emp_conrolpanel'] == 1) $allowed = true; else $allowed = false; } // user not logined if ($allowed == true) { ?> <div id="js_main_wrapper"> <span class="js_controlpanel_section_title"><?php echo JText::_('JS_MY_STUFF');?></span> <?php $print = checkLinks('formcompany',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=company&view=company&layout=formcompany&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/addcompany.png" alt="New Company" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_NEW_COMPANY'); ?></span> </div> </a> <?php } $print = checkLinks('mycompanies',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=company&view=company&layout=mycompanies&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/mycompanies.png" alt="My Companies" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_MY_COMPANIES');?></span> </div> </a> <?php } $print = checkLinks('formjob',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=job&view=job&layout=formjob&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/addjob.png" alt="New Job" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_NEW_JOB');?></span> </div> </a> <?php } $print = checkLinks('myjobs',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=job&view=job&layout=myjobs&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/myjobs.png" alt="My Jobs" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_MY_JOBS');?></span> </div> </a> <?php } $print = checkLinks('formdepartment',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=department&view=department&layout=formdepartment&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/adddepartment.png" alt="Form Department" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_NEW_DEPARTMENT');?></span> </div> </a> <?php } $print = checkLinks('mydepartment',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=department&view=department&layout=mydepartments&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/mydepartments.png" alt="My Department" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_MY_DEPARTMENTS');?></span> </div> </a> <?php } if($emcontrolpanel['emploginlogout'] == 1){ if(isset($userrole->rolefor)){//jobseeker $link = "index.php?option=com_users&c=users&task=logout&Itemid=".$this->Itemid; $text = JText::_('JS_LOGOUT'); $icon = "logout.png"; }else{ $redirectUrl = JRoute::_('index.php?option=com_jsjobs&c=jobseeker&view=jobseeker&layout=controlpanel&Itemid='.$this->Itemid); $redirectUrl = '&amp;return=' . $this->getJSModel('common')->b64ForEncode($redirectUrl); $link = 'index.php?option=com_users&view=login' . $redirectUrl; $text = JText::_('JS_LOGIN'); $icon = "login.png"; } ?> <a class="js_controlpanel_link" href="<?php echo $link; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/<?php echo $icon;?>" alt="Messages" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo $text; ?></span> </div> </a> <?php } ?> <span class="js_controlpanel_section_title"><?php echo JText::_('JS_RESUMES');?></span> <?php $print = checkLinks('resumesearch',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=resume&view=resume&layout=resumesearch&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/resumesearch.png" alt="Search Resume" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_SEARCH_RESUME'); ?></span> </div> </a> <?php } $print = checkLinks('resumesearch',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=resume&view=resume&layout=my_resumesearches&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/resumesavesearch.png" alt="Search Resume" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_RESUME_SAVE_SEARCHES'); ?></span> </div> </a> <?php } $print = checkLinks('resumesearch',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=resume&view=resume&layout=resumebycategory&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/resumebycat.png" alt=" Resume By Category" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_RESUME_BY_CATEGORY'); ?></span> </div> </a> <?php } ?> <span class="js_controlpanel_section_title"><?php echo JText::_('JS_STATISTICS');?></span> <?php $print = checkLinks('packages',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=employerpackages&view=employerpackages&layout=packages&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/packages.png" alt=" Packages" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_PACKAGES'); ?></span> </div> </a> <?php } $print = checkLinks('purchasehistory',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=purchasehistory&view=purchasehistory&layout=employerpurchasehistory&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/purchase_history.png" alt=" Employer Purchase History" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_PURCHASE_HISTORY'); ?></span> </div> </a> <?php } $print = checkLinks('my_stats',$userrole,$config,$emcontrolpanel); if($print){ ?> <a class="js_controlpanel_link" href="index.php?option=com_jsjobs&c=employer&view=employer&layout=my_stats&Itemid=<?php echo $this->Itemid; ?>"> <img class="js_controlpanel_link_image" src="components/com_jsjobs/images/mystats.png" alt="My Stats" /> <div class="js_controlpanel_link_text_wrapper"> <span class="js_controlpanel_link_title"><?php echo JText::_('JS_MY_STATS'); ?></span> </div> </a> <?php } ?> </div> <?php if($emcontrolpanel['empexpire_package_message'] == 1){ $message = ''; if(!empty($this->packagedetail[0]->packageexpiredays)){ $days = $this->packagedetail[0]->packageexpiredays - $this->packagedetail[0]->packageexpireindays; if($days == 1) $days = $days.' '.JText::_('JS_DAY'); else $days = $days.' '.JText::_('JS_DAYS'); $message = "<strong><font color='red'>".JText::_('JS_YOUR_PACKAGE').' &quot;'.$this->packagedetail[0]->packagetitle.'&quot; '.JText::_('JS_HAS_EXPIRED').' '.$days.' ' .JText::_('JS_AGO')." <a href='index.php?option=com_jsjobs&c=jobseekerpackages&view=jobseekerpackages&layout=packages&Itemid=$this->Itemid'>".JText::_('JS_EMPLOYER_PACKAGES')."</a></font></strong>"; } if($message != ''){?> <div id="errormessage" class="errormessage"> <div id="message"><?php echo $message;?></div> </div> <?php } }?> <?php } else{ // not allowed job posting ?> <div class="js_job_error_messages_wrapper"> <div class="js_job_messages_image_wrapper"> <img class="js_job_messages_image" src="components/com_jsjobs/images/2.png"/> </div> <div class="js_job_messages_data_wrapper"> <span class="js_job_messages_main_text"> <?php echo JText::_('EA_YOU_ARE_NOT_ALLOWED_TO_VIEW'); ?> </span> <span class="js_job_messages_block_text"> <?php echo JText::_('JS_YOU_ARE_NOT_ALLOWED_TO_VIEW_EMPLOYER_CONTROL_PANEL'); ?> </span> </div> </div> <?php } }//ol ?> <div id="jsjobs_footer"><?php echo '<table width="100%" style="table-layout:fixed;"> <tr><td height="15"></td></tr> <tr><td style="vertical-align:top;" align="center"> <a class="img" target="_blank" href="http://www.joomsky.com"><img src="http://www.joomsky.com/logo/jsjobscrlogo.png"></a> <br> Copyright &copy; 2008 - '.date('Y').', <span id="themeanchor"> <a class="anchor"target="_blank" href="http://www.joomsky.com">Joom Sky</a></span></td></tr> </table></div>';?></div> <?php function checkLinks($name,$userrole,$config,$emcontrolpanel){ $print = false; if (isset($userrole->rolefor)){ if ($userrole->rolefor == 1){ if ($emcontrolpanel[$name] == 1) $print = true; } }else{ if($name == 'empmessages') $name = 'vis_emmessages'; elseif($name == 'empresume_rss') $name = 'vis_resume_rss'; else $name = 'vis_em'.$name; if($config[$name] == 1) $print = true; } return $print; } ?>
gpl-2.0
Greyvy/Nonvella
parts/shared/purchase.php
513
<?php if( get_field("print_copy_link") || get_field("digital_copy_link") ) : ?> <p class="btn--more btn--small"> <?php if( get_field("print_copy_link") ) : ?> <a href="<?php esc_url( the_field('print_copy_link') ); ?>">Print Copy &middot; </a> <?php endif; ?> <?php if( get_field("digital_copy_link") ) : ?> <a href="<?php esc_url( the_field('digital_copy_link') ); ?>">Digital Copy</a> <?php endif; ?> </p><!-- .btn--more --> <?php endif; ?>
gpl-2.0
ManuelPalomo/MineSweeper
src/board/Board.java
2458
package board; import utils.Cons; /** * Logic part of the game, manages the board and it's contents * * Numbers: 0=Empty 1=Mine * * @author Manuel Palomo <manuel_palomo@hotmail.es> * */ public class Board { private int sizeX; private int sizeY; private int mines; private int[][] board; public Board(int sizeX, int sizeY, int mines) { this.sizeX = sizeX; this.sizeY = sizeY; this.mines = mines; this.board = setupBoard(); } private int[][] setupBoard() { int[][] board = initializeBoardToEmpty(); for (int i = 0; i < mines; i++) { placeMine(board); } for (int x = 0; x < sizeX; x++) { for (int y = 0; y < sizeY; y++) { if (board[x][y] != Cons.MINE) { board[x][y] = calculateCellValue(x, y); } } } return board; } private int[][] initializeBoardToEmpty() { board = new int[sizeX][sizeY]; for (int x = 0; x < sizeX; x++) { for (int y = 0; y < sizeY; y++) { board[x][y] = Cons.EMPTY; } } return board; } /** * Generates a random address and places a mine in it, if there's a mine * already generates another one * * @return */ private void placeMine(int board[][]) { boolean placed = false; int x = (int) (Math.random() * sizeX); int y = (int) (Math.random() * sizeY); while (!placed) { if (isCellEmpty(x, y)) { board[x][y] = Cons.MINE; placed = true; } else { x = (int) (Math.random() * sizeX); y = (int) (Math.random() * sizeY); } } } /** * Calculate and initializes the given cell */ private int calculateCellValue(int x, int y) { int bombs = 0; for (int i = x - 1; i < x + 2; i++) { for (int j = y - 1; j < y + 2; j++) { if (i >= 0 && j >= 0 && i < sizeX && j < sizeY && (i != x || j != y)) { if (board[i][j] == Cons.MINE) { bombs++; } } } } return bombs; } private boolean isCellEmpty(int x, int y) { if (board[x][y] == Cons.EMPTY) { return true; } else { return false; } } public int getCellContent(int x, int y) { return board[x][y]; } public String toString() { String boardToString = ""; for (int x = 0; x < sizeX; x++) { String row = "["; for (int y = 0; y < sizeY; y++) { row += Integer.toString(board[x][y]); } row += "]"; boardToString += row; } return boardToString; } public int getSizeX() { return sizeX; } public int getSizeY() { return sizeY; } public int getMinesNumber() { return mines; } }
gpl-2.0
DigitalMediaServer/DigitalMediaServer
src/main/java/net/pms/formats/AudioAsVideo.java
937
/* * PS3 Media Server, for streaming any medias to your PS3. * Copyright (C) 2008 A.Brochard * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 2 * of the License only. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package net.pms.formats; public class AudioAsVideo extends MKV { @Override public Identifier getIdentifier() { return Identifier.AUDIO_AS_VIDEO; } }
gpl-2.0
klst-com/metasfresh
de.metas.migration/de.metas.migration.base/src/test/java/de/metas/migration/scanner/impl/GloballyOrderedScannerDecoratorTests.java
3888
package de.metas.migration.scanner.impl; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Comparator; import java.util.Iterator; import java.util.TreeSet; import org.junit.Test; import com.google.common.collect.ImmutableList; import de.metas.migration.IScript; import de.metas.migration.impl.LocalScript; /* * #%L * de.metas.migration.base * %% * Copyright (C) 2015 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 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/gpl-2.0.html>. * #L% */ public class GloballyOrderedScannerDecoratorTests { /** * See {@link GloballyOrderedScannerDecorator#extractSequenceNumber(String)} for the tested behavior. */ @Test public void testExtractSequenceNumber() { // return prefix before first '_' assertThat(GloballyOrderedScannerDecorator.extractSequenceNumber("1234_sys_test.sql"), is("1234")); // no '_' => full name assertThat(GloballyOrderedScannerDecorator.extractSequenceNumber("1234-sys-test.sql"), is("1234-sys-test.sql")); // empty => empty assertThat(GloballyOrderedScannerDecorator.extractSequenceNumber(""), is("")); // empty prefix (just '_') => full name assertThat(GloballyOrderedScannerDecorator.extractSequenceNumber("_sys_test.sql"), is("_sys_test.sql")); assertThat(GloballyOrderedScannerDecorator.extractSequenceNumber("5441640_sys_09848_add_table_AD_JAXRS_Endpoint.sql"), is("5441640")); assertThat(GloballyOrderedScannerDecorator.extractSequenceNumber("5442050_sys_09628_add_AD_JavaClasses_and_JaxRs_Endpoints.sql"), is("5442050")); } /** * Verified that the files are returned in the order of their sequence number */ @Test public void testSupplier() { final InputStream is1 = new ByteArrayInputStream("somecommand".getBytes(StandardCharsets.UTF_8)); final IScript script1 = new LocalScript("10-test", "10-de.metas.adempiere", "5442050_sys_09628_add_AD_JavaClasses_and_JaxRs_Endpoints.sql", is1); final InputStream is2 = new ByteArrayInputStream("somecommand".getBytes(StandardCharsets.UTF_8)); final IScript script2 = new LocalScript("20-test", "20-de.metas.jax.rs", "5441640_sys_09848_add_table_AD_JAXRS_Endpoint.sql", is2); final GloballyOrderedScannerDecorator testee = new GloballyOrderedScannerDecorator(PlainListScriptScanner.fromScripts(ImmutableList.<IScript>of(script1, script2))); final Iterator<IScript> iterator = testee.lexiographicallyOrderedScriptsSupplier.get(); assertThat(iterator.hasNext(), is(true)); assertThat(iterator.next(), is(script2)); assertThat(iterator.hasNext(), is(true)); assertThat(iterator.next(), is(script1)); } /** * Just to visualize {@link TreeSet}'s behavior: if two different objects compare to 0, then they can't both be added. * Note: we don't use TreeSet anymore, but this test is still nice, in case we'll reconsider it :-). */ @Test public void testTreeSet() { final TreeSet<String> set = new TreeSet<String>(new Comparator<String>() { @Override public int compare(final String o1, final String o2) { return o1.substring(0, 1).compareTo(o2.substring(0, 1)); } }); set.add("String1"); set.add("String2"); assertThat(set.size(), is(1)); } }
gpl-2.0
kinko912000/public_html
wp-content/plugins/wp-config-file-editor/vendor/xptrdev/WPPluginFramework/Include/Forms/HTML/ElementsCollection.class.php
2752
<?php /** * */ namespace WPPFW\Forms\HTML; use WPPFW\Forms\HTML\Elements\IElement; /** * */ abstract class ElementsCollection extends Elements\HTMLFormNode { /** * put your comment there... * * @var mixed */ protected $elements = array(); /** * put your comment there... * * @param IElement $element */ public function add(IElement & $element) { # Add $this->addChain($element); # Return element return $element; } /** * put your comment there... * */ protected function & addField() { # Initialize $linker =& $this->getLinker(); # Create Form FIELD! $linker->create($this); # Chain return $this; } /** * put your comment there... * * @param IElement $element */ public function addChain(IElement & $element) { # Set linker if not has been set if (!$element->getLinker()) { $element->setLinker($this->getLinker()); } # Add element $this->elements[$element->getField()->getName()] =& $element; # Chain return $this; } /** * put your comment there... * */ protected function & addElementsFields() { # INitialize $elements =& $this->getElements(); # Create Fields structure foreach ($elements as $element) { # Associate with parent $element->setParent($this); # Add field at correspodning collection field $element->createField(); } # Chain return $this; } /** * put your comment there... * */ protected function & createField() { # Add collection field $this->addField(); # Create Fields structure $this->addElementsFields(); # Chain return $this; } /** * put your comment there... * */ public function & getElements() { return $this->elements; } /** * put your comment there... * * @param \DOMDocument $document * @param {\DOMDocument|\DOMNode} $parent * @return {\DOMDocument|\DOMNode|ElementsCollection} */ public function & render(\DOMDocument & $document, \DOMNode & $parent) { # Render element $listElement =& $this->renderList($document, $parent); # Render collection $this->renderElements($document, $listElement); # Chain return $this; } /** * put your comment there... * * @param \DOMDocument $document * @param {\DOMDocument|\DOMNode} $parent * @return {\DOMDocument|\DOMNode|ElementsCollection} */ protected function & renderElements(\DOMDocument & $document, \DOMNode & $parent) { # Rendering elements foreach ($this->getElements() as $element) { # Render list's element $element->render($document, $parent); } # Chain return $this; } /** * put your comment there... * * @param \DOMDocument $document * @param {\DOMDocument|\DOMNode} $parent */ protected abstract function & renderList(\DOMDocument & $document, \DOMNode & $parent); }
gpl-2.0
brlopes/trampo
py_notify/toggle_notifications.php
666
<h4> STATUS CHANGED: </h4> <?php $menu = $_POST['action']; switch ($menu) { case 'start': echo "| SCRIPT TURNED ON | "; system("./recursive_notification_check.py >/dev/null 2>/dev/null &"); break; case 'stop': echo "| SCRIPT TURNED OFF | "; system("sudo kill $(ps aux | grep 'recursive_notification_check' | awk '{print $2}')"); system("sudo sh logTail.sh"); break; default: echo "| inside default | "; break; } ?> <script> function goBack() { window.history.back(); } </script> <br> <br> <button type="submit" onclick="goBack()">[BACK]</button>
gpl-2.0
paulgibbs/bp-grunt-lite
tests/assets/group-extensions.php
3774
<?php /** * The following implementations of BP_Group_Extension act as dummy plugins * for our unit tests */ class BPTest_Group_Extension_Parse_Legacy_Properties extends BP_Group_Extension { function __construct() { $class_name = get_class( $this ); $this->name = $class_name; $this->slug = sanitize_title( $class_name ); $this->admin_name = $this->name . ' Edit'; $this->admin_slug = $this->slug . '-edit'; $this->create_name = $this->name . ' Create'; $this->create_slug = $this->slug . '-create'; $this->visibility = 'private'; $this->create_step_position = 58; $this->nav_item_position = 63; $this->admin_metabox_context = 'high'; $this->admin_metabox_priority = 'side'; $this->enable_create_step = false; $this->enable_nav_item = true; $this->enable_edit_item = false; $this->enable_admin_item = true; $this->nav_item_name = $this->name . ' Nav'; $this->display_hook = 'foo_hook'; $this->template_file = 'foo_template'; } /** * Provides access to protected method unneeded in BP */ function _parse_legacy_properties() { return $this->parse_legacy_properties(); } /** * Provides access to protected property unneeded in BP */ function _get_legacy_properties_converted() { return $this->legacy_properties_converted; } } class BPTest_Group_Extension_Setup_Screens_Use_Global_Fallbacks extends BP_Group_Extension { function __construct() { $class_name = get_class( $this ); $this->slug = sanitize_title( $class_name ); $this->name = $class_name; } /** * Provides access to protected method unneeded in BP */ function _get_default_screens() { return $this->get_default_screens(); } /** * Provides access to protected method unneeded in BP */ function _setup_class_info() { return $this->setup_class_info(); } function settings_screen( $group_id = null ) {} function settings_screen_save( $group_id = null ) {} } class BPTest_Group_Extension_Setup_Screens_Define_Edit_Screens_Locally extends BP_Group_Extension { function __construct() { $class_name = get_class( $this ); $this->slug = sanitize_title( $class_name ); $this->name = $class_name; } function edit_screen( $group_id = null ) {} function edit_screen_save( $group_id = null ) {} function settings_screen( $group_id = null ) {} function settings_screen_save( $group_id = null ) {} /** * Provides access to protected method unneeded in BP */ function _get_default_screens() { return $this->get_default_screens(); } /** * Provides access to protected method unneeded in BP */ function _setup_class_info() { return $this->setup_class_info(); } } class BPTest_Group_Extension_Access_Root_Property extends BP_Group_Extension { function __construct() { $class_name = get_class( $this ); $args = array( 'slug' => sanitize_title( $class_name ), 'name' => $class_name, 'nav_item_position' => 39, ); parent::init( $args ); } } class BPTest_Group_Extension_Access_Init_Property_Using_Legacy_Location extends BP_Group_Extension { function __construct() { $class_name = get_class( $this ); $args = array( 'slug' => sanitize_title( $class_name ), 'name' => $class_name, 'screens' => array( 'create' => array( 'position' => 18, ), ), ); parent::init( $args ); } } class BPTest_Group_Extension_Get_Screen_Callback_Fallbacks extends BP_Group_Extension { function __construct() { $class_name = get_class( $this ); $args = array( 'slug' => sanitize_title( $class_name ), 'name' => $class_name, ); parent::init( $args ); } function settings_screen( $group_id = null ) {} function settings_screen_save( $group_id = null ) {} function edit_screen( $group_id = null ) {} function edit_screen_save( $group_id = null ) {} }
gpl-2.0
drazenzadravec/nequeo
Tools/MikTex/Programs/MiKTeX/MO/MFC/PropPageFormats.cpp
9141
/* PropPageFormats.cpp: Copyright (C) 2000-2016 Christian Schenk This file is part of MiKTeX Options. MiKTeX Options 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, or (at your option) any later version. MiKTeX Options 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 MiKTeX Options; if not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "StdAfx.h" #include "mo.h" #include "FormatDefinitionDialog.h" #include "miktex/UI/MFC/ProgressDialog" #include "PropPageFormats.h" #include "PropSheet.h" #include "resource.hm" PropPageFormats::PropPageFormats() : CPropertyPage(PropPageFormats::IDD) { m_psp.dwFlags &= ~(PSP_HASHELP); } void PropPageFormats::DoDataExchange(CDataExchange * pDX) { CPropertyPage::DoDataExchange(pDX); DDX_Control(pDX, IDC_EDIT, editButton); DDX_Control(pDX, IDC_LIST, listControl); DDX_Control(pDX, IDC_MAKE, makeButton); DDX_Control(pDX, IDC_NEW, newButton); DDX_Control(pDX, IDC_REMOVE, removeButton); } BEGIN_MESSAGE_MAP(PropPageFormats, CPropertyPage) ON_BN_CLICKED(IDC_EDIT, OnEdit) ON_BN_CLICKED(IDC_MAKE, OnMake) ON_BN_CLICKED(IDC_NEW, OnNew) ON_BN_CLICKED(IDC_REMOVE, OnRemove) ON_NOTIFY(LVN_ITEMCHANGED, IDC_LIST, OnSelectionChange) ON_NOTIFY(NM_DBLCLK, IDC_LIST, OnListDoubleClick) ON_WM_CONTEXTMENU() ON_WM_HELPINFO() END_MESSAGE_MAP(); void PropPageFormats::OnMake() { try { PropSheet * pSheet = reinterpret_cast<PropSheet*>(GetParent()); unique_ptr<ProgressDialog> ppd(ProgressDialog::Create()); ppd->StartProgressDialog(GetParent()->GetSafeHwnd()); if (listControl.GetSelectedCount() > 1) { ppd->SetTitle(T_("Making Format Files")); } else { ppd->SetTitle(T_("Making Format File")); } ppd->SetLine(1, T_("Creating format file:")); POSITION pos = listControl.GetFirstSelectedItemPosition(); while (pos != nullptr) { int idx = listControl.GetNextSelectedItem(pos); CString formatKey = listControl.GetItemText(idx, 0); FormatInfo formatInfo = session->GetFormatInfo(TU_(formatKey)); CommandLineBuilder cmdLine; cmdLine.AppendOption("--dump=", formatInfo.key); if (!pSheet->RunIniTeXMF(formatInfo.description.c_str(), cmdLine, ppd.get())) { // TODO } } ppd->StopProgressDialog(); } catch (const MiKTeXException & e) { ErrorDialog::DoModal(this, e); } catch (const exception & e) { ErrorDialog::DoModal(this, e); } } void PropPageFormats::OnNew() { try { FormatDefinitionDialog dlg(this, nullptr); if (dlg.DoModal() != IDOK) { return; } FormatInfo formatInfo = dlg.GetFormatInfo(); session->SetFormatInfo(formatInfo); Refresh(); MakeAlias(formatInfo); } catch (const MiKTeXException & e) { ErrorDialog::DoModal(this, e); } catch (const exception & e) { ErrorDialog::DoModal(this, e); } } void PropPageFormats::MakeAlias(const FormatInfo & formatInfo) { if (session->IsMiKTeXDirect()) { MIKTEX_FATAL_ERROR(T_("Operation not supported.")); } PathName compilerPath; if (!session->FindFile(formatInfo.compiler.c_str(), FileType::EXE, compilerPath)) { MIKTEX_FATAL_ERROR_2(T_("The compiler could not be found."), "compuler", formatInfo.compiler); } PathName pathBinDir = session->GetSpecialPath(SpecialPath::BinDirectory); PathName pathAlias(pathBinDir, formatInfo.name, ".exe"); if (compilerPath != pathAlias && !File::Exists(pathAlias)) { Directory::Create(pathBinDir); File::Copy(compilerPath, pathAlias); if (!Fndb::FileExists(pathAlias)) { Fndb::Add(pathAlias); } } } void PropPageFormats::OnEdit() { try { int idx = GetSelectedItem(); CString formatKey = listControl.GetItemText(idx, 0); FormatDefinitionDialog dlg(this, TU_(formatKey)); if (dlg.DoModal() != IDOK) { return; } FormatInfo formatInfo = dlg.GetFormatInfo(); if (PathName::Compare(formatInfo.key.c_str(), TU_(formatKey)) != 0) { // rename key: delete old, create new session->DeleteFormatInfo(TU_(formatKey)); formatKey = UT_(formatInfo.key); } session->SetFormatInfo(formatInfo); Refresh(); MakeAlias(formatInfo); } catch (const MiKTeXException & e) { ErrorDialog::DoModal(this, e); } catch (const exception & e) { ErrorDialog::DoModal(this, e); } } void PropPageFormats::OnRemove() { try { int n = listControl.GetSelectedCount(); for (int i = 0; i < n; ++i) { int idx = GetSelectedItem(); CString formatKey = listControl.GetItemText(idx, 0); session->DeleteFormatInfo(TU_(formatKey)); if (!listControl.DeleteItem(idx)) { MIKTEX_FATAL_WINDOWS_ERROR("CListCtrl::DeleteItem"); } } EnableButtons(); } catch (const MiKTeXException & e) { ErrorDialog::DoModal(this, e); } catch (const exception & e) { ErrorDialog::DoModal(this, e); } } void PropPageFormats::InsertColumn(int colIdx, const char * lpszLabel, const char * lpszLongest) { if (listControl.InsertColumn(colIdx, UT_(lpszLabel), LVCFMT_LEFT, listControl.GetStringWidth(UT_(lpszLongest)), colIdx) < 0) { MIKTEX_FATAL_WINDOWS_ERROR("CListCtrl::InsertColumn"); } } BOOL PropPageFormats::OnInitDialog() { BOOL ret = CPropertyPage::OnInitDialog(); try { listControl.SetExtendedStyle(listControl.GetExtendedStyle() | LVS_EX_FULLROWSELECT); InsertColumn(0, T_("Key"), T_("pdfjadetex ")); InsertColumn(1, T_("Description"), T_("pdfLaTeX bla bla ")); InsertColumn(2, T_("Attributes"), T_("Exclude, bla bla ")); Refresh(); } catch (const MiKTeXException & e) { ErrorDialog::DoModal(this, e); } catch (const exception & e) { ErrorDialog::DoModal(this, e); } return ret; } void PropPageFormats::EnableButtons() { UINT n = listControl.GetSelectedCount(); makeButton.EnableWindow(n > 0 && !modified); removeButton.EnableWindow(n > 0); editButton.EnableWindow(n == 1); } int PropPageFormats::GetSelectedItem() { POSITION pos = listControl.GetFirstSelectedItemPosition(); if (pos == nullptr) { MIKTEX_UNEXPECTED(); } return listControl.GetNextSelectedItem(pos); } void PropPageFormats::Refresh() { if (!listControl.DeleteAllItems()) { MIKTEX_FATAL_WINDOWS_ERROR("CListCtrl::DeleteAllItems"); } int idx = 0; for (const FormatInfo & formatInfo : session->GetFormats()) { LV_ITEM lvitem; lvitem.iItem = static_cast<int>(idx); lvitem.mask = LVIF_TEXT | LVIF_PARAM; lvitem.iSubItem = 0; CString key(UT_(formatInfo.key)); lvitem.pszText = key.GetBuffer(); lvitem.lParam = idx; int whereIndex = listControl.InsertItem(&lvitem); if (whereIndex < 0) { MIKTEX_FATAL_WINDOWS_ERROR("CListCtrl::InsertItem"); } lvitem.iItem = whereIndex; lvitem.mask = LVIF_TEXT; lvitem.iSubItem = 1; CString description(UT_(formatInfo.description)); lvitem.pszText = description.GetBuffer(); if (!listControl.SetItem(&lvitem)) { MIKTEX_FATAL_WINDOWS_ERROR("CListCtrl::SetItem"); } lvitem.mask = LVIF_TEXT; lvitem.iSubItem = 2; lvitem.pszText = (formatInfo.exclude ? T_(_T("exclude")) : _T("")); if (!listControl.SetItem(&lvitem)) { MIKTEX_FATAL_WINDOWS_ERROR("CListCtrl::SetItem"); } ++idx; } EnableButtons(); } #define MAKE_ID_HID_PAIR(id) id, H##id namespace { const DWORD aHelpIDs[] = { MAKE_ID_HID_PAIR(IDC_EDIT), MAKE_ID_HID_PAIR(IDC_LIST), MAKE_ID_HID_PAIR(IDC_MAKE), MAKE_ID_HID_PAIR(IDC_NEW), MAKE_ID_HID_PAIR(IDC_REMOVE), 0, 0, }; } BOOL PropPageFormats::OnHelpInfo(HELPINFO * pHelpInfo) { return ::OnHelpInfo(pHelpInfo, aHelpIDs, "FormatsPage.txt"); } void PropPageFormats::OnContextMenu(CWnd * pWnd, CPoint point) { try { DoWhatsThisMenu(pWnd, point, aHelpIDs, "FormatsPage.txt"); } catch (const MiKTeXException & e) { ErrorDialog::DoModal(this, e); } catch (const exception & e) { ErrorDialog::DoModal(this, e); } } void PropPageFormats::OnSelectionChange(NMHDR * pNMHDR, LRESULT * pResult) { UNUSED_ALWAYS(pNMHDR); try { EnableButtons(); } catch (const MiKTeXException & e) { ErrorDialog::DoModal(this, e); } catch (const exception & e) { ErrorDialog::DoModal(this, e); } *pResult = 0; } void PropPageFormats::OnListDoubleClick(NMHDR * pNMHDR, LRESULT * pResult) { UNUSED_ALWAYS(pNMHDR); try { OnEdit(); } catch (const MiKTeXException & e) { ErrorDialog::DoModal(this, e); } catch (const exception & e) { ErrorDialog::DoModal(this, e); } *pResult = 0; }
gpl-2.0
little-pan/Mycat-Server
src/main/java/org/opencloudb/handler/SelectHandler.java
2266
/* * Copyright (c) 2013, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software;Designed and Developed mainly by many Chinese * opensource volunteers. you can redistribute it and/or modify it under the * terms of the GNU General Public License version 2 only, as published by the * Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Any questions about this component can be directed to it's project Web address * https://code.google.com/p/opencloudb/. * */ package org.opencloudb.handler; import static org.opencloudb.parser.ManagerParseSelect.SESSION_AUTO_INCREMENT; import static org.opencloudb.parser.ManagerParseSelect.VERSION_COMMENT; import static org.opencloudb.parser.ManagerParseSelect.SESSION_TX_READ_ONLY; import org.opencloudb.config.ErrorCode; import org.opencloudb.manager.ManagerConnection; import org.opencloudb.parser.ManagerParseSelect; import org.opencloudb.response.SelectSessionAutoIncrement; import org.opencloudb.response.SelectTxReadOnly; import org.opencloudb.response.SelectVersionComment; /** * @author mycat */ public final class SelectHandler { public static void handle(String stmt, ManagerConnection c, int offset) { switch (ManagerParseSelect.parse(stmt, offset)) { case VERSION_COMMENT: SelectVersionComment.execute(c); break; case SESSION_AUTO_INCREMENT: SelectSessionAutoIncrement.execute(c); break; case SESSION_TX_READ_ONLY: SelectTxReadOnly.response(c); break; default: c.writeErrMessage(ErrorCode.ER_YES, "Unsupported statement"); } } }
gpl-2.0
alafon/ezpublish-community-built
ezpublish_legacy/kernel/private/eztemplate/ezpattributeoperatorformatter.php
1477
<?php /** * File containing ezpAttributeOperatorFormatter base class definition * * @copyright Copyright (C) 1999-2013 eZ Systems AS. All rights reserved. * @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 * @version 2013.5 * @package kernel */ class ezpAttributeOperatorFormatter { /** * Returns type for given item * * @param mixed $item * @return string */ protected function getType( $item ) { $type = gettype( $item ); if ( is_object( $item ) ) $type .= "[" . get_class( $item ) . "]"; return $type; } /** * Returns value for given item * * @param mixed $item * @return string */ protected function getValue( $item ) { if ( is_bool( $item ) ) $value = $item ? "true" : "false"; else if ( is_array( $item ) ) $value = 'Array(' . count( $item ) . ')'; else if ( is_numeric( $item ) ) $value = $item; else if ( is_string( $item ) ) $value = "'" . $item . "'"; else if ( is_object( $item ) ) $value = method_exists( $item, '__toString' ) ? (string)$item : 'Object'; else $value = $item; return $value; } /** * @see ezpAttributeOperatorFormatterInterface::exportScalar() */ public function exportScalar( $value ) { return var_export( $value, true ); } }
gpl-2.0
chronoxor/Depth
source/stream/CStreamDebugger.cpp
4319
/*! * \file CStreamDebugger.cpp Debugger stream class gives ability to write * buffer into the system debugger stream. * \brief Debugger stream class (source). * \author Ivan Shynkarenka aka 4ekucT * \version 1.0 * \date 01.09.2008 */ /*==========================================================================*/ /* FILE DESCRIPTION: Debugger stream class (source). AUTHOR: Ivan Shynkarenka aka 4ekucT GROUP: The NULL workgroup PROJECT: The Depth PART: Stream VERSION: 1.0 CREATED: 01.09.2008 01:52:10 EMAIL: chronoxor@gmail.com WWW: http://code.google.com/p/depth COPYRIGHT: (C) 2005-2010 The NULL workgroup. All Rights Reserved. */ /*--------------------------------------------------------------------------*/ /* Copyright (C) 2005-2010 The NULL workgroup. 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 */ /*--------------------------------------------------------------------------*/ /* FILE ID: $Id$ CHANGE LOG: $Log$ */ /*==========================================================================*/ #include <Depth/include/base.hpp> /*--------------------------------------------------------------------------*/ #include <Depth/include/stream/CStreamDebugger.hpp> #include <Depth/include/system/CSystemBase.hpp> /*==========================================================================*/ #ifndef __CSTREAMDEBUGGER_CPP__ #define __CSTREAMDEBUGGER_CPP__ /*==========================================================================*/ /* NAMESPACE DECLARATIONS */ /*==========================================================================*/ namespace NDepth { /*--------------------------------------------------------------------------*/ namespace NStream { /*==========================================================================*/ /* CLASS IMPLEMENTATIONS */ /*==========================================================================*/ Tbool CStreamDebugger::set(const CStreamDebugger& a_crInstance) { CALL // Check if the given class instance is not the same to the current one. ASSERT((&a_crInstance != this), STR("Setting the same CStreamDebugger class instance.")) { return false; } // Close opened debugger stream. if (isOpened()) if (!close()) return false; // Initialize base writer interface. return IWriter::set(a_crInstance); } /*--------------------------------------------------------------------------*/ Tuint CStreamDebugger::onWriteBinary(Tcptr a_cpBuffer, const Tuint a_cSize) { CALL return NSystem::CSystemBase::debuggerWriteBinary(a_cpBuffer, a_cSize); } /*--------------------------------------------------------------------------*/ Tuint CStreamDebugger::onWriteText(Tcsstr a_cpBuffer, const Tuint a_cSize) { CALL return NSystem::CSystemBase::debuggerWriteText(a_cpBuffer, a_cSize); } /*--------------------------------------------------------------------------*/ Tuint CStreamDebugger::onWriteText(Tcwstr a_cpBuffer, const Tuint a_cSize) { CALL return NSystem::CSystemBase::debuggerWriteText(a_cpBuffer, a_cSize); } /*--------------------------------------------------------------------------*/ Tbool CStreamDebugger::onFlush() { CALL return NSystem::CSystemBase::debuggerFlush(); } /*==========================================================================*/ } /*--------------------------------------------------------------------------*/ } /*==========================================================================*/ #endif
gpl-2.0
bentiss/hid-replay
tools/capture_usbmon.py
13959
#!/bin/env python # -*- coding: utf-8 -*- # # Hid replay / capture_usbmon.py # # must be run as root. # # This program is useful to capture both the raw usb events from an input # device and its kernel generated events. # # Requires several tools to be installed: usbmon, evemu and pyudev # # Copyright (c) 2014 Benjamin Tissoires <benjamin.tissoires@gmail.com> # Copyright (c) 2014 Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; 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/>. # import os import sys import threading import subprocess import shlex import time from optparse import OptionParser import pyudev import inspect module_path = os.path.abspath(inspect.getsourcefile(lambda _: None)) module_dirname = os.path.dirname(module_path) usbmon2hid_replay = module_dirname + "/usbmon2hid-replay.py" class UDevObject(object): """ Abstract class for an udev tree element""" def __init__(self, device, parent, children_class): "device being an udev device" self.device = device self.parent = parent self.children_class = children_class self.childrens = {} self.bind_file = None def is_child_type(self, other): "is the other UDevObject from the correct child type" # abstract method, has to be overwritten in the subclasses return False def is_parent(self, other): "true if the current UDevObject is a parent of the given UDevObject" return self.device.sys_path in other.sys_path def add_child(self, device): """add a child to the hierarchy: instanciate a new subclass of UDevObject stored in self.children_class. """ if not self.children_class: return child = self.children_class(device, self) self.childrens[device.sys_path] = child def removed(self): "called when the item is removed from the parent" # abstract method, has to be overwritten in the subclasses pass def clean(self): "remove all of the children of the UDevObject" for child in self.childrens.values(): child.removed() child.clean() self.childrens = {} def udev_event(self, action, device): "called when a udev event is processed" if self.is_child_type(device): # the device is our direct child, add/remove it to the hierarchy if action == "add": self.add_child(device) else: if device.sys_path in self.childrens.keys(): # be sure to notify the "removed" call before deleting it self.childrens[device.sys_path].removed() del(self.childrens[device.sys_path]) else: # maybe our children know how to handle it for child in self.childrens.values(): if child.is_parent(device): child.udev_event(action, device) def get_name(self): "return a more convenient name for the current object" return self.device.sys_path def print_tree(self, level = 0): "convenient function to print a tree of the current known devices" print self.get_name() for child in self.childrens.values(): print (" " * level) + u' └', child.print_tree(level + 1) def unbind(self): "unbind the device from its current driver" path = self.device.sys_path unbind_path = "{0}/driver/unbind".format(path) bind_path = "{0}/driver/bind".format(path) if not os.path.exists(unbind_path): return False self.unbind_file = open(unbind_path, "w") self.bind_file = open(bind_path, "w") self.unbind_file.write(self.device.sys_name) self.unbind_file.close() return True def rebind(self): "rebind the device to its driver (unbind has to be called first)" if not self.bind_file: raise Exception, "trying to rebind an unbind device" self.bind_file.write(self.device.sys_name) self.bind_file.close() self.bind_file = None class EventNode(UDevObject): def __init__(self, device, parent): # no children devices for this one UDevObject.__init__(self, device, parent, None) self.index = int(self.device.sys_name.replace("event", "")) self.start_evemu() def get_name(self): return "{0}_{1}.ev".format(self.parent.get_name(), self.index) def removed(self): # close the underlying evemu process when the device is removed self.p.terminate() self.p.wait() self.output.close() def start_evemu(self): # start an evemu-record of the event node print "dumping evdev events in", self.get_name() self.output = open(self.get_name(), 'w') evemu_command = "evemu-record /dev/input/{0}".format(self.device.sys_name) print evemu_command self.p = subprocess.Popen(shlex.split(evemu_command), stdout=self.output) class USBInterface(UDevObject): def __init__(self, device, parent): UDevObject.__init__(self, device, parent, EventNode) self.intf_number = device.sys_name.split(':')[-1] self.lsusb() def is_child_type(self, other): return other.subsystem == u'input' and u'event' in other.sys_name def get_name(self): return "{0}_{1}".format(self.parent.get_name(), self.intf_number) def write_hid_file(self): "convert the usbmon recording into a hid recording" intf = self.intf_number.split(".")[-1] usbmon = self.parent.get_usbmon_filename() usbmon_command = "python {0} {1} --intf {2}".format(usbmon2hid_replay, usbmon, intf) f = open(self.get_name() + ".hid", "w") p = subprocess.Popen(shlex.split(usbmon_command), stdout=f) p.wait() print "written", self.get_name() + ".hid" def removed(self): self.parent.remove_interface(self) def lsusb(self): """when the usb driver does not checks for the report descriptors, we have to ask them ourself: call `lsusb -v' when the driver is not bound.""" # unbind the device first if not self.unbind(): return # call lsusb -v lsusbcall = "lsusb -v -d {0}:{1}".format(self.parent.vid, self.parent.pid) subprocess.call(shlex.split(lsusbcall), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) #rebind the device self.rebind() class USBDev(UDevObject): """ A USB device object: - will keep the interface hierarchy - at unplug, convert the usb recording into the various hid files (one per known interface) """ def __init__(self, device): UDevObject.__init__(self, device, None, USBInterface) self.vid = device.get("ID_VENDOR_ID") self.pid = device.get("ID_MODEL_ID") self.vendor = device.get("ID_VENDOR").replace(".", "") self.start_usbmon() self.removed_intf = [] def is_child_type(self, other): return other.device_type == u'usb_interface' def get_name(self): return "{0}_{1}_{2}".format(self.vendor, self.vid, self.pid) def get_usbmon_filename(self): "return the usbmon file name were the events are recorded" return self.get_name() + ".usbmon" def start_usbmon(self): "start the usbmon subprocess" number = self.device.device_node.split('/')[-1] bus = int(self.device.device_node.split('/')[-2]) # start usbmon print "dumping usb events in", self.get_usbmon_filename() self.usbmon_file = open(self.get_usbmon_filename(), 'w') USBMon.add_listener(bus, number, self.usbmon_file) def remove_interface(self, intf): "when an interface is removed, this method is called" self.removed_intf.append(intf) def terminate(self): """clean up and terminate the usb device: - stop the usbmon capture for this device - remove any zombi child - ask for each known interface to translate the usbmon capture into a hid one """ number = self.device.device_node.split('/')[-1] bus = int(self.device.device_node.split('/')[-2]) USBMon.remove_listener(bus, number) self.usbmon_file.close() self.clean() for intf in self.removed_intf: intf.write_hid_file() class USBMon(threading.Thread): """usbmon recorder class: - calling a new object USBMon(bus) starts recording usb events on this bus - each device gets buffered in its own queue of events - when someone add a listener for a specific device, the buffered events are dumped into the given file and each new event is dumped too """ busses = {} def __init__(self, bus): threading.Thread.__init__(self) self.bus = bus USBMon.busses[bus] = self self.devices = {} self.bufs = {} # launch the actual usbmon tool with a buffer big enough to store # the various hid report descriptors self.p = subprocess.Popen(shlex.split("usbmon -i {0} -fu -s 512".format(bus)), stdout=subprocess.PIPE) self.start() def pump_events(self, addr): """matches the given device with the current listeners and dumps the queue of events into the correct listener""" if not addr in self.devices.keys(): # no listener found, keep the events for later return while len(self.bufs[addr]) > 0: line = self.bufs[addr].pop(0) self.devices[addr].write(line) def run(self): while self.p: line = self.p.stdout.readline() if not line: # end of capture break # extract the device address tag, timestamp, event_type, address, status, usbmon_data = line.rstrip().split(" ", 5) URB_type, bus, dev_address, endpoint = address.split(":") key_addr = USBMon.create_key(bus, dev_address) if not self.bufs.has_key(key_addr): # new device, add a new queue to the list self.bufs[key_addr] = [] # add the event to the queue self.bufs[key_addr].append(line) # try flushing the event into the listeners self.pump_events(key_addr) def stop(self): p = self.p if not p: return self.p = None p.terminate() @classmethod def create_key(cls, bus, number): "create a uniq key for a given usb device (bus, number)" return "{0}:{1}:".format(bus, number) @classmethod def add_listener(cls, bus, number, file): "append a listener (an opened writable file) for a given usb device" if not cls.busses.has_key(bus): USBMon(bus) usbmon = cls.busses[bus] usbmon.devices[cls.create_key(bus, number)] = file @classmethod def remove_listener(cls, bus, number): "remove the listener from the given usb device" usbmon = cls.busses[bus] del(usbmon.devices[cls.create_key(bus, number)]) @classmethod def terminate_usbmon(cls): "terminate all instances of usbmon tools" for usbmon in cls.busses.values(): usbmon.stop() cls.busses = {} class Conductor(object): """ In charge of reading udev events and launching the various external program.""" def __init__(self): self.context = pyudev.Context() # create udev notification system self.monitor = pyudev.Monitor.from_netlink(pyudev.Context()) self.monitor.filter_by('input') self.monitor.filter_by('usb') self.cv = threading.Condition() self.done = False self.devices = {} self.start_usbmon() self.observer = pyudev.MonitorObserver(self.monitor, self.udev_event) def start_usbmon(self): "look for any root hub and start usbmon on every found one" for device in self.context.list_devices(subsystem='usb', DEVTYPE='usb_device'): id_model = device.get('ID_MODEL_FROM_DATABASE') if id_model and " root hub" in id_model: USBMon(int(device.get('BUSNUM'))) def start(self): "start monitoring udev events" self.observer.start() def stop(self): "stop monitoring udev events" self.observer.stop() self.cv.acquire() self.done = True self.cv.notify() self.cv.release() def wait(self): "wait for the user to hit ctrl-C to terminate the monitoring/recording" self.cv.acquire() try: while not self.done: self.cv.wait(timeout=1.0) except (KeyboardInterrupt, SystemExit): print "" self.stop() self.cv.release() def print_tree(self): "convenient function to print a tree of the current known devices" for usb in self.devices.values(): usb.print_tree() def udev_event(self, action, device): "called when an udev event is processed" # print action, device if device.device_type == u'usb_device': # the device is a new usb device (hub), add/remove it to # the tree if action == "add": usb = USBDev(device) self.devices[device.sys_path] = usb else: if device.sys_path in self.devices.keys(): usb = self.devices[device.sys_path] del(self.devices[device.sys_path]) # stopping all captures and flush the various files usb.terminate() else: # this device is unknown at this level, maybe the usb device # knows how to handle it for usb in self.devices.values(): if usb.is_parent(device): usb.udev_event(action, device) def flush(self): for usb in self.devices.values(): usb.terminate() USBMon.terminate_usbmon() def get_options(): description = \ """ %prog will capture several traces from the plugged USB devices: the raw usb events, the evemu events generated by the kernel, and if possible will convert the usb events into hid events for later replay. Be careful when recording events (from keyboards for instance), it _can_ (will) record any password you type, so use it carefully. """ parser = OptionParser(description=description) # parser.add_option("", "--intf", dest="intf", # help="capture only the given interface number, omit if you don't want to filter") return parser.parse_args() def main(): (options, args) = get_options() conductor = Conductor() conductor.start() print """ This program will capture the usb raw events, the kernel emitted input events and also will convert the usb capture into a HID recording. Please now plug any device you wish to capture, make some events with it, and unplug it when you have finished. You can plug/unplug several different devices at the same time, but only the latest recordings from each device will be kept. Hit Ctrl-C to terminate the program. """ conductor.wait() conductor.flush() if __name__ == "__main__": main()
gpl-2.0
chris-magic/xbmc_dualaudio_pvr
xbmc/video/dialogs/GUIDialogVideoOverlay.cpp
1867
/* * Copyright (C) 2005-2008 Team XBMC * http://www.xbmc.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, 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 XBMC; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ #include "GUIDialogVideoOverlay.h" #include "GUIInfoManager.h" #include "guilib/GUIWindowManager.h" #define CONTROL_PLAYTIME 2 #define CONTROL_PLAY_LOGO 3 #define CONTROL_PAUSE_LOGO 4 #define CONTROL_INFO 5 #define CONTROL_BIG_PLAYTIME 6 #define CONTROL_FF_LOGO 7 #define CONTROL_RW_LOGO 8 CGUIDialogVideoOverlay::CGUIDialogVideoOverlay() : CGUIDialog(WINDOW_DIALOG_VIDEO_OVERLAY, "VideoOverlay.xml") { m_renderOrder = 0; m_visibleCondition = SKIN_HAS_VIDEO_OVERLAY; } CGUIDialogVideoOverlay::~CGUIDialogVideoOverlay() {} void CGUIDialogVideoOverlay::FrameMove() { if (g_windowManager.GetActiveWindow() == WINDOW_FULLSCREEN_VIDEO) { // close immediately Close(true); return; } CGUIDialog::FrameMove(); } EVENT_RESULT CGUIDialogVideoOverlay::OnMouseEvent(const CPoint &point, const CMouseEvent &event) { return EVENT_RESULT_UNHANDLED; } void CGUIDialogVideoOverlay::SetDefaults() { CGUIDialog::SetDefaults(); m_renderOrder = 0; m_visibleCondition = SKIN_HAS_VIDEO_OVERLAY; }
gpl-2.0
bigace/bigace2-extensions
MODUL/rssNewsReader/system/classes/rss/RSSParser.php
13574
<?php /** * @package bigace.classes */ /** * RSS Parser * * Klasse zur Anzeige von News-Channels, die im RDF/RSS-Format vorliegen * * (c) 2002 - 2003 Stefan Fischer * * @author Stefan Fischer <post@stefan-fischer.net> * @version 0.2 * @package bigace.classes * @access public */ class RSSParser { var $fileUrl; var $parser; var $case_folding = TRUE; var $data = array(); var $current_tag = ''; var $item_count = 0; var $image_flag = false; var $input_flag = false; var $channel_flag = false; var $item_flag = false; var $options = array( 'CHANNELDESC' => TRUE, 'ITEMDESC' => TRUE, 'IMAGE' => TRUE, 'TEXTINPUT' => TRUE ); var $styles = array( 'MAXITEM' => 15, 'ITEMSEPARATOR' => '<hr>', 'DESCSEPARATOR' => '<p>', 'CHANNELTITLE' => '', 'CHANNELDESC' => '', 'CHANNELLINK' => '', 'ITEMTITLE' => '', 'ITEMDESC' => '', 'ITEMLINK' => '', 'TEXTINPUT' => '', 'SUBMIT' => '', 'TEXTINPUTTITLE' => '', 'TEXTINPUTDESC' => '', 'SUBMITVALUE' => 'GO', 'TABLEWIDTH' => 300, 'TABLECLASS' => '', 'TABLEALIGN' => 'left', 'LINKTARGET' => '_blank' ); var $error = array( 100 => 'RSS Source: Not available', 101 => 'RSS Source: Fehler beim Parsen', 102 => 'Unbekannte Output Option', 103 => 'Unbekannter Output Style' ); var $current_error = false; function RSSParser() { $this->data = array(); $this->current_tag = ''; $this->item_count = 0; $this->image_flag = false; $this->input_flag = false; $this->channel_flag = false; $this->item_flag = false; $this->current_error = false; } function parseRSS($file) { $this->getRSSData($file); if ($this->current_error) { return false; } else { return $this->getOutput(); } } function getOutput() { if ($this->styles['MAXITEM'] < $this->item_count) { $this->item_count = $this->styles['MAXITEM']; } $out = '<TABLE align="'.$this->styles['TABLEALIGN'].'" class="'.$this->styles['TABLECLASS'].'" width="'.$this->styles['TABLEWIDTH'].'" cellspacing="2" cellpadding="2" border="0">'; $out .= '<TR><TH>'; // Channel - Section $out .= '<TABLE width="100%" cellspacing="0" cellpadding="3" border="0">'; $out .= '<TR>'; // Image - Section if ($this->options['IMAGE'] == true && isset($this->data['IMAGE'])) { $out .= '<TD>'; $out .='<A href="'.$this->data['IMAGE']['LINK'].'" target="'.$this->styles['LINKTARGET'].'">'; $out .= '<IMG src="'.$this->data['IMAGE']['URL'].'" alt="'.@$this->data['IMAGE']['TITLE'].'" border="0"'; if (isset($this->data['IMAGE']['WIDTH'])) { $out .= ' width="'.$this->data['IMAGE']['WIDTH'].'"'; } if (isset($this->data['IMAGE']['HEIGHT'])) { $out .= ' height="'.$this->data['IMAGE']['HEIGHT'].'"'; } $out .= '>'; $out .= '</A>'; $out .= '</TD>'; } $out .= '<TD width="90%">'; $out .= '<SPAN class="'.$this->styles['CHANNELTITLE'].'">'.$this->data['CHANNEL']['TITLE'].'</SPAN>'; $out .= $this->styles['DESCSEPARATOR']; if ($this->options['CHANNELDESC'] == true) { $out .= '<SPAN class="'.$this->styles['CHANNELDESC'].'">'.$this->data['CHANNEL']['DESCRIPTION'].'</SPAN>'; $out .= $this->styles['DESCSEPARATOR']; } $out .='<A href="'.$this->data['CHANNEL']['LINK'].'" target="'.$this->styles['LINKTARGET'].'" class="'.$this->styles['CHANNELLINK'].'">'.$this->data['CHANNEL']['LINK'].'</A>'; $out .= $this->styles['DESCSEPARATOR']; $out .= '</TD>'; $out .= '<TD valign="top" align="right"><a href="' . $this->fileUrl . '" target="_blank"><img src="' . _BIGACE_DIR_PUBLIC_WEB . 'system/images/rss.png" width="36" height="14" border="0"></a></TD>'; $out .= '</TR>'; $out .= '</TABLE>'; $out .= '</TH></TR>'; $out .= '<TR><TD>'; $out .= $this->styles['ITEMSEPARATOR']; $out .= '</TD></TR>'; // Item - Section for ($i = 1; $i <= $this->item_count; $i++) { $out .= '<TR><TD>'; $out .='<A href="'.$this->data['ITEM'][$i]['LINK'].'" target="'.$this->styles['LINKTARGET'].'" class="'.$this->styles['ITEMLINK'].'">'.$this->data['ITEM'][$i]['TITLE'].'</A>'; $out .= $this->styles['DESCSEPARATOR']; if ($this->options['ITEMDESC'] == true && isset($this->data['ITEM'][$i]['DESCRIPTION'])) { $out .= '<SPAN class="'.$this->styles['ITEMDESC'].'">'.$this->data['ITEM'][$i]['DESCRIPTION'].'</SPAN>'; $out .= $this->styles['DESCSEPARATOR']; } $out .= '</TD></TR>'; $out .= '<TR><TD>'; $out .= $this->styles['ITEMSEPARATOR']; $out .= '</TD></TR>'; } // Textinput - Section if ($this->options['TEXTINPUT'] == true && isset($this->data['TEXTINPUT'])) { $out .= '<TR><TD>'; $out .= '<TABLE width="'.$this->styles['TABLEWIDTH'].'" cellspacing="0" cellpadding="3" border="0">'; $out .= '<TR><TD align="left">'; $out .= '<SPAN class="'.$this->styles['TEXTINPUTTITLE'].'">'.$this->data['TEXTINPUT']['TITLE'].'</SPAN>'; $out .= $this->styles['DESCSEPARATOR']; $out .= '<SPAN class="'.$this->styles['TEXTINPUTDESC'].'">'.$this->data['TEXTINPUT']['DESCRIPTION'].'</SPAN>'; $out .= $this->styles['DESCSEPARATOR']; $out .= '<FORM action="'.$this->data['TEXTINPUT']['LINK'].'" method="post" target="'.$this->styles['LINKTARGET'].'">'; $out .= '<INPUT type="text" class="'.$this->styles['TEXTINPUT'].'" name="'.$this->data['TEXTINPUT']['NAME'].'">'; $out .= '<INPUT type="submit" class="'.$this->styles['SUBMIT'].'" value="'.$this->styles['SUBMITVALUE'].'">'; $out .= '</FORM>'; $out .= '</TD></TR>'; $out .= '</TABLE>'; $out .= '</TD></TR>'; $out .= '<TR><TD>'; $out .= $this->styles['ITEMSEPARATOR']; $out .= '</TD></TR>'; } $out .= '</TABLE>'; return $out; } // function OutputOptions($arr) { for (reset($arr); list($k, $v) = each($arr);) { if (isset($this->options[strtoupper($k)])) { $this->options[strtoupper($k)] = $v; } else { $this->error(102); } } } // function OutputStyles($arr) { for (reset($arr); list($k, $v) = each($arr);) { if (isset($this->styles[strtoupper($k)])) { $this->styles[strtoupper($k)] = $v; } else { $this->error(103); } } } // function getRSSData($file) { $this->set_parser(); $this->xml_file($file); if (!$this->current_error) { return $this->data; } return false; } // function startElement($parser, $tag, $attribute) { if (strtoupper(substr($tag,0,3)) == 'RDF') { $tag = substr($tag,4,strlen($tag)); } $this->current_tag = $this->StringToUpper($tag); switch($this->current_tag) { case 'CHANNEL': $this->channel_flag = true; break; case 'IMAGE': $this->image_flag = true; break; case 'TEXTINPUT': $this->input_flag = true; break; case 'ITEM': $this->item_flag = true; $this->item_count++; break; default: break; } } // function endElement($parser, $tag) { switch ($this->StringToUpper($tag)) { case 'CHANNEL': $this->channel_flag = false; break; case 'IMAGE': $this->image_flag = false; break; case 'TEXTINPUT': $this->input_flag = false; break; case 'ITEM': $this->item_flag = false; break; default: break; } } // function getCharacterData($parser, $cdata) { if ($this->channel_flag == true && $this->item_flag == false && $this->image_flag == false && $this->input_flag == false) { if ($this->current_tag != 'CHANNEL') { if (!isset($this->data['CHANNEL'][$this->current_tag])) { $this->data['CHANNEL'][$this->current_tag] = ''; } $this->data['CHANNEL'][$this->current_tag] .= $cdata; } } if ($this->image_flag == true) { if ($this->current_tag != 'IMAGE') { if (!isset($this->data['IMAGE'][$this->current_tag])) { $this->data['IMAGE'][$this->current_tag] = ''; } $this->data['IMAGE'][$this->current_tag] .= $cdata; } } if ($this->input_flag == true) { if ($this->current_tag != 'TEXTINPUT') { if (!isset($this->data['TEXTINPUT'][$this->current_tag])) { $this->data['TEXTINPUT'][$this->current_tag] = ''; } $this->data['TEXTINPUT'][$this->current_tag] .= $cdata; } } if ($this->item_flag == true) { if ($this->current_tag != 'ITEM') { if (!isset($this->data['ITEM'][$this->item_count][$this->current_tag])) { $this->data['ITEM'][$this->item_count][$this->current_tag] = ''; } $this->data['ITEM'][$this->item_count][$this->current_tag] .= $cdata; } } } // function xml_file($file) { $this->fileUrl = $file; if (!($fp = @fopen($file, "r"))) { $this->error(100); } while($data = @fread($fp, 4096)) { if (!(xml_parse($this->parser,$data))) { $this->error(101); } } xml_parser_free($this->parser); } // function set_parser() { $this->parser = xml_parser_create(); xml_set_object($this->parser, $this); xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, $this->case_folding); xml_set_element_handler($this->parser,"startElement","endElement"); xml_set_character_data_handler($this->parser,"getCharacterData"); } // function StringToUpper($tagname) { if ($this->case_folding) { return strtoupper($tagname); } else { return $tagname; } } // function getErrorCode() { if ($this->current_error) { return $this->current_error; } return false; } // function getErrorMessage() { if ($this->current_error) { if (isset($this->error[$this->current_error])) { return $this->error[$this->current_error]; } return false; } return false; } // function error($code) { $this->current_error = $code; } } // end of class /** * @package bigace.classes */ class RSSParserCache extends RSSParser { // var $caching = true; // var $cache_dir = ''; // var $lifetime = 3600; // var $probability = 50; // var $cache_id = ''; // var $error = array( 100 => 'RSS Source: Not avilable', 101 => 'RSS Source: Error while parsing', 102 => 'Unbekannte Output Option', 103 => 'Unbekannter Output Style', 104 => 'Cache Verzeichnis existiert nicht', 105 => 'Cache Directory could not be opened', 106 => 'Konnte Cache Datei nicht lesen', 107 => 'Konnte Cache Datei nicht schreiben' ); // function RSSParserCache($dir) { if (!is_dir($dir)) { $this->error(104); } else { if ( (substr($dir,0,1) != '/') ) { $this->cache_dir = $dir.'/'; } else { $this->cache_dir = $dir; } if ($this->doGarbageCollection()) { $this->deleteTrash(); } $this->RSSParser(); } } // function parseRSS($file) { if ($this->current_error) { return false; } if ($this->caching) { $this->setCacheId($file); if ( !$this->deleteCacheFile($this->cache_dir.$this->cache_id) ) { if (!$output = $this->readCacheFile()) { $this->error(106); } } else { if ( $this->getRSSData($file) ) { $output = $this->getOutput(); if ( !$this->writeCacheFile($output) ) { $this->error(107); } } } } else { $this->getRSSData($file); $output = $this->getOutput(); } if ($this->current_error) { return false; } else { return $output; } } // function enableCaching($caching = true) { $this->caching = $caching; } // function setLifetime($lt) { $this->lifetime = $lt; } // function setCacheId($rssfile) { $options = serialize($this->options); $styles = serialize($this->styles); $this->cache_id = md5($rssfile.$options.$styles); } // function deleteTrash() { if (!($dh = opendir($this->cache_dir))) { $this->error(105); } while ($file = readdir($dh)) { if ($file != '.' && $file != '..') { $this->deleteCacheFile($this->cache_dir.$file); } } closedir($dh); } // function doGarbageCollection() { $nr = rand(1,100); if ($nr <= $this->probability) { return true; } else { return FALSE; } } // function deleteCacheFile($file) { if (!file_exists($file)) { return true; } else { if (is_file($file)){ if (!$fh = fopen($file, "r")) { return true; } $data = fread($fh, filesize($file)); $valid = explode('###', $data); fclose($fh); if (trim($valid[0]) < time()) { @unlink($file); return true; } } } return false; } // function writeCacheFile($output) { if (!$fh = fopen($this->cache_dir.$this->cache_id, "w")) { return false; } $valid = time() + $this->lifetime; flock($fh,2); fwrite($fh, $valid."###".$output); flock($fh,3); fclose($fh); return true; } // function readCacheFile() { if (!($fh = fopen($this->cache_dir.$this->cache_id, "r"))) { return false; } $data = fread($fh, filesize($this->cache_dir.$this->cache_id)); $out = explode('###', $data); fclose($fh); return $out[1]; } } // end of class ?>
gpl-2.0
poeschlr/kicad-3d-models-in-freecad
cadquery/FCAD_script_generator/Battery/battery_pins.py
9172
import battery_common from battery_common import * import battery_contact from battery_contact import * def make_pins(params): manufacture = params.manufacture # Model name serie = params.serie # Model name cellsize = params.cellsize # Battery type cellcnt = params.cellcnt # Number of battery L = params.L # Package width W = params.W # Package width H = params.H # Package height LC = params.LC # Large circle [x pos, y pos, outer diameter, inner diameter, height] BC = params.BC # Blend height A1 = params.A1 # package board seperation pins = params.pins # Pins tht/smd, x pos, y pos, 'round/rect', diameter/x size, y size, length npthpins = params.npthpins # npth holes socket = params.socket # 'type', centre diameter, length, height spigot = params.spigot # Spigot, distance from edge to pin 1, height topear = params.topear # Top ear rotation = params.rotation # Rotation if required modelname = params.modelname # Model name pp = None A11 = get_body_offset(params) for n in pins: if n[0] == 'tht': xx = n[1] yy = n[2] dd1 = n[4] dd2 = n[5] pl = n[6] if n[3] == 'round': pint = cq.Workplane("XY").workplane(offset=A1 + A11).moveTo(xx, 0.0 - yy).circle(dd1 / 2.0, False).extrude(0.0 - (pl + A11)) pint = pint.faces("<Z").fillet(dd1 / 2.2) elif n[3] == 'rect': pint = cq.Workplane("XY").workplane(offset=A1 + A11).moveTo(xx, 0.0 - yy).rect(dd1, dd2).extrude(0.0 - (pl + A11)) if (A11 - A1) > 0.1: pine = cq.Workplane("XY").workplane(offset=A1).moveTo(xx, 0.0 - yy).rect(dd1, 2.0 * dd2).extrude((A11 - A1) + 0.2) pint = pint.union(pine) elif n[3] == 'rectround': pint = cq.Workplane("XY").workplane(offset=A1 + A11).moveTo(xx, 0.0 - yy).rect(dd1, dd2).extrude(0.0 - (pl + A11)) if (A11 - A1) > 0.1: pine = cq.Workplane("XY").workplane(offset=A1).moveTo(xx, 0.0 - yy).rect(dd1, 2.0 * dd2).extrude(A11 + 0.1) pint = pint.union(pine) if dd1 < dd2: pint = pint.faces("<Z").edges(">Y").fillet(dd2 / 2.2) pint = pint.faces("<Z").edges("<Y").fillet(dd2 / 2.2) else: pint = pint.faces("<Z").edges(">X").fillet(dd1 / 2.2) pint = pint.faces("<Z").edges("<X").fillet(dd1 / 2.2) elif n[3] == 'rectbend': # pins = [('tht', -06.605, 00.00, 'rectbend', 01.57, 00.20, 03.16, 01.26), ('tht', 06.605, 00.00, 'rectbend', 01.57, 00.20, 03.16, 01.26)], # Pins tht/smd, x pos, y pos, 'round/rect', diameter/x size, y size, length bh = n[7] dL_3 = pl - (2.0 * bh) hddy = dL_3 * math.sin(math.radians(45.0)) hddx = dL_3 * math.cos(math.radians(45.0)) pts = [] pts.append((0.0, 0.0 - dL_3)) pts.append((0.0 - hddx, 0.0 - dL_3 - hddy)) pts.append((0.0, 0.0 - dL_3 - (2.0 * hddy))) pts.append((0.0, 0.0 - dL_3 - (2.0 * hddy) - 0.2)) pts.append((0.0 - hddx - 0.2, 0.0 - dL_3 - hddy)) pts.append((0.0 - dd2, 0.0 - dL_3)) pts.append((0.0 - dd2, 0.0)) pint = cq.Workplane("XZ").workplane(offset = 0.0).polyline(pts).close().extrude(dd1) if pp == None: pint = pint.translate((xx + (dd2 / 2.0), yy + (3.0 * dd2), A1 + A11)) else: pint = pint.rotate((0,0,0), (0,0,1), 180.0) pint = pint.translate((xx - (dd2 / 2.0), yy - (3.0 * dd2), A1 + A11)) elif n[0] == 'smd': xx = n[1] yy = n[2] dd1 = n[4] dd2 = n[5] if n[3] == 'rect': pint = cq.Workplane("XY").workplane(offset=A1 + A11).moveTo(xx, yy).rect(dd1, dd2).extrude(0.2) if len(n) > 6: dhl2 = n[6] pine = cq.Workplane("XY").workplane(offset=A1 + A11 - 0.1).moveTo(xx, yy).circle(dhl2 / 2.0, False).extrude(0.3) pint = pint.cut(pine) if pp == None: pp = pint else: pp = pp.union(pint) # # The little ear ontop # if topear != None: for n in topear: xx = n[0] yy = n[1] tw = n[2] th = n[3] pint = cq.Workplane("XY").workplane(offset=A1 + A11 + H - 0.1).moveTo(xx, yy).rect(1.0, tw).extrude(th) pint = pint.faces(">Z").edges(">Y").fillet(tw / 2.2) pint = pint.faces(">Z").edges("<Y").fillet(tw / 2.2) pine = cq.Workplane("YZ").workplane(offset=xx - 2.0).moveTo(yy, A1 + A11 + H + th - (tw / 1.5)).circle(tw / 4.0, False).extrude(4.0) pint = pint.cut(pine) pp = pp.union(pint) if BC != None: if BC[0] == 'BC1': pint, pint1 = make_battery_contact_BC1(params) pp = pp.union(pint) pp = pp.union(pint1) elif BC[0] == 'BC2': pint, pint1 = make_battery_contact_BC2(params) pp = pp.union(pint) pp = pp.union(pint1) elif BC[0] == 'BC3': pint, pint1 = make_battery_contact_BC3(params) pp = pp.union(pint) pp = pp.union(pint1) elif BC[0] == 'BC4': pint, pint1 = make_battery_contact_BC4(params) pp = pp.union(pint) pp = pp.union(pint1) elif BC[0] == 'BC5': pint, pint1 = make_battery_contact_BC5(params) pp = pp.union(pint) pp = pp.union(pint1) elif BC[0] == 'BC6': pint, pint1 = make_battery_contact_BC6(params) pp = pp.union(pint) pp = pp.union(pint1) elif BC[0] == 'BC7': pint, pint1 = make_battery_contact_BC7(params) pp = pp.union(pint) pp = pp.union(pint1) elif BC[0] == 'BC8': pint, pint1 = make_battery_contact_BC8(params) pp = pp.union(pint) pp = pp.union(pint1) if (rotation > 0.01): pp = pp.rotate((0,0,0), (0,0,1), rotation) return (pp) def make_npthpins_S2(params): manufacture = params.manufacture # Model name serie = params.serie # Model name cellsize = params.cellsize # Battery type cellcnt = params.cellcnt # Number of battery L = params.L # Package width W = params.W # Package width H = params.H # Package height LC = params.LC # Large circle [x pos, y pos, outer diameter, inner diameter, height] BC = params.BC # Blend height A1 = params.A1 # package board seperation pins = params.pins # Pins tht/smd, x pos, y pos, 'round/rect', diameter/x size, y size, length npthpins = params.npthpins # npth holes socket = params.socket # 'type', centre diameter, length, height spigot = params.spigot # Spigot, distance from edge to pin 1, height topear = params.topear # Top ear rotation = params.rotation # Rotation if required modelname = params.modelname # Model name A11 = get_body_offset(params) # npthpins = ['S2', 15.2, 0.0, 19.00, 1.57, 2.54], # 'type', x, y, circle diameter, pig diameter, pig height))] x1 = npthpins[1] y1 = npthpins[2] largeradie = npthpins[3] / 2.0 pinradie = npthpins[4] / 2.0 pinlength = npthpins[5] # x = largeradie * math.sin(math.radians(0.0)) y = 0.0 - largeradie * math.cos(math.radians(0.0)) pint = cq.Workplane("XY").workplane(offset=A1 + A11).moveTo(x1 + x, y1 + y).circle(pinradie, False).extrude(0.0 - pinlength) pint = pint.faces("<Z").fillet(pinradie / 2.2) # x = largeradie * math.sin(math.radians(120.0)) y = 0.0 - largeradie * math.cos(math.radians(120.0)) pine = cq.Workplane("XY").workplane(offset=A1 + A11).moveTo(x1 + x, y1 + y).circle(pinradie, False).extrude(0.0 - pinlength) pine = pine.faces("<Z").fillet(pinradie / 2.2) pint = pint.union(pine) # x = largeradie * math.sin(math.radians(240.0)) y = 0.0 - largeradie * math.cos(math.radians(240.0)) pine = cq.Workplane("XY").workplane(offset=A1 + A11).moveTo(x1 + x, y1 + y).circle(pinradie, False).extrude(0.0 - pinlength) pine = pine.faces("<Z").fillet(pinradie / 2.2) pint = pint.union(pine) return pint
gpl-2.0
srinivas-qfor/jkc-wp
wp-content/themes/jeanknowscars/assets/js/mod-list-item-faq-management.js
2578
;var SorcWeb = SorcWeb || {}; // Global object (function(sorcWeb, $){ "use strict"; sorcWeb.modFaqManagement = {}; var mod = sorcWeb.modFaqManagement; mod.vars = {}; mod.init = function(){ this.setVars(); this.setSelectors(); this.setEvents(); }; mod.setVars = function(){ }; mod.setSelectors = function(){ mod.module = $('.mod-list-item-faq-management'); }; mod.setEvents = function(){ mod.processTextArea(); mod.module.on('click', '.post-answer-button', function() { if (!$(this).hasClass('disabled')) { var wrap = $(this).parent().parent(); var parent = $(this).parent(); var text = parent.find('textarea').val(); var pid = $(this).attr('data-pid'); parent.find('.ajax-loader').show(); $.ajax({ url: '/ask-jean-question/management/post/', data: {text : text, pid : pid}, type: "POST", dataType: 'JSON' }).done(function(data) { if (data.status == 'success') { wrap.html('<div class="thanks">Answered</div>'); } else { wrap.html('<div class="error">'+data.message+'</div>') } }).error(function(){ wrap.html('<div class="error">Post was not successful, please try again or contact an administrator.</div>') }); } }); mod.module.on('click', '.answer-link', function(){ $(this).hide(); $(this).parent().find('.answer-wrap').show(); }); mod.module.on('click', '.cancel-answer-button', function() { $(this).parent().hide(); $(this).parent().parent().find('.answer-link').show(); }); }; mod.processTextArea = function() { mod.module.find('textarea.no-js').each(function(){ $(this).removeClass('no-js').keyup(function () { var charLength = $(this).val().length; if (charLength === 0) { $(this).parent().find('.post-answer-button').toggleClass('disabled', true); } else { $(this).parent().find('.post-answer-button').toggleClass('disabled', false); } }); }); }; return(mod.init()); })(SorcWeb, jQuery);
gpl-2.0
seobrand/twit2pay_dev
backup-29-07/cakeversion/app/View/Themed/Admin/webroot/js/e_styleswitcher.1.0.js
4203
/* * ************************************************************* * * Name : eStyleSwitcher * * Date : January 2012 * * Owner : CreativeMilk * * Url : www.creativemilk.net * * Version : 1.0 * * Updated : --/--/---- * * Developer : Mark * * Dependency : * * Lib : jQuery 1.7+ * * Licence : NOT free * * http://themeforest.net/item/elite-a-powerfull-responsive-admin-theme/2997200 * ************************************************************* * */ ;(function($, window, document, undefined){ $.fn.eStyleSwitcher = function(options) { options = $.extend({}, $.fn.eStyleSwitcher.options, options); return this.each(function() { /** * Variables. **/ var obj = $(this); /** * Check for touch support and set right click events. **/ if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch){ var clickEvent = 'click tap'; }else{ var clickEvent = 'click'; } /** * Append a loading image/overlay to the body. **/ $('body').append('<div id="e-styleswitcher-overlay"><div><img src="img/loaders/type3/dark/24.gif" alt=""/><span>Changing style...</span></div></div>'); /** * Function for re-use. **/ function switchCss(style){ /** * Add the new stylesheet to the DOM. **/ $(options.target).attr('href', options.dir+''+style+'.css'); } /** * Run the localstorage if there is a key present and we can use localstorage. **/ if(options.storeStyle === true && localStorage && localStorage.getItem('e_style') != null){ switchCss(localStorage.getItem('e_style')); } if(obj.is('select')){ obj.change(function(e){ /** * Get the new stylesheet. **/ var theme = $(this).val(); /** * Show a indicator image. **/ $('#e-styleswitcher-overlay').fadeTo(100,1.0,function(){ /** * Run the callback function. **/ if(typeof options.onSwitch == 'function'){ options.onSwitch.call(this); } /** * Switch css function. **/ switchCss(theme); /** * Save the value. **/ if(options.storeStyle === true && localStorage ){ localStorage.setItem('e_style', theme); } }); /** * Fadeout. **/ $('#e-styleswitcher-overlay').delay(1000).fadeOut(); }); }else{ /** * Run with a simple click. **/ obj.on(clickEvent, 'a', function(e){ /** * Get the new stylesheet. **/ var theme = $(this).data('styleswitcher-color'); /** * Show a indicator image. **/ $('#e-styleswitcher-overlay').fadeTo(100,1.0,function(){ /** * Run the callback function. **/ if(typeof options.onSwitch == 'function'){ options.onSwitch.call(this); } /** * Switch css function. **/ switchCss(theme); /** * Save the value. **/ if(options.storeStyle === true && localStorage ){ localStorage.setItem('e_style', theme); } }); /** * Fadeout. **/ $('#e-styleswitcher-overlay').delay(100).fadeOut(); e.preventDefault(); }); } }); }; /** * Default settings(dont change). * You can globally override these options * by using $.fn.pluginName.key = 'value'; **/ $.fn.eStyleSwitcher.options = { target: '#themesheet', dir: WEBROOT+'css/theme/', storeStyle: true, onSwitch: function(){ } }; })(jQuery, window, document);
gpl-2.0
udacity/discourse
app/models/activity.rb
784
class Activity < ActiveRecord::Base belongs_to :user belongs_to :trackable, :polymorphic => true attr_accessible :action, :trackable validates :user_id, :trackable_id, :trackable_type, :action, :presence => true BATCH_SIZE = 1000 MAX_BATCH_SIZE = 5000 scope :logged_after, ->(options) do return unless options[:offset] user_id = options[:user_id] batch_size = options[:batch_size] || BATCH_SIZE include_trackable = options[:detailed] == 'true' batch_size = [batch_size, MAX_BATCH_SIZE].min conditions = where('id > ?', options[:offset]).order(:id).limit(batch_size).includes(:user) conditions = conditions.includes(:trackable) if include_trackable conditions = conditions.where(:user_id => user_id) if user_id conditions end end
gpl-2.0
AlexeyGuryev/TestTasks
FurnitureStorage/StoragePersistence/Migrations/Configuration.cs
1061
namespace StoragePersistence.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<StoragePersistence.StorageEFContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(StoragePersistence.StorageEFContext context) { context.Rooms.AddOrUpdate(); // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // } } }
gpl-2.0
ngocphan123/nukeviet-1
includes/language/fr/admin_themes.php
9508
<?php /** * @Project NUKEVIET 4.x * @Author VINADES.,JSC <contact@vinades.vn> * @Copyright (C) 2017 VINADES.,JSC. All rights reserved * @Language Français * @License CC BY-SA (http://creativecommons.org/licenses/by-sa/4.0/) * @Createdate Jun 21, 2010, 10:30:00 AM */ if (!defined('NV_ADMIN') or !defined('NV_MAINFILE')) { die('Stop!!!'); } $lang_translator['author'] = 'Phạm Chí Quang'; $lang_translator['createdate'] = '21/6/2010, 17:30'; $lang_translator['copyright'] = '@Copyright (C) 2010 VINADES.,JSC. Tous droits réservés.'; $lang_translator['info'] = 'Langue française pour NukeViet 4'; $lang_translator['langtype'] = 'lang_module'; $lang_module['blocks'] = 'Gestion des blocks'; $lang_module['change_func_name'] = 'Renommer la fonction &ldquo;%1$s&rdquo; du module &ldquo;%2$s&rdquo;'; $lang_module['bl_list_title'] = 'Les blocks à &ldquo;%1$s&rdquo; de la fonction &ldquo;%2$s&rdquo;'; $lang_module['add_block_title'] = 'Ajouter le block à &ldquo;%1$s&rdquo; de la fonction &ldquo;%2$s&rdquo; du module &ldquo;%3$s&rdquo;'; $lang_module['edit_block_title'] = 'Modifier le block &ldquo;%1$s&rdquo; à &ldquo;%2$s&rdquo; de la fonction &ldquo;%3$s&rdquo; du module &ldquo;%4$s&rdquo;'; $lang_module['block_add'] = 'Ajouter un block'; $lang_module['block_edit'] = 'Modifier le block'; $lang_module['block_title'] = 'Titre de block'; $lang_module['block_link'] = 'Lien de titre de block'; $lang_module['block_file_path'] = 'Prendre contenu du fichier'; $lang_module['block_global_apply'] = 'Appliquer pour tous'; $lang_module['block_type_theme'] = 'bloque d\'interface'; $lang_module['block_select_type'] = 'Sélectionner un type'; $lang_module['block_tpl'] = 'Modèle'; $lang_module['block_pos'] = 'Position'; $lang_module['block_groupbl'] = 'Dans le groupe'; $lang_module['block_leavegroup'] = 'Retirer du groupe et créer un nouveau groupe'; $lang_module['block_group_notice'] = 'Note: Si on modifie une bloque dans un groupe alors cela modifie toutes les autres bloques dans les autres groupes.Si vous voulez modifier des autres bloques dans le meme groupe, séparez-les en nouveaux groupes en cochant le rubrique <em>Enlever du groupe et créer un nouveau groupe</em>.'; $lang_module['block_group_block'] = 'Groupe'; $lang_module['block_no_more_func'] = 'Si vous cochez Retirer du groupe, sélectionnez une seule fonction'; $lang_module['block_no_func'] = 'Sélectionnez au moins une fonction'; $lang_module['block_limit_func'] = 'Si vous confirmez de retirer du groupe, désignnez une fonction à un block'; $lang_module['block_func'] = 'Aréa'; $lang_module['block_nums'] = 'Quantité de blocks du groupe'; $lang_module['block_count'] = 'blocks'; $lang_module['block_func_list'] = 'Fonctions'; $lang_module['blocks_by_funcs'] = 'Gestion des blocks selon fonction'; $lang_module['block_yes'] = 'Oui'; $lang_module['block_active'] = 'Activer'; $lang_module['block_group'] = 'Qui peut voir'; $lang_module['block_module'] = 'Afficher au module'; $lang_module['block_all'] = 'Tous les modules'; $lang_module['block_confirm'] = 'Confirmer'; $lang_module['block_default'] = 'Défaut'; $lang_module['block_exp_time'] = 'Date d\'expiration'; $lang_module['block_sort'] = 'Arranger'; $lang_module['block_change_pos_warning'] = 'Si vous changez la position de ce block, la position de tous les autres blocks du groupe sera changée'; $lang_module['block_change_pos_warning2'] = 'Confirmer le changement de position?'; $lang_module['block_error_nogroup'] = 'Choisissez au moins 1 groupe'; $lang_module['block_error_noblock'] = 'Choisissez au moins 1 block'; $lang_module['block_error_nsblock'] = 'Block pas encore choisi ou nom du block invalide'; $lang_module['block_delete_confirm'] = 'Êtes-vous sûr de vouloir supprimer tous les blocks sélectionnés? Attention: il est impossible de les restaurer'; $lang_module['block_delete_per_confirm'] = 'Êtes-vous sûr de vouloir supprimer ce block?'; $lang_module['block_add_success'] = 'Ajout réussi!'; $lang_module['block_update_success'] = 'Mise à jour réussie!'; $lang_module['block_checkall'] = 'Sélectionner tout'; $lang_module['block_uncheckall'] = 'Désélectionner tout'; $lang_module['block_delete_success'] = 'Suppression réussie'; $lang_module['block_error_nomodule'] = 'Choisissez au moins 1 module'; $lang_module['error_empty_content'] = 'Ce Block n\'est pas accès au fichier, bannière ou manque de contenu'; $lang_module['block_type'] = 'Type de block'; $lang_module['block_file'] = 'Fichier'; $lang_module['block_html'] = 'HTML'; $lang_module['block_typehtml'] = 'Type HTML'; $lang_module['functions'] = 'Fonctionnalité'; $lang_module['edit_block'] = 'Modifier le block'; $lang_module['block_function'] = 'Sélectionnez la fonction'; $lang_module['add_block_module'] = 'Appliquer pour les modules'; $lang_module['add_block_all_module'] = 'Tous les modules'; $lang_module['add_block_select_module'] = 'Sélectionnez le module'; $lang_module['block_layout'] = 'Sélectionner Layout'; $lang_module['block_select'] = 'Sélectionner block'; $lang_module['block_check'] = 'Vérifier'; $lang_module['block_select_module'] = 'Sélectionner le module'; $lang_module['block_select_function'] = 'Sélectionner la fonction'; $lang_module['block_error_fileconfig_title'] = 'Erreur du fichier de configuration de Thème'; $lang_module['block_error_fileconfig_content'] = 'Fichier de configuration de Thème incorrect ou inexistant. Vérifiez votre répertoire de Thème'; $lang_module['package_theme_module'] = 'Emballer le thème du module'; $lang_module['autoinstall_continue'] = 'Suivant'; $lang_module['back'] = 'Revenir'; $lang_module['autoinstall_error_nomethod'] = 'Choississez une méthode d\'installation !'; $lang_module['autoinstall_package_select'] = 'Sélectionner le Thème à paqueter'; $lang_module['autoinstall_package_noselect'] = 'Sélectionner un Thème pour paqueter'; $lang_module['autoinstall_package_module_select'] = 'Sélectionner le module pour paqueter'; $lang_module['autoinstall_package_noselect_module'] = 'Choisissez 1 module pour paqueter le Thème'; $lang_module['autoinstall_method_theme_none'] = 'Sélectionez le Thème'; $lang_module['autoinstall_method_module_none'] = 'Choisissez un modules'; $lang_module['package_noselect_module_theme'] = 'Obligé de choisir un thème et un nom de module pour l\'emballage'; $lang_module['setup_layout'] = 'Configuration de Layout'; $lang_module['setup_module'] = 'Module'; $lang_module['setup_select_layout'] = 'Sélectionner le Layout'; $lang_module['setup_updated_layout'] = 'Configuration de Layout avec succès!'; $lang_module['setup_error_layout'] = 'Impossible de configurer le Layout'; $lang_module['setup_save_layout'] = 'Sauver'; $lang_module['theme_manager'] = 'Gestion de Thèmes'; $lang_module['theme_recent'] = 'Liste des Thèmes existants'; $lang_module['theme_created_by'] = 'Réalisé par'; $lang_module['theme_created_website'] = 'Visiter le site de l\'auteur'; $lang_module['theme_created_folder'] = 'Les Fichiers et Répertoires:'; $lang_module['theme_created_position'] = 'Les positions conçus du Thème:'; $lang_module['theme_created_activate'] = 'Activer'; $lang_module['theme_created_setting'] = 'Configuration de l\'interface selon la configuration par défaut'; $lang_module['theme_created_activate_layout'] = 'Erreur: Vous devez configurer le Layout avant d\'activer le Thème'; $lang_module['theme_delete'] = 'Supprimer les configurations'; $lang_module['theme_delete_confirm'] = 'Voulez-vous vraiment supprimer les configurations:'; $lang_module['theme_delete_success'] = 'Suppression des configuration de l\'interface réussite'; $lang_module['theme_delete_unsuccess'] = 'Erreur dans la suppression de la configuration de l\'interface'; $lang_module['theme_created_current_use'] = 'Thème actuel'; $lang_module['block_front_delete_error'] = 'Erreur: Impossible de supprimer le block, merci de vérifier vos attributions'; $lang_module['block_front_outgroup_success'] = 'Le Block a été retiré et ajouté au groupe'; $lang_module['block_front_outgroup_cancel'] = 'Il n\'est pas nécessaire de retirer le block du groupe par ce qu\'il y a un seul block dans ce groupe'; $lang_module['block_front_outgroup_error_update'] = 'Erreur de mise à jour de données'; $lang_module['xcopyblock'] = 'Copie de blocks'; $lang_module['xcopyblock_to'] = 'vers'; $lang_module['xcopyblock_from'] = ' à partir de'; $lang_module['xcopyblock_position'] = 'Choisir la position'; $lang_module['xcopyblock_process'] = 'Copier'; $lang_module['xcopyblock_no_position'] = 'Choisissez au moins 1 position'; $lang_module['xcopyblock_notice'] = 'Le système supprimera les blocks existants au thème cible. Merci de patienter.'; $lang_module['xcopyblock_success'] = 'Copie avec succès!'; $lang_module['block_weight'] = 'Rétablir la position des blocks'; $lang_module['block_weight_confirm'] = 'Êtes vous sur de vouloir rétablir la position des blocks?'; $lang_module['autoinstall_theme_error_warning_overwrite'] = 'Notification: Fichiers existants. Voulez-vous remplacer ces fichiers?'; $lang_module['autoinstall_theme_overwrite'] = 'Remplacer'; $lang_module['config'] = 'Configuration d\'interface'; $lang_module['config_not_exit'] = 'L\'interface %s ne peut pas être configurée'; $lang_module['show_device'] = 'Affiche le nom de l\'appareil'; $lang_module['show_device_1'] = 'Tous'; $lang_module['show_device_2'] = 'Afficher mobiles'; $lang_module['show_device_3'] = 'Afficher sur tablette'; $lang_module['show_device_4'] = 'Autres équipements';
gpl-2.0
auth0/wp-auth0
examples/auth0_jwt_max_age.php
278
<?php /** * Filter the max_age login parameter. * * @param integer $max_age - Existing max_age time, defaults to empty. * * @return integer */ function example_auth0_jwt_max_age( $max_age ) { return 1200; } add_filter( 'auth0_jwt_max_age', 'example_auth0_jwt_max_age' );
gpl-2.0
koalagon/supexlms
Lms.Domain/Models/Commons/Currency.cs
763
using Lms.Domain.Models.Plans; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lms.Domain.Models.Commons { public class Currency { public Currency() { this.Id = Guid.NewGuid().ToString(); } [Key] [StringLength(128)] [DatabaseGenerated(DatabaseGeneratedOption.None)] public string Id { get; set; } [StringLength(128)] public string Name { get; set; } [StringLength(128)] public string Code { get; set; } public virtual ICollection<Plan> Plans { get; set; } } }
gpl-2.0
bb-generation/gobby
code/core/documentinfostorage.hpp
3316
/* Gobby - GTK-based collaborative text editor * Copyright (C) 2008-2011 Armin Burgmeier <armin@arbur.net> * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef _GOBBY_OPERATIONS_DOCUMENTINFO_STORAGE_HPP_ #define _GOBBY_OPERATIONS_DOCUMENTINFO_STORAGE_HPP_ #include <libinfgtk/inf-gtk-browser-model.h> #include <libxml++/nodes/element.h> #include <glibmm/ustring.h> #include <sigc++/trackable.h> #include <map> namespace Gobby { class DocumentInfoStorage: public sigc::trackable { public: enum EolStyle { EOL_CRLF, EOL_LF, EOL_CR }; struct Info { Glib::ustring uri; EolStyle eol_style; std::string encoding; }; DocumentInfoStorage(InfGtkBrowserModel* model); ~DocumentInfoStorage(); std::string get_key(InfcBrowser* browser, InfcBrowserIter* iter) const; const Info* get_info(InfcBrowser* browser, InfcBrowserIter* iter) const; const Info* get_info(const std::string& key) const; void set_info(InfcBrowser* browser, InfcBrowserIter* iter, const Info& info); void set_info(const std::string& key, const Info& info); protected: static void on_set_browser_static(InfGtkBrowserModel* model, GtkTreePath* path, GtkTreeIter* iter, InfcBrowser* browser, gpointer user_data) { static_cast<DocumentInfoStorage*>(user_data)-> on_set_browser(iter, browser); } static void on_begin_explore_static(InfcBrowser* browser, InfcBrowserIter* iter, InfcExploreRequest* request, gpointer user_data) { static_cast<DocumentInfoStorage*>(user_data)-> on_begin_explore(browser, iter, request); } static void on_node_removed_static(InfcBrowser* browser, InfcBrowserIter* iter, gpointer user_data) { static_cast<DocumentInfoStorage*>(user_data)-> on_node_removed(browser, iter); } void on_set_browser(GtkTreeIter* iter, InfcBrowser* browser); void on_begin_explore(InfcBrowser* browser, InfcBrowserIter* iter, InfcExploreRequest* request); void on_node_removed(InfcBrowser* browser, InfcBrowserIter* iter); typedef std::map<std::string, Info> InfoMap; InfoMap m_infos; class BrowserConn; typedef std::map<InfcBrowser*, BrowserConn*> BrowserMap; BrowserMap m_browsers; gulong m_set_browser_handler; InfGtkBrowserModel* m_model; private: void init(xmlpp::Element* node); }; } #endif // _GOBBY_OPERATIONS_DOCUMENTINFO_STORAGE_HPP_
gpl-2.0
yast/yast-installation
test/ssh_config_test.rb
8439
#! /usr/bin/env rspec # Copyright (c) 2016 SUSE LLC. # All Rights Reserved. # This program is free software; you can redistribute it and/or # modify it under the terms of version 2 or 3 of the GNU General # Public License 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 General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program; if not, contact SUSE LLC. # To contact SUSE about this file by physical or electronic mail, # you may find current contact information at www.suse.com require_relative "./test_helper" require "installation/ssh_config" require "tmpdir" require "fileutils" describe Installation::SshConfig do describe ".from_dir" do textdomain "installation" let(:recent_root1_atime) { Time.now } let(:old_root1_atime) { Time.now - 60 } let(:root1_dir) { FIXTURES_DIR.join("root1") } let(:root2_dir) { FIXTURES_DIR.join("root2") } let(:root3_dir) { FIXTURES_DIR.join("root3") } let(:root4_dir) { FIXTURES_DIR.join("root4") } before do textdomain "installation" # The ssh_host private key file is more recent than any other file allow(File).to receive(:atime) do |path| (path =~ /ssh_host_key$/) ? recent_root1_atime : old_root1_atime end end it "reads the name of the systems with /etc/os-release" do root1 = described_class.from_dir(root1_dir) expect(root1.system_name).to eq "Operating system 1" end it "does not crash if /etc/os-release contains empty value" do # root1 contains empty `EMPTY=` line expect { described_class.from_dir(root1_dir) }.to_not raise_error end it "uses 'Linux' as name for systems without /etc/os-release file" do root2 = described_class.from_dir(root2_dir) expect(root2.system_name).to eq _("Linux") root4 = described_class.from_dir(root4_dir) expect(root4.system_name).to eq _("Linux") end it "uses name and version when PRETTY_NAME is missing in /etc/os-release" do root3 = described_class.from_dir(root3_dir) expect(root3.system_name).to eq "SUSE 10" end it "stores all the keys and files with their names" do root1 = described_class.from_dir(root1_dir) root2 = described_class.from_dir(root2_dir) expect(root1.config_files.map(&:name)).to contain_exactly( "moduli", "ssh_config", "sshd_config" ) expect(root1.keys.map(&:name)).to contain_exactly( "ssh_host_dsa_key", "ssh_host_key" ) expect(root2.config_files.map(&:name)).to contain_exactly( "known_hosts", "ssh_config", "sshd_config" ) expect(root2.keys.map(&:name)).to contain_exactly( "ssh_host_ed25519_key", "ssh_host_key" ) end it "stores the content of the config files" do root1 = described_class.from_dir(root1_dir) expect(root1.config_files.map(&:content)).to contain_exactly( "root1: content of moduli file\n", "root1: content of ssh_config file\n", "root1: content of sshd_config file\n" ) end it "stores the content of both files for the keys" do root1 = described_class.from_dir(root1_dir) contents = root1.keys.map { |k| k.files.map(&:content) } expect(contents).to contain_exactly( ["root1: content of ssh_host_dsa_key file\n", "root1: content of ssh_host_dsa_key.pub file\n"], ["root1: content of ssh_host_key file\n", "root1: content of ssh_host_key.pub file\n"] ) end it "uses the most recent file of each key to set #atime" do root1 = described_class.from_dir(root1_dir) host_key = root1.keys.detect { |k| k.name == "ssh_host_key" } host_dsa_key = root1.keys.detect { |k| k.name == "ssh_host_dsa_key" } expect(host_key.atime).to eq recent_root1_atime expect(host_dsa_key.atime).to eq old_root1_atime end end describe ".write_files" do def permissions(file) format("%o", File.stat(file).mode)[-3..-1] end around do |example| # Git does not preserve file permissions (only the executable bit), # so let's copy test/fixtures to a temporal directory and ensure # sensible permissions there Dir.mktmpdir do |dir| ::FileUtils.cp_r(FIXTURES_DIR.join("root1"), dir) Dir.glob("#{dir}/root1/etc/ssh/*").each do |file| if file.end_with?("_key", "sshd_config", "moduli") File.chmod(0o600, file) elsif File.directory?(file) File.chmod(0o755) else File.chmod(0o644, file) end end @config = Installation::SshConfig.from_dir(File.join(dir, "root1")) end Dir.mktmpdir do |dir| @target_dir = dir example.run end end let(:ssh_dir) { File.join(@target_dir, "etc", "ssh") } it "creates /etc/ssh/ if it does not exist" do @config.write_files(@target_dir) expect(Dir.glob("#{@target_dir}/etc/*")).to eq ["#{@target_dir}/etc/ssh"] end it "reuses /etc/ssh if it's already there" do ::FileUtils.mkdir_p(ssh_dir) ::FileUtils.touch(File.join(ssh_dir, "preexisting_file")) @config.write_files(@target_dir, write_keys: false) files = Dir.glob("#{ssh_dir}/*") expect(files.size).to eq(@config.config_files.size + 1) expect(files).to include "#{ssh_dir}/preexisting_file" end it "writes all the files by default" do @config.write_files(@target_dir) target_content = Dir.glob("#{ssh_dir}/*") expect(target_content).to contain_exactly( "#{ssh_dir}/ssh_host_key", "#{ssh_dir}/ssh_host_key.pub", "#{ssh_dir}/ssh_host_dsa_key", "#{ssh_dir}/ssh_host_dsa_key.pub", "#{ssh_dir}/moduli", "#{ssh_dir}/ssh_config", "#{ssh_dir}/sshd_config" ) end it "writes only the key files if write_config_files is false" do @config.write_files(@target_dir, write_config_files: false) target_content = Dir.glob("#{ssh_dir}/*") expect(target_content).to contain_exactly( "#{ssh_dir}/ssh_host_key", "#{ssh_dir}/ssh_host_key.pub", "#{ssh_dir}/ssh_host_dsa_key", "#{ssh_dir}/ssh_host_dsa_key.pub" ) end it "writes only the config files if write_keys is false" do @config.write_files(@target_dir, write_keys: false) target_content = Dir.glob("#{ssh_dir}/*") expect(target_content).to contain_exactly( "#{ssh_dir}/moduli", "#{ssh_dir}/ssh_config", "#{ssh_dir}/sshd_config" ) end it "preserves original permissions for files and keys" do @config.write_files(@target_dir) expect(permissions("#{ssh_dir}/moduli")).to eq "600" expect(permissions("#{ssh_dir}/ssh_config")).to eq "644" expect(permissions("#{ssh_dir}/ssh_host_key")).to eq "600" expect(permissions("#{ssh_dir}/ssh_host_key.pub")).to eq "644" end it "backups config files found in the target directory" do ::FileUtils.mkdir_p(ssh_dir) ::FileUtils.touch(File.join(ssh_dir, "moduli")) @config.write_files(@target_dir) expect(File.exist?(File.join(ssh_dir, "moduli.yast.orig"))).to eq true end it "writes the original content for each file" do @config.write_files(@target_dir) expect(File.read("#{ssh_dir}/moduli")).to eq( "root1: content of moduli file\n" ) expect(File.read("#{ssh_dir}/ssh_host_key")).to eq( "root1: content of ssh_host_key file\n" ) expect(File.read("#{ssh_dir}/ssh_host_key.pub")).to eq( "root1: content of ssh_host_key.pub file\n" ) end end describe "#keys_atime" do subject(:config) { ::Installation::SshConfig.new("name") } let(:now) { Time.now } it "returns the access time of the most recently accessed key" do config.keys = [ instance_double("Installation::SshKey", atime: now), instance_double("Installation::SshKey", atime: now + 1200), instance_double("Installation::SshKey", atime: now - 1200) ] expect(config.keys_atime).to eq(now + 1200) end it "returns nil if no keys has been read" do expect(config.keys_atime).to be_nil end end end
gpl-2.0
upei/drupal6-cms
sites/all/modules/webfm/js/webfm.js
137201
/* $Id: webfm.js,v 1.29 2008/12/06 04:49:16 robmilne Exp $ */ /* namespace */ function Webfm() {} /* ** Global variables */ //Translation possible by changing the array values (DO NOT ALTER KEYS!) Webfm.js_msg = []; Webfm.js_msg["mkdir"] = "Create New Dir"; Webfm.js_msg["file"] = "file"; Webfm.js_msg["dir"] = "directory"; Webfm.js_msg["u_file"] = "File"; Webfm.js_msg["u_dir"] = "Directory"; Webfm.js_msg["tree"] = ""; Webfm.js_msg["work"] = "Working... please wait"; Webfm.js_msg["refresh"] = "refresh"; Webfm.js_msg["sort"] = "sort by this column"; Webfm.js_msg["new-dir"] = "Create New Folder"; Webfm.js_msg["add-2-db"] = "Add files in this folder to database"; Webfm.js_msg["r-add-2-db"] = "Recursive add files to database"; Webfm.js_msg["column1"] = "Name"; Webfm.js_msg["column2"] = "Modified"; Webfm.js_msg["column3"] = "Size"; Webfm.js_msg["column4"] = "Owner"; Webfm.js_msg["attach-title"] = "Attached Files"; Webfm.js_msg["meta-title"] = "File Meta Data"; Webfm.js_msg["search-title"] = "File Search"; Webfm.js_msg["debug-title"] = "WebFM Debug"; Webfm.js_msg["cache-title"] = "Directory Cache"; Webfm.js_msg["search-cur"] = "Search current directory (see listing breadcrumb trail)"; Webfm.js_msg["no-match"] = "No match found"; Webfm.js_msg["search"] = "Search"; Webfm.js_msg["submit"] = "Submit"; Webfm.js_msg["reset"] = "Reset"; Webfm.js_msg["clear"] = "Clear"; Webfm.js_msg["cancel"] = "Cancel"; Webfm.js_msg["close"] = "Close"; Webfm.js_msg["resize"] = "Resize"; Webfm.js_msg["replace"] = "Replace and Version original copy of "; Webfm.js_msg["replace-del"] = "Replace and Delete original copy of "; Webfm.js_msg["no-replace"] = "Version new copy of "; Webfm.js_msg["cache"] = "Cache Content"; Webfm.js_msg["curdir-undef"] = "current directory undefined"; Webfm.js_msg["ajax-err"] = "server is unreachable"; Webfm.js_msg["move-err"] = "move operation fail"; Webfm.js_msg["len-err"] = "Too long"; Webfm.js_msg["confirm-del0"] = "Do you want to delete the "; Webfm.js_msg["confirm-del1"] = " and all its contents"; Webfm.js_msg["confirm-det"] = "Do you want to detach "; Webfm.js_msg["confirm-dbrem0"] = "Do you want to remove "; Webfm.js_msg["confirm-dbrem1"] = " from the database?\n All metadata and attachments for this file will be lost"; Webfm.js_msg["enum_local"] = "Do you want to add all files of this directory into the database?"; Webfm.js_msg["enum_recur"] = "Do you want to add all files of this directory and sub-directories into the database?"; Webfm.js_msg["file-dwld"] = "download file"; Webfm.js_msg["no-file-dwld"] = "file not in database"; Webfm.js_msg["inserted"] = " files inserted into db"; Webfm.js_msg["not-inserted"] = " files failed to insert into db"; Webfm.js_msg["metadata"] = "Metadata"; Webfm.js_msg["fix_input"] = "correct input"; Webfm.js_msg["perm"] = "File Permissions"; Webfm.meta_msg = []; Webfm.meta_msg["fid"] = "fid"; Webfm.meta_msg["uid"] ="uid"; Webfm.meta_msg["uname"] ="file owner"; Webfm.meta_msg["name"] = "name"; Webfm.meta_msg["title"] = "title"; Webfm.meta_msg["desc"] = "description"; Webfm.meta_msg["lang"] = "language"; Webfm.meta_msg["pub"] = "publisher"; Webfm.meta_msg["format"] = "format"; Webfm.meta_msg["ver"] = "version"; Webfm.meta_msg["type"] = "image type"; Webfm.meta_msg["width"] = "width"; Webfm.meta_msg["height"] = "height"; Webfm.meta_msg["dl_cnt"] = "downloads"; Webfm.meta_msg["link"] = "link"; Webfm.perm_msg = []; Webfm.perm_msg["pub_view"] = "Public download"; Webfm.perm_msg["rol_view"] = "Role View/Download"; Webfm.perm_msg["rol_att"] = "Role Attach"; Webfm.perm_msg["rol_full"] = "Role Full Access"; Webfm.menu_msg = []; Webfm.menu_msg["mkdir"] = "Create Subdirectory"; Webfm.menu_msg["rmdir"] = "Delete Directory"; Webfm.menu_msg["rm"] = "Delete File"; Webfm.menu_msg["rendir"] = "Rename Directory"; Webfm.menu_msg["search"] = "Search Directory"; Webfm.menu_msg["ren"] = "Rename File"; Webfm.menu_msg["meta"] = "File meta data"; Webfm.menu_msg["att"] = "Attach to Node"; Webfm.menu_msg["det"] = "Detach from Node"; Webfm.menu_msg["dwnld"] = "Download as file"; Webfm.menu_msg["view"] = "View file"; Webfm.menu_msg["enum"] = "Add file to database"; Webfm.menu_msg["denum"] = "Remove file from database"; Webfm.menu_msg["perm"] = "File permissions"; Webfm.menu_msg["clip"] = "Copy link to clipboard"; Webfm.menu_msg["paste"] = "Paste link in editor window"; //Do not translate any code below this line Webfm.current = null; Webfm.dragCont = null; Webfm.metaCont = null; Webfm.contextCont = null; Webfm.searchCont = null; Webfm.debugCont = null Webfm.viewCont = null; Webfm.dragStart = null; Webfm.dragging = false; Webfm.oldOnContextMenu = null; Webfm.activeDropCont = null; Webfm.dropContainers = []; Webfm.attachContainer = null; Webfm.browser = null; Webfm.menuHT = null; Webfm.metadataHT = null; Webfm.dirTreeObj = null; Webfm.dirListObj = null; Webfm.attachObj = null; Webfm.alrtObj = null; Webfm.contextMenuObj = null; Webfm.progressObj = null; Webfm.dbgObj = null; Webfm.metaObj = null; Webfm.searchObj = null; Webfm.permObj = null; Webfm.permKey = null; Webfm.permHT = null; Webfm.permInfoHT = null; Webfm.renameActive = null; Webfm.admin = false; Webfm.zindex = 1000; Webfm.scrollVal = null; // freeze scroll Webfm.eventListeners = []; //Name of node edit form hidden field where attached node list is populated by js Webfm.attachFormInput = "edit-attachlist" Webfm.icons = { epdf:"pdf", ephp:"php", ephps:"php", ephp4:"php", ephp5:"php", eswf:"swf", esfa:"swf", exls:"xls", edoc:"doc", ertf:"doc", ezip:"zip", erar:"zip", egz:"zip", e7z:"zip", etxt:"doc", echm:"hlp", ehlp:"hlp", enfo:"nfo", expi:"xpi", ec:"c", eh:"h", emp3:"mp3", ewav:"mp3", esnd:"mp3", einc:"cod", esql:"sql", edbf:"sql", ediz:"nfo", eion:"nfo", emod:"mp3", es3m:"mp3", eavi:"avi", empg:"avi", empeg:"avi", ewma:"mp3", ewmv:"avi", edwg:"dwg", ejpg:"i", ejpeg:"i", egif:"i", epng:"i", etiff:"i", ebmp:"i", eico:"i", eai:"ai", eskp:"skp", emov:"qt", epps:"pps", eppt:"pps" }; Webfm.lastarea = null; /* ** Functions */ if (Drupal.jsEnabled) { $(window).load(webfmLayout); } /** * Remember last used textarea for inserting file hrefs. */ function webfmSetlast(){ Webfm.lastarea = this; } /** * Determine browser */ Webfm.browserDetect = function() { this.isIE = false; this.isOP = false; var b = navigator.userAgent.toLowerCase(); if (b.indexOf("msie") >= 0) { this.isIE = true; } if (b.indexOf("opera") >= 0) { this.isOP = true; } } /** * Hashtable (used by directory listing cache and metadata) */ Webfm.ht = function() { this.flush(); } Webfm.ht.prototype.put = function(key, value) { if((key == null) || (value == null)) throw "NullPointerException {" + key + "},{" + value + "}"; this.hash[key] = value; } Webfm.ht.prototype.get = function(key) { return this.hash[key]; } Webfm.ht.prototype.containsKey = function(key) { for(var i in this.hash) { if (i == key && this.hash[i] != null) { return true; } } return false; } Webfm.ht.prototype.remove = function(key) { if(this.hash[key]) { this.hash[key] = null; return true; } return false; } Webfm.ht.prototype.dump = function() { var values = new Array(); for (var i in this.hash) { if (this.hash[i] != null) values.push(this.hash[i]); } return values; } Webfm.ht.prototype.flush = function() { this.hash = new Array(); } /** * Hashable Hashtable (used by menus) */ Webfm.hht = function() { this.flush(); } Webfm.hht.prototype.put = function(key, obj) { if((key == null) || (obj == null)) throw "NullPointerException {" + key + "},{" + obj + "}"; if(this.hash[key] == null) { this.keys[this.keys.length] = key; this.hash[key] = new Array(); } // append new object to array this.hash[key].push(obj); } Webfm.hht.prototype.get = function(key) { return this.hash[key]; } Webfm.hht.prototype.remove = function(key) { if(this.hash[key]) { this.hash[key] = null; return true; } return false; } Webfm.hht.prototype.removeSub = function(key, subkey) { if(this.hash[key][subkey]) { this.hash[key][subkey] = null; return true; } return false; } Webfm.hht.prototype.flush = function() { this.hash = new Array(); this.keys = new Array(); } //Webfm.metaElement objects have description/edit/max_size params Webfm.metaElement = function(desc, edit, size) { this.desc = desc; this.edit = edit; this.size = size; } /** * Create Web File Manager at 'webfm' id anchor * ..or at node-edit 'webfm-inline' id anchor */ function webfmLayout() { // Initialize textarea for pasting file hrefs with the most often used // in case we try to paste before a textarea or -field was focussed. Webfm.lastarea = document.getElementById('edit-body'); if (!Webfm.lastarea) { Webfm.lastarea = document.getElementById('edit-comment'); } // Tell textareas and text fields to remember which one was last focussed. textareas = document.getElementsByTagName('textarea'); i = textareas.length; while( i-- ) { textareas[i].onfocus = webfmSetlast; } textfields = document.getElementsByTagName('input'); i = textfields.length; while( i-- ) { if (textfields[i].type=='text') { textfields[i].onfocus = webfmSetlast; } } var layoutDiv = ''; layoutDiv = Webfm.$('webfm'); if(layoutDiv) { Webfm.commonInterface(layoutDiv); //first param forces trees refresh //second param forces list refresh Webfm.dirTreeObj.fetch(true, true); } else { layoutDiv = Webfm.$('webfm-inline'); if(layoutDiv) { Webfm.commonInterface(layoutDiv); //Add attach-list menu and attach option to listing menu try { Webfm.menuHT.put('file', new Webfm.menuElement(Webfm.menu_msg["att"], Webfm.menuAttach, Webfm.menuFidVal)); Webfm.menuHT.put('det', new Webfm.menuElement(Webfm.menu_msg["meta"], Webfm.menuGetMeta, '')); Webfm.menuHT.put('det', new Webfm.menuElement(Webfm.menu_msg["det"], Webfm.menuDetach, '')); Webfm.menuHT.put('det', new Webfm.menuElement(Webfm.menu_msg["paste"], Webfm.menuPasteHref, '')); } catch(err) { alert("Menu Create err\n" + err); } // attach-list anchored to 'webfm-attach' div in webfm_form_alter() Webfm.attachObj = new Webfm.attach('webfm-attach'); Webfm.attachObj.fetch(); Webfm.dirTreeObj.fetch(true, true); } } } Webfm.commonInterface = function(parent) { Webfm.browser = new Webfm.browserDetect(); //create the popup container for file/dir object draggables Webfm.dragCont = new Webfm.popup("webfm-dragCont"); //create the popup container for image view Webfm.viewCont = new Webfm.popup("webfm-viewCont"); //create context menu popup Webfm.oldOnContextMenu = document.body.oncontextmenu; Webfm.contextCont = new Webfm.popup("webfm-cxtCont"); Webfm.contextMenuObj = new Webfm.context(Webfm.contextCont); //create metadata popup Webfm.metaCont = new Webfm.popup("webfm-paneCont"); Webfm.metaObj = new Webfm.metadata(Webfm.metaCont, 440, 420); //create file permissions popup Webfm.permCont = new Webfm.popup("webfm-permCont"); Webfm.permObj = new Webfm.perm(Webfm.permCont, 300, 200); //create search popup Webfm.searchCont = new Webfm.popup("webfm-searchCont"); Webfm.searchObj = new Webfm.search(Webfm.searchCont, 280, 200); //create debug popup Webfm.debugCont = new Webfm.popup("webfm-debugCont"); Webfm.dbgObj = new Webfm.debug(Webfm.debugCont, 800, 400); //build menu hashtable //global to allow external functions to push new menu elements into the menu array Webfm.menuHT = new Webfm.hht(); try { Webfm.menuHT.put('root', new Webfm.menuElement(Webfm.menu_msg["mkdir"], Webfm.menuMkdir, Webfm.menuAdmin)); Webfm.menuHT.put('root', new Webfm.menuElement(Webfm.menu_msg["search"], Webfm.menuSearch, '')); Webfm.menuHT.put('dir', new Webfm.menuElement(Webfm.menu_msg["mkdir"], Webfm.menuMkdir, Webfm.menuAdmin)); Webfm.menuHT.put('dir', new Webfm.menuElement(Webfm.menu_msg["rmdir"], Webfm.menuRemove, Webfm.menuAdmin)); Webfm.menuHT.put('dir', new Webfm.menuElement(Webfm.menu_msg["rendir"], Webfm.menuRename, Webfm.menuAdmin)); Webfm.menuHT.put('dir', new Webfm.menuElement(Webfm.menu_msg["search"], Webfm.menuSearch, '')); Webfm.menuHT.put('file', new Webfm.menuElement(Webfm.menu_msg["rm"], Webfm.menuRemove, Webfm.menuFileUid)); Webfm.menuHT.put('file', new Webfm.menuElement(Webfm.menu_msg["ren"], Webfm.menuRename, Webfm.menuRenFileUid)); Webfm.menuHT.put('file', new Webfm.menuElement(Webfm.menu_msg["meta"], Webfm.menuGetMeta, Webfm.menuFidVal)); Webfm.menuHT.put('file', new Webfm.menuElement(Webfm.menu_msg["view"], Webfm.menuView, '')); Webfm.menuHT.put('file', new Webfm.menuElement(Webfm.menu_msg["dwnld"], Webfm.menuDownload, Webfm.menuFidVal)); Webfm.menuHT.put('file', new Webfm.menuElement(Webfm.menu_msg["enum"], Webfm.menuInsert, Webfm.menuAdminNoFidVal)); Webfm.menuHT.put('file', new Webfm.menuElement(Webfm.menu_msg["denum"], Webfm.menuDbRem, Webfm.menuAdminFidVal)); Webfm.menuHT.put('file', new Webfm.menuElement(Webfm.menu_msg["perm"], Webfm.menuGetPerm, Webfm.menuFilePerm)); Webfm.menuHT.put('file', new Webfm.menuElement(Webfm.menu_msg["paste"], Webfm.menuPasteHref, '')); Webfm.menuHT.put('file', new Webfm.menuElement(Webfm.menu_msg["clip"], Webfm.menuPutLinkInClipboard, '')) } catch(err) { alert("Menu Create err\n" + err); } //build metadata hashtable //Webfm.metaElement objects have description/edit/max_size properties Webfm.metadataHT = new Webfm.ht(); Webfm.metadataHT.put('id',new Webfm.metaElement(Webfm.meta_msg["fid"], false,0 )); Webfm.metadataHT.put('u', new Webfm.metaElement(Webfm.meta_msg["uid"], true, 10 )); Webfm.metadataHT.put('un',new Webfm.metaElement(Webfm.meta_msg["uname"], false,0 )); Webfm.metadataHT.put('n', new Webfm.metaElement(Webfm.meta_msg["name"], false,0 )); Webfm.metadataHT.put('t', new Webfm.metaElement(Webfm.meta_msg["title"], true, 255)); Webfm.metadataHT.put('d', new Webfm.metaElement(Webfm.meta_msg["desc"], true, 256)); Webfm.metadataHT.put('l', new Webfm.metaElement(Webfm.meta_msg["lang"], true, 16 )); Webfm.metadataHT.put('p', new Webfm.metaElement(Webfm.meta_msg["pub"], true, 255)); Webfm.metadataHT.put('f', new Webfm.metaElement(Webfm.meta_msg["format"],true, 255)); Webfm.metadataHT.put('v', new Webfm.metaElement(Webfm.meta_msg["ver"], false,0 )); Webfm.metadataHT.put('i', new Webfm.metaElement(Webfm.meta_msg["type"], false,0 )); Webfm.metadataHT.put('w', new Webfm.metaElement(Webfm.meta_msg["width"], false,0 )); Webfm.metadataHT.put('h', new Webfm.metaElement(Webfm.meta_msg["height"],false,0 )); Webfm.metadataHT.put('c', new Webfm.metaElement(Webfm.meta_msg["dl_cnt"],false,0 )); Webfm.metadataHT.put('lk', new Webfm.metaElement(Webfm.meta_msg["link"], false,0 )); //build permissions hashtable //key is permission bit, value is string Webfm.permInfoHT = new Webfm.ht(); Webfm.permInfoHT.put("id", Webfm.meta_msg["fid"]); Webfm.permInfoHT.put("u", Webfm.meta_msg["uid"]); Webfm.permInfoHT.put("n", Webfm.meta_msg["name"]); Webfm.permKey = new Array('1', '2', '4', '8'); Webfm.permHT = new Webfm.ht(); Webfm.permHT.put('1', Webfm.perm_msg["pub_view"]); Webfm.permHT.put('2', Webfm.perm_msg["rol_view"]); Webfm.permHT.put('4', Webfm.perm_msg["rol_att"] ); Webfm.permHT.put('8', Webfm.perm_msg["rol_full"]); var layout_cont = Webfm.ce('div'); Webfm.alrtObj = new Webfm.alert(layout_cont, 'webfm-alert'); //Container for tree(s) var elTreeDiv = Webfm.ce('div'); elTreeDiv.setAttribute('id', 'tree'); //css id layout_cont.appendChild(elTreeDiv); Webfm.dirTreeObj = new Webfm.treeBuilder(elTreeDiv, Webfm.menuHT.get('root'), Webfm.menuHT.get('dir')); //progress indicator Webfm.progressObj = new Webfm.progress(layout_cont, 'webfm-progress'); //Directory Listing Webfm.dirListObj = new Webfm.list(layout_cont, 'dirlist', 'file', 'narrow', true, Webfm.menuHT.get('dir'), Webfm.menuHT.get('file')); //insert trees, listing, search, metadata, progress and alert divs before upload fset built in php parent.insertBefore(layout_cont, parent.firstChild); // parent.appendChild(layout_cont); //If upload desired to be placed above browser webfmUploadAutoAttach(); } //Attaches the upload behaviour to the upload form (borrowed jquery). function webfmUploadAutoAttach(){ $('input.webfmupload').each(function () { var uri = this.value; var button = 'wfmatt-button'; var wrapper = 'wfmatt-wrapper'; var hide = 'wfmatt-hide'; var upload = new Webfm.jsUpload(uri, button, wrapper, hide); }); } /** * Webfm.jsUpload constructor * 1st param is upload iframe url * 2nd param is id of redirected button object) * 3rd param is id of container of html repainted by ajax * 4th param is id of upload input field * TODO: fix progress throbber */ Webfm.jsUpload = function(uri, button, wrapper, hide) { // Note: these elements are replaced after an upload, so we re-select them // everytime they are needed. this.button = '#'+ button; this.wrapper = '#'+ wrapper; this.hide = '#'+ hide; Drupal.redirectFormButton(uri, $(this.button).get(0), this); } //Handler for the form redirection submission. Webfm.jsUpload.prototype.onsubmit = function () { Webfm.progressObj.show(Webfm.js_msg["work"], "blue"); var hide = this.hide; $(hide).fadeOut('slow'); } //Handler for the form redirection completion. Webfm.jsUpload.prototype.oncomplete = function (data) { // Remove old form Drupal.freezeHeight(); // Avoid unnecessary scrolling $(this.wrapper).html(''); // Place HTML into temporary div var div = document.createElement('div'); $(div).html(data['html']); $(this.wrapper).append(div); //div with id='replace-options' present only in case of file overwrite this.confirm = Webfm.$('replace-options'); if(this.confirm) { var hide = this.hide; $(hide).fadeOut('slow'); var cp = this; this.confirm.id = 'replace-options'; var replaceButton = Webfm.ce('input'); replaceButton.setAttribute('type', 'button'); replaceButton.setAttribute('value', Webfm.js_msg["submit"]); var listener = Webfm.eventListenerAdd(Webfm.eventListeners, replaceButton, "click", function(e) { cp.submit(); Webfm.stopEvent(e); }); this.confirm.appendChild(replaceButton); this.confirm.file = data['file']; } else { $(this.hide, div).fadeIn('slow'); webfmUploadAutoAttach(); } Drupal.unfreezeHeight(); Webfm.progressObj.hide(); Webfm.dirListObj.refresh(); if(typeof(Webfm.$('webfm-inline')) != 'undefined') { // attach file to node if inside node-edit if(typeof(data['fid']) != 'undefined') { Webfm.menuAttach(null, data['fid']); } } } //Handler for the form redirection error. Webfm.jsUpload.prototype.onerror = function (error) { alert('An error occurred:\n\n'+ error); Webfm.progressObj.hide(); if(this.confirm) Webfm.clearNodeById('replace-options'); // Undo hide $(this.hide).css({ position: 'static', left: '0px' }); } Webfm.jsUpload.prototype.submit = function () { var inputs = []; inputs = this.confirm.getElementsByTagName('input'); var selection = ''; for(var i = 0; i < inputs.length; i++) { if(inputs[i].checked == true) { selection = i; break; } } if(typeof(selection) != 'undefined') { var url = Webfm.ajaxUrl(); Webfm.progressObj.show(Webfm.js_msg["work"], "blue"); var postObj = { action:encodeURIComponent("version"), param0:encodeURIComponent(selection), param1:encodeURIComponent(this.confirm.file)}; Webfm.HTTPPost(url, this.callback, this, postObj); } } Webfm.jsUpload.prototype.callback = function(string, xmlhttp, cp) { Webfm.progressObj.hide(); // Remove overwrite radios var parent = cp.confirm.parentNode; parent.removeChild(parent.firstChild); var hide = cp.hide; if (xmlhttp.status == 200) { var result = Drupal.parseJson(string); if(result.status) Webfm.dirListObj.refresh(); cp.confirm.style.display = 'none'; // Insert ajax feedback before upload form var elDiv = Webfm.ce('div'); elDiv.className = 'upload-msg'; elDiv.appendChild(Webfm.ctn(result.data['msg'])); $(hide).before($(elDiv)); // Undo hide Webfm.dbgObj.dbg("hide:", Webfm.dump(hide)); $(hide).css({ display: 'block' }); webfmUploadAutoAttach(); if(typeof(Webfm.$('webfm-inline')) != 'undefined') { // attach file to node if inside node-edit if(typeof(result.data['fid']) != 'undefined') { Webfm.menuAttach(null, result.data['fid']); } } } else { Webfm.alrtObj.msg(Webfm.js_msg["ajax-err"]); } } /** * Webfm.list constructor * 1st param is object to append this list object to * 2nd param is base id of listing (multiple listing objects must have unique ids) * 3rd param is base id of file rows of table * 4th param sets styling for listing * 5th param enables drag and drop * 6th param is directory menu array * 7th param is file menu array */ Webfm.list = function(parent, id, type, class_name, dd_enable, dir_menu, file_menu) { var wl = this; this.id = id; this.type = type; this.dd_enable = dd_enable; this.url = Webfm.ajaxUrl(); this.sc_n = 0; this.sc_m = 0; this.sc_s = 0; this.content = ''; this.iconDir = getWebfmIconDir(); this.dir_menu = dir_menu; this.file_menu = file_menu; //directory cache hashtable (key= directory path, val= directory contents) this.cache = new Webfm.ht(); this.eventListeners = [] var node = Webfm.ce("div"); node.setAttribute('id', this.id); node.className = class_name; this.obj = node; var elTable = Webfm.ce('table'); var elTableBody = Webfm.ce('tbody'); // elTableBody.setAttribute('id', this.id + 'body'); this.body = elTableBody; // First Row var elTr = Webfm.ce('tr'); elTr.setAttribute('id','webfm-top-tr'); // Refresh Icon var elTd = Webfm.ce('td'); elTd.className = 'navi'; var elA = Webfm.ce('a'); elA.setAttribute('href', '#'); elA.setAttribute('title', Webfm.js_msg["refresh"]); var elImg = Webfm.ce('img'); elImg.setAttribute('src', this.iconDir+ '/r.gif'); elImg.setAttribute('alt', Webfm.js_msg["refresh"]); elA.appendChild(elImg); elTd.appendChild(elA); elTr.appendChild(elTd); var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elA, "click", function(e) { wl.refresh(Webfm.current);Webfm.stopEvent(e); }); // Breadcrumb trail var elTd = Webfm.ce('td'); elTd.colSpan = 4; elTd.setAttribute('id','webfm-bcrumb-td'); elTd.setAttribute('class','navi'); // Build breadcrumb trail inside span var elSpan = Webfm.ce('span'); elSpan.setAttribute('id', this.id + 'bcrumb'); elTd.appendChild(elSpan); elTr.appendChild(elTd); elTableBody.appendChild(elTr); // Second Row var elTr = Webfm.ce('tr'); this.secondRow = elTr; // icon column var elTd = Webfm.ce('td'); elTd.className = 'head'; elTr.appendChild(elTd); // Sort dir/files column var elTd = Webfm.ce('td'); elTd.className = 'head'; var elA = Webfm.ce('a'); elA.setAttribute('href', '#'); elA.setAttribute('title', Webfm.js_msg["sort"]); var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elA, "click", function(e) { wl.sc_n^=1;wl.loadList("n");wl.sortIcon(e,wl.sc_n);Webfm.stopEvent(e); }); var elImg = Webfm.ce('img'); elImg.setAttribute('alt', Webfm.js_msg["sort"]); elImg.setAttribute('src', this.iconDir + '/down.gif'); elA.appendChild(elImg); elA.appendChild(Webfm.ctn(Webfm.js_msg["column1"])); elTd.appendChild(elA); elTr.appendChild(elTd); // date/time column var elTd = Webfm.ce('td'); elTd.className = 'head'; var elA = Webfm.ce('a'); elA.setAttribute('href', '#'); var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elA, "click", function(e) { wl.sc_m^=1;wl.loadList("m");wl.sortIcon(e,wl.sc_m);Webfm.stopEvent(e); }); var elImg = Webfm.ce('img'); elImg.setAttribute('alt', Webfm.js_msg["sort"]); elImg.setAttribute('src', this.iconDir + '/down.gif'); elA.appendChild(elImg); elA.appendChild(Webfm.ctn(Webfm.js_msg["column2"])); elTd.appendChild(elA); elTr.appendChild(elTd); // size column var elTd = Webfm.ce('td'); elTd.className = 'head'; var elA = Webfm.ce('a'); elA.setAttribute('href', '#'); var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elA, "click", function(e) { wl.sc_s^=1;wl.loadList("s");wl.sortIcon(e,wl.sc_s);Webfm.stopEvent(e); }); var elImg = Webfm.ce('img'); elImg.setAttribute('alt', Webfm.js_msg["sort"]); elImg.setAttribute('src', this.iconDir + '/down.gif'); elA.appendChild(elImg); elA.appendChild(Webfm.ctn(Webfm.js_msg["column3"])); elTd.appendChild(elA); elTr.appendChild(elTd); // owner column var elTd = Webfm.ce('td'); elTd.className = 'head'; var elA = Webfm.ce('a'); elA.setAttribute('href', '#'); var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elA, "click", function(e) { wl.sc_o^=1;wl.loadList("o");wl.sortIcon(e,wl.sc_o);Webfm.stopEvent(e); }); var elImg = Webfm.ce('img'); elImg.setAttribute('alt', Webfm.js_msg["sort"]); elImg.setAttribute('src', this.iconDir + '/down.gif'); elA.appendChild(elImg); elA.appendChild(Webfm.ctn(Webfm.js_msg["column4"])); elTd.appendChild(elA); elTr.appendChild(elTd); elTableBody.appendChild(elTr); elTable.appendChild(elTableBody); node.appendChild(elTable); parent.appendChild(node); } Webfm.list.prototype.bcrumb = function() { var cp = this; Webfm.clearNodeById(this.id + 'bcrumb'); elSpan = Webfm.$(this.id + 'bcrumb'); var pth = []; for(var i = 0; i < this.content.bcrumb.length - 1; i++) { pth.push(this.content.bcrumb[i]); elSpan.appendChild(Webfm.ctn(" / ")); // No breadcrumb link necessary for current directory var elA = Webfm.ce('a'); elA.setAttribute('href', '#'); // join previous loop iterations to create path for title elA.setAttribute('title', "/" + pth.join("/")); elA.appendChild(Webfm.ctn(this.content.bcrumb[i])); //IE fix var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elA, "click", function(e) { cp.selectBC(e);Webfm.stopEvent(e); }); elSpan.appendChild(elA); } elSpan.appendChild(Webfm.ctn(" / ")); elSpan.appendChild(Webfm.ctn(this.content.bcrumb[i])); } Webfm.list.prototype.selectBC = function(event) { var el = event.target||window.event.srcElement; Webfm.selectDir(el.title); } Webfm.list.prototype.sortIcon = function(event, up_down) { var el = event.target||window.event.srcElement; if(el.firstChild) { el.firstChild.src = this.iconDir + '/' + (up_down?"up":"down") + '.gif'; } } Webfm.list.prototype.refresh = function(path, rename_dir) { if(path == null) path = Webfm.current; this.cache.remove(path); if(typeof rename_dir != 'undefined') { this.rename_dir = rename_dir; } this.fetch(path); } Webfm.list.prototype.fetch = function(curr_dir) { Webfm.alrtObj.msg(); if(curr_dir || (curr_dir = Webfm.current)) { Webfm.progressObj.show(Webfm.js_msg["work"], "blue"); //update current dir if specific dir selected Webfm.current = curr_dir; Webfm.dbgObj.dbg('fetch: ', curr_dir); if(this.cache.containsKey(Webfm.current)) { Webfm.dbgObj.dbg('cache hit: ', Webfm.current); this.content = this.cache.get(Webfm.current); this.bcrumb(); this.loadList(); var uploadpath = Webfm.$('edit-webfmuploadpath'); if(uploadpath) { uploadpath.value = Webfm.current; } Webfm.progressObj.hide(); } else { Webfm.admin = false; var postObj = { action:encodeURIComponent("read"), param0:encodeURIComponent(curr_dir) }; Webfm.HTTPPost(this.url, this.callback, this, postObj); } } else { Webfm.dbgObj.dbg(Webfm.js_msg["curdir-undef"]); } } Webfm.list.prototype.callback = function(string, xmlhttp, cp) { Webfm.progressObj.hide(); if (xmlhttp.status == 200) { cp.content = Drupal.parseJson(string); if(cp.content.status) { cp.cache.put(cp.content.current, cp.content); //Sets client permissions - server will always validate any action Webfm.admin = cp.content.admin; cp.bcrumb(); cp.loadList("n"); // Insert current directory path into upload form var uploadpath = Webfm.$('edit-webfmuploadpath'); if(uploadpath) { uploadpath.value = cp.content.current; Webfm.dbgObj.dbg('uploadpath: ', uploadpath.value); } Webfm.current = cp.content.current; cp.adminCtl(Webfm.admin); if(cp.rename_dir) { var found = false; for(var i = 0; i < Webfm.dirListObj.dirrows.length; i++) { if(cp.dirrows[i].clickObj.title == "/" + cp.rename_dir) { found = true; break; } } if(found) Webfm.menuRename(cp.dirrows[i]); } } else { Webfm.alrtObj.str_arr(cp.content.data); } } else { Webfm.alrtObj.msg(Webfm.js_msg["ajax-err"]); } } //build admin icons for create dir and file db insertion //maintain 4 column table Webfm.list.prototype.adminCtl = function(admin) { if(admin) { if(Webfm.$('webfm-bcrumb-td').colSpan == 4) { var wl = this; Webfm.$('webfm-bcrumb-td').colSpan = 3; // Create New Directory and allow db insertions var elTd = Webfm.ce('td'); var elSpan = Webfm.ce('span'); elSpan.id = this.id + "-ctls"; var elA = Webfm.ce('a'); elA.title = Webfm.js_msg["new-dir"]; var elImg = Webfm.ce('img'); elImg.setAttribute('alt', Webfm.js_msg["new-dir"]); elImg.setAttribute('src', this.iconDir + '/dn.gif'); elA.appendChild(elImg); var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elA, "click", function(e) { Webfm.stopEvent(e);wl.mkdir(); }); var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elA, "mouseover", function(e) { wl.hover(e, true, 0); }); var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elA, "mouseout", function(e) { wl.hover(e, false, 0); }); elSpan.appendChild(elA); var elA = Webfm.ce('a'); elA.title = Webfm.js_msg["add-2-db"]; var elImg = Webfm.ce('img'); elImg.setAttribute('alt', Webfm.js_msg["add-2-db"]); elImg.setAttribute('src', this.iconDir + '/add_loc.gif'); elA.appendChild(elImg); var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elA, "click", function(e) { Webfm.stopEvent(e);wl.enumLocal(); }); var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elA, "mouseover", function(e) { wl.hover(e, true); }); var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elA, "mouseout", function(e) { wl.hover(e, false); }); elSpan.appendChild(elA); var elA = Webfm.ce('a'); elA.title = Webfm.js_msg["r-add-2-db"]; var elImg = Webfm.ce('img'); elImg.setAttribute('alt', Webfm.js_msg["r-add-2-db"]); elImg.setAttribute('src', this.iconDir + '/add_recur.gif'); elA.appendChild(elImg); var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elA, "click", function(e) { Webfm.stopEvent(e);wl.enumRecur(); }); var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elA, "mouseover", function(e) { wl.hover(e, true); }); var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elA, "mouseout", function(e) { wl.hover(e, false); }); elSpan.appendChild(elA); elTd.appendChild(elSpan); Webfm.$('webfm-top-tr').appendChild(elTd); } else { Webfm.$('webfm-bcrumb-td').colSpan = 3; } } else { Webfm.$('webfm-bcrumb-td').colSpan = 4; } } // IE does not understand 'this' inside event listener func Webfm.list.prototype.hover = function(event, state) { var el = event.target||window.event.srcElement; el.className = state ? 'selected' : ''; } // Function to create a new directory Webfm.list.prototype.mkdir = function() { Webfm.alrtObj.msg(); Webfm.progressObj.show(Webfm.js_msg["work"], "blue"); var postObj = { action:encodeURIComponent("mkdir"), param0:encodeURIComponent(this.content.current) }; Webfm.HTTPPost(this.url, this.mkdir_callback, this, postObj); } Webfm.list.prototype.enumLocal = function() { if(Webfm.confirm(Webfm.js_msg["enum_local"])) { Webfm.insert(this.content.current, "dir"); } } Webfm.list.prototype.enumRecur = function() { if(Webfm.confirm(Webfm.js_msg["enum_recur"])) { Webfm.insert(this.content.current, "recur"); } } Webfm.list.prototype.mkdir_callback = function(string, xmlhttp, cp) { Webfm.progressObj.hide(); if (xmlhttp.status == 200) { var result = Drupal.parseJson(string); Webfm.dbgObj.dbg("mkdir data:", result.data); if(result.status) { cp.refresh(cp.content.current, result.data); if(Webfm.dirTreeObj) { //we just updated the listing - 2nd var must be false Webfm.dirTreeObj.fetch(true, false); } } else { Webfm.alrtObj.str_arr(result.data); } } else { Webfm.alrtObj.msg(Webfm.js_msg["ajax-err"]); } } Webfm.list.prototype.loadList = function(sortcol) { this.c_dir = 0; this.c_fil = 0; //remove all rows beneath second row of listing table body while(this.secondRow.nextSibling) this.body.removeChild(this.secondRow.nextSibling); //clear event listeners for old listing Webfm.eventUnregister(this.eventListeners); // Build directory rows and append to table if(this.content.dirs.length) { this.dirrows = []; //IE hack since dirs have no size and no owner if(!(Webfm.browser.isIE && (sortcol == "s")) && !(sortcol == "o")) this.sortTable(this.content.dirs, sortcol); for(var i = 0; i < this.content.dirs.length; i++) { this.dirrows[i] = new Webfm.dirrow(this.body, this.content.dirs[i], i, this.dd_enable, this.dir_menu, this.eventListeners); } } // Build file rows and append to table // type determines file context menu if(this.content.files.length) { this.sortTable(this.content.files, sortcol); for(var i = 0; i < this.content.files.length; i++) { var filerow = new Webfm.filerow(this.body, this.content.files[i], this.type, i, this.dd_enable, this.file_menu, this.eventListeners); } } } Webfm.list.prototype.sortTable = function(arr, key) { switch (key) { case "o": arr.sort(Webfm.sortByOwner); if(this.sc_o) arr.reverse(); break; case "s": arr.sort(Webfm.sortBySize); if(this.sc_s) arr.reverse(); break; case "m": arr.sort(Webfm.sortByModified); if(this.sc_m) arr.reverse(); break; case "n": arr.sort(Webfm.sortByName); if(this.sc_n) arr.reverse(); break; } } /** * Webfm.dirrow constructor * 1st param is parent obj * 2nd param is dir object * 3rd param is unique number to append to id * 4th param enables drag and drop * 5th param is directory menu array * 6th param is event listener array for closure cleanup */ Webfm.dirrow = function(parent, dir, index, dd_enable, menu, eventListenerArr) { var dr = this; this.draggable = dd_enable; this.iconDir = getWebfmIconDir(); //id used for drop container var _id = 'dirlist' + index; var elTr = Webfm.ce('tr'); this.element = elTr; this.element.className = 'dirrow'; elTr.setAttribute('id', _id); elTr.setAttribute('title', dir.p); if(dd_enable && Webfm.admin) { //Webfm.draggable must be created after title assigned to set current path this.dd = new Webfm.draggable(Webfm.dragCont, elTr, this.element.className); } else { this.draggable = false; } var elTd = Webfm.ce('td'); var elImg = Webfm.ce('img'); elImg.setAttribute('src', this.iconDir + '/d.gif'); elImg.setAttribute('id', _id + 'dd'); elImg.setAttribute('alt', Webfm.js_msg["u_dir"]); this.menu = menu; elTd.appendChild(elImg); elTr.appendChild(elTd); var elTd = Webfm.ce('td'); // Title of link = path this.clickObj = Webfm.ce('a'); this.clickObj.setAttribute('href', '#'); //title is path this.clickObj.setAttribute('title', dir.p); this.clickObj.appendChild(Webfm.ctn(dir.n)); elTd.appendChild(this.clickObj); elTr.appendChild(elTd); var elTd = Webfm.ce('td'); elTd.className = 'txt'; elTd.appendChild(Webfm.ctn(Webfm.convertunixtime(parseInt(dir.m)))); elTr.appendChild(elTd); var elTd = Webfm.ce('td'); elTd.className = 'txt'; if(dir.s) { var size = Webfm.size(dir.s); elTd.appendChild(Webfm.ctn(size)); } elTr.appendChild(elTd); var elTd = Webfm.ce('td'); elTd.className = 'txt'; if(dir.o) { var owner = Webfm.ce(dir.o); elTd.appendChild(Webfm.ctn(owner)); } elTr.appendChild(elTd); //mouse event listeners if(dd_enable) { var listener = Webfm.eventListenerAdd(eventListenerArr, this.element, "mousedown", function(e) { Webfm.contextMenuObj.hideContextMenu(e); dr.select(e); }); } else { var listener = Webfm.eventListenerAdd(eventListenerArr, this.element, "click", function(e) { Webfm.contextMenuObj.hideContextMenu(e); if(Webfm.renameActive == false)Webfm.selectDir(dr.element.title); }); } if(this.draggable) { var listener = Webfm.eventListenerAdd(eventListenerArr, this.element, "mouseover", function() { dr.hover(dr.element, true); }); var listener = Webfm.eventListenerAdd(eventListenerArr, this.element, "mouseout", function() { dr.hover(dr.element, false); }); } if(Webfm.browser.isOP) { var listener = Webfm.eventListenerAdd(eventListenerArr, this.element, "mouseup", function(e) { if( e && e.button == 0 && e.altKey == true ) { if(Webfm.renameActive == false)Webfm.contextMenuObj.showContextMenu(e, dr);Webfm.stopEvent(e); }; }); } else { var listener = Webfm.eventListenerAdd(eventListenerArr, this.element, "contextmenu", function(e) { if(Webfm.renameActive == false)Webfm.contextMenuObj.showContextMenu(e, dr);Webfm.stopEvent(e); }); } parent.appendChild(elTr); this.c_dir ++; } Webfm.dirrow.prototype.hover = function(el, state) { if(state) el.className += ' selected'; else el.className = el.className.split(' ', 1); } Webfm.dirrow.prototype.select = function(event) { var cp = this; if(Webfm.renameActive == true) return false; event = event || window.event; switch(event.target||event.srcElement) { case this.clickObj: // Determine mouse button var rightclick = Webfm.rclick(event); if(rightclick) break; setTimeout(function(){ //if click then no dragging... if(Webfm.dragging==false) { Webfm.selectDir(cp.element.title); } },200); //passthrough default: if(typeof this.dd != "undefined") this.dd.mouseButton(event); break; } return false; } /** * Webfm.filerow constructor * 1st param is parent obj * 2nd param is fileobject (see desc below) * 3rd param is base id name of file row * 4th param is unique number to append to id * 5th param enables drag and drop * 6th param is file menu array * 7th param is event listener array for closure cleanup * * fileobject elements: * id -> fid * n -> file name * p -> path (includes name) * s -> file size * m -> modified date * e -> mimetype extension * i -> image file. * w -> image width * h -> image height * un -> file owner user name */ Webfm.filerow = function(parent, fileObj, idtype, index, dd_enable, file_menu, eventListenerArr) { var fr = this; this.draggable = dd_enable; this.iconDir = getWebfmIconDir(); this.ext = fileObj.e; this.filepath = fileObj.p + '/' + fileObj.n; this.uid = fileObj.u; this.ftitle = null; this.funame = fileObj.un; if(typeof fileObj.ftitle != "undefined") this.ftitle = fileObj.ftitle; var elTr = Webfm.ce('tr'); this.element = elTr; elTr.className = idtype + 'row'; //drag object id used for download type if(typeof fileObj.id == "undefined") { this.row_id = 'nodb' + index; } else { if(fileObj.id == 0) this.row_id = idtype + index; else //TODO: fix - this causes repeat ids for attach rows! this.row_id = 'fid' + fileObj.id; } elTr.setAttribute('id', this.row_id); //title of drag object is path for move elTr.setAttribute('title', this.filepath); if(dd_enable) { //Only admins or owner of file can move it if(Webfm.admin || fileObj.u == getWebfmUid()) { this.dd = new Webfm.draggable(Webfm.dragCont, elTr, elTr.className); } else { this.draggable = false; } } var elTd = Webfm.ce('td'); var elImg = Webfm.ce('img'); if(fileObj.i) elImg.setAttribute('src', this.iconDir + '/i.gif'); else elImg.setAttribute('src', fr.getIconByExt()); if((typeof fileObj.id == "undefined") || fileObj.id == 0) { // Make icon transparent if file not in db - TODO: fix for IE elImg.style.opacity = 0.25; elImg.style.filter = "alpha(opacity=25)"; } elImg.setAttribute('alt', Webfm.js_msg["u_file"]); this.menu = file_menu; elTd.appendChild(elImg); elTr.appendChild(elTd); var elTd = Webfm.ce('td'); this.clickObj = Webfm.ce('a'); this.clickObj.setAttribute('href', '#'); if((typeof fileObj.id == "undefined") || fileObj.id == 0) { this.clickObj.setAttribute('title', this.filepath); } else { if(Webfm.browser.isOP) this.clickObj.setAttribute('href', getBaseUrl() + "\/webfm_send\/" + fileObj.id); this.clickObj.setAttribute('title', fileObj.id); } if(this.ftitle) this.clickObj.appendChild(Webfm.ctn(fileObj.ftitle)); else this.clickObj.appendChild(Webfm.ctn(fileObj.n)); elTd.appendChild(this.clickObj); elTr.appendChild(elTd); var elTd = Webfm.ce('td'); elTd.className = 'txt'; elTd.appendChild(Webfm.ctn(Webfm.convertunixtime(parseInt(fileObj.m)))); elTr.appendChild(elTd); var elTd = Webfm.ce('td'); elTd.className = 'txt'; var size = Webfm.size(fileObj.s); elTd.appendChild(Webfm.ctn(size)); elTr.appendChild(elTd); //owner field to row var elTd = Webfm.ce('td'); elTd.className = 'txt'; elTd.appendChild(Webfm.ctn(fileObj.un)); elTr.appendChild(elTd); //mouse event listeners if(dd_enable) var listener = Webfm.eventListenerAdd(eventListenerArr, this.element, "mousedown", function(e) { Webfm.contextMenuObj.hideContextMenu(e); fr.select(e); }); else var listener = Webfm.eventListenerAdd(eventListenerArr, this.element, "click", function(e) { Webfm.contextMenuObj.hideContextMenu(e); if(Webfm.renameActive == false)Webfm.selectFile(fr.clickObj.title, fr.element); }); if(this.draggable) { var listener = Webfm.eventListenerAdd(eventListenerArr, this.element, "mouseover", function() { fr.hover(fr.element, true); }); var listener = Webfm.eventListenerAdd(eventListenerArr, this.element, "mouseout", function() { fr.hover(fr.element, false); }); } if(Webfm.browser.isOP) { var listener = Webfm.eventListenerAdd(eventListenerArr, this.element, "mouseup", function(e) { if( e && e.button == 0 && e.altKey == true ) { if(Webfm.renameActive == false)Webfm.contextMenuObj.showContextMenu(e, fr);Webfm.stopEvent(e); }; }); } else { var listener = Webfm.eventListenerAdd(eventListenerArr, this.element, "contextmenu", function(e) { if(Webfm.renameActive == false)Webfm.contextMenuObj.showContextMenu(e, fr);Webfm.stopEvent(e); }); } parent.appendChild(elTr); this.c_fil++; } Webfm.filerow.prototype.hover = function(el, state) { if(state) el.className += ' selected'; else el.className = el.className.split(' ', 1); } Webfm.filerow.prototype.select = function(event) { var cp = this; if(Webfm.renameActive == true) return false; event = event || window.event; switch(event.target||event.srcElement) { case this.clickObj: // Determine mouse button var rightclick = Webfm.rclick(event); if(rightclick) break; setTimeout(function(){ //if click then no dragging... if(Webfm.dragging == false) { //element id used for download method (webfm_send||direct http access) Webfm.selectFile(cp.clickObj.title, cp.element); } },200); //passthrough default: if(typeof this.dd != "undefined") this.dd.mouseButton(event); break; } return false; } Webfm.filerow.prototype.getIconByExt = function() { // extension stored in file record of db fails - use pathname var ext = new String(this.ext); if(ext) { ext = ext.replace(/\//g, "_"); } else { ext = new String(this.filepath); var last = ext.lastIndexOf("."); if(last != -1) // "." found ext = ext.slice(last + 1); else ext = ""; } var icon = this.iconDir + '/' + ((Webfm.icons["e" + ext]) ? Webfm.icons["e" + ext] : "f") + '.gif'; return icon; } /* * Webfm.treeBuilder constructor */ Webfm.treeBuilder = function(parent, root_menu, dir_menu) { this.parent = parent; this.root_menu = root_menu; this.dir_menu = dir_menu; this.trees = []; } Webfm.treeBuilder.prototype.fetch = function(tree_refresh, list_refresh) { this.tree_refresh = tree_refresh; this.list_refresh = list_refresh var url = Webfm.ajaxUrl(); Webfm.alrtObj.msg(); Webfm.progressObj.show(Webfm.js_msg["work"], "blue"); var postObj = { action:encodeURIComponent("readtrees") }; if(tree_refresh) postObj.param0 = encodeURIComponent(true); Webfm.admin = false; Webfm.HTTPPost(url, this.callback, this, postObj); } Webfm.treeBuilder.prototype.callback = function(string, xmlhttp, cp) { Webfm.progressObj.hide(); if (xmlhttp.status == 200) { result = Drupal.parseJson(string); // Webfm.dbgObj.dbg("trees fetch:", Webfm.dump(result)); if(result.status) { if(result.err) { Webfm.alrtObj.msg(result.err); } Webfm.admin = result.admin; // build directory trees from php associative array // first var used to fetch listing of first tree var first = true; for(var i in result.tree) { // Webfm.dbgObj.dbg("tree" + i, Webfm.dump(result.tree[i])); if(!cp.trees[i]) { cp.trees[i] = new Webfm.tree(cp.parent, i, cp.root_menu, cp.dir_menu); } if(first) { cp.trees[i].fetch(cp.tree_refresh, cp.list_refresh); } else { cp.trees[i].fetch(cp.tree_refresh, false); } first = false; } } else { Webfm.alrtObj.msg(result.err); } } else { Webfm.alrtObj.msg(Webfm.js_msg["ajax-err"]); } } /** * Webfm.tree constructor * 1st param is parent node to append this Webfm.tree object * 2nd param is index to append to base id of Webfm.tree object * 3rd param is root directory menu array * 4th param is non-root directory menu array */ Webfm.tree = function(parent, treeIdx, root_menu, dir_menu) { var wt = this; this.id = 'dirtree' + treeIdx; this.treeIdx = treeIdx; this.icondir = getWebfmIconDir(); this.content = ''; this.expAllData = [['collapse', 'minus', 'block'], ['expand', 'plus', 'none']]; // Set tree exp/collapse behaviour on load (0 = expanded, 1 = collapsed) this.expAllIndex = 1; this.root_menu = root_menu; this.dir_menu = dir_menu; this.eventListeners = [] var node = Webfm.ce("div"); node.setAttribute('id', this.id); node.className = 'dirtree'; //build tree and display var elA = Webfm.ce('a'); elA.setAttribute('href', '#'); elA.setAttribute('title', Webfm.js_msg["refresh"]); var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elA, "click", function(e) { wt.fetch(true, '');Webfm.stopEvent(e); }); var elImg = Webfm.ce('img'); elImg.setAttribute('src', this.icondir + '/r.gif'); elImg.setAttribute('alt', Webfm.js_msg["refresh"]); elA.appendChild(elImg); node.appendChild(elA); var elSpan = Webfm.ce("span"); elSpan.appendChild(Webfm.ctn(' ')); elSpan.setAttribute('id', this.id + 'Name'); node.appendChild(elSpan); // Expand/Collapse all folders buttons var elSpan = Webfm.ce("span"); elSpan.setAttribute('id', this.id + 'exp'); for(var i = 0; i < 2; i++) { var elA = Webfm.ce('a'); elA.setAttribute('href', '#'); if (i) { elA.setAttribute('title', 'expand tree'); var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elA, "click", function(e) { wt.exp(0);Webfm.stopEvent(e); }); } else { elA.setAttribute('title', 'collapse tree'); var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elA, "click", function(e) { wt.exp(1);Webfm.stopEvent(e); }); } var elImg = Webfm.ce('img'); elImg.setAttribute('alt', this.expAllData[i][0]); elImg.setAttribute('src', this.icondir + '/' + this.expAllData[i][1] + '.gif'); elA.appendChild(elImg); elSpan.appendChild(elA); } node.appendChild(elSpan); //container div for tree var elDiv = Webfm.ce("div"); this.treeCont = elDiv; node.appendChild(elDiv); parent.appendChild(node); } Webfm.tree.prototype.fetch = function(tree_refresh, list_refresh) { // Reset ul count (0=root) this.treeUlCounter = 0; this.treeNodeCounter = 0; this.list_refresh = list_refresh; var url = Webfm.ajaxUrl(); Webfm.alrtObj.msg(); Webfm.progressObj.show(Webfm.js_msg["work"], "blue"); Webfm.dbgObj.dbg("tree fetch path:", this.treeIdx); var postObj = { action:encodeURIComponent("readtree"), param0:encodeURIComponent(this.treeIdx) }; if(tree_refresh) postObj.param1 = encodeURIComponent(true); Webfm.HTTPPost(url, this.callback, this, postObj); } Webfm.tree.prototype.callback = function(string, xmlhttp, cp) { Webfm.progressObj.hide(); if (xmlhttp.status == 200) { cp.content = Drupal.parseJson(string); // Webfm.dbgObj.dbg("tree fetch:", Webfm.dump(cp.content)); //clear tree content while (cp.treeCont.hasChildNodes()) cp.treeCont.removeChild(cp.treeCont.firstChild); //clear event listeners for old tree content Webfm.eventUnregister(cp.eventListeners); //clear drop container array; Webfm.dropContainers = []; //update tree name var treeName = Webfm.$(cp.id + 'Name'); treeName.removeChild(treeName.firstChild); for(var j in cp.content.tree) { //textnode = last directory of root path treeName.appendChild(Webfm.ctn(' ' + j.substring(j.lastIndexOf("/") + 1) + ' ' + Webfm.js_msg["tree"])); break; } // Recursively build directory tree from php associative array cp.buildTreeRecur(cp.content.tree, cp.treeCont, ''); cp.init(); if(cp.list_refresh) { Webfm.dirListObj.refresh(cp.content.current); } } else { Webfm.alrtObj.msg(Webfm.js_msg["ajax-err"]); } } Webfm.tree.prototype.getpath = function() { return this.content.current; } Webfm.tree.prototype.showHideNode = function (event) { event = event || window.event; var collapseIcon = event.target||event.srcElement; if(collapseIcon.style.visibility == 'hidden') return; var ul = collapseIcon.parentNode.parentNode.getElementsByTagName('ul')[0]; if(collapseIcon.title == this.expAllData[0][0]) { collapseIcon.src = this.icondir + '/' + this.expAllData[1][1] + '.gif'; collapseIcon.alt = this.expAllData[1][0]; collapseIcon.title = this.expAllData[1][0]; ul.style.display = this.expAllData[1][2]; }else{ collapseIcon.src = this.icondir + '/' + this.expAllData[0][1] + '.gif'; collapseIcon.alt = this.expAllData[0][0]; collapseIcon.title = this.expAllData[0][0]; ul.style.display = this.expAllData[0][2]; } } Webfm.tree.prototype.buildTreeRecur = function(content, parent, input_path) { var cp = this; //php associative array is always a single member array with nested objects if(Webfm.isArray(content)) { this.buildTreeRecur(content[0], parent, ''); } else if (Webfm.isObject(content)) { if(input_path) input_path += "/"; var elUl = Webfm.ce('ul'); if(!(this.treeUlCounter++)) elUl.className = 'root-list'; // sort object here since php does not have a case-sensitive ksort var sortDir = []; for(var i in content) { sortDir.push(i); } if(sortDir.length) { sortDir.sort(Webfm.sortByKey); for(var j = 0; j < sortDir.length; j++) { var newpath = input_path + sortDir[j]; var elLi = Webfm.ce('li'); var _id = this.id + 'node' + this.treeNodeCounter; elLi.setAttribute('id', _id); elLi.setAttribute('title', newpath); elLi.className = "treenode"; var elDiv = Webfm.ce('div'); var elImg = Webfm.ce('img'); elImg.setAttribute('src', this.icondir + '/' + this.expAllData[this.expAllIndex][1] + '.gif'); elImg.setAttribute('alt', this.expAllData[this.expAllIndex][0]); elImg.setAttribute('title', this.expAllData[this.expAllIndex][0]); elDiv.appendChild(elImg); elLi.appendChild(elDiv); var listener = Webfm.eventListenerAdd(this.eventListeners, elImg, "click", function(e) { cp.showHideNode(e);Webfm.stopEvent(e); }); var treeNode = new Webfm.treeNode(elDiv, newpath, _id, elImg, this.treeNodeCounter ? this.dir_menu : this.root_menu, this.eventListeners); var listener = Webfm.eventListenerAdd(this.eventListeners, elDiv, "mouseover", function(e) { cp.hover(e, true); }); var listener = Webfm.eventListenerAdd(this.eventListeners, elDiv, "mouseout", function(e) { cp.hover(e, false); }); this.treeNodeCounter++; this.buildTreeRecur(content[sortDir[j]], elLi, newpath); elUl.appendChild(elLi); } } // Always show root if(elUl.className == 'root-list') elUl.style.display = 'block'; else elUl.style.display = this.expAllData[this.expAllIndex][2]; parent.appendChild(elUl); } } // IE does not understand 'this' inside event listener func Webfm.tree.prototype.hover = function(event, state) { var el = event.target||window.event.srcElement; if(state) { el.className = 'selected'; el.parentNode.className = 'selected'; // el.parentNode.className += ' selected'; } else { // var class_names = []; // class_names = el.parentNode.className.split(' '); // el.parentNode.className = class_names[0]; el.className = ''; el.parentNode.className = ''; } } Webfm.tree.prototype.init = function() { // Determine if expand/collapse icon is present // Create event objects for each element var dirItems = this.treeCont.getElementsByTagName('li'); if (dirItems.length) { for(var i = 0; i < dirItems.length; i++) { var subItems = dirItems[i].getElementsByTagName('ul'); if(!subItems.length) // Hide collapse icon if no sub-directories dirItems[i].getElementsByTagName('img')[0].style.visibility='hidden'; } } } Webfm.tree.prototype.exp = function(expcol) { //clear tree while(this.treeCont.hasChildNodes()) this.treeCont.removeChild(this.treeCont.firstChild); // Rebuild dirtree ul/li objects from dirtree object this.expAllIndex = expcol; this.treeUlCounter = 0; this.treeNodeCounter = 0; this.buildTreeRecur(this.content.tree, this.treeCont, ''); this.init(); } Webfm.treeNode = function(parent, path, id, expImg, menu, eventListenerArr) { var tn = this; this.parent = parent; this.element = parent.parentNode; var icondir = getWebfmIconDir(); this.expClickObj = expImg; var elImg = Webfm.ce('img'); elImg.setAttribute('id', id + 'dd'); elImg.setAttribute('src', icondir + '/d.gif'); parent.appendChild(elImg); this.clickObj = Webfm.ce('a'); this.clickObj.href = '#'; //anchor title is path this.clickObj.setAttribute('title', path); var nodeNumPos = this.element.id.indexOf("node") + 4; if((this.element.id.substring(nodeNumPos) != "0") && (Webfm.admin)) // root treenode isn't draggable this.dd = new Webfm.draggable(Webfm.dragCont, this.element, this.element.className); var root = []; root = path.split('/'); //textNode is last directory name of path string (used for root path) this.clickObj.appendChild(Webfm.ctn(root[root.length - 1])); parent.appendChild(this.clickObj); //mouse event listeners this.menu = menu; if(typeof this.dd != "undefined") { var listener = Webfm.eventListenerAdd(eventListenerArr, parent, "mousedown", function(e) { Webfm.contextMenuObj.hideContextMenu(e); tn.select(e); }); } else { var listener = Webfm.eventListenerAdd(eventListenerArr, parent, "click", function(e) { Webfm.selectDir(tn.clickObj.title); Webfm.stopEvent(e); }); } if(Webfm.browser.isOP) { var listener = Webfm.eventListenerAdd(eventListenerArr, parent, "mouseup", function(e) { if( e && e.button == 0 && e.altKey == true ) { if(Webfm.renameActive == false)Webfm.contextMenuObj.showContextMenu(e, tn);Webfm.stopEvent(e); }; }); } else { var listener = Webfm.eventListenerAdd(eventListenerArr, parent, "contextmenu", function(e) { if(Webfm.renameActive == false)Webfm.contextMenuObj.showContextMenu(e, tn);Webfm.stopEvent(e); }); } } Webfm.treeNode.prototype.select = function(event) { var cp = this; // disable during rename if(Webfm.renameActive == true) return false; event = event|| window.event; switch(event.target||event.srcElement) { case this.expClickObj: break; case this.clickObj: // Determine mouse button var rightclick = Webfm.rclick(event); if(rightclick) // oncontextmenu will handle this break; setTimeout(function(){ //if click then no dragging... if(Webfm.dragging==false) { Webfm.selectDir(cp.clickObj.title); } },200); //passthrough default: if(typeof this.dd != "undefined") this.dd.mouseButton(event); break; } return false; } Webfm.selectDir = function(path) { Webfm.dirListObj.fetch(path); } // File download Webfm.selectFile = function(path, el, as_file) { //files not in db use file path in tr title for download //files inside webfm have 'fidxxx' as title var fid = null; var sent = false; var pths = []; pths = el.title.split('/'); if(el.id.substring(0,3) == 'fid') { fid = el.id.substring(3); var fullpath = 'webfm_send/' + path; if(as_file) fullpath += '/1'; } else { //replace / with ~ since server uses / as param delimiter var pluspath = pths.join('~'); var fullpath = 'webfm_send/' + encodeURIComponent(pluspath); } if(getWebfmCleanUrl()) { var url = getBaseUrl() + '/' + fullpath; } else { var url = '?q=' + fullpath; } if(as_file) { // Send download/open dialog window.location = url; } else { var cache = Webfm.dirListObj.cache.get(Webfm.current); for(var i in cache.files) { // Display downloaded image in iframe // check cache files[] array for path match and image type if (((cache.files[i].id == fid) || ((cache.files[i].p + '/' + cache.files[i].n) == path)) && cache.files[i].i) { // FF needs unique name per iframe - Webfm.zindex guaranteed unique // since incremented with each new pane var iframeName = "dwnld" + Webfm.zindex; var pane = new Webfm.pane(Webfm.viewCont, pths[pths.length - 1], "view-file", null, 200, 200); // I hate using innerHTML but IE iframe requires this method: pane.content.innerHTML='<iframe src="" style="margin:0;padding:0;width:100%;height:100%" name="'+iframeName+'"></iframe>'; if(fid) pane.headerMsg("fid:" + path); pane.show(); window.frames[iframeName].location.replace(url); sent = true; break; } } // Not an image - launch file in new browser instance if(!sent) { // window.open(url); window.location = url; } } } /** * Webfm.context constructor */ Webfm.context = function(container) { Webfm.renameActive = false; this.container = container; this.eventListeners = this.container.eventListenerArr; } Webfm.context.prototype.hideContextMenu = function(event) { // Hide context menu and restore document oncontextmenu handler this.container.obj.style.visibility = "hidden"; document.body.oncontextmenu = Webfm.oldOnContextMenu; } //obj is treenode|filerow|dirrow Webfm.context.prototype.showContextMenu = function(event, obj) { var cp = this; this.element = obj.element; this.clickObj = obj.clickObj; //Webfm.dbgObj.dbg('this.element.title:', this.element.title); document.body.oncontextmenu = new Function ("return false"); event = event || window.event; var pos = Drupal.mousePosition(event); // Remove any existing list in our contextMenu. this.container.destroy(); // Build menu ul and append to this.container if(obj.menu != null) { var elUl = Webfm.ce('ul'); for(var j = 0; j < obj.menu.length; j++) { var elLi = Webfm.ce('li'); //Run prepare function and return true if menuElement to appear in menu if(typeof(obj.menu[j].prepFunc) == 'function' && !obj.menu[j].prepFunc(obj)) { continue; } elLi.appendChild(Webfm.ctn(obj.menu[j].desc)); //menu selection is title of event elLi.id = 'cxtMenu' + j; var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elLi, "mousedown", function(e) { cp.selectMenu(e, obj); cp.hideContextMenu(e); Webfm.stopEvent(e); }); var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elLi, "mouseover", function(e) { cp.hover(e, true); }); var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elLi, "mouseout", function(e) { cp.hover(e, false); }); elUl.appendChild(elLi); } this.container.obj.appendChild(elUl); this.container.obj.style.visibility = "visible"; if(pos.x + this.container.obj.offsetWidth > (document.documentElement.offsetWidth-20)){ pos.x = pos.x + (document.documentElement.offsetWidth - (pos.x + this.container.obj.offsetWidth)) - 20; } this.container.obj.style.left = pos.x + 'px'; this.container.obj.style.top = pos.y + 'px'; this.container.obj.style.display ='block'; this.container.obj.style.zIndex = ++Webfm.zindex; } var listener = Webfm.eventListenerAdd(Webfm.eventListeners, document, "mousedown", function(e) { cp.hideContextMenu(e); }); return false; } // IE does not understand 'this' inside event listener func Webfm.context.prototype.hover = function(event, state) { var el = event.target||window.event.srcElement; el.className = state ? 'selected' : ''; } // Call Webfm.menuElement execute function Webfm.context.prototype.selectMenu = function(event, obj) { event = event || window.event; obj.menu[(event.target||event.srcElement).id.substring(7)].execFunc(obj); return false; } Webfm.menuElement = function(desc, execFunc, prepFunc) { this.desc = desc; this.execFunc = execFunc; this.prepFunc = prepFunc; } //obj is treenode|filerow|dirrow Webfm.menuElement.prototype.exec = function(obj) { this.execFunc(obj); } Webfm.menuRemove = function(obj) { var url = Webfm.ajaxUrl(); if(typeof obj.ext != "undefined") //directories don't have extension properties obj.is_file = true; var path = obj.element.title; obj.parentPath = path.substring(0, path.lastIndexOf("/")); if(Webfm.confirm(Webfm.js_msg["confirm-del0"] + (obj.is_file ? Webfm.js_msg["file"] : Webfm.js_msg["dir"]) + " " + path + (obj.is_file ? "" : Webfm.js_msg["confirm-del1"]) + "?")) { Webfm.progressObj.show(Webfm.js_msg["work"], "blue"); var postObj = { action:encodeURIComponent("delete"), param0:encodeURIComponent(path) }; Webfm.HTTPPost(url, Webfm.ctxMenuCallback, obj, postObj); return false; } } Webfm.menuMkdir = function(obj) { var url = Webfm.ajaxUrl(); obj.is_file = false; var path = obj.element.title; obj.parentPath = path; Webfm.progressObj.show(Webfm.js_msg["work"], "blue"); var postObj = { action:encodeURIComponent("mkdir"), param0:encodeURIComponent(path) }; Webfm.HTTPPost(url, Webfm.ctxMenuMkdirCallback, obj, postObj); } Webfm.menuRename = function(obj) { if(typeof obj.ext != "undefined") //directories don't have extension properties obj.is_file = true; obj.renInput = Webfm.ce('input'); obj.renInput.setAttribute('type', 'textfield'); obj.renInput.value = obj.clickObj.firstChild.nodeValue; //clone input element since Webfm.contextMenuObj isn't destroyed on DOM obj.tempInput = obj.renInput.cloneNode(true); obj.tempInput.setAttribute('autocomplete','off'); //FF focus bug obj.clickparent = obj.clickObj.parentNode; obj.clickparent.replaceChild(obj.tempInput, obj.clickObj); //no change (blur) - restore original textNode var listener = Webfm.eventListenerAdd(Webfm.eventListeners, obj.tempInput, "blur", function (e) { Webfm.renameActive = false; obj.clickparent.replaceChild(obj.clickObj, obj.tempInput);Webfm.stopEvent(e); }); //listen for enter key up - swap names (illegal names are ignored on server and next list //refresh will restore the proper filename) var listener = Webfm.eventListenerAdd(Webfm.eventListeners, obj.tempInput, "keydown", function(e) { if(Webfm.enter(e) && Webfm.renameActive == true){ Webfm.renameActive = false; Webfm.menuSwapname(obj); this.blur(); Webfm.stopEvent(e);} }); setTimeout(function(){ obj.tempInput.focus();Webfm.renameActive = true; },10); } Webfm.menuSearch = function(obj) { Webfm.searchObj.createForm(obj.element.title); } Webfm.menuSwapname = function(obj) { var url = Webfm.ajaxUrl(); var oldpath = obj.element.title; obj.parentPath = oldpath.substring(0, oldpath.lastIndexOf("/")); var newpath = obj.parentPath + '/' + obj.tempInput.value; var postObj = { action:encodeURIComponent("rename"), param0:encodeURIComponent(oldpath), param1:encodeURIComponent(newpath) }; Webfm.HTTPPost(url, Webfm.ctxMenuCallback, obj, postObj); return true; } Webfm.menuGetMeta = function(obj) { var url = Webfm.ajaxUrl(); // Webfm.dbgObj.dbg("obj.clickObj.title:", obj.clickObj.title); Webfm.progressObj.show(Webfm.js_msg["work"], "blue"); var postObj = { action:encodeURIComponent("getmeta"), param0:encodeURIComponent(obj.clickObj.title) }; Webfm.HTTPPost(url, Webfm.ctxMenuMetaCallback, '', postObj); } Webfm.menuAttach = function(obj, _fid) { var url = Webfm.ajaxUrl(); if(obj == null) var fid = _fid; else fid = obj.clickObj.title; //check that this file is not already attached var attach_arr = []; attach_arr = Webfm.$(Webfm.attachFormInput).value.split(','); for(var i = 0; i < attach_arr.length; i++) { if(fid == attach_arr[i]) break; } if(i == attach_arr.length) { Webfm.progressObj.show(Webfm.js_msg["work"], "blue"); var postObj = { action:encodeURIComponent("attachfile"), param0:encodeURIComponent(fid) }; Webfm.HTTPPost(url, Webfm.ctxMenuAttachCallback, '', postObj); } } Webfm.menuDetach = function(obj) { Webfm.alrtObj.msg(); var path = obj.element.title; if(Webfm.confirm(Webfm.js_msg["confirm-det"] + path + "?")) { // update table obj.element.parentNode.removeChild(obj.element); // update form input var attach_arr = []; attach_arr = Webfm.$(Webfm.attachFormInput).value.split(','); var new_attach_arr = []; var j = 0; // tr elements use 'fid#' in 'title' field var fid = obj.element.id.substring(3); for(var i = 0; i < attach_arr.length; i++) { if(attach_arr[i] != fid) { new_attach_arr[j++] = attach_arr[i]; } } Webfm.$(Webfm.attachFormInput).value = new_attach_arr.join(','); } } Webfm.menuView = function(obj) { Webfm.selectFile(obj.clickObj.title, obj.element, false); } Webfm.menuDownload = function(obj) { Webfm.selectFile(obj.clickObj.title, obj.element, true); } Webfm.menuDbRem = function(obj) { var path = obj.element.title; //strip 'fid' from front of id var fid = obj.element.id.substring(3); if(Webfm.confirm(Webfm.js_msg["confirm-dbrem0"] + path + Webfm.js_msg["confirm-dbrem1"])) { var url = Webfm.ajaxUrl(); Webfm.progressObj.show(Webfm.js_msg["work"], "blue"); var postObj = { action:encodeURIComponent("dbrem"), param0:encodeURIComponent(fid) }; // path for callback must be a directory - not a file path = path.substring(0, path.lastIndexOf("/")); Webfm.HTTPPost(url, Webfm.dbrem_callback, path, postObj); } return false; } Webfm.menuGetPerm = function(obj) { var url = Webfm.ajaxUrl(); Webfm.progressObj.show(Webfm.js_msg["work"], "blue"); var postObj = { action:encodeURIComponent("getperm"), param0:encodeURIComponent(obj.clickObj.title) }; Webfm.HTTPPost(url, Webfm.ctxMenuPermCallback, '', postObj); } Webfm.dbrem_callback = function(string, xmlhttp, path) { Webfm.alrtObj.msg(); Webfm.progressObj.hide(); if (xmlhttp.status == 200) { var result = Drupal.parseJson(string); Webfm.dbgObj.dbg("dbrem:", Webfm.dump(result)); if (result.status) { Webfm.dirListObj.refresh(path); } else { if(result.data) { Webfm.alrtObj.str_arr(result.data); } else { Webfm.alrtObj.msg("operation fail"); } } } else { Webfm.alrtObj.msg(Webfm.js_msg["ajax-err"]); } } Webfm.menuInsert = function(obj) { Webfm.insert(obj.element.title, "file"); } Webfm.insert = function(path, type) { var url = Webfm.ajaxUrl(); Webfm.progressObj.show(Webfm.js_msg["work"], "blue"); var postObj = { action:encodeURIComponent("insert"), param0:encodeURIComponent(path), param1:encodeURIComponent(type) }; if(type == "file") { // path for callback must be a directory - not a file path = path.substring(0, path.lastIndexOf("/")); } Webfm.HTTPPost(url, Webfm.insert_callback, path, postObj); return false; } Webfm.insert_callback = function(string, xmlhttp, path) { Webfm.alrtObj.msg(); Webfm.progressObj.hide(); if (xmlhttp.status == 200) { var result = Drupal.parseJson(string); Webfm.dbgObj.dbg("insert:", Webfm.dump(result)); if (result.status) { //if success, update fetch if(result.data.cnt) { Webfm.dirListObj.refresh(path); Webfm.alrtObj.msg(result.data.cnt + Webfm.js_msg["inserted"]); } if(result.data.errcnt) { Webfm.alrtObj.msg(result.data.errcnt + Webfm.js_msg["not-inserted"]); Webfm.alrtObj.str_arr(result.data.err); } } else if(result.data.err) { Webfm.alrtObj.str_arr(result.data.err); } else { Webfm.alrtObj.msg(result.data); } } else { Webfm.alrtObj.msg(Webfm.js_msg["ajax-err"]); } } Webfm.generateFileHref = function(obj, url) { if(typeof url == 'undefined') { url = getBaseUrl(); } var title = ''; if(typeof obj.ftitle != "undefined" && obj.ftitle != null && obj.ftitle.length) title = obj.ftitle; else title = obj.element.title.substring(obj.element.title.lastIndexOf("/") + 1); if(getWebfmCleanUrl()) { string = "<a href=\"" + url + "\/webfm_send\/" + obj.element.id.substring(3) + "\">" + title + "</a>"; } else { string = "<a href=\"" + url + "\/?q=webfm_send\/" + obj.element.id.substring(3) + "\">" + title + "</a>"; } return string; } Webfm.menuPutLinkInClipboard = function(obj) { Webfm.copyToClipboard(Webfm.generateFileHref(obj)); } Webfm.menuPasteHref = function(obj) { var fileHref = Webfm.generateFileHref(obj, getBasePath().replace(/\/$/,'')); var myField = Webfm.lastarea; //IE support if(document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = fileHref; } //other browsers else if(myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; myField.value = myField.value.substring(0, startPos)+ fileHref + myField.value.substring(endPos, myField.value.length); } else { myField.value += fileHref; } } Webfm.menuAdmin = function() { return(Webfm.admin); } Webfm.menuFileUid = function(obj) { //determine if we are the owner of this file return((Webfm.admin || obj.uid == getWebfmUid()) ? true : false); } Webfm.menuRenFileUid =function(obj) { if(Webfm.menuFileUid(obj)) // Determine if name is a metadata title return(obj.ftitle == null); return false; } Webfm.menuFilePerm = function(obj) { // object must be file in db with user access if(Webfm.menuFidVal(obj)) { return(Webfm.menuFileUid(obj)); } return false; } Webfm.menuAdminFidVal = function(obj) { if(Webfm.admin) return(Webfm.menuFidVal(obj)); return false; } Webfm.menuAdminNoFidVal = function(obj) { if(Webfm.admin) return(Webfm.menuNoFidVal(obj)); return false; } //menu prepFunc to determine if filerow has 'fid' as first 3 letters of id Webfm.menuFidVal = function(obj) { if(obj.element.id.substring(0,3) == 'fid') return true; return false; } Webfm.menuNoFidVal = function(obj) { if(obj.element.id.substring(0,3) != 'fid') return true; return false; } Webfm.confirm = function(text) { var agree = confirm(text); return agree ? true : false; } /** * Context menu callbacks */ Webfm.ctxMenuAttachCallback = function(string, xmlhttp, cp) { Webfm.progressObj.hide(); if (xmlhttp.status == 200) { var result = Drupal.parseJson(string); // Webfm.dbgObj.dbg("attach:", Webfm.dump(result)); if (result.status) { Webfm.admin = result.admin; var filerow = new Webfm.filerow(Webfm.attachObj.body, result.data, 'attach', '', true, Webfm.menuHT.get('det'), Webfm.attachObj.eventListeners); var elInput = Webfm.$(Webfm.attachFormInput); elInput.setAttribute('value', (elInput.getAttribute('value')?elInput.getAttribute('value')+',':'') + result.data.id); } else Webfm.alrtObj.msg(result.data); } else { Webfm.alrtObj.msg(Webfm.js_msg["ajax-err"]); } } Webfm.ctxMenuCallback = function(string, xmlhttp, obj, mkdir_flag) { Webfm.progressObj.hide(); Webfm.alrtObj.msg(); if (xmlhttp.status == 200) { var result = Drupal.parseJson(string); // Webfm.dbgObj.dbg("context:", Webfm.dump(result)); // Webfm.dbgObj.dbg("obj:", obj.droppath); if (result.status) { if(!obj.is_file && Webfm.dirTreeObj) { Webfm.dirTreeObj.fetch(true, false); } //if success, flush cache for updated fetch if(typeof mkdir_flag != "undefined") { Webfm.dirListObj.refresh(obj.parentPath, result.data); } else { Webfm.dirListObj.refresh(obj.parentPath); } } else if(result.data) { Webfm.alrtObj.str_arr(result.data); } else { Webfm.alrtObj.msg("operation fail"); } } else { Webfm.alrtObj.msg(Webfm.js_msg["ajax-err"]); } } Webfm.ctxMenuMkdirCallback = function(string, xmlhttp, obj) { var mkdir_flag = true; // fourth var to signal the listing to rename the new directory Webfm.ctxMenuCallback(string, xmlhttp, obj, mkdir_flag) } Webfm.ctxMenuMetaCallback = function(string, xmlhttp, obj) { Webfm.progressObj.hide(); if(xmlhttp.status == 200) { var result = Drupal.parseJson(string); // Webfm.dbgObj.dbg("meta result:", Webfm.dump(result)); if(result.status) { Webfm.metaObj.createForm(result.data); } else Webfm.alrtObj.msg(result.data); } else { Webfm.alrtObj.msg(Webfm.js_msg["ajax-err"]); } } Webfm.ctxMenuPermCallback = function(string, xmlhttp, obj) { Webfm.progressObj.hide(); if(xmlhttp.status == 200) { var result = Drupal.parseJson(string); // Webfm.dbgObj.dbg("perm result:", Webfm.dump(result)); if(result.status) { Webfm.permObj.createForm(result.data); } else Webfm.alrtObj.msg(result.data); } else { Webfm.alrtObj.msg(Webfm.js_msg["ajax-err"]); } } /** * Webfm.perm constructor * 1st param is popup container obj * 2nd param is default startup width * 2nd param is default startup height */ Webfm.perm = function(container, width, height) { var elDiv = Webfm.ce('div'); elDiv.setAttribute('id', 'webfm-perm-form'); var elForm = Webfm.ce('form'); elDiv.appendChild(elForm); var elTable = Webfm.ce('table'); elForm.appendChild(elTable); var elTBody = Webfm.ce('tbody'); elTable.appendChild(elTBody); var elControls = Webfm.ce('div'); elForm.appendChild(elControls); this.obj = elDiv; this.container = container; this.form = elForm; this.tbody = elTBody; this.controls = elControls; this.width = width; this.height = height; this.eventListeners = this.container.eventListenerArr; } Webfm.perm.prototype.createForm = function(data) { cp = this; this.data = data; this.permit = (Webfm.admin || this.data["u"] == getWebfmUid()) ? true : false; //clear any permissions info this.resetForm(); //create new pane to house this perm object this.pane = new Webfm.pane(this.container, Webfm.js_msg["perm"], "perm-pane", this.obj, this.width, this.height); //create permissions checkboxes this.fillFormData(); //create controls if owner has rights to file if(this.permit) { this.buildFormControls(); } else { //put read-only indicator in pane header pane.headerMsg("read-only"); } } Webfm.perm.prototype.resetForm = function() { var tbody = this.tbody; while(tbody.hasChildNodes()) { tbody.removeChild(tbody.firstChild); } var controls = this.controls; while(controls.hasChildNodes()) { controls.removeChild(controls.firstChild); } } Webfm.perm.prototype.fillFormData = function() { for(var j in this.data) { if (j != "p") { var elTr = Webfm.ce('tr'); // label td var elTd = Webfm.ce('td'); elTd.appendChild(Webfm.ctn(Webfm.permInfoHT.get(j) + ': ')); elTr.appendChild(elTd); // info td var elTd = Webfm.ce('td'); elTd.appendChild(Webfm.ctn(this.data[j])); elTr.appendChild(elTd); this.tbody.appendChild(elTr); } } // Webfm.permKey keys correspond to permission bitfields for(var i in Webfm.permKey) { var elTr = Webfm.ce('tr'); // label td var elTd = Webfm.ce('td'); elTd.appendChild(Webfm.ctn(Webfm.permHT.get(Webfm.permKey[i]) + ': ')); elTr.appendChild(elTd); // checkbox td var elTd = Webfm.ce('td'); // use bitwise operator to determine permission bits var check = (parseInt(Webfm.permKey[i]) & parseInt(this.data["p"])) > 0; if(this.permit) { var elInput = Webfm.ce('input'); elInput.setAttribute('type', 'checkbox'); // checkbox name is used to build the new permission value elInput.setAttribute('name', Webfm.permKey[i]); if(check) elInput.setAttribute('checked', check); elTd.appendChild(elInput); } else { elTd.appendChild(Webfm.ctn(check ? "True" : "False")); } elTr.appendChild(elTd); this.tbody.appendChild(elTr); } } //build perm control buttons Webfm.perm.prototype.buildFormControls = function() { var cp = this; var submitButton = Webfm.ce('input'); submitButton.setAttribute('type', 'button'); submitButton.setAttribute('value', Webfm.js_msg["submit"]); submitButton.className = "perm-button"; var listener = Webfm.eventListenerAdd(cp.eventListeners, submitButton, "click", function(e) { if(cp.submitPerm()){cp.container.destroy();}Webfm.stopEvent(e); }); this.controls.appendChild(submitButton); var resetButton = Webfm.ce('input'); resetButton.setAttribute('type', 'button'); resetButton.setAttribute('value', Webfm.js_msg["reset"]); resetButton.className = "perm-button"; var listener = Webfm.eventListenerAdd(cp.eventListeners, resetButton, "click", function(e) { cp.createForm(cp.data); Webfm.stopEvent(e); }); this.controls.appendChild(resetButton); } Webfm.perm.prototype.submitPerm = function() { var url = Webfm.ajaxUrl(); var inputs = []; inputs = this.tbody.getElementsByTagName('input'); var output = 0; for(var i in inputs) { // Build permission val from checkbox name if(inputs[i].checked) output += parseInt(inputs[i].name); } Webfm.progressObj.show(Webfm.js_msg["work"], "blue"); var postObj = { action:encodeURIComponent("putperm"), param0:encodeURIComponent(this.data["id"]), param1:encodeURIComponent(output)}; Webfm.HTTPPost(url, this.submitPermcallback, this, postObj); } Webfm.perm.prototype.submitPermcallback = function(string, xmlhttp, obj) { Webfm.progressObj.hide(); if (xmlhttp.status == 200) { var result = Drupal.parseJson(string); if (result.status) { //put confirmed result back into this.data for proper 'reset' obj.data["p"] = result.data["perm"]; // Webfm.dbgObj.dbg('new perm :', obj.data["p"]); } obj.pane.headerMsg(result.msg); } else { Webfm.alrtObj.msg(Webfm.js_msg["ajax-err"]); } } /** * Webfm.metadata constructor * 1st param is popup container obj * 2nd param is default startup width * 2nd param is default startup height */ Webfm.metadata = function(container, width, height) { var elDiv = Webfm.ce('div'); elDiv.setAttribute('id', 'webfm-meta-form'); var elForm = Webfm.ce('form'); elDiv.appendChild(elForm); var elTable = Webfm.ce('table'); elForm.appendChild(elTable); var elTBody = Webfm.ce('tbody'); elTable.appendChild(elTBody); var elControls = Webfm.ce('div'); elForm.appendChild(elControls); this.obj = elDiv; this.container = container; this.form = elForm; this.tbody = elTBody; this.controls = elControls; this.fid = null; this.width = width; this.height = height; this.eventListeners = this.container.eventListenerArr; } Webfm.metadata.prototype.createForm = function(data) { cp = this; this.data = data; //clear any metadata info this.resetForm(); //create new pane to house this metadata object this.pane = new Webfm.pane(this.container, Webfm.js_msg["metadata"], "meta-pane", this.obj, this.width, this.height); //create metadata fields this.fillFormData(); //create controls if owner has rights to file if(this.fid) { this.buildFormControls(); } else { //put read-only indicator in pane header this.pane.headerMsg("read-only"); } } Webfm.metadata.prototype.resetForm = function() { var tbody = this.tbody; while(tbody.hasChildNodes()) { tbody.removeChild(tbody.firstChild); } var controls = this.controls; while(controls.hasChildNodes()) { controls.removeChild(controls.firstChild); } this.fid = null; } Webfm.metadata.prototype.fillFormData = function() { if(typeof this.data["id"] != "undefined") { this.fid = this.data["id"]; } for(var i in this.data) { var meta = Webfm.metadataHT.get(i); var elTr = Webfm.ce('tr'); // label td var elTd = Webfm.ce('td'); elTd.appendChild(Webfm.ctn(meta.desc + ': ')); elTr.appendChild(elTd); // info td var elTd = Webfm.ce('td'); if(this.fid && meta.edit) { switch(meta.size) { case 256: // textarea var elTextArea = Webfm.ce('textarea'); elTextArea.setAttribute('name', i); elTextArea.cols = "40"; elTextArea.rows = "4"; elTextArea.value = decodeURI(this.data[i]); elTd.appendChild(elTextArea); break; default: // textfield var elInput = Webfm.ce('input'); elInput.setAttribute('type', 'textfield'); elInput.setAttribute('name', i); elInput.setAttribute('size', '40'); elInput.setAttribute('value', decodeURI(this.data[i])); elTd.appendChild(elInput); break; } } else { elTd.appendChild(Webfm.ctn(decodeURI(this.data[i]))); } elTr.appendChild(elTd); // validation td var elTd = Webfm.ce('td'); elTd.appendChild(Webfm.ctn(String.fromCharCode(160))); //&nbsp; elTr.appendChild(elTd); this.tbody.appendChild(elTr); } } //build metadata control buttons Webfm.metadata.prototype.buildFormControls = function() { var cp = this; var submitButton = Webfm.ce('input'); submitButton.setAttribute('type', 'button'); submitButton.setAttribute('value', Webfm.js_msg["submit"]); submitButton.className = "meta-button"; var listener = Webfm.eventListenerAdd(cp.eventListeners, submitButton, "click", function(e) { if(cp.submitMeta()){cp.container.destroy();}Webfm.stopEvent(e); }); this.controls.appendChild(submitButton); var resetButton = Webfm.ce('input'); resetButton.setAttribute('type', 'button'); resetButton.setAttribute('value', Webfm.js_msg["reset"]); resetButton.className = "meta-button"; var listener = Webfm.eventListenerAdd(cp.eventListeners, resetButton, "click", function(e) { cp.createForm(cp.data); Webfm.stopEvent(e); }); this.controls.appendChild(resetButton); } // Validate the length of input Webfm.metadata.prototype.validateMetaInput = function(elInput) { var len = Webfm.metadataHT.get(elInput.name).size; // Webfm.dbgObj.dbg("validateMetaInput", elInput.name); if(len < 256) { var data = Webfm.trim(elInput.value); if(data.length > len) { // Append error msg to validation td var err_msg = Webfm.ctn(Webfm.js_msg["len-err"]); elInput.parentNode.nextSibling.style.color = 'red'; elInput.parentNode.nextSibling.appendChild(err_msg); setTimeout(function(){elInput.focus();},10); return false; } else { // Remove any contents of validation td while (elInput.parentNode.nextSibling.hasChildNodes()) elInput.parentNode.nextSibling.removeChild(elInput.parentNode.nextSibling.firstChild); } } return true; } Webfm.metadata.prototype.submitMeta = function() { var url = Webfm.ajaxUrl(); var inputs = []; var arr = []; var textareas = []; inputs = this.tbody.getElementsByTagName('input'); textareas = this.tbody.getElementsByTagName('textarea'); var input_num = inputs.length; for(var i = 0; i < input_num; i++) { if(!(this.validateMetaInput(inputs[i]))) break; } // All fields validated // TODO: Data format needs to be reworked (json?) if(i == input_num) { this.output = ""; for(var i = 0; i < input_num; i++) { this.output += encodeURIComponent(inputs[i].name) + ":" + encodeURIComponent(Webfm.trim(inputs[i].value)) + ","; } for(i = 0; i < textareas.length; i++) { this.output += encodeURIComponent(textareas[i].name) + ":" + encodeURIComponent(Webfm.trim(textareas[i].value)) + ","; } if(this.output.length) { Webfm.progressObj.show(Webfm.js_msg["work"], "blue"); //strip off final comma this.output = this.output.substring(0, this.output.length - 1); var postObj = { action:encodeURIComponent("putmeta"), param0:encodeURIComponent(this.fid), param1:encodeURIComponent(this.output)}; Webfm.HTTPPost(url, this.submitMetacallback, this, postObj); } } else { alert(Webfm.js_msg["fix_input"]); } return false; } Webfm.metadata.prototype.submitMetacallback = function(string, xmlhttp, obj) { Webfm.progressObj.hide(); if (xmlhttp.status == 200) { var result = Drupal.parseJson(string); // Webfm.dbgObj.dbg('submitMetacallback: ', Webfm.dump(result)); if (result.status) { //update data for reset button var params = []; params = obj.output.split(','); for(var i = 0; i < params.length; i++) { var key = params[i].substring(0, params[i].indexOf(":")); var val = params[i].substring(params[i].indexOf(":") + 1); obj.data[key] = val; } } obj.pane.headerMsg(result.data); } else { Webfm.alrtObj.msg(Webfm.js_msg["ajax-err"]); } } // Trim leading/trailing whitespace off string Webfm.trim = function(str) { return str.replace(/^\s+|\s+$/g, ''); } /* * Webfm.attach constructor * param is parentId from hook_form_alter */ Webfm.attach = function(parentId) { var wa = this; this.id = parentId this.attached = ''; this.eventListeners = []; var elTable = Webfm.ce('table'); var elTableBody = Webfm.ce('tbody'); //attached file rows are appended to this div this.body = elTableBody; //Header var elTr = Webfm.ce('tr'); // icon column var elTd = Webfm.ce('td'); elTd.className = 'head'; elTr.appendChild(elTd); // Sort dir/files column var elTd = Webfm.ce('td'); elTd.className = 'head'; elTd.appendChild(Webfm.ctn(Webfm.js_msg["attach-title"])); elTr.appendChild(elTd); // date/time column var elTd = Webfm.ce('td'); elTd.className = 'head'; elTd.appendChild(Webfm.ctn(Webfm.js_msg["column2"])); elTr.appendChild(elTd); // file size column var elTd = Webfm.ce('td'); elTd.className = 'head'; elTd.appendChild(Webfm.ctn(Webfm.js_msg["column3"])); elTr.appendChild(elTd); // owner column var elTd = Webfm.ce('td'); elTd.className = 'head'; elTd.appendChild(Webfm.ctn(Webfm.js_msg["column4"])); elTr.appendChild(elTd); elTableBody.appendChild(elTr); elTable.appendChild(elTableBody); Webfm.$(parentId).appendChild(elTable); } Webfm.attach.prototype.fetch = function() { var url = Webfm.ajaxUrl(); // action attribute of node-edit form contains the node number var node_url; if(Webfm.$('node-form')) { node_url = Webfm.$('node-form').action; } if(Webfm.$('comment-form')) { node_url = Webfm.$('comment-form').action; } Webfm.progressObj.show(Webfm.js_msg["work"], "blue"); var postObj = { action:encodeURIComponent("attach"), param0:encodeURIComponent(node_url) }; // If we are in a preview/validate, the fids are still stored in the form. // Pass them to webfm_ajax to reload them. var fids = Webfm.$(Webfm.attachFormInput).value; if (fids.length != 0) { postObj.param1 = encodeURIComponent(fids); } Webfm.HTTPPost(url, this.callback, this, postObj); } Webfm.attach.prototype.callback = function(string, xmlhttp, obj) { Webfm.progressObj.hide(); if (xmlhttp.status == 200) { result = Drupal.parseJson(string); // Webfm.dbgObj.dbg("attach.fetch:", Webfm.dump(result)); if(result.status) { if(result.data.length) { Webfm.admin = result.admin; var elInput = Webfm.$(Webfm.attachFormInput); var attach_arr = []; attach_arr = Webfm.$(Webfm.attachFormInput).value.split(','); for(var i = 0; i < result.data.length; i++) { var filerow = new Webfm.filerow(obj.body, result.data[i], 'attach', '', true, Webfm.menuHT.get('det'), obj.eventListeners); // Don't add if it already exists. // Note that values are kept in the form for preview/failed validate. for (var j = 0; j < attach_arr.length; j++) { if (result.data[i].id == attach_arr[j]) break; } if (j == attach_arr.length) { elInput.setAttribute('value', (elInput.getAttribute('value')?elInput.getAttribute('value')+',':'') + result.data[i].id); } } } } else Webfm.alrtObj.msg(result.data); } else { Webfm.alrtObj.msg(Webfm.js_msg["ajax-err"]); } } /** * Webfm.search constructor * 1st param is popup container obj * 2nd param is default startup width * 2nd param is default startup height */ Webfm.search = function(container, width, height) { var elDiv = Webfm.ce('div'); elDiv.setAttribute('id', 'webfm-search'); var elForm = Webfm.ce('form'); elDiv.appendChild(elForm); var elResults = Webfm.ce('div'); elDiv.appendChild(elResults); this.obj = elDiv; this.container = container; this.form = elForm; this.results = elResults; this.width = width; this.height = height; this.iconDir = getWebfmIconDir(); this.eventListeners = this.container.eventListenerArr; } Webfm.search.prototype.resetForm = function() { var form = this.form; while(form.hasChildNodes()) { form.removeChild(form.firstChild); } } Webfm.search.prototype.resetResults = function() { var results = this.results; while(results.hasChildNodes()) { results.removeChild(results.firstChild); } } Webfm.search.prototype.createForm = function(source) { cp = this; this.source = source; //clear any metadata info this.resetForm(); cp.resetResults(); //create new pane to house this metadata object var pane = new Webfm.pane(this.container, Webfm.js_msg["search-title"], "search-pane", this.obj, this.width, this.height); //put search path in header pane.headerMsg(source); //create search fields var elInput = Webfm.ce('input'); elInput.setAttribute('type', 'textfield'); elInput.setAttribute('size', '30'); setTimeout(function(){elInput.focus();},10); var listener = Webfm.eventListenerAdd(this.eventListeners, elInput, "keydown", function(e) { if(Webfm.enter(e)){ cp.submit(elInput.value); elInput.blur(); Webfm.stopEvent(e);} }); this.form.appendChild(elInput); var searchButton = Webfm.ce('input'); searchButton.setAttribute('type', 'button'); searchButton.setAttribute('value', Webfm.js_msg["search"]); var listener = Webfm.eventListenerAdd(this.eventListeners, searchButton, "click", function(e) { cp.submit(elInput.value);Webfm.stopEvent(e); }); this.form.appendChild(searchButton); pane.show(); } Webfm.search.prototype.submit = function(value) { var url = Webfm.ajaxUrl(); Webfm.progressObj.show(Webfm.js_msg["work"], "blue"); var postObj = { action:encodeURIComponent("search"), param0:encodeURIComponent(this.source), param1:encodeURIComponent(value) }; Webfm.HTTPPost(url, this.callback, this, postObj); } Webfm.search.prototype.callback = function(string, xmlhttp, cp) { Webfm.progressObj.hide(); if (xmlhttp.status == 200) { cp.resetResults(); //build ul of search results var result = Drupal.parseJson(string); if(result.files.length) { var searchList = Webfm.ce('ul'); for(var i = (result.files.length - 1); i >= 0; i--) { var elLi = Webfm.ce('li'); var elImg = Webfm.ce('img'); elImg.setAttribute('src', cp.iconDir + '/d.gif'); elImg.setAttribute('alt', Webfm.js_msg["u_dir"]); //title is path to directory elImg.setAttribute('title', result.files[i].p); var listener = Webfm.eventListenerAdd(cp.eventListeners, elImg, "click", function(e) { cp.selectDir(e); Webfm.stopEvent(e); }); var listener = Webfm.eventListenerAdd(cp.eventListeners, elImg, "mouseover", function(e) { cp.hoverDir(e, true); }); var listener = Webfm.eventListenerAdd(cp.eventListeners, elImg, "mouseout", function(e) { cp.hoverDir(e, false); }); elLi.appendChild(elImg); elLi.appendChild(Webfm.ctn(' ')); var elA = Webfm.ce('a'); elA.setAttribute('href', '#'); if(result.files[i].id) { //first three letters of id must be 'fid' for selectFile //tooltip indicates if file is downloadable elA.setAttribute('id', 'fidsrch' + result.files[i].id); elA.setAttribute('title', Webfm.js_msg["file-dwld"]); var listener = Webfm.eventListenerAdd(cp.eventListeners, elA, "click", function(e) { cp.selectFile(e); Webfm.stopEvent(e); }); } else { elA.setAttribute('title', Webfm.js_msg["no-file-dwld"]); } elA.appendChild(Webfm.ctn(result.files[i].n)); elLi.appendChild(elA); searchList.appendChild(elLi); } cp.results.appendChild(searchList); } else { var no_match = Webfm.ctn(Webfm.js_msg["no-match"]); cp.results.style.color = 'red'; cp.results.appendChild(no_match); } } else { Webfm.alrtObj.msg(Webfm.js_msg["ajax-err"]); } } // IE does not understand 'this' inside event listener func Webfm.search.prototype.hoverDir = function(event, state) { var el = event.target||window.event.srcElement; el.src = this.iconDir + (state ? '/open.gif' : '/d.gif'); } Webfm.search.prototype.selectDir = function(event) { var el = event.target||window.event.srcElement; Webfm.selectDir(el.title); } Webfm.search.prototype.selectFile = function(event) { var el = event.target||window.event.srcElement; Webfm.selectFile(el.id.substring(7), el, true); } /* * debug constructor * 1st param is popup container obj * 2nd param is default startup width * 2nd param is default startup height */ Webfm.debug = function(container, width, height) { var dbgButton = ''; //id from webfm_main() dbgButton = Webfm.$("webfm-debug-link"); this.enable = dbgButton; if(dbgButton) { this.container = container; this.eventListeners = this.container.eventListenerArr; this.width = width; this.height = height; var cp = this; //create cache popup var cacheCont = new Webfm.popup("webfm-cacheCont"); this.cacheCont = cacheCont; var report = Webfm.ce('div'); this.report = report; //attach popup creation to [debug] link var listener = Webfm.eventListenerAdd(Webfm.eventListeners, dbgButton, "click", function() { cp.show(); }); } } Webfm.debug.prototype.dbg = function(title, msg) { if(this.enable) { //put latest msg at top (less scrolling) elBr = Webfm.ce('br'); this.report.insertBefore(elBr, this.report.firstChild); if(msg) { this.report.insertBefore(Webfm.ctn(msg), this.report.firstChild); } if(title) { var elSpan = Webfm.ce('span'); elSpan.className = 'g'; elSpan.appendChild(Webfm.ctn(title)); this.report.insertBefore(elSpan, this.report.firstChild); } } } Webfm.debug.prototype.clear = function() { if(this.enable) { Webfm.alrtObj.msg(); while(this.report.hasChildNodes()) { this.report.removeChild(this.report.firstChild); } this.cacheCont.destroy(); } } Webfm.debug.prototype.show = function() { if(this.enable) { var elDiv = Webfm.ce('div'); elDiv.setAttribute('id', 'webfm-debug'); this.obj = elDiv; //create new pane to house this metadata object var pane = new Webfm.pane(this.container, Webfm.js_msg["debug-title"], "debug-pane", this.obj, this.width, this.height); var cp = this; var elControls = Webfm.ce('div'); this.controls = elControls; var elClear = Webfm.ce('input'); elClear.setAttribute('type', 'button'); elClear.setAttribute('value', Webfm.js_msg["clear"]); elClear.className = "dbg-button"; var listener = Webfm.eventListenerAdd(this.eventListeners, elClear, "click", function() { cp.clear(); }); this.controls.appendChild(elClear); var elCache = Webfm.ce('input'); elCache.setAttribute('type', 'button'); elCache.setAttribute('value', Webfm.js_msg["cache"]); elCache.className = "dbg-button"; var listener = Webfm.eventListenerAdd(this.eventListeners, elCache, "click", function(e) { cp.showCache();Webfm.stopEvent(e); }); this.controls.appendChild(elCache); this.obj.appendChild(elControls); var report = this.report; this.obj.appendChild(report); } } Webfm.debug.prototype.showCache = function() { if(this.enable) { //create new pane to house this metadata object var dump = Webfm.ctn(Webfm.dump(Webfm.dirListObj.cache.dump())); var pane = new Webfm.pane(this.cacheCont, Webfm.js_msg["cache-title"], "cache-pane", dump, this.width, this.height); pane.show(); } } /** * Progress indicator */ Webfm.progress = function(parent, id) { this.id = id; this.flag = false; var elSpan = Webfm.ce('span'); elSpan.setAttribute('id', this.id); parent.appendChild(elSpan); } Webfm.progress.prototype.hide = function() { if(this.flag) { this.flag = false; Webfm.clearNodeById(this.id); } } Webfm.progress.prototype.show = function(x, y) { if(!this.flag) { this.flag = true; var prog = Webfm.$(this.id); var elSpan = Webfm.ce('span'); elSpan.style.backgroundColor = y; elSpan.appendChild(Webfm.ctn(x)); prog.appendChild(elSpan); prog.style.visibility = 'visible'; } } /** * Alert indicator */ Webfm.alert = function(parent, id) { this.id = id; var elDiv = Webfm.ce('div'); this.node = elDiv; elDiv.setAttribute('id', id); parent.appendChild(elDiv); } Webfm.alert.prototype.msg = function(msg) { if(!msg) { Webfm.clearNodeById(this.id); } else { var elSpan = Webfm.ce('span'); elSpan.className = 'alertspan'; elSpan.appendChild(Webfm.ctn(msg)); this.node.appendChild(elSpan); this.lf(); } } Webfm.alert.prototype.lf = function() { var elBr = Webfm.ce('br'); this.node.appendChild(elBr); } /* * Display an array of strings alert */ Webfm.alert.prototype.str_arr = function(arr) { if(typeof(arr) == 'function') return; else if(Webfm.isArray(arr)) { for(var i = 0; i < arr.length; i++) { this.str_arr(arr[i]); } } if(typeof(arr) == 'string') { this.msg(arr); } } /** * Webfm.popup constructor */ Webfm.popup = function(Id) { this.id = Id; var elDiv = Webfm.ce('div'); elDiv.id = Id; //id for css elDiv.style.cssText = 'position:absolute;display:none;'; document.body.appendChild(elDiv); this.obj = elDiv; //vars used for storing position info for contained object (pane) this.width = null; this.content_height = null; this.top = null; this.left = null; this.eventListenerArr = []; } Webfm.popup.prototype.getScrollY = function () { var scrY = 0; if(typeof(window.pageYOffset) == 'number') { scrY = window.pageYOffset; } else if(document.body && document.body.scrollTop) { scrY = document.body.scrollTop; } else if(document.documentElement && document.documentElement.scrollTop) { scrY = document.documentElement.scrollTop; } return scrY; } Webfm.popup.prototype.getObjectOffset = function(event, element, comp) { var objPos = this.objPosition(element, comp); var mousePos = Drupal.mousePosition(event); return {x:mousePos.x - objPos.x, y:mousePos.y - objPos.y}; } Webfm.popup.prototype.objPosition = function(element, comp) { var curleft = curtop = 0; if(element.offsetParent) { curleft = element.offsetLeft; curtop = element.offsetTop; while(element = element.offsetParent) { curleft += element.offsetLeft; curtop += element.offsetTop; } } // IE must compensate for relative positioning in css if(Webfm.browser.isIE && comp) { curleft += parseInt(getWebfmIEListOffset()); if(comp == 'tree') { curleft += parseInt(getWebfmIETreeOffset()); } } return { x:curleft, y:curtop }; } Webfm.popup.prototype.destroy = function () { //cleanup event closures for this popup Webfm.eventUnregister(this.eventListenerArr); while(this.obj.hasChildNodes()) this.obj.removeChild(this.obj.firstChild); document.onmousemove = null; document.onmouseup = null; this.obj.style.display = 'none'; } Webfm.popup.prototype.isEmpty = function () { return (!this.obj.hasChildNodes()); } /** * Webfm.pane constructor * 1st param is popup container obj * 2nd param is title displayed in pane header * 3rd param is this obj id * 4th param is content appended to this obj content div * 5th param is default startup width * 6th param is default startup height */ Webfm.pane = function(popupCont, title, paneId, content, paneWidth, contentHeight) { this.popupCont = popupCont; var cp = this; var body_scroll_top = this.popupCont.getScrollY(); var body_height = (Webfm.browser.isIE)? document.documentElement.clientHeight : window.innerHeight; // locate pane in centre of screen only if drag container not already in use if((!popupCont.width) || (!popupCont.content_height) || (!popupCont.top) || (!popupCont.left)) { var body_scroll_left = (Webfm.browser.isIE)? document.documentElement.scrollLeft : window.pageXOffset; var body_width = (Webfm.browser.isIE)? document.documentElement.clientWidth : window.innerWidth; this.popupCont.width = paneWidth; this.popupCont.content_height = contentHeight; this.popupCont.top = body_scroll_top + (body_height - contentHeight)/2; this.popupCont.left = body_scroll_left + (body_width - paneWidth)/2; } //Compensate pane position for vertical scroll that places it out of view if((body_scroll_top + body_height) < this.popupCont.top) { this.popupCont.top = body_scroll_top + (body_height - contentHeight)/2; } if((body_scroll_top) > this.popupCont.top + this.popupCont.content_height) { this.popupCont.top = body_scroll_top + (body_height - contentHeight)/2; } // Set top of drag popup and empty any contents this.popupCont.obj.style.top = this.popupCont.top + "px"; this.popupCont.obj.style.left = this.popupCont.left + "px"; this.popupCont.destroy(); // Pane container div var iconDir = getWebfmIconDir(); var pane = Webfm.ce('div'); this.pane = pane; pane.id = paneId; pane.className = "pane"; pane.style.width = this.popupCont.width + "px"; this.popupCont.obj.appendChild(this.pane); // pane header var header = Webfm.ce('div'); this.header = header; header.id = pane.id + '-header'; header.className = "pane-header"; var elTitle = Webfm.ce('div'); elTitle.appendChild(Webfm.ctn(title)); elTitle.className = "pane-title"; header.appendChild(elTitle); var elMsg = Webfm.ce('div'); this.msg = elMsg; elMsg.className = "pane-msg"; header.appendChild(elMsg); var cp = this; var listener = Webfm.eventListenerAdd(Webfm.eventListeners, header, "mousedown", function(e) { cp.dragStart(e, 1); }); var elA = Webfm.ce('a'); elA.setAttribute('href', '#'); elA.setAttribute('title', Webfm.js_msg["close"]); elA.className = "pane-close"; var elImg = Webfm.ce('img'); elImg.setAttribute('src', iconDir+ '/x.gif'); elImg.setAttribute('alt', Webfm.js_msg["close"]); elA.appendChild(elImg); header.appendChild(elA); var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elA, "click", function(e) { cp.popupCont.destroy();Webfm.stopEvent(e); }); pane.appendChild(header); // pane content var contentContainer = Webfm.ce('div'); this.content = contentContainer; contentContainer.id = pane.id + '-content'; contentContainer.className = "pane-content"; contentContainer.style.height = this.popupCont.content_height + "px"; pane.appendChild(contentContainer); // pane footer var footer = Webfm.ce('div'); this.footer = footer; footer.className = "pane-footer"; var elResize = Webfm.ce('a'); elResize.setAttribute('href', '#'); elResize.setAttribute('title', Webfm.js_msg["resize"]); elResize.className = "pane-resize"; var elImg = Webfm.ce('img'); elImg.setAttribute('src', iconDir+ '/resize.gif'); elImg.setAttribute('alt', Webfm.js_msg["resize"]); elResize.appendChild(elImg); footer.appendChild(elResize); var listener = Webfm.eventListenerAdd(Webfm.eventListeners, elResize, "mousedown", function(e) { cp.dragStart(e, 0); }); pane.appendChild(footer); if(content) this.fill(content); } Webfm.pane.prototype.dragStart = function(event, move) { Webfm.dragging = true; var cp = this; event = event || window.event; // Hide content - mousing over visible iframe can cause problems this.content.style.visibility = "hidden"; this.popupCont.obj.style.zIndex = ++Webfm.zindex; if(move == 1) { //Offset of cursor position form top/left corner of drag object on mousedown this.offset = this.popupCont.getObjectOffset(event, this.header); document.onmousemove = function(e) { cp.drag(e); }; document.onmouseup = function(e) { cp.dragEnd(e); }; this.drag(event); } else { //Start position of cursor on mousedown this.initPos = Drupal.mousePosition(event); //Start width and height of pane content on mousedown this.width = parseInt(this.pane.offsetWidth); this.height = parseInt(this.content.offsetHeight); document.onmousemove = function(e) { cp.resize(e); }; document.onmouseup = function(e) { cp.resizeEnd(e); }; Webfm.scrollVal = this.popupCont.getScrollY(); this.resize(event); } } Webfm.pane.prototype.drag = function(event) { event = event || window.event; var pos = Drupal.mousePosition(event); var x = pos.x - this.offset.x; var y = pos.y - this.offset.y; //Scroll page if near top or bottom edge. Hardcoded values var scroll = this.popupCont.getScrollY(); if(typeof(window.innerHeight) == 'number') { if(pos.y > (window.innerHeight + scroll - 35)) { window.scrollBy(0,20); } else if(pos.y - scroll < (25)) { window.scrollBy(0,-20); } } else if(document.documentElement && document.documentElement.clientHeight) { if(pos.y > (document.documentElement.clientHeight + scroll - 35)) { window.scrollBy(0,20); } else if(pos.y - scroll < (25)) { window.scrollBy(0,-20); } } // Move our drag container to wherever the mouse is (adjusted by mouseOffset) this.popupCont.obj.style.top = y + 'px'; this.popupCont.obj.style.left = x + 'px'; // Prevent selection of textnodes Webfm.stopEvent(event); } Webfm.pane.prototype.resize = function(event) { event = event || window.event; // Calculate distance from start position var pos = Drupal.mousePosition(event); var x = this.width + (pos.x - this.initPos.x); var y = this.height + (pos.y - this.initPos.y); // Adjust pane width and height css with min size constraint this.pane.style.width = Math.max(x, 100) + "px"; this.content.style.height = Math.max(y, 100) + "px"; // Prevent selection of textnodes Webfm.stopEvent(event); } Webfm.pane.prototype.dragEnd = function (event) { // Store popup container top/left position global vars this.popupCont.top = parseInt(this.popupCont.obj.style.top); this.popupCont.left = parseInt(this.popupCont.obj.style.left); this.end(event); } Webfm.pane.prototype.resizeEnd = function (event) { // Store popup container width/height size global vars this.popupCont.width = parseInt(this.pane.style.width); this.popupCont.content_height = parseInt(this.content.style.height); this.end(event); // counter browser scrolling setTimeout(function(){window.scrollTo(0, Webfm.scrollVal);}, 1); } Webfm.pane.prototype.end = function (event) { this.content.style.visibility = "visible"; Webfm.dragging = false; document.onmousemove = null; document.onmouseup = null; Webfm.stopEvent(event); } Webfm.pane.prototype.headerMsg = function (string) { while(this.msg.hasChildNodes()) this.msg.removeChild(this.msg.firstChild); this.msg.appendChild(Webfm.ctn(string)); } Webfm.pane.prototype.fill = function (content) { if(content) this.content.appendChild(content); this.show(); } Webfm.pane.prototype.clear = function () { while(this.content.hasChildNodes()) this.content.removeChild(this.content.firstChild); while(this.msg.hasChildNodes()) this.msg.removeChild(this.content.firstChild); } Webfm.pane.prototype.hide = function () { this.popupCont.obj.style.display = 'none' } Webfm.pane.prototype.show = function () { this.popupCont.obj.style.zIndex = ++Webfm.zindex; this.popupCont.obj.style.display = 'block' } /** * Webfm.draggable constructor */ Webfm.draggable = function(popupCont, element, _class) { this.dragCont = popupCont; this.element = element; this.curpath = element.title; this.isTree = _class.substring(0,4) == 'tree'; this.isDir = (_class == 'dirrow') || this.isTree; this.isAttach = _class == 'attachrow'; this.icondir = getWebfmIconDir(); this.comp = this.isTree ? 'tree' : 'list'; } Webfm.draggable.prototype.mouseButton = function(event) { event = event || window.event; // Determine mouse button var rightclick = Webfm.rclick(event); if(!rightclick && event.altKey == false) this.dragStart(event); } Webfm.draggable.prototype.dragStart = function (event) { Webfm.dragging = true; // Destroy all contents in popup container. this.dragCont.destroy(); var cp = this; document.onmousemove = function(e) { cp.drag(e); }; document.onmouseup = function(e) { cp.dragEnd(e); }; // Make transparent this.element.style.opacity = 0.5; // Process this.drag(event); } Webfm.draggable.prototype.drag = function (event) { var cp = this; event = event || window.event; //Build Webfm.dropContainers array //The dragStart flag ensures that the following executes once only at the //beginning of a drag-drop if (!(Webfm.dragStart)) { Webfm.dragStart = true; //copy dragged element into drag container and make visible this.offset = this.dragCont.getObjectOffset(event, this.element, this.comp); if(Webfm.browser.isIE && !this.isTree) { /* IE cannot clone table rows */ var elDiv = Webfm.ce('div'); elDiv.setAttribute('id', 'webfm-ieDD'); elDiv.appendChild(this.element.getElementsByTagName('img')[0].cloneNode(false)); elDiv.appendChild(this.element.getElementsByTagName('a')[0].firstChild.cloneNode(false)); this.dragCont.obj.appendChild(elDiv); } else { this.dragCont.obj.appendChild(this.element.cloneNode(true)); } this.dragCont.obj.style.display = 'block' this.dragCont.obj.style.zIndex = ++Webfm.zindex; Webfm.dropContainers = []; // Build list drop container array if(!this.isAttach) { var dirListRows = Webfm.dirListObj.obj.getElementsByTagName('tr'); var dirListCont = []; for(var k = 0; k < dirListRows.length; k++) { if (dirListRows[k].className == 'dirrow') { dirListCont.push(dirListRows[k]); } } if (dirListCont.length) { for(var i = 0; i < dirListCont.length; i++) { // DragDrop element is folder icon var droptarget = dirListCont[i]; var cont_pos = this.dragCont.objPosition(droptarget, this.comp); var skip = false; var droppath = dirListCont[i].title; if(this.curpath == droppath) continue; if(this.isTree) { var curtemp = []; curtemp = this.curpath.split('/'); var droptemp = []; droptemp = droppath.split('/'); // Test if drop path is beneath the drag path for(var j = 0; j < curtemp.length; j++) { if(curtemp[j] != droptemp[j]) break; } if(j == curtemp.length) { skip = true; } else { // Test if drop path is directly above drag path (already a subdir) for(var j = 0; j < droptemp.length; j++) { if(curtemp[j] != droptemp[j]) break; } if((j == droptemp.length) && (curtemp.length == j + 1)) skip = true; } } if(skip == false) { // Valid drop container var container = { id: dirListCont[i].id, x: cont_pos.x, y: cont_pos.y, w: droptarget.offsetWidth, h: droptarget.offsetHeight }; Webfm.dropContainers.push(container); } } } var dirTreeCont = ''; dirTreeCont = Webfm.$("tree") if(dirTreeCont) { //reuse var for container list dirTreeCont = Webfm.$("tree").getElementsByTagName('li'); if (dirTreeCont.length) { // Build tree drop container array for(var i = 0; i < dirTreeCont.length; i++) { // DragDrop element is folder icon var droptarget = dirTreeCont[i].getElementsByTagName('div')[0]; var cont_pos = this.dragCont.objPosition(droptarget, this.comp); var skip = false; if(this.isTree) { // Prevent a directory drop onto itself or its direct parent li (already a sub-directory) if((dirTreeCont[i] != this.element) && (dirTreeCont[i] != this.element.parentNode.parentNode)) { var children = this.element.getElementsByTagName('li'); // Prevent a directory drop into a sub-directory for(var j = 0; j < children.length; j++) { if(children[j] == dirTreeCont[i]) skip = true; } } else { skip = true; } } else { var droppath = dirTreeCont[i].title; // A regex would be preferable here if(this.curpath != droppath){ var curtemp = []; curtemp = this.curpath.split('/'); var droptemp = []; droptemp = droppath.split('/'); // Test if drop path is beneath the drag path for(var j = 0; j < curtemp.length; j++) { if(curtemp[j] != droptemp[j]) break; } if(j == curtemp.length) { skip = true; } else { // Test if drop path is directly above drag path (already a subdir) for(var j = 0; j < droptemp.length; j++) { if(curtemp[j] != droptemp[j]) break; } if((j == droptemp.length) && (curtemp.length == j + 1)) skip = true; } } else { skip = true; } } if(skip == false) { // Valid drop container - add to array of drop containers var container = { id: dirTreeCont[i].id, x: cont_pos.x, y: cont_pos.y, w: droptarget.offsetWidth, h: droptarget.offsetHeight }; Webfm.dropContainers.push(container); } } } } } else { // attachment container is attach table body var droptarget = Webfm.attachObj.body; var cont_pos = this.dragCont.objPosition(droptarget, this.comp); Webfm.attachContainer = { x: cont_pos.x, y: cont_pos.y, w: droptarget.offsetWidth, h: droptarget.offsetHeight }; } } var pos = Drupal.mousePosition(event); var x = pos.x - this.offset.x; var y = pos.y - this.offset.y; //Scroll page if near top or bottom edge. Hardcoded values var scroll = this.dragCont.getScrollY(); if(typeof(window.innerHeight) == 'number') { if(pos.y > (window.innerHeight + scroll - 35)) { window.scrollBy(0,20); } else if(pos.y - scroll < (25)) { window.scrollBy(0,-20); } } else if(document.documentElement && document.documentElement.clientHeight) { if(pos.y > (document.documentElement.clientHeight + scroll - 35)) { window.scrollBy(0,20); } else if(pos.y - scroll < (25)) { window.scrollBy(0,-20); } } // move our drag container to wherever the mouse is (adjusted by mouseOffset) this.dragCont.obj.style.top = y + 'px'; this.dragCont.obj.style.left = x + 'px'; if(!this.isAttach) { Webfm.activeDropCont = null; if(Webfm.dropContainers.length) { // Compare mouse position to every drop container for(var i = 0; i < Webfm.dropContainers.length; i++) { if((Webfm.dropContainers[i].x < pos.x) && (Webfm.dropContainers[i].y < pos.y) && ((Webfm.dropContainers[i].w + Webfm.dropContainers[i].x) > pos.x) && ((Webfm.dropContainers[i].h + Webfm.dropContainers[i].y) > pos.y)) { // Found a valid drop container - Highlight selection Webfm.activeDropCont = Webfm.$(Webfm.dropContainers[i].id); Webfm.$(Webfm.dropContainers[i].id + 'dd').src = this.icondir + '/open.gif'; Webfm.$(Webfm.dropContainers[i].id).className += ' selected'; } else { // De-highlight container Webfm.$(Webfm.dropContainers[i].id + 'dd').src = this.icondir + '/d.gif'; var class_names = []; class_names = Webfm.$(Webfm.dropContainers[i].id).className.split(' '); Webfm.$(Webfm.dropContainers[i].id).className = class_names[0]; } } } } else { // Ignore all movement outside of the attach table if((Webfm.attachContainer.x < pos.x) && (Webfm.attachContainer.y < pos.y) && ((Webfm.attachContainer.w + Webfm.attachContainer.x) > pos.x) && ((Webfm.attachContainer.h + Webfm.attachContainer.y) > pos.y)) { // In attach container var att_table_body = Webfm.attachObj.body; var attachRows = att_table_body.getElementsByTagName('TR'); var prevNode = ''; var nextNode = ''; var curr = false; // Start at 1 since first row is header for(var i = 1; i < attachRows.length; i++) { if(this.element.id != attachRows[i].id) { var att_pos = this.dragCont.objPosition(attachRows[i], this.comp); if((att_pos.y + (attachRows[i].offsetHeight / 2)) < pos.y) { if(curr == true) prevNode = attachRows[i]; } else if((att_pos.y + (attachRows[i].offsetHeight / 2)) > pos.y) { if(curr == false) nextNode = attachRows[i]; } } else curr = true; } if(prevNode) att_table_body.insertBefore(prevNode, this.element); else if (nextNode) att_table_body.insertBefore(this.element, nextNode); } } //prevent selection of textnodes Webfm.stopEvent(event); } Webfm.draggable.prototype.dragEnd = function (event) { event = event || window.event; // Restore opacity this.element.style.opacity = 1.0; Webfm.dragging = false; Webfm.dragStart = false; this.dragCont.obj.style.display = 'none'; Webfm.stopEvent(event); if(!this.isAttach) { // Move dragged object if a valid drop container if(Webfm.activeDropCont) { this.droppath = Webfm.activeDropCont.title; // De-highlight container Webfm.$(Webfm.activeDropCont.id + 'dd').src = this.icondir + '/d.gif'; var class_names = []; class_names = Webfm.activeDropCont.className.split(' '); Webfm.activeDropCont.className = class_names[0]; var url = Webfm.ajaxUrl(); Webfm.progressObj.show(Webfm.js_msg["work"], "blue"); var postObj = { action:encodeURIComponent("move"), param0:encodeURIComponent(this.curpath), param1:encodeURIComponent(this.droppath) }; Webfm.HTTPPost(url, this.callback, this, postObj); Webfm.activeDropCont = null; } } else { // Put the current order of attachments into the form in preparation for submit var elInput = Webfm.$('edit-attachlist'); var attachRows = Webfm.attachObj.body.getElementsByTagName('tr'); elInput.setAttribute('value', ''); // Ignore 1st row (header) for(var i = 1; i < attachRows.length; i++) { var fid = attachRows[i].id.substring(3); elInput.setAttribute('value', (elInput.getAttribute('value')?elInput.getAttribute('value')+',':'') + fid); } } // Empty drag container + uncapture mouse. document.onmousemove = null; document.onmouseup = null; this.dragCont.destroy(); } Webfm.draggable.prototype.callback = function(string, xmlhttp, cp) { Webfm.progressObj.hide(); Webfm.alrtObj.msg(); if(xmlhttp.status == 200) { var result = Drupal.parseJson(string); Webfm.dbgObj.dbg("move result:", Webfm.dump(result)); if(result.status) { //flush cache for target dir and source dir of object Webfm.dirListObj.cache.remove(cp.droppath); Webfm.dirListObj.cache.remove(cp.curpath.substring(0, cp.curpath.lastIndexOf("/"))); //update tree if directory is moved if(cp.isDir) Webfm.dirTreeObj.fetch(true); if(!cp.isTree) //listing draggable - update current listing by removing dropped item cp.element.parentNode.removeChild(cp.element); else //tree draggable - update target directory Webfm.dirListObj.fetch(cp.droppath); } if(result.data) Webfm.alrtObj.str_arr(result.data); else Webfm.alrtObj.msg(Webfm.js_msg["move-err"]); } else { Webfm.alrtObj.msg(Webfm.js_msg["ajax-err"]); } } /** * Event Handler adapted from http://ajaxcookbook.org (Creative Commons Attribution 2.5) */ Webfm.eventListenerAdd = function(listener_arr, instance, eventName, listener) { var listenerFn = listener; if (instance.addEventListener) { instance.addEventListener(eventName, listenerFn, false); } else if (instance.attachEvent) { listenerFn = function() { listener(window.event); } instance.attachEvent("on" + eventName, listenerFn); } else { throw new Error("Event registration not supported"); } var event = { instance: instance, name: eventName, listener: listenerFn }; listener_arr.push(event); return event; } Webfm.eventListenerRemove = function(event, listener_arr) { var instance = event.instance; if (instance.removeEventListener) { instance.removeEventListener(event.name, event.listener, false); } else if (instance.detachEvent) { instance.detachEvent("on" + event.name, event.listener); } for (var i = 0; i < listener_arr.length; i++) { if (listener_arr[i] == event) { listener_arr.splice(i, 1); break; } } } //remove local event listeners Webfm.eventUnregister = function(listener_arr) { while (listener_arr.length > 0) { Webfm.eventListenerRemove(listener_arr[0], listener_arr); } listener_arr = []; } //remove global events at window.onunload Webfm.eventUnregisterWebfm = function() { while (Webfm.eventListeners.length > 0) { Webfm.eventListenerRemove(Webfm.eventListeners[0], Webfm.eventListeners); } Webfm.eventListeners = []; } /** * Helper Functions */ Webfm.$ = function(id) { return document.getElementById(id); } Webfm.ctn = function(textNodeContents) { var textNode = document.createTextNode(textNodeContents); return textNode; } Webfm.ce = function(elementName) { elementName = elementName.toLowerCase(); var element = document.createElement(elementName); return element; } /** * Creates an HTTP POST request and sends the response to the callback function * * Note: passing null or undefined for 'object' makes the request fail in Opera 8. * Pass an empty string instead. */ Webfm.HTTPPost = function(uri, callbackFunction, callbackParameter, object) { if(window.XMLHttpRequest){ // If IE7, Mozilla, Safari, etc: Use native object var xmlHttp = new XMLHttpRequest() } else { if(window.ActiveXObject){ // ...otherwise, use the ActiveX control for IE5.x and IE6 var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } } var bAsync = true; if (!callbackFunction) { bAsync = false; } xmlHttp.open('POST', uri, bAsync); var toSend = ''; if (typeof object == 'object') { xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xmlHttp.setRequestHeader("X-Requested-With", "XMLHttpRequest"); for (var i in object) { toSend += (toSend ? '&' : '') + i + '=' + encodeURIComponent(object[i]); } } else { toSend = object; } xmlHttp.send(toSend); if (bAsync) { xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4) { callbackFunction(xmlHttp.responseText, xmlHttp, callbackParameter); } } return xmlHttp; } else { return xmlHttp.responseText; } } /** * Prevents an event from propagating. */ Webfm.stopEvent = function(event) { event = event || window.event; if (event.preventDefault) { event.preventDefault(); event.stopPropagation(); } else { event.returnValue = false; event.cancelBubble = true; } } //the getModUrl() is used by contrib modules for custom ajax Webfm.ajaxUrl = function() { var path = getBaseUrl() + "/?q="; return path += (typeof getModUrl == "undefined") ? "webfm_js" : getModUrl(); } // Empty all child nodes Webfm.clearNodeById = function(elementId) { var node = Webfm.$(elementId); while (node.hasChildNodes()) node.removeChild(node.firstChild); } // Sort methods Webfm.sortByName = function(a, b) { if(typeof a.ftitle != "undefined") { var x = a.ftitle.toLowerCase(); } else { var x = a.n.toLowerCase(); } if(typeof b.ftitle != "undefined") { var y = b.ftitle.toLowerCase(); } else { var y = b.n.toLowerCase(); } return ((x < y) ? -1 : ((x > y) ? 1 : 0)); } Webfm.sortBySize = function(a, b) { var x = parseInt(parseFloat(a.s)); var y = parseInt(parseFloat(b.s)); return x - y; } Webfm.sortByModified = function(a, b) { var x = a.m; var y = b.m; return ((x < y) ? -1 : ((x > y) ? 1 : 0)); } Webfm.sortByOwner = function(a, b) { if(typeof a.funame != "undefined") { var x = a.funame.toLowerCase(); } else { var x = a.un.toLowerCase(); } if(typeof b.funame != "undefined") { var y = b.funame.toLowerCase(); } else { var y = b.un.toLowerCase(); } return ((x < y) ? -1 : ((x > y) ? 1 : 0)); } Webfm.sortByKey = function(a, b) { var x = a.toLowerCase(); var y = b.toLowerCase(); return ((x < y) ? -1 : ((x > y) ? 1 : 0)); } // Build date stamp Webfm.convertunixtime = function(unixtime) { // unix date format doesn't have millisec component var _date = new Date(unixtime * 1000); var _min = _date.getMinutes(); var _hours = _date.getHours(); var _day = _date.getDate(); var _mon = _date.getMonth() + 1; var _year = _date.getFullYear(); _min = Webfm.doubleDigit(_min); _hours = Webfm.doubleDigit(_hours); _day = Webfm.doubleDigit(_day); _mon = Webfm.doubleDigit(_mon); if(_year > 1999) _year -= 2000; else _year -= 1900; _year = Webfm.doubleDigit(_year); // Get day/month order from db variable var format = getWebfmDateFormat(); if(format == 1) return _day + "/" + _mon + "/" + _year + " " + _hours + ":" + _min; else return _mon + "/" + _day + "/" + _year + " " + _hours + ":" + _min; } Webfm.doubleDigit = function(num) { return(num < 10) ? "0" + num : num; } Webfm.size = function(sz) { var size = sz; var units; if(size < 1024) units = " B"; else { size = parseInt(size >> 10); if(size < 1024) units = " KB"; else { size = parseInt(size >> 10); if(size < 1024) units = " MB"; else { size = parseInt(size >> 10); if(size < 1024) units = " GB"; else { size = parseInt(size >> 10); suffix = " TB"; } } } } return size + units; } Webfm.enter = function(event) { event = event || window.event; var code; if (event.keyCode) code = event.keyCode; else if (e.which) code = e.which; return(code == 13) ? true : false; } Webfm.rclick= function(event) { if (event.which) { var rightclick = (event.which == 3); } else { if (event.button) var rightclick = (event.button == 2); } return rightclick; } Webfm.copyToClipboard = function(s) { if(window.clipboardData && clipboardData.setData) { clipboardData.setData("Text", s); } else if(Webfm.browser.isOP) { alert("Clipboard function not supported in Opera. Copy link address from context menu."); } else if(window.netscape) { // You have to sign the code to enable this or allow the action in about:config by changing // user_pref("signed.applets.codebase_principal_support", true); try { netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect'); } catch(e) { alert("This feature requires 'signed.applets.codebase_principal_support=true' at about:config"); return false; } var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard); if(!clip) return; // create a transferable var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable); if(!trans) return; // specify the data we wish to handle. Plaintext in this case. trans.addDataFlavor('text/unicode'); // To get the data from the transferable we need two new objects var str = new Object(); var len = new Object(); var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString); var copytext = s; str.data = copytext; trans.setTransferData("text/unicode", str, copytext.length * 2); var clipid = Components.interfaces.nsIClipboard; if(!clip) return false; clip.setData(trans, null, clipid.kGlobalClipboard); } } // Dump debug function // return a string version of a thing, without name. // calls recursive function to actually traverse content. Webfm.dump = function(content, txt_arr) { if(txt_arr == 'undefined') txt_arr = false; return Webfm.dumpRecur(content, 0, true, txt_arr) + "\n"; } // recursive function traverses content, returns string version of thing // content: what to dump. // indent: how far to indent. // neednl: true if need newline, false if not Webfm.dumpRecur = function(content,indent,neednl,txt_arr) { var out = ""; if (typeof(content) == 'function') return 'function'; else if (Webfm.isArray(content)) { // handle real arrays in brackets if (neednl) out += "\n"+Webfm.dumpSpaces(indent); if(!txt_arr) out+="[ "; var inside = false; for (var i=0; i<content.length; i++) { if (inside) out+=" \n"+Webfm.dumpSpaces(indent+1); else inside=true; out+=Webfm.dumpRecur(content[i],indent+1,false,txt_arr); } out+="\n"+Webfm.dumpSpaces(indent); if(!txt_arr) out+="]"; } else if (Webfm.isObject(content)) { // handle objects by association if (neednl) out+="\n"+Webfm.dumpSpaces(indent); if(!txt_arr) out+="{ "; var inside = false; for (var i in content) { if (inside) out+=" \n"+Webfm.dumpSpaces(indent+1); else inside = true; out+="'" + i + "':" + Webfm.dumpRecur(content[i],indent+1,true,txt_arr); } out+="\n"+Webfm.dumpSpaces(indent); if(!txt_arr) out+="}"; } else if (typeof(content) == 'string') { out+="'" + content + "'"; } else { out+=content; } return out; } // print n groups of two spaces for indent Webfm.dumpSpaces = function(n) { var out = ''; for (var i=0; i<n; i++) out += ' '; return out; } Webfm.isArray = function(array) { return(array && array.constructor == Array); } Webfm.isObject = function(object) { return(object && object.constructor == Object); } // Unregister all global listener events window.onunload = Webfm.eventUnregisterWebfm; ///////////////////////////////////////////////////////ADD IN LEGACY DRUPAL JS FUNCTIONS USED BY WEBFM//////////////////////////////////////////////// /** * Redirects a button's form submission to a hidden iframe and displays the result * in a given wrapper. The iframe should contain a call to * window.parent.iframeHandler() after submission. */ Drupal.redirectFormButton = function (uri, button, handler) { // Trap the button button.onmouseover = button.onfocus = function() { button.onclick = function() { // Create target iframe Drupal.createIframe(); // Prepare variables for use in anonymous function. var button = this; var action = button.form.action; var target = button.form.target; // Redirect form submission to iframe this.form.action = uri; this.form.target = 'redirect-target'; handler.onsubmit(); // Set iframe handler for later window.iframeHandler = function () { var iframe = $('#redirect-target').get(0); // Restore form submission button.form.action = action; button.form.target = target; // Get response from iframe body try { response = (iframe.contentWindow || iframe.contentDocument || iframe).document.body.innerHTML; // Firefox 1.0.x hack: Remove (corrupted) control characters response = response.replace(/[\f\n\r\t]/g, ' '); if (window.opera) { // Opera-hack: it returns innerHTML sanitized. response = response.replace(/&quot;/g, '"'); } } catch (e) { response = null; } response = Drupal.parseJson(response); // Check response code if (response.status == 0) { handler.onerror(response.data); return; } handler.oncomplete(response.data); return true; } return true; } } button.onmouseout = button.onblur = function() { button.onclick = null; } }; /** * Create an invisible iframe for form submissions. */ Drupal.createIframe = function () { if ($('#redirect-holder').size()) { return; } // Note: some browsers require the literal name/id attributes on the tag, // some want them set through JS. We do both. window.iframeHandler = function () {}; var div = document.createElement('div'); div.id = 'redirect-holder'; $(div).html('<iframe name="redirect-target" id="redirect-target" class="redirect" onload="window.iframeHandler();"></iframe>'); var iframe = div.firstChild; $(iframe) .attr({ name: 'redirect-target', id: 'redirect-target' }) .css({ position: 'absolute', height: '1px', width: '1px', visibility: 'hidden' }); $('body').append(div); }; /** * Delete the invisible iframe */ Drupal.deleteIframe = function () { $('#redirect-holder').remove(); }; /** * Returns the position of the mouse cursor based on the event object passed */ Drupal.mousePosition = function(e) { return { x: e.clientX + document.documentElement.scrollLeft, y: e.clientY + document.documentElement.scrollTop }; };
gpl-2.0
Automattic/wp-calypso
client/state/data-layer/wpcom/sites/posts/likes/index.js
1098
import { POST_LIKES_REQUEST } from 'calypso/state/action-types'; import { mergeHandlers } from 'calypso/state/action-watchers/utils'; import { registerHandlers } from 'calypso/state/data-layer/handler-registry'; import { http } from 'calypso/state/data-layer/wpcom-http/actions'; import { dispatchRequest } from 'calypso/state/data-layer/wpcom-http/utils'; import { receiveLikes } from 'calypso/state/posts/likes/actions'; import mine from './mine'; import newLike from './new'; export const fetch = ( action ) => http( { method: 'GET', path: `/sites/${ action.siteId }/posts/${ action.postId }/likes`, apiVersion: '1.1', }, action ); export const fromApi = ( data ) => ( { found: +data.found, iLike: !! data.i_like, likes: data.likes, } ); export const onSuccess = ( { siteId, postId }, data ) => receiveLikes( siteId, postId, data ); registerHandlers( 'state/data-layer/wpcom/sites/posts/likes/index.js', mergeHandlers( newLike, mine, { [ POST_LIKES_REQUEST ]: [ dispatchRequest( { fetch, fromApi, onSuccess, onError: () => {}, } ), ], } ) );
gpl-2.0
sdwolf/redmine_autostatus
db/migrate/004_create_autostatus_rule_conditions.rb
303
class CreateAutostatusRuleConditions < ActiveRecord::Migration def change create_table :autostatus_rule_conditions do |t| t.integer :rule_type t.references :tracker t.references :autostatus_rule_definition end add_index :autostatus_rule_conditions, :tracker_id end end
gpl-2.0
dsx-tech/e-voting
sources/e-voting/common/src/main/java/uk/dsxt/voting/common/nxt/walletapi/Attachment.java
1976
package uk.dsxt.voting.common.nxt.walletapi; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Value; @Value public class Attachment { int phasingFinishHeight; int phasingHolding; int phasingQuorum; int versionPhasing; int phasingMinBalance; int phasingMinBalanceModel; int versionOrdinaryPayment; int phasingVotingModel; int versionMessage; int versionArbitraryMessage; boolean messageIsText; String message; @JsonCreator public Attachment(@JsonProperty("phasingFinishHeight") int phasingFinishHeight, @JsonProperty("phasingHolding") int phasingHolding, @JsonProperty("phasingQuorum") int phasingQuorum, @JsonProperty("version.Phasing") int version, @JsonProperty("phasingMinBalance") int phasingMinBalance, @JsonProperty("phasingMinBalanceModel") int phasingMinBalanceModel, @JsonProperty("version.OrdinaryPayment") int versionOrdinaryPayment, @JsonProperty("phasingVotingModel") int phasingVotingModel, @JsonProperty("version.Message") int versionMessage, @JsonProperty("version.ArbitraryMessage") int versionArbitraryMessage, @JsonProperty("messageIsText") boolean messageIsText, @JsonProperty("message") String message) { this.phasingFinishHeight = phasingFinishHeight; this.phasingHolding = phasingHolding; this.phasingQuorum = phasingQuorum; this.versionPhasing = version; this.phasingMinBalance = phasingMinBalance; this.phasingMinBalanceModel = phasingMinBalanceModel; this.versionOrdinaryPayment = versionOrdinaryPayment; this.phasingVotingModel = phasingVotingModel; this.versionMessage = versionMessage; this.versionArbitraryMessage = versionArbitraryMessage; this.messageIsText = messageIsText; this.message = message; } }
gpl-2.0
Arquisoft/Trivial4b
game/src/main/java/es/uniovi/asw/trivial/db/impl/local/persistencia/model/Usuario.java
3750
package es.uniovi.asw.trivial.db.impl.local.persistencia.model; import java.io.Serializable; import java.util.Collections; import java.util.HashSet; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; @SuppressWarnings("serial") @Entity @Table(name="TUSUARIOS") public class Usuario implements Serializable{ @Id @GeneratedValue private Long id; private String usuario; private String contrasenia; private String nombre; private boolean privilegiado; @Transient private String color; @Transient private int casillaActual; @Transient private String[] quesitos; @Transient private String icono; @OneToMany(mappedBy = "usuario") protected Set<UsuariosPartida> partidas= new HashSet<UsuariosPartida>(); public Set<UsuariosPartida> getPartida() { return Collections.unmodifiableSet(partidas); } public Set<UsuariosPartida> _getPartida() { return partidas; } public Usuario(){ super(); } public Usuario(Long id, String usuario, String contrasenia, String nombre){ this.id = id; this.usuario = usuario; this.contrasenia = contrasenia; this.nombre = nombre; this.color = ""; this.casillaActual = -1; this.quesitos = new String[4]; this.privilegiado = false; } public void addQuesito(String categoria) { if(quesitos == null) quesitos = new String[4]; if(categoria.equalsIgnoreCase("espectáculos")) quesitos[0] = categoria; else if(categoria.equalsIgnoreCase("ciencias y naturaleza")) quesitos[1] = categoria; else if(categoria.equalsIgnoreCase("geografía")) quesitos[2] = categoria; else if(categoria.equalsIgnoreCase("historia")) quesitos[3] = categoria; actualizarIconoQuesitos(); } public void actualizarIconoQuesitos(){ icono = icono.split("_")[0]; for(String quesito : quesitos){ if(quesito != null) icono += "_"+quesito.replace(" ", ""); else icono += "_"+quesito; } icono += ".png"; } public Long getId() { return id; } public void setId(Long id){ this.id=id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public void setContrasenia(String contrasenia) { this.contrasenia = contrasenia; } public void setColor(String colorJugador) { this.color = colorJugador; } public void setCasillaActual(int casillaActual){ this.casillaActual = casillaActual; } public int getCasillaActual(){ return casillaActual; } public void setIcono(String icono){ this.icono = icono; } public String getIcono(){ return icono; } public String getContrasenia(){ return contrasenia; } public String getUsuario() { return usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public boolean isPrivilegiado() { return privilegiado; } public boolean todosLosQuesitos() { for(String string : quesitos) if(string == null) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Usuario other = (Usuario) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
gpl-2.0
chenrui1988/bloger
usr/themes/material/index.php
1688
<?php /** * 这是HanSon 基于material 的Typecho模板 * * @package Material Theme * @author HanSon * @version 1.0.0 * @link http://hanc.cc */ $this->need('header.php'); ?> <section class="billboard"> <div class="container"> <div class="row"> <div class="col-md-7"> <div class="intro animate fadeIn"> <h1><?php $this->options->slogan() ?></h1> <p class="lead"></p> </div> </div> </div> </div> </section> <div class="container"> <div class="row"> <div class="col-md-9"> <?php while($this->next()): ?> <div class="panel panel-default"> <div class="panel-body"> <h3 class="post-title"><a href="<?php $this->permalink() ?>"><?php $this->title() ?></a></h3> <div class="post-meta"> <span>作者:<a href="<?php $this->author->permalink(); ?>"><?php $this->author(); ?></a> | </span> <span>时间:<?php $this->date('F j, Y'); ?> | </span> <span>分类:<?php $this->category(','); ?> | </span> <span>评论:<a href="<?php $this->permalink() ?>"><?php $this->commentsNum('%d 评论'); ?></a> | </span> <span>浏览:<a href="<?php $this->permalink() ?>"><?php Views_Plugin::theViews("","", 1); ?></a> </span> </div> <div class="post-content"><?php $this->content('<button class="btn btn-success btn-raised">阅读全文</button>'); ?></div> </div> </div> <?php endwhile; ?> <?php $this->pageNav('<< 上一页', '下一页 >>'); ?> </div> <?php $this->need('sidebar.php'); ?> <?php $this->need('footer.php'); ?>
gpl-2.0
davidgraeff/Android-NetPowerctrl
app/src/main/java/oly/netpowerctrl/data/query/DeviceQueryInterface.java
1078
package oly.netpowerctrl.data.query; import java.util.Collection; import java.util.List; import oly.netpowerctrl.credentials.Credentials; import oly.netpowerctrl.ioconnection.DeviceIOConnections; /** * Created by david on 08.06.15. */ public interface DeviceQueryInterface { boolean removeContainedSuccess(Credentials credentials); boolean removeContainedFailed(Credentials credentials); long computeMissingRuntimeUntilMinimum(); void finish(); long getTimeoutInMS(); /** * @return Return true if the Query is valid. An invalid query could be a specific devices query, * where no actual devices have been added. */ boolean isValid(); boolean isEmpty(); /** * @return Return a list of times (e.g. 20, 100, 200) for repeating the request if no response * could be observed in the given time. */ int[] getRepeatTimes(); List<Credentials> addAllToFailed(); Collection<Credentials> getCredentials(); boolean doAction(Credentials credentials, DeviceIOConnections deviceIOConnections); }
gpl-2.0
willblaschko/AlexaAndroid
libs/AlexaAndroid/src/main/java/com/willblaschko/android/alexa/AlexaManager.java
25349
package com.willblaschko.android.alexa; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.util.Log; import com.willblaschko.android.alexa.callbacks.AsyncCallback; import com.willblaschko.android.alexa.callbacks.AuthorizationCallback; import com.willblaschko.android.alexa.data.Event; import com.willblaschko.android.alexa.interfaces.AvsException; import com.willblaschko.android.alexa.interfaces.AvsItem; import com.willblaschko.android.alexa.interfaces.AvsResponse; import com.willblaschko.android.alexa.interfaces.GenericSendEvent; import com.willblaschko.android.alexa.interfaces.audioplayer.AvsPlayAudioItem; import com.willblaschko.android.alexa.interfaces.response.ResponseParser; import com.willblaschko.android.alexa.interfaces.speechrecognizer.SpeechSendAudio; import com.willblaschko.android.alexa.interfaces.speechrecognizer.SpeechSendText; import com.willblaschko.android.alexa.interfaces.speechrecognizer.SpeechSendVoice; import com.willblaschko.android.alexa.interfaces.speechsynthesizer.AvsSpeakItem; import com.willblaschko.android.alexa.requestbody.DataRequestBody; import com.willblaschko.android.alexa.service.DownChannelService; import com.willblaschko.android.alexa.system.AndroidSystemHandler; import com.willblaschko.android.alexa.utility.Util; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.net.HttpURLConnection; import okhttp3.Call; import okhttp3.Response; import okio.BufferedSink; import static com.willblaschko.android.alexa.AuthorizationManager.createCodeVerifier; import static com.willblaschko.android.alexa.interfaces.response.ResponseParser.getBoundary; import static com.willblaschko.android.alexa.utility.Util.IDENTIFIER; /** * The overarching instance that handles all the state when requesting intents to the Alexa Voice Service servers, it creates all the required instances and confirms that users are logged in * and authenticated before allowing them to send intents. * * Beyond initialization, mostly it supplies wrapped helper functions to the other classes to assure authentication state. */ public class AlexaManager { private static final String TAG = "AlexaManager"; private static final String KEY_URL_ENDPOINT = "url_endpoint"; private static AlexaManager mInstance; private static AndroidSystemHandler mAndroidSystemHandler; private AuthorizationManager mAuthorizationManager; private SpeechSendVoice mSpeechSendVoice; private SpeechSendText mSpeechSendText; private SpeechSendAudio mSpeechSendAudio; private VoiceHelper mVoiceHelper; private String urlEndpoint; private Context mContext; private boolean mIsRecording = false; private AlexaManager(Context context, String productId){ mContext = context.getApplicationContext(); if(productId == null){ productId = context.getString(R.string.alexa_product_id); } urlEndpoint = Util.getPreferences(context).getString(KEY_URL_ENDPOINT, context.getString(R.string.alexa_api)); mAuthorizationManager = new AuthorizationManager(mContext, productId); mAndroidSystemHandler = AndroidSystemHandler.getInstance(context); Intent stickyIntent = new Intent(context, DownChannelService.class); context.startService(stickyIntent); if(!Util.getPreferences(mContext).contains(IDENTIFIER)){ Util.getPreferences(mContext) .edit() .putString(IDENTIFIER, createCodeVerifier(30)) .apply(); } } /** * Return an instance of AlexaManager * * @param context application context * @return AlexaManager instance */ public static AlexaManager getInstance(Context context){ return getInstance(context, null); } /** * Return an instance of AlexaManager * * Deprecated: use @getInstance(Context) instead and set R.string.alexa_product_id in your application resources, * this change was made to properly support the DownChannelService * * @param context application context * @param productId AVS product id * @return AlexaManager instance */ @Deprecated public static AlexaManager getInstance(Context context, String productId){ if(mInstance == null){ mInstance = new AlexaManager(context, productId); } return mInstance; } public AuthorizationManager getAuthorizationManager(){ return mAuthorizationManager; } public void setUrlEndpoint(String url){ urlEndpoint = url; Util.getPreferences(mContext) .edit() .putString(KEY_URL_ENDPOINT, url) .apply(); } public SpeechSendVoice getSpeechSendVoice(){ if(mSpeechSendVoice == null){ mSpeechSendVoice = new SpeechSendVoice(); } return mSpeechSendVoice; } public SpeechSendText getSpeechSendText(){ if(mSpeechSendText == null){ mSpeechSendText = new SpeechSendText(); } return mSpeechSendText; } public SpeechSendAudio getSpeechSendAudio(){ if(mSpeechSendAudio == null){ mSpeechSendAudio = new SpeechSendAudio(); } return mSpeechSendAudio; } public VoiceHelper getVoiceHelper(){ if(mVoiceHelper == null){ mVoiceHelper = VoiceHelper.getInstance(mContext); } return mVoiceHelper; } /** * Check if the user is logged in to the Amazon service, uses an async callback with a boolean to return response * @param callback state callback */ public void checkLoggedIn(@NotNull final AsyncCallback<Boolean, Throwable> callback){ mAuthorizationManager.checkLoggedIn(mContext, new AsyncCallback<Boolean, Throwable>() { @Override public void start() { } @Override public void success(Boolean result) { callback.success(result); } @Override public void failure(Throwable error) { callback.failure(error); } @Override public void complete() { } }); } /** * Send a log in request to the Amazon Authentication Manager * @param callback state callback */ public void logIn(@Nullable final AuthorizationCallback callback){ //check if we're already logged in mAuthorizationManager.checkLoggedIn(mContext, new AsyncCallback<Boolean, Throwable>() { @Override public void start() { } @Override public void success(Boolean result) { //if we are, return a success if(result){ if(callback != null){ callback.onSuccess(); } }else{ //otherwise start the authorization process mAuthorizationManager.authorizeUser(callback); } } @Override public void failure(Throwable error) { if(callback != null) { callback.onError(new Exception(error)); } } @Override public void complete() { } }); } /** * Send a synchronize state {@link Event} request to Alexa Servers to retrieve pending {@link com.willblaschko.android.alexa.data.Directive} * See: {@link #sendEvent(String, AsyncCallback)} * @param callback state callback */ public void sendSynchronizeStateEvent(@Nullable final AsyncCallback<AvsResponse, Exception> callback){ sendEvent(Event.getSynchronizeStateEvent(), callback); } /** * Helper function to check if we're currently recording * @return */ public boolean isRecording(){ return mIsRecording; } /** * Send a text string request to the AVS server, this is run through Text-To-Speech to create the raw audio file needed by the AVS server. * * This allows the developer to pre/post-pend or send any arbitrary text to the server, versus the startRecording()/stopRecording() combination which * expects input from the user. This operation, because of the extra steps is generally slower than the above option. * * @param text the arbitrary text that we want to send to the AVS server * @param callback the state change callback */ public void sendTextRequest(final String text, @Nullable final AsyncCallback<AvsResponse, Exception> callback){ //check if the user is already logged in mAuthorizationManager.checkLoggedIn(mContext, new ImplCheckLoggedInCallback() { @Override public void success(Boolean result) { if (result) { //if the user is logged in //set our URL final String url = getEventsUrl(); //do this off the main thread new AsyncTask<Void, Void, AvsResponse>() { @Override protected AvsResponse doInBackground(Void... params) { //get our access token TokenManager.getAccessToken(mAuthorizationManager.getAmazonAuthorizationManager(), mContext, new TokenManager.TokenCallback() { @Override public void onSuccess(String token) { try { getSpeechSendText().sendText(mContext, url, token, text, new AsyncEventHandler(AlexaManager.this, callback)); } catch (Exception e) { e.printStackTrace(); //bubble up the error if(callback != null) { callback.failure(e); } } } @Override public void onFailure(Throwable e) { } }); return null; } @Override protected void onPostExecute(AvsResponse avsResponse) { super.onPostExecute(avsResponse); } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { //if the user is not logged in, log them in and then call the function again logIn(new ImplAuthorizationCallback<AvsResponse>(callback) { @Override public void onSuccess() { //call our function again sendTextRequest(text, callback); } }); } } }); } /** * Send raw audio data to the Alexa servers, this is a more advanced option to bypass other issues (like only one item being able to use the mic at a time). * * @param data the audio data that we want to send to the AVS server * @param callback the state change callback */ public void sendAudioRequest(final byte[] data, @Nullable final AsyncCallback<AvsResponse, Exception> callback){ sendAudioRequest(new DataRequestBody() { @Override public void writeTo(BufferedSink sink) throws IOException { sink.write(data); } }, callback); } /** * Send streamed raw audio data to the Alexa servers, this is a more advanced option to bypass other issues (like only one item being able to use the mic at a time). * * @param requestBody a request body that incorporates either a static byte[] write to the BufferedSink or a streamed, managed byte[] data source * @param callback the state change callback */ public void sendAudioRequest(final DataRequestBody requestBody, @Nullable final AsyncCallback<AvsResponse, Exception> callback){ //check if the user is already logged in mAuthorizationManager.checkLoggedIn(mContext, new ImplCheckLoggedInCallback() { @Override public void success(Boolean result) { if (result) { //if the user is logged in //set our URL final String url = getEventsUrl(); //get our access token TokenManager.getAccessToken(mAuthorizationManager.getAmazonAuthorizationManager(), mContext, new TokenManager.TokenCallback() { @Override public void onSuccess(final String token) { //do this off the main thread new AsyncTask<Void, Void, AvsResponse>() { @Override protected AvsResponse doInBackground(Void... params) { try { getSpeechSendAudio().sendAudio(url, token, requestBody, new AsyncEventHandler(AlexaManager.this, callback)); } catch (IOException e) { e.printStackTrace(); //bubble up the error if(callback != null) { callback.failure(e); } } return null; } @Override protected void onPostExecute(AvsResponse avsResponse) { super.onPostExecute(avsResponse); } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } @Override public void onFailure(Throwable e) { } }); } else { //if the user is not logged in, log them in and then call the function again logIn(new ImplAuthorizationCallback<AvsResponse>(callback) { @Override public void onSuccess() { //call our function again sendAudioRequest(requestBody, callback); } }); } } }); } public void cancelAudioRequest() { //check if the user is already logged in mAuthorizationManager.checkLoggedIn(mContext, new ImplCheckLoggedInCallback() { @Override public void success(Boolean result) { if (result) { //if the user is logged in getSpeechSendAudio().cancelRequest(); } } }); } /** Send a confirmation to the Alexa server that the device volume has been changed in response to a directive * See: {@link #sendEvent(String, AsyncCallback)} * * @param volume volume as reported by the {@link com.willblaschko.android.alexa.interfaces.speaker.AvsAdjustVolumeItem} Directive * @param isMute report whether the device is currently muted * @param callback state callback */ public void sendVolumeChangedEvent(final long volume, final boolean isMute, @Nullable final AsyncCallback<AvsResponse, Exception> callback){ sendEvent(Event.getVolumeChangedEvent(volume, isMute), callback); } /** Send a confirmation to the Alexa server that the mute state has been changed in response to a directive * See: {@link #sendEvent(String, AsyncCallback)} * * @param isMute mute state as reported by the {@link com.willblaschko.android.alexa.interfaces.speaker.AvsSetMuteItem} Directive * @param callback */ public void sendMutedEvent(final boolean isMute, @Nullable final AsyncCallback<AvsResponse, Exception> callback){ sendEvent(Event.getMuteEvent(isMute), callback); } /** * Send confirmation that the device has timed out without receiving a speech request when expected * See: {@link #sendEvent(String, AsyncCallback)} * * @param callback */ public void sendExpectSpeechTimeoutEvent(final AsyncCallback<AvsResponse, Exception> callback){ sendEvent(Event.getExpectSpeechTimedOutEvent(), callback); } /** * Send an event to indicate that playback of a speech item has started * See: {@link #sendEvent(String, AsyncCallback)} * * @param item our speak item * @param callback */ public void sendPlaybackStartedEvent(AvsItem item, long milliseconds, final AsyncCallback<AvsResponse, Exception> callback) { if (item == null) { return; } String event; if (isAudioPlayItem(item)) { event = Event.getPlaybackStartedEvent(item.getToken(), milliseconds); } else { event = Event.getSpeechStartedEvent(item.getToken()); } sendEvent(event, callback); } /** * Send an event to indicate that playback of a speech item has finished * See: {@link #sendEvent(String, AsyncCallback)} * * @param item our speak item * @param callback */ public void sendPlaybackFinishedEvent(AvsItem item, final AsyncCallback<AvsResponse, Exception> callback){ if (item == null) { return; } String event; if (isAudioPlayItem(item)) { event = Event.getPlaybackFinishedEvent(item.getToken()); } else { event = Event.getSpeechFinishedEvent(item.getToken()); } sendEvent(event, callback); } /** * Send an event to indicate that playback of an item has nearly finished * * @param item our speak/playback item * @param callback */ public void sendPlaybackNearlyFinishedEvent(AvsPlayAudioItem item, long milliseconds, final AsyncCallback<AvsResponse, Exception> callback){ if (item == null) { return; } String event = Event.getPlaybackNearlyFinishedEvent(item.getToken(), milliseconds); sendEvent(event, callback); } /** * Send a generic event to the AVS server, this is generated using {@link com.willblaschko.android.alexa.data.Event.Builder} * @param event the string JSON event * @param callback */ public void sendEvent(final String event, final AsyncCallback<AvsResponse, Exception> callback){ //check if the user is already logged in mAuthorizationManager.checkLoggedIn(mContext, new ImplCheckLoggedInCallback() { @Override public void success(Boolean result) { if (result) { //if the user is logged in //set our URL final String url = getEventsUrl(); //get our access token TokenManager.getAccessToken(mAuthorizationManager.getAmazonAuthorizationManager(), mContext, new TokenManager.TokenCallback() { @Override public void onSuccess(final String token) { //do this off the main thread new AsyncTask<Void, Void, AvsResponse>() { @Override protected AvsResponse doInBackground(Void... params) { Log.i(TAG, event); new GenericSendEvent(url, token, event, new AsyncEventHandler(AlexaManager.this, callback)); return null; } @Override protected void onPostExecute(AvsResponse avsResponse) { super.onPostExecute(avsResponse); } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } @Override public void onFailure(Throwable e) { } }); } else { //if the user is not logged in, log them in and then call the function again logIn(new ImplAuthorizationCallback<AvsResponse>(callback) { @Override public void onSuccess() { //call our function again sendEvent(event, callback); } }); } } }); } private boolean isAudioPlayItem (AvsItem item) { return item != null && (item instanceof AvsPlayAudioItem || !(item instanceof AvsSpeakItem)); } public String getUrlEndpoint(){ return urlEndpoint; } public String getPingUrl(){ return new StringBuilder() .append(getUrlEndpoint()) .append("/ping") .toString(); } public String getEventsUrl(){ return new StringBuilder() .append(getUrlEndpoint()) .append("/") .append(mContext.getString(R.string.alexa_api_version)) .append("/") .append("events") .toString(); } public String getDirectivesUrl(){ return new StringBuilder() .append(getUrlEndpoint()) .append("/") .append(mContext.getString(R.string.alexa_api_version)) .append("/") .append("directives") .toString(); } private static class AsyncEventHandler implements AsyncCallback<Call, Exception>{ AsyncCallback<AvsResponse, Exception> callback; AlexaManager manager; public AsyncEventHandler(AlexaManager manager, AsyncCallback<AvsResponse, Exception> callback){ this.callback = callback; this.manager = manager; } @Override public void start() { if (callback != null) { callback.start(); } } @Override public void success(Call currentCall) { try { Response response = currentCall.execute(); if(response.code() == HttpURLConnection.HTTP_NO_CONTENT){ Log.w(TAG, "Received a 204 response code from Amazon, is this expected?"); } final AvsResponse items = response.code() == HttpURLConnection.HTTP_NO_CONTENT ? new AvsResponse() : ResponseParser.parseResponse(response.body().byteStream(), getBoundary(response)); response.body().close(); mAndroidSystemHandler.handleItems(items); if (callback != null) { callback.success(items); } } catch (IOException|AvsException e) { if (!currentCall.isCanceled()) { if (callback != null) { callback.failure(e); } } } } @Override public void failure(Exception error) { //bubble up the error if (callback != null) { callback.failure(error); } } @Override public void complete() { if (callback != null) { callback.complete(); } manager.mSpeechSendAudio = null; manager.mSpeechSendVoice = null; manager.mSpeechSendText = null; } } private abstract static class ImplAuthorizationCallback<E> implements AuthorizationCallback{ AsyncCallback<E, Exception> callback; public ImplAuthorizationCallback(AsyncCallback<E, Exception> callback){ this.callback = callback; } @Override public void onCancel() { } @Override public void onError(Exception error) { if (callback != null) { //bubble up the error callback.failure(error); } } } private abstract static class ImplCheckLoggedInCallback implements AsyncCallback<Boolean, Throwable>{ @Override public void start() { } @Override public void failure(Throwable error) { } @Override public void complete() { } } }
gpl-2.0
Insubric/fire-calculator
fireindiceslib/src/main/scala/ch/wsl/fireindices/metadata/Variable_cases_indices.scala
71662
package ch.wsl.fireindices.metadata import ch.wsl.fireindices.functions.Functions import ch.wsl.fireindices.functions.ListFunctions import ch.wsl.fireindices.functions.Utils import ch.wsl.fireindices.ImplicitConversions._ import ch.wsl.fireindices.log.DataLog import scala.collection.mutable.MutableList case object Nesterov extends Variable("Nesterov index value","Nesterov","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (T15::T12::T::Nil) in += (Tdew15::Tdew12::Tdew::Nil) in += (P15::P12::P::Nil) /** * Calculate Nesterov index DataSerie * * @param prev previous value of Nesterov index * @param T15 temperature at 15:00 DataSerie * @param Tdew15 dewpoint temperature at 15:00 DataSerie * @param P precipitations Dataserie * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(prev:Double,T15:DataSerie,Tdew15:DataSerie,P:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(T15.start,T15.interval,ListFunctions.applyFunctionPrev(Functions.Nesterov,prev,T15.values,Tdew15.values,P.values), log, "start = "+prev+", "+notes) } /** * launch calculate on DataCollection with a previous val * * @param prev previous value of index * @param dss DataCollection > all DataSeries * @return DataSerie */ def calculate(prev:Double,dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(prev,v.ds(T15),v.ds(Tdew15),v.ds(P15), this.getLog(v)) } def calculate(dss:DataCollection):DataSerie={ calculate(Double.NaN,dss) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(me.prev.asInstanceOf[Double],v.ds(T15,1),v.ds(Tdew15,1),v.ds(P15,1), this.getLog(v))) } } case object Angstroem extends Variable("Angstroem index value","Angstroem","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (T13::T12::T::Nil) in += (H13::H12::H::Nil) /** * Calculate PETpen DataSerie * * @param T temperature DataSerie * @param H relative humidity DataSerie * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(T13:DataSerie,H13:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(T13.start,T13.interval,ListFunctions.applyFunction(Functions.Angstroem,T13.values,H13.values), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(T13),v.ds(H13), this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(T13,1),v.ds(H13,1), this.getLog(v))) } } case object Munger extends Variable("Munger index value","Munger","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (P::P12::P13::P15::Nil) /** * Calculate Munger index DataSerie * * @param prev previous value of Munger Indedx * @param P precipitation DataSerie * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(prev:Double,P:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(P.start,P.interval,ListFunctions.applyFunctionPrev(Functions.Munger,prev,P.values), log,"start = "+prev+" "+notes) } /** * launch calculate on DataCollection with a previous val * * @param prev previous value of index * @param dss DataCollection > all DataSeries * @return DataSerie */ def calculate(prev:Double,dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(prev,v.ds(P), this.getLog(v)) } def calculate(dss:DataCollection):DataSerie={ calculate(Double.NaN,dss) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(me.prev.asInstanceOf[Double],v.ds(P,1), this.getLog(v))) } } case object MC1 extends Variable("1-hour timelag fuel moisture","MC1","%",0,100, classOf[Double]) with Serie with Calculable{ in += (EMCfa::Nil) /** * Calculate MC1 index DataSerie * * @param EMCfa Equilibrium moisture content at fuel-atmosphere interface * @param notes some notes on DataSerie creation * @return MC1 */ def calculate(EMCfa:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(EMCfa.start,EMCfa.interval, EMCfa.values.map(Functions.MC1(_)), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(EMCfa), this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(EMCfa,1), this.getLog(v))) } } case object MC10 extends Variable("10-hour timelag fuel moisture","MC10","%",0,100, classOf[Double]) with Serie with Calculable{ in += (EMCfa::Nil) /** * Calculate MC10 index DataSerie * * @param EMCfa Equilibrium moisture content at fuel-atmosphere interface * @param notes some notes on DataSerie creation * @return MC10 */ def calculate(EMCfa:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(EMCfa.start,EMCfa.interval, EMCfa.values.map(Functions.MC10(_)), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(EMCfa), this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(EMCfa,1), this.getLog(v))) } } case object MC100 extends Variable("100-hour timelag fuel moisture","MC100","%",0,100, classOf[Double]) with Serie with Calculable{ in += (EMC24::Nil) in += (PDur::Nil) /** * Calculate MC100 index DataSerie * * @param EMC24 Weighted 24-hour average EMC * @param PDur duration of precipitation [h] * @param notes some notes on DataSerie creation * @return MC100 */ def calculate(prev:Double,EMC24:DataSerie,PDur:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(EMC24.start,EMC24.interval,ListFunctions.applyFunctionPrev(Functions.MC100,prev,EMC24.values,PDur.values), log, "start = "+prev+" "+notes) } /** * launch calculate on DataCollection with a previous val * * @param prev previous value of index * @param dss DataCollection > all DataSeries * @return DataSerie */ def calculate(prev:Double,dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(prev ,v.ds(EMC24),v.ds(PDur), this.getLog(v)) } /** * launch calculate on DataCollection (30% initial value) * * @param dss DataCollection > all DataSeries * @return DataSerie */ def calculate(dss:DataCollection):DataSerie={ calculate(30.0 ,dss) //30 % initial value } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(me.prev.asInstanceOf[Double],v.ds(EMC24,1),v.ds(PDur,1), this.getLog(v))) } } case object MC1000 extends Variable("1000-hour timelag fuel moisture","MC1000","%",0,100, classOf[Double]) with Serie with Calculable{ in += (EMC24::Nil) in += (PDur::Nil) /** * Calculate MC1000 index DataSerie * * @param EMC24 Weighted 24-hour average EMC * @param PDur duration of precipitation [h] * @param notes some notes on DataSerie creation * @return MC1000 */ def calculate(EMC24:DataSerie,PDur:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(EMC24.start,EMC24.interval,Functions.MC1000(EMC24.values,PDur.values), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(EMC24),v.ds(PDur), this.getLog(v)) //30 % initial value } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(EMC24,1),v.ds(PDur,1), this.getLog(v))) //30 % initial value } } case object FFWI extends Variable("FFWI index value","FFWI","--",-100000,100000, classOf[Double]) with Serie with Calculable{ // in += (T::T12::Tmax::T13::Nil) // in += (H::H12::Hmax::H13::Nil) in += (EMC::Nil) in += (U::U12::U13::Nil) /** * Calculate FFWI index DataSerie * * @param EMC equilibrium moisture content DataSerie * @param U wind speed DataSerie * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(EMC:DataSerie,U:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(EMC.start,EMC.interval,ListFunctions.applyFunction(Functions.FFWI,EMC.values,U.values), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(EMC),v.ds(U), this.getLog(v)) } /** * launch complete on DataCollection * * @param dss DataCollection > all DataSeries * @return DataSerie */ def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(EMC,1),v.ds(U,1), this.getLog(v))) } } case object FFWImod extends Variable("modified FFWI index value","FFWImod","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (KBDI::Nil) in += (FFWI::Nil) /** * Calculate modified FFWI index DataSerie * * @param KBDI KBDI index [inch/100] * @param FFWI Fosberg index * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(KBDI:DataSerie,FFWI:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(KBDI.start,KBDI.interval,ListFunctions.applyFunction(Functions.FFWImod,KBDI.values,FFWI.values), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(KBDI),v.ds(FFWI), this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(KBDI,1),v.ds(FFWI,1), this.getLog(v))) } } case object KBDI extends Variable("KBDI index value","KBDI","inches/100",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (Tmax::T15::T13::T12::T::Nil) in += (P::P12::P13::P15::Nil) in += MeanAnnualRain::Nil in += RainyWeekThreshold::Nil in += RainSum::Nil in += WeekRain::Nil in += RainyDayThreshold::Nil /** * Calculate KBDI index DataSerie (inches values) * * @param prev previous value of KBDI Indedx * @param threshold threshold to initalize KBDI index at zero * @param meanAnnualRain mean annual rainfall parameter * @param Tmax maximal temperature DataSerie * @param SumPrevRain consecutive rainfall sum DataSerie * @param P precipitation DataSerie * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(prev:Double,threshold:Double,meanAnnualRain:Double,Tmax:DataSerie,SumPrevRain:DataSerie,P:DataSerie,WeekRain:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(Tmax.start,Tmax.interval,ListFunctions.applyFunctionPrevThreshold(Functions.KBDI,prev,threshold,meanAnnualRain,Tmax.values,SumPrevRain.values,P.values,WeekRain.values), log, "start = "+prev+" "+notes) } /** * launch calculate on DataCollection with a previous val * * @param prev previous value of index * @param dss DataCollection > all DataSeries * @return DataSerie */ def calculate(prev:Double,dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(prev,v.par(RainyWeekThreshold).value,v.par(MeanAnnualRain).value,v.ds(Tmax),v.ds(RainSum),v.ds(P),v.ds(WeekRain), this.getLog(v)) } def calculate(dss:DataCollection):DataSerie={ calculate(Double.NaN,dss) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(me.prev.asInstanceOf[Double],v.par(RainyWeekThreshold).value,v.par(MeanAnnualRain).value,v.ds(Tmax,1),v.ds(RainSum,1),v.ds(P,1),v.ds(WeekRain,1), this.getLog(v))) } } case object KBDISI extends Variable("KBDISI index value","KBDISI","mm",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (Tmax::T15::T13::T12::T::Nil) in += (P::P12::P13::P15::Nil) in += MeanAnnualRain::Nil in += RainyWeekThreshold::Nil in += RainSum::Nil in += WeekRain::Nil in += RainyDayThreshold::Nil /** * Calculate KBDISI index DataSerie (metrical values) * * @param prev previous value of KBDISI Indedx * @param PweekThreshold threshold to initalize KBDISI index at zero * @param meanAnnualRain mean annual rainfall parameter * @param Tmax maximal temperature DataSerie * @param SumPrevRain consecutive rainfall sum DataSerie * @param P precipitation DataSerie * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(prev:Double,PweekThreshold:Double,Py_avg:Double,Tmax:DataSerie,SumPrevRain:DataSerie,P:DataSerie,WeekRain:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(Tmax.start,Tmax.interval,ListFunctions.applyFunctionPrevThreshold(Functions.KBDI_SI,prev,PweekThreshold,Py_avg,Tmax.values,SumPrevRain.values,P.values,WeekRain.values), log, "start = "+prev+" "+notes) } /** * launch calculate on DataCollection with a previous val * * @param prev previous value of index * @param dss DataCollection > all DataSeries * @return DataSerie */ def calculate(prev:Double,dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(prev,v.par(RainyWeekThreshold).value,v.par(MeanAnnualRain).value,v.ds(Tmax),v.ds(RainSum),v.ds(P),v.ds(WeekRain), this.getLog(v)) } def calculate(dss:DataCollection):DataSerie={ calculate(Double.NaN,dss) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(me.prev.asInstanceOf[Double],v.par(RainyWeekThreshold).value,v.par(MeanAnnualRain).value,v.ds(Tmax,1),v.ds(RainSum,1),v.ds(P,1),v.ds(WeekRain,1), this.getLog(v))) } } case object Sharples extends Variable("Sharples index value","Sharples","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (T::T12::T13::T15::Tmax::Nil) in += (H::H12::H13::H15::Nil) in += (U::U12::U13::U15::Umax::Nil) /** * Calculate Sharples index DataSerie * * @param T temperature DataSerie * @param H relative humidity DataSerie * @param U wind speed DataSerie * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(T:DataSerie,H:DataSerie,U:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(T.start,T.interval,ListFunctions.applyFunction(Functions.Sharples,T.values,H.values,U.values), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(T),v.ds(H),v.ds(U), this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(T,1),v.ds(H,1),v.ds(U,1), this.getLog(v))) } } case object FMI extends Variable("Sharples fuel moisture index","FMI","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (T::T12::T13::T15::Tmax::Nil) in += (H::H12::H13::H15::Nil) /** * Calculate FMI index DataSerie * * @param T temperature DataSerie * @param H relative humidity DataSerie * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(T:DataSerie,H:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(T.start,T.interval,ListFunctions.applyFunction(Functions.FMI,T.values,H.values), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(T),v.ds(H), this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(T,1),v.ds(H,1), this.getLog(v))) } } case object OrieuxDanger extends Variable("Orieux Danger classes","OrieuxDanger","",0,3, classOf[Double]) with Serie with Calculable{ in += res::Nil in += U::U12::U13::U15::Nil /** * Calculate OrieuxDanger DataSerie * * @param r soil reserve DataSerie [mm] * @param U wind speed DataSerie [m/s * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(r:DataSerie,U:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(r.start,r.interval,ListFunctions.applyFunction(Functions.OrieuxDanger,r.values,U.values), log, notes) } /** * launch calculate on DataCollection * * @param prev previous value of index * @param dss DataCollection > all DataSeries * @return DataSerie */ def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(res),v.ds(U), this.getLog(v)) } /** * launch complete on DataCollection * * @param prev previous value of index * @param dss DataCollection > all DataSeries * @return DataSerie */ def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(res,1),v.ds(U,1), this.getLog(v))) } } case object res extends Variable("soil water reserve (Orieux Index)","res","mm",-100000,100000, classOf[Double]) with Serie with Calculable{ in += P::P12::P13::P15::Nil in += PETthorn::Nil in += WeekRain::Nil in += RainyWeekThreshold::Nil /** * Calculate soil water reserve of Orieux index DataSerie [mm] * * @param prev previous value of Orieux index * @param PweekThreshold weekly rain threshol to initialize index * @param P precipitations * @param PETthorn potential evapotranspiration after Thorntwaite * @param WeekRain weekly rain sum to initialize index * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(prev:Double,PweekThreshold:Double,P:DataSerie,PETthorn:DataSerie,WeekRain:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(P.start,P.interval,ListFunctions.applyFunctionPrevThreshold(Functions.r,prev,PweekThreshold,P.values,PETthorn.values,WeekRain.values), log, "start = "+prev+",PweekThreshold = "+PweekThreshold+" "+notes) } /** * launch calculate on DataCollection with a previous val * * @param prev previous value of index * @param dss DataCollection > all DataSeries * @return DataSerie */ def calculate(prev:Double,dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(prev,v.par(RainyWeekThreshold).value,v.ds(P),v.ds(PETthorn),v.ds(WeekRain), this.getLog(v)) } def calculate(dss:DataCollection):DataSerie={ calculate(Double.NaN,dss) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(me.prev.asInstanceOf[Double], v.par(RainyWeekThreshold).value,v.ds(P,1),v.ds(PETthorn,1),v.ds(WeekRain,1), this.getLog(v))) } } case object res_surf extends Variable("surface soil water reserve (Carrega 1988)","res_surf","mm",-100000,100000, classOf[Double]) with Serie with Calculable{ in += P::P12::P13::P15::Nil in += PETthorn::Nil in += RainSum::Nil /** * Calculate rs (surface soil water reserve) DataSerie (Carrega 1988) * * @param prev previous'day rs DataSerie * @param P rainfall [mm] DataSerie * @param PETth potential evapotranspiration after Thornthwaite DataSerie * @param RainSum sum of continuous rain DataSerie * @param notes some notes on DataSerie creation * @return rs DataSerie */ def calculate(prev:Double,P:DataSerie,PETthorn:DataSerie,RainSum:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(P.start,P.interval,ListFunctions.applyFunctionPrev(Functions.rs,prev,P.values,PETthorn.values,RainSum.values), log, "start = "+prev+" "+notes) } /** * launch calculate on DataCollection with a previous val * * @param prev previous value of index * @param dss DataCollection > all DataSeries * @return DataSerie */ def calculate(prev:Double,dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(prev,v.ds(P),v.ds(PETthorn),v.ds(RainSum), this.getLog(v)) } def calculate(dss:DataCollection):DataSerie={ calculate(Double.NaN,dss) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(me.prev.asInstanceOf[Double] ,v.ds(P,1),v.ds(PETthorn,1),v.ds(RainSum,1), this.getLog(v))) } } case object I87 extends Variable("I87 index (Carrega 1988)","I87","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += T::Nil in += H::Nil in += U::Nil in += P::Nil in += res::Nil in += res_surf::Nil in += PC::Nil /** * Calculate I87 index DataSerie (Carrega 1988) * * @param T air temperature * @param H air humidity [%] * @param U wind speed [m/s] * @param P rainfall [mm] * @param r Orieux soil water reserve [mm] * @param rs Carrega surface soil water reserve [mm] * @param PC phenological coefficient * @param notes some notes on DataSerie creation * @return I87 DataSerie */ def calculate(T:DataSerie,H:DataSerie,U:DataSerie,P:DataSerie,r:DataSerie,rs:DataSerie,PC:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(T.start,T.interval,ListFunctions.applyFunction(Functions.I87,T.values,H.values,U.values,P.values,r.values,rs.values,PC.values.map(_.toInt)), log, notes) } /** * launch calculate on DataCollection * * @param dss all DataSeries * @return DataSerie */ def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(T),v.ds(H),v.ds(U),v.ds(P),v.ds(res),v.ds(res_surf),v.ds(PC), this.getLog(v)) } /** * launch complete on DataCollection * * @param dss all DataSeries * @return DataSerie */ def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(T,1),v.ds(H,1),v.ds(U,1),v.ds(P,1),v.ds(res,1),v.ds(res_surf,1),v.ds(PC,1), this.getLog(v))) } } case object pM68 extends Variable("pM68 index value","pM68","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (T13::T12::T::Nil) in += (VPD13::VPD12::VPD::Nil) // in += (H13::H12::Hmax::H::Nil) in += (P13::P12::P::Nil) in += (SnowCover::Nil) in += FireSeasonStart::Nil in += FireSeasonEnd::Nil /** * Calculate pM68 index DataSerie (M68 precipitation correction) * * @param prev previous value of pM68 * @param T13 temperature at 13:00 DataSerie * @param VPD13 vapour pressure deficit at 13:00 DataSerie * @param P13 precipitation sum at 13:00 DataSerie * @param P_1 precipitations of day before * @param P_2 precipitations of 2 days before * @param P_3 precipitations of 3 days before * @param snowcover DataSerie > snowcover DataSerie * @param snowcover_1 snowcover of day before * @param snowcover_2 snowcover of 2 days before * @param beginFireSeason date of beginning of the fire season (millisec) * @param endFireSeason date of ending of the fire season (millisec) * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(prev:Double,T13:DataSerie,VPD13:DataSerie,P13:DataSerie,P_1:Double,P_2:Double,P_3:Double,snowcover:DataSerie, snowcover_1:Int, snowcover_2:Int,startFireSeason:Long,endFireSeason:Long, log: DataLog, notes:String=""):DataSerie={ createDataSerie(T13.start,T13.interval,ListFunctions.applyFunctionPrev(Functions.pM68_vpd,prev,T13.values,VPD13.values,T13.getDates,P13.values,P_1,P_2,P_3,snowcover.values.map(_.toInt),snowcover_1,snowcover_2,startFireSeason,endFireSeason), log, "start = "+prev+" "+notes) } /** * launch calculate on DataCollection with a previous val * * @param prev previous value of index * @param dss DataCollection > all DataSeries * @return DataSerie */ def calculate(prev:Double,dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(prev,v.ds(T13),v.ds(VPD13),v.ds(P13),Double.NaN,Double.NaN,Double.NaN,v.ds(SnowCover),Null.Int,Null.Int,v.par(FireSeasonStart).value,v.par(FireSeasonEnd).value, this.getLog(v)) } def calculate(dss:DataCollection):DataSerie={ calculate(Double.NaN,dss) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val p13=v.ds(P13,4).values val sc=v.ds(SnowCover,3).values val me=dss.dss(this) me.updateLastAndNotes(calculate(me.prev.asInstanceOf[Double], v.ds(T13,1),v.ds(VPD13,1),v.ds(P13,1),p13(2),p13(1),p13(0),v.ds(SnowCover,1),sc(1),sc(0),v.par(FireSeasonStart).value,v.par(FireSeasonEnd).value, this.getLog(v))) } } case object pM68dwd extends Variable("pM68 index value (DWD modification)","pM68dwd","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (T13::T12::T15::T::Nil) in += (H13::H12::H15::H::Nil) in += (P13::P12::P15::P::Nil) in += (SnowCover::Nil) in += FireSeasonStart::Nil in += FireSeasonEnd::Nil /** * Calculate pM68dwd index DataSerie (M68 precipitation correction) * * @param prev previous value of pM68 * @param T13 temperature at 13:00 DataSerie * @param H13 relative humidity at 13:00 DataSerie * @param P13 precipitation sum at 13:00 DataSerie * @param P_1 precipitations of day before * @param P_2 precipitations of 2 days before * @param P_3 precipitations of 3 days before * @param snowcover DataSerie > snowcover DataSerie * @param snowcover_1 snowcover of day before * @param snowcover_2 snowcover of 2 days before * @param beginFireSeason date of beginning of the fire season (millisec) * @param endFireSeason date of ending of the fire season (millisec) * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(prev:Double,T13:DataSerie,H13:DataSerie,P13:DataSerie,P_1:Double,P_2:Double,P_3:Double,snowcover:DataSerie,snowcover_1:Int,snowcover_2:Int,startFireSeason:Long,endFireSeason:Long, log: DataLog, notes:String=""):DataSerie={ createDataSerie(T13.start,T13.interval,ListFunctions.applyFunctionPrev(Functions.pM68dwd,prev,T13.values,H13.values,T13.getDates,P13.values,P_1,P_2,P_3,snowcover.values.map(_.toInt),snowcover_1,snowcover_2,startFireSeason,endFireSeason), log, "start = "+prev+" "+notes) } /** * launch calculate on DataCollection with a previous val * * @param prev previous value of index * @param dss DataCollection > all DataSeries * @return DataSerie */ def calculate(prev:Double,dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(prev,v.ds(T13),v.ds(H13),v.ds(P13),Double.NaN,Double.NaN,Double.NaN,v.ds(SnowCover),Null.Int,Null.Int,v.par(FireSeasonStart).value,v.par(FireSeasonEnd).value, this.getLog(v)) } def calculate(dss:DataCollection):DataSerie={ calculate(Double.NaN,dss) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val p13=v.ds(P13,4).values val sc=v.ds(SnowCover,3).values val me=dss.dss(this) me.updateLastAndNotes(calculate(me.prev.asInstanceOf[Double], v.ds(T13,1),v.ds(H13,1),v.ds(P13,1),p13(2),p13(1),p13(0),v.ds(SnowCover,1),sc(1),sc(0),v.par(FireSeasonStart).value,v.par(FireSeasonEnd).value, this.getLog(v))) } } case object M68 extends Variable("M68 index value","M68","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (pM68::Nil) in += (P::P12::P13::P15::Nil) in += BirchLeaves::Nil in += RobiniaBlossom::Nil in += M68VegCorrStep3Start::Nil in += M68VegCorrStep3End::Nil /** * Calculate M68 index DataSerie (M68 vegetation correction) * * @param pM68 pM68 DataSerie * @param P precipitations DataSerie * @param birchPhase DataSerie > birch leaves phenological phase DataSerie * @param robiniaPhase DataSerie > robinia blossom phenological phase DataSerie * @param vegCorrStep3Start first date for cegetation correction(millisec) * @param vegCorrStep3end second date for cegetation correction(millisec) * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(pM68:DataSerie,P:DataSerie,birchPhase:DataSerie,robiniaPhase:DataSerie,vegCorrStep3Start:Long,vegCorrStep3End:Long, log:DataLog, notes:String=""):DataSerie={ createDataSerie(pM68.start,pM68.interval,Functions.M68(pM68.values,pM68.getDates,P.values,birchPhase.values,robiniaPhase.values,vegCorrStep3Start,vegCorrStep3End), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(pM68),v.ds(P),v.ds(BirchLeaves),v.ds(RobiniaBlossom),v.par(M68VegCorrStep3Start).value,v.par(M68VegCorrStep3End).value, this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(pM68,366),v.ds(P,366),v.ds(BirchLeaves,366),v.ds(RobiniaBlossom,366),v.par(M68VegCorrStep3Start).value,v.par(M68VegCorrStep3End).value, this.getLog(v))) } } case object M68dwd extends Variable("M68 index value (DWD modification)","M68dwd","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (pM68dwd::Nil) in += (P::P12::P13::P15::Nil) in += BirchLeaves::Nil in += RobiniaBlossom::Nil in += M68VegCorrStep3Start::Nil in += M68VegCorrStep3End::Nil /** * Calculate M68 index DataSerie (M68 vegetation correction) * * @param pM68 pM68 DataSerie * @param P precipitations DataSerie * @param birchPhase DataSerie > birch leaves phenological phase DataSerie * @param robiniaPhase DataSerie > robinia blossom phenological phase DataSerie * @param vegCorrStep3Start first date for cegetation correction(millisec) * @param vegCorrStep3end second date for cegetation correction(millisec) * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(pM68dwd:DataSerie,P:DataSerie,birchPhase:DataSerie,robiniaPhase:DataSerie,vegCorrStep3Start:Long,vegCorrStep3End:Long, log:DataLog, notes:String=""):DataSerie={ createDataSerie(pM68dwd.start,pM68dwd.interval,Functions.M68(pM68dwd.values,pM68dwd.getDates,P.values,birchPhase.values,robiniaPhase.values,vegCorrStep3Start,vegCorrStep3End), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(pM68dwd),v.ds(P),v.ds(BirchLeaves),v.ds(RobiniaBlossom),v.par(M68VegCorrStep3Start).value,v.par(M68VegCorrStep3End).value, this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(pM68dwd,366),v.ds(P,366),v.ds(BirchLeaves,366),v.ds(RobiniaBlossom,366),v.par(M68VegCorrStep3Start).value,v.par(M68VegCorrStep3End).value, this.getLog(v))) } } case object DFnoble extends Variable("Drought factor (Noble 1980)","DFnoble","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (lastRainSum::Nil) in += (DaysSinceRain::Nil) in += (KBDISI::Nil) /** * Calculate DF DataSerie * * @param lastRainSum last consecutive rainfall sum DataSerie * @param DaysSinceRain consecutive days wihtout rain DataSerie * @param KBDISI KBDISI index DataSerie * @param notes some notes on DataSerie creation * @return DataSerie */ // def calculate(lastRainSum:DataSerie,DaysSinceRain:DataSerie,KBDISI:DataSerie, log: DataLog, notes:String=""):DataSerie={ def calculate(lastRainSum:DataSerie,DaysSinceRain:DataSerie,KBDISI:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(lastRainSum.start,lastRainSum.interval,ListFunctions.applyFunction(Functions.DFnoble,lastRainSum.values,DaysSinceRain.values,KBDISI.values), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(lastRainSum),v.ds(DaysSinceRain),v.ds(KBDISI), this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(lastRainSum,1),v.ds(DaysSinceRain,1),v.ds(KBDISI,1), this.getLog(v))) } } case object DFgriffith extends Variable("Drought factor (Griffith 1999)","DFgriffith","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (lastRainSum_2_20::lastRainSum::Nil) // in += (P::Nil) in += (AgeRainEvent_2_20::DaysSinceRain::Nil) in += (KBDISI::Nil) /** * Calculate DF DataSerie * * @param lastRainSum sum of the last consecutive rain event (days above 2mm) in the past 20 days * @param ageRainEvent age of rain event [days] (Finkele 2006) * @param KBDISI KBDISI index DataSerie * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(lastRainSum:DataSerie,ageRainEvent:DataSerie,KBDISI:DataSerie, log: DataLog, notes:String=""):DataSerie={ // def calculate(P:DataSerie,DaysSinceRain:DataSerie,KBDISI:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(lastRainSum.start,lastRainSum.interval,ListFunctions.applyFunction(Functions.DFgriffith,lastRainSum.values,ageRainEvent.values,KBDISI.values), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(lastRainSum_2_20),v.ds(AgeRainEvent_2_20),v.ds(KBDISI), this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(lastRainSum_2_20),v.ds(AgeRainEvent_2_20),v.ds(KBDISI), this.getLog(v))) } } case object DFgriffithAdj extends Variable("Drought factor (Finkele et al.2006)","DFgriffithAdj","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (lastRainSum_2_20::lastRainSum::Nil) // in += (P::Nil) in += (AgeRainEvent_2_20::DaysSinceRain::Nil) in += (KBDISI::Nil) /** * Calculate DF DataSerie * * @param lastRainSum sum of the last consecutive rain event (days above 2mm) in the past 20 days * @param ageRainEvent age of rain event [days] (Finkele 2006) * @param KBDISI KBDISI index DataSerie * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(lastRainSum:DataSerie,ageRainEvent:DataSerie,KBDISI:DataSerie, log: DataLog, notes:String=""):DataSerie={ // def calculate(P:DataSerie,DaysSinceRain:DataSerie,KBDISI:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(lastRainSum.start,lastRainSum.interval,ListFunctions.applyFunction(Functions.DFgriffithAdj,lastRainSum.values,ageRainEvent.values,KBDISI.values), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(lastRainSum_2_20),v.ds(AgeRainEvent_2_20),v.ds(KBDISI), this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(lastRainSum_2_20,1),v.ds(AgeRainEvent_2_20,1),v.ds(KBDISI,1), this.getLog(v))) } } case object FFDI extends Variable("MacArthur5 index value","FFDI","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (DFgriffithAdj::DFgriffith::DFnoble::Nil) in += (T15::T13::T12::T::Nil) in += (H15::H13::H12::H::Nil) in += (U15::U13::U12::U::Nil) /** * Calculate FFDI index DataSerie, with Drought factor according to Griffith 1999 * * @param DF drougth factor DataSerie * @param Tmax maximal temperature DataSerie * @param H relative humidity DataSerie * @param U wind speed DataSerie * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(DF:DataSerie,T15:DataSerie,H15:DataSerie,U15:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(DF.start,DF.interval,ListFunctions.applyFunction(Functions.FFDI,DF.values,T15.values,H15.values,U15.values), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(DFgriffithAdj),v.ds(T15),v.ds(H15),v.ds(U15), this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(DFgriffithAdj,1),v.ds(T15,1),v.ds(H15,1),v.ds(U15,1), this.getLog(v))) } } case object FFMC extends Variable("Fine fuel moisture code","FFMC","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (T12::T13::T15::T::Nil) in += (H12::H13::H15::H::Nil) in += (U12::U13::U15::U::Nil) in += (P12::P13::P15::P::Nil) in += (SnowCover::Nil) in += FFMCstart::Nil /** * Calculate FFMC index DataSerie * * @param start to initialize index (generally 85) * @param prev previous value of FFMC index * @param P12 precipitations at noon DataSerie * @param T12 temperature at noon DataSerie * @param H12 relative humidity at noon DataSerie * @param U12 wind speed at noon DataSerie * @param snowcover DataSerie > snowcover DataSerie * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(start:Double=85.0,prev:Double,P12:DataSerie,T12:DataSerie,H12:DataSerie,U12:DataSerie,SnowCover:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(P12.start,P12.interval,ListFunctions.applyFunctionPrev_k(Functions.FFMC,prev,P12.values,T12.values,H12.values,U12.values,SnowCover.values.map(_.toInt),start), log, "start = "+prev+" "+notes) } /** * launch calculate on DataCollection with a previous val * * @param prev previous value of index * @param dss DataCollection > all DataSeries * @return DataSerie */ def calculate(prev:Double,dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.par(FFMCstart).value,prev,v.ds(P12),v.ds(T12),v.ds(H12),v.ds(U12),v.ds(SnowCover), this.getLog(v)) } def calculate(dss:DataCollection):DataSerie={ //calculate(dss.pars(FFMCstart).value, dss) calculate(Double.NaN,dss) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.par(FFMCstart).value, me.prev.asInstanceOf[Double], v.ds(P12,1),v.ds(T12,1),v.ds(H12,1),v.ds(U12,1),v.ds(SnowCover,1), this.getLog(v))) } } case object DMC extends Variable("Duff moisture code","DMC","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (T12::T13::T15::T::Nil) in += (H12::H13::H15::H::Nil) in += (P12::P13::P15::P::Nil) in += (SnowCover::Nil) in += DMCstart::Nil //in += Latitude::Nil #currently not used, since also DC should be adapted for daylight and no standard definition exists /** * Calculate DMC index DataSerie * * @param start to initialize index (generally 6) * @param prev previous value of DMC index * @param P12 precipitations at noon DataSerie * @param T12 temperature at noon DataSerie * @param U12 wind speed at noon DataSerie * @param snowcover DataSerie > snowcover DataSerie * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(start:Double=6,prev:Double,P12:DataSerie,T12:DataSerie,H12:DataSerie,SnowCover:DataSerie,latitude:Double=Double.NaN, log: DataLog, notes:String=""):DataSerie={ createDataSerie(P12.start,P12.interval,ListFunctions.applyFunctionPrev_kk(Functions.DMC,prev,P12.getDates,P12.values,T12.values,H12.values,SnowCover.values.map(_.toInt),latitude,start), log, "start = "+prev+" "+notes) } /** * launch calculate on DataCollection with a previous val * * @param prev previous value of index * @param dss DataCollection > all DataSeries * @return DataSerie */ def calculate(prev:Double,dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) //calculate(v.par(DMCstart).value,prev,v.ds(P12),v.ds(T12),v.ds(H12),v.ds(SnowCover), v.par(Latitude).value, this.getLog(v)) calculate(v.par(DMCstart).value,prev,v.ds(P12),v.ds(T12),v.ds(H12),v.ds(SnowCover), Double.NaN, this.getLog(v)) } def calculate(dss:DataCollection):DataSerie={ calculate(Double.NaN,dss) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) //calculate(v.par(DMCstart).value, me.prev.asInstanceOf[Double] ,v.ds(P12,1),v.ds(T12,1),v.ds(H12,1),v.ds(SnowCover,1), v.par(Latitude).value, this.getLog(v)) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.par(DMCstart).value, me.prev.asInstanceOf[Double] ,v.ds(P12,1),v.ds(T12,1),v.ds(H12,1),v.ds(SnowCover,1), Double.NaN, this.getLog(v))) } } case object DMC_lat extends Variable("Duff moisture code adapted for latitude","DMC_lat","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (T12::T13::T15::T::Nil) in += (H12::H13::H15::H::Nil) in += (P12::P13::P15::P::Nil) in += (SnowCover::Nil) in += DMCstart::Nil in += Latitude::Nil /** * Calculate DMC index DataSerie * * @param start to initialize index (generally 6) * @param prev previous value of DMC index * @param P12 precipitations at noon DataSerie * @param T12 temperature at noon DataSerie * @param U12 wind speed at noon DataSerie * @param snowcover DataSerie > snowcover DataSerie * @param latitude latitude of measurement location to calculate the daylight factor * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(start:Double=6,prev:Double,P12:DataSerie,T12:DataSerie,H12:DataSerie,SnowCover:DataSerie,latitude:Double=Double.NaN, log: DataLog, notes:String=""):DataSerie={ createDataSerie(P12.start,P12.interval,ListFunctions.applyFunctionPrev_kk(Functions.DMC,prev,P12.getDates,P12.values,T12.values,H12.values,SnowCover.values.map(_.toInt),latitude,start), log, "start = "+prev+" "+notes) } /** * launch calculate on DataCollection with a previous val * * @param prev previous value of index * @param dss DataCollection > all DataSeries * @return DataSerie */ def calculate(prev:Double,dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.par(DMCstart).value,prev,v.ds(P12),v.ds(T12),v.ds(H12),v.ds(SnowCover), v.par(Latitude).value, this.getLog(v)) } def calculate(dss:DataCollection):DataSerie={ calculate(Double.NaN,dss) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.par(DMCstart).value, me.prev.asInstanceOf[Double] ,v.ds(P12,1),v.ds(T12,1),v.ds(H12,1),v.ds(SnowCover,1), v.par(Latitude).value, this.getLog(v))) } } case object DC extends Variable("Drought code","DC","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (T12::T13::T15::T::Nil) in += (P12::P13::P15::P::Nil) in += (SnowCover::Nil) in += DCstart::Nil //in += Latitude::Nil #currently not used, since also DC should be adapted for daylight and no standard definition exists /** * Calculate DC index DataSerie * * @param start to initialize index (generally 15) * @param prev previous value of DC index * @param P12 precipitations at noon DataSerie * @param T12 temperature at noon DataSerie * @param snowcover DataSerie > snowcover DataSerie * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(start:Double=15,prev:Double,P12:DataSerie,T12:DataSerie,SnowCover:DataSerie,latitude:Double=Double.NaN, log: DataLog, notes:String=""):DataSerie={ createDataSerie(P12.start,P12.interval,ListFunctions.applyFunctionPrev_kk(Functions.DC,prev,P12.getDates,P12.values,T12.values,SnowCover.values.map(_.toInt),latitude,start), log, "start = "+prev+" "+notes) } /** * launch calculate on DataCollection with a previous val * * @param prev previous value of index * @param dss DataCollection > all DataSeries * @return DataSerie */ def calculate(prev:Double,dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.par(DCstart).value,prev,v.ds(P12),v.ds(T12),v.ds(SnowCover), Double.NaN, this.getLog(v)) } def calculate(dss:DataCollection):DataSerie={ calculate(Double.NaN,dss) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.par(DCstart).value, me.prev.asInstanceOf[Double] ,v.ds(P12,1),v.ds(T12,1),v.ds(SnowCover,1), Double.NaN, this.getLog(v))) } } case object DC_lat extends Variable("Drought code adapted for latitude","DC_lat","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (T12::T13::T15::T::Nil) in += (P12::P13::P15::P::Nil) in += (SnowCover::Nil) in += DCstart::Nil in += Latitude::Nil /** * Calculate DC index DataSerie * * @param start to initialize index (generally 15) * @param prev previous value of DC index * @param P12 precipitations at noon DataSerie * @param T12 temperature at noon DataSerie * @param snowcover DataSerie > snowcover DataSerie * @param latitude latitude of measurement location to calculate the daylight factor * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(start:Double=15,prev:Double,P12:DataSerie,T12:DataSerie,SnowCover:DataSerie,latitude:Double=Double.NaN, log: DataLog, notes:String=""):DataSerie={ createDataSerie(P12.start,P12.interval,ListFunctions.applyFunctionPrev_kk(Functions.DC,prev,P12.getDates,P12.values,T12.values,SnowCover.values.map(_.toInt),latitude,start), log, "start = "+prev+" "+notes) } /** * launch calculate on DataCollection with a previous val * * @param prev previous value of index * @param dss DataCollection > all DataSeries * @return DataSerie */ def calculate(prev:Double,dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.par(DCstart).value,prev,v.ds(P12),v.ds(T12),v.ds(SnowCover), v.par(Latitude).value, this.getLog(v)) } def calculate(dss:DataCollection):DataSerie={ calculate(Double.NaN,dss) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.par(DCstart).value, me.prev.asInstanceOf[Double] ,v.ds(P12,1),v.ds(T12,1),v.ds(SnowCover,1), v.par(Latitude).value, this.getLog(v))) } } case object ISI extends Variable("Initial spread index","ISI","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (FFMC::Nil) in += (U12::U13::U15::U::Nil) /** * Calculate ISI index DataSerie * * @param FFMC FFMC DataSerie * @param U12 wind speed at noon DataSerie * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(FFMC:DataSerie,U12:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(FFMC.start,FFMC.interval,ListFunctions.applyFunction(Functions.ISI,FFMC.values,U12.values), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(FFMC),v.ds(U12), this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(FFMC,1),v.ds(U12,1), this.getLog(v))) } } case object BUI extends Variable("Buildup index","BUI","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (DMC::Nil) in += (DC::Nil) /** * Calculate BUI index DataSerie * * @param DMC DMC DataSerie * @param DC DC DataSerie * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(DMC:DataSerie,DC:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(DMC.start,DMC.interval,ListFunctions.applyFunction(Functions.BUI,DMC.values,DC.values), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(DMC),v.ds(DC), this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(DMC,1),v.ds(DC,1), this.getLog(v))) } } case object BUI_lat extends Variable("Buildup index adapted for latitude","BUI_lat","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (DMC_lat::Nil) in += (DC_lat::Nil) /** * Calculate BUI index DataSerie * * @param DMC_lat DMC_lat DataSerie * @param DC_lat DC_lat DataSerie * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(DMC_lat:DataSerie,DC_lat:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(DMC_lat.start,DMC_lat.interval,ListFunctions.applyFunction(Functions.BUI,DMC_lat.values,DC_lat.values), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(DMC_lat),v.ds(DC_lat), this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(DMC_lat,1),v.ds(DC_lat,1), this.getLog(v))) } } case object FWI extends Variable("Fire weather index","FWI","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (BUI::Nil) in += (ISI::Nil) /** * Calculate FWI index DataSerie * * @param BUI BUI DataSerie * @param ISI ISI DataSerie * @param U12 wind speed at noon DataSerie * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(BUI:DataSerie,ISI:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(BUI.start,BUI.interval,ListFunctions.applyFunction(Functions.FWI,BUI.values,ISI.values), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(BUI),v.ds(ISI), this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(BUI,1),v.ds(ISI,1), this.getLog(v))) } } case object FWI_lat extends Variable("Fire weather index adapted for latitude","FWI_lat","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (BUI_lat::Nil) in += (ISI::Nil) /** * Calculate FWI index DataSerie * * @param BUI BUI DataSerie * @param ISI ISI DataSerie * @param U12 wind speed at noon DataSerie * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(BUI_lat:DataSerie,ISI:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(BUI_lat.start,BUI_lat.interval,ListFunctions.applyFunction(Functions.FWI,BUI_lat.values,ISI.values), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(BUI_lat),v.ds(ISI), this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(BUI_lat,1),v.ds(ISI,1), this.getLog(v))) } } case object Baumgartner extends Variable("Baumgartner index","Baumgartner","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (P::P12::P13::P15::Nil) in += (PETpen::Nil) /** * Calculate Baumgartner index DataSerie * * @param PETpen PETpen DataSerie * @param P precipitations DataSerie * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(PETpen:DataSerie,P:DataSerie, log: DataLog, notes:String=""):DataSerie={ val FivePrecDaysPETpen = ListFunctions.runningSumPos(5,5,PETpen.values) val FivePrecDaysRain = ListFunctions.runningSumPos(5,5,P.values) createDataSerie(PETpen.start,PETpen.interval,ListFunctions.applyFunction(Functions.Baumgartner,FivePrecDaysPETpen,FivePrecDaysRain), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(PETpen),v.ds(P), this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(PETpen,7),v.ds(P,7), this.getLog(v))) } } case object BaumgartnerDanger extends Variable("Baumgartner Danger classes","BaumgartnerDanger","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (Baumgartner::Nil) /** * Calculate Baumgartner Danger classes DataSerie * * @param Baumgartner Baumgartner Index * @param notes some notes on DataSerie creation * @return DataSerie */ def calculate(Baumgartner:DataSerie, log: DataLog, notes:String=""):DataSerie={ val months = Baumgartner.getDates.map(Utils.solarDate2String(_,"MM").toInt) createDataSerie(Baumgartner.start,Baumgartner.interval,ListFunctions.applyFunction(Functions.BaumgartnerDanger,Baumgartner.values,months), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(Baumgartner), this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(Baumgartner,1), this.getLog(v))) } } case object RN extends Variable("Numerical risk index","RN","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (T::Nil) in += (Tdew::Nil) in += (U::Nil) in += (Cc::Nil) in += (res::Nil) /** * Calculate Numerical risk index DataSerie * * @param T air temperature DataSerie * @param Tdew dewpoint temperature DataSerie * @param U wind [m/s] DataSerie * @param Cc cloud cover [fraction] DataSerie * @param r soil water reserve [mm] DataSerie * @return numerical risk index DataSerie */ def calculate(T:DataSerie,Tdew:DataSerie,U:DataSerie,Cc:DataSerie,r:DataSerie, log: DataLog, notes:String=""):DataSerie={ createDataSerie(T.start,T.interval,ListFunctions.applyFunction(Functions.RN,T.values,Tdew.values,U.values,Cc.values,r.values,T.getDates), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(T),v.ds(Tdew),v.ds(U),v.ds(Cc),v.ds(res), this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(T,1),v.ds(Tdew,1),v.ds(U,1),v.ds(Cc,1),v.ds(res,1), this.getLog(v))) } } case object Ifa extends Variable("Ifa index (Portuguese Index)","Ifa","--",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (T12::T13::T15::T::Tmax::Nil) in += (Tdew12::Tdew::Tdew15::Nil) in += (P12::P::P13::P15::Nil) in += (U12::U::U13::U15::Nil) //according to MEGAFires project U12 first in += (FireSeasonStart::Nil) in += (FireSeasonEnd::Nil) /** * Calculate Ifa index DataSerie * * @param T12 air temperature at noon DataSerie * @param Tdew12 dewpoint temperature at noon DataSerie * @param P12 rainfall [mm] DataSerie (cut at noon) * @param U12 windspeed [m/s] DataSerie at noon * @param FireSeasonStart start of fire season [msec] * @param FireSeasonEnd end of fire season [msec] * @return Ifa index DataSerie */ def calculate(T12:DataSerie,Tdew12:DataSerie,P12:DataSerie,U12:DataSerie,FireSeasonStart:Long,FireSeasonEnd:Long, log: DataLog, notes:String=""):DataSerie={ createDataSerie(T12.start,T12.interval, Functions.Ifa(T12.getDates,ListFunctions.applyFunction( Functions.IG,T12.values,Tdew12.values),P12.values,U12.values,FireSeasonStart,FireSeasonEnd), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(T12),v.ds(Tdew12),v.ds(P12),v.ds(U12),v.par(FireSeasonStart).value,v.par(FireSeasonEnd).value, this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(T12,366),v.ds(Tdew12,366),v.ds(P12,366),v.ds(U12,366),v.par(FireSeasonStart).value,v.par(FireSeasonEnd).value, this.getLog(v))) } } case object Risico_dffm extends Variable("dead fuel humidity","Risico_dffm","mass-%",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (T::Nil) in += (H::Nil) in += (U::Nil) in += (P::Nil) in += (Risico_sat::Nil) in += (Risico_T0::Nil) // in += (Risico_dT::Nil) /** * Calculate Risico_WindEffect DataSerie * * @param T12 air temperature at noon DataSerie * @return Ifa index DataSerie */ def calculate(prev:Double,T:DataSerie,H:DataSerie,U:DataSerie,P:DataSerie,Risico_sat:Double, Risico_T0:Double, /*Risico_dT:Double,*/ RainThreshold:Double=0.0, log: DataLog, notes:String=""):DataSerie={ createDataSerie(T.start,T.interval,ListFunctions.applyFunctionPrev_kkkk(Functions.Dffm, prev, T.values,H.values,U.values,P.values, Risico_sat,Risico_T0, T.interval / 1000.0 / 60.0 / 60.0, // T.interval / Variable.msecInOneHour.toDouble, RainThreshold), log, notes) } def calculate(prev:Double, dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(prev, v.ds(T),v.ds(H),v.ds(U),v.ds(P),v.par(Risico_sat).value,v.par(Risico_T0).value, /*v.par(Risico_dT).value,*/ 0.0, this.getLog(v)) } def calculate(dss:DataCollection):DataSerie={ calculate(Double.NaN,dss) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(me.prev,v.ds(T,1),v.ds(H,1),v.ds(U,1),v.ds(P,1),v.par(Risico_sat).value,v.par(Risico_T0).value, /*v.par(Risico_dT).value,*/ 0.0, this.getLog(v))) } } case object Risico_WindEffect extends Variable("wind effect on fire propagation speed","Risico_WindEffect","-",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (U::Nil) in += (D::Nil) in += (Slope::Nil) in += (Aspect::Nil) /** * Calculate Risico_WindEffect DataSerie * * @param T12 air temperature at noon DataSerie * @return Ifa index DataSerie */ def calculate(U:DataSerie,D:DataSerie,Slope:Double, Aspect:Double, log: DataLog, notes:String=""):DataSerie={ createDataSerie(U.start,U.interval,ListFunctions.applyFunction_kk(Functions.WindEffect, U.values,D.values, Slope, Aspect), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(U),v.ds(D),v.par(Slope).value,v.par(Aspect).value, this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(U,1),v.ds(D,1),v.par(Slope).value,v.par(Aspect).value, this.getLog(v))) } } case object Risico_V extends Variable("fire propagation speed","Risico_V","m/h",-100000,100000, classOf[Double]) with Serie with Calculable{ in += (Risico_dffm::Nil) in += (Risico_WindEffect::Nil) in += (SnowCover::Nil) in += (Risico_v0::Nil) in += (Risico_d0::Nil) in += (Risico_d1::Nil) in += (Slope::Nil) /** * Calculate Ifa index DataSerie * * @param T12 air temperature at noon DataSerie * @param Tdew12 dewpoint temperature at noon DataSerie * @param P rainfall [mm] DataSerie * @param U windspeed [m/s] DataSerie * @param FireSeasonStart start of fire season [msec] * @param FireSeasonEnd end of fire season [msec] * @return Ifa index DataSerie */ def calculate(Risico_dffm:DataSerie,Risico_WindEffect:DataSerie,SnowCover:DataSerie,Risico_v0:Double,Risico_d0:Double, Risico_d1:Double, Slope:Double, log: DataLog, notes:String=""):DataSerie={ createDataSerie(Risico_dffm.start,Risico_dffm.interval,ListFunctions.applyFunction_kkkk(Functions.V, Risico_dffm.values,Risico_WindEffect.values,SnowCover.values, Risico_v0,Risico_d0,Risico_d1,Slope), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(Risico_dffm),v.ds(Risico_WindEffect),v.ds(SnowCover),v.par(Risico_v0).value,v.par(Risico_d0).value, v.par(Risico_d1).value, v.par(Slope).value, this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(Risico_dffm,1),v.ds(Risico_WindEffect,1),v.ds(SnowCover,1),v.par(Risico_v0).value,v.par(Risico_d0).value, v.par(Risico_d1).value, v.par(Slope).value, this.getLog(v))) } } case object Risico_FI extends Variable("fireline intensity","Risico_FI","kW/m",0,10000, classOf[Double]) with Serie with Calculable{ in += (Risico_dffm::Nil) in += (Risico_V::Nil) in += (Risico_d0::Nil) in += (Risico_d1::Nil) in += (Risico_hhv::Nil) in += (Risico_humidity::Nil) /** * Calculate Ifa index DataSerie * * @param T12 air temperature at noon DataSerie * @param Tdew12 dewpoint temperature at noon DataSerie * @param P rainfall [mm] DataSerie * @param U windspeed [m/s] DataSerie * @param FireSeasonStart start of fire season [msec] * @param FireSeasonEnd end of fire season [msec] * @return Ifa index DataSerie */ def calculate(Risico_dffm:DataSerie,Risico_V:DataSerie,Risico_d0:Double, Risico_d1:Double, Risico_hhv:Double, Risico_humidity:Double, log: DataLog, notes:String=""):DataSerie={ createDataSerie(Risico_dffm.start,Risico_dffm.interval,ListFunctions.applyFunction_kkkk(Functions.FI, Risico_dffm.values,Risico_V.values, Risico_d0,Risico_d1,Risico_hhv,Risico_humidity), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(Risico_dffm),v.ds(Risico_V),v.par(Risico_d0).value,v.par(Risico_d1).value,v.par(Risico_hhv).value,v.par(Risico_humidity).value, this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(Risico_dffm,1),v.ds(Risico_V,1),v.par(Risico_d0).value,v.par(Risico_d1).value,v.par(Risico_hhv).value,v.par(Risico_humidity).value, this.getLog(v))) } } case object IREPI extends Variable("IREPI","IREPI","--",0,10000, classOf[Double]) with Serie with Calculable{ in += (P::Nil) in += (PETpen::Nil) in += RainyWeekThreshold::Nil in += WeekRain::Nil /** * Calculate Ifa index DataSerie * * @param T12 air temperature at noon DataSerie * @param Tdew12 dewpoint temperature at noon DataSerie * @param P rainfall [mm] DataSerie * @param U windspeed [m/s] DataSerie * @param FireSeasonStart start of fire season [msec] * @param FireSeasonEnd end of fire season [msec] * @return Ifa index DataSerie */ def calculate(P:DataSerie,PETpen:DataSerie, PweekThreshold:Double,WeekRain:DataSerie, log: DataLog, notes:String=""):DataSerie={ import ListFunctions.IREPIconst._ createDataSerie(P.start, P.interval, ListFunctions.IREPI(P.values, PETpen.values, soilWaterAtSaturation, PweekThreshold, WeekRain.values), log, notes) } def calculate(dss:DataCollection):DataSerie={ val v=chooseVariablesAndCalculate(dss) calculate(v.ds(P),v.ds(PETpen), v.par(RainyWeekThreshold).value, v.ds(WeekRain), this.getLog(v)) } def complete(dss:DataCollection):DataSerie={ val v=chooseVariablesAndComplete(dss) val me=dss.dss(this) me.updateLastAndNotes(calculate(v.ds(P),v.ds(PETpen), v.par(RainyWeekThreshold).value, v.ds(WeekRain), this.getLog(v))) //by omitting the number of rows will recalculate all } }
gpl-2.0
espertechinc/nesper
src/NEsper.Compat/compat/collections/ListExtensions.cs
2720
/////////////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2006-2019 Esper Team. All rights reserved. / // http://esper.codehaus.org / // ---------------------------------------------------------------------------------- / // The software in this package is published under the terms of the GPL license / // a copy of which has been included with this distribution in the license.txt file. / /////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using com.espertech.esper.compat.magic; namespace com.espertech.esper.compat.collections { public static class ListExtensions { public static IList<object> AsObjectList(this object value, MagicMarker magicMarker) { if (value == null) { return null; } else if (value is IList<object> asList) { return asList; } else if (value.GetType().IsGenericList()) { return magicMarker .GetListFactory(value.GetType()) .Invoke(value); } throw new ArgumentException("invalid value for object list"); } public static bool AreEqual<T>(IList<T> listThis, IList<T> listThat) { var listThisCount = listThis.Count; var listThatCount = listThat.Count; if (listThisCount != listThatCount) { return false; } for (var ii = 0; ii < listThisCount; ii++) { if (!Equals(listThis[ii], listThat[ii])) { return false; } } return true; } public static IList<T> CopyList<T>(IList<T> sourceList) { return new List<T>(sourceList); } public static object TryCopy(object sourceList) { if (sourceList == null) { return null; } var sourceListType = sourceList.GetType(); if (sourceListType.IsGenericList()) { var valType = sourceListType.GetListType(); var method = typeof(ListExtensions).GetMethod("CopyList")?.MakeGenericMethod(valType); return method.Invoke(null, new[] { sourceList }); } throw new ArgumentException("argument is not a dictionary", nameof(sourceList)); } } }
gpl-2.0
davidbjanes/NovintFalconExampleCode
chai3d-2.0.0/external/VirtualDevice/src/sai/CShape.cpp
3270
//=========================================================================== // - UNIT - // // Copyright (C) 2002. Stanford University - Robotics Laboratory /*! \author conti@robotics.stanford.edu \file CShape.cpp \version 1.0 \date 01/2002 */ //=========================================================================== //--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "CShape.h" #pragma package(smart_init) //--------------------------------------------------------------------------- #include "gl/gl.h" #include "gl/glu.h" #include "XMatrix.h" //--------------------------------------------------------------------------- //=========================================================================== // - PUBLIC METHOD - /*! Constructor of cShape. \fn cShape::cShape() \return Return a pointer to new shape instance. */ //=========================================================================== cShape::cShape() { // INITIALIZE POSITION AND ORIENTATION: pos = xSet(0.0, 0.0, 0.0); rot = xIdentity33d(); // INITIALIZE COLOR (GRAY): color = xSetColor4f(0.8, 0.8, 0.8); // Set red-green-blue components. // INITIALIZE SPRING CONSTANT: kSpring = 100; // units: [netwons per meter] } //=========================================================================== // - PUBLIC METHOD - /*! Constructor of cShapePlan. \fn cShapePlan::cShapePlan() \return Return a pointer to new shape plan instance. */ //=========================================================================== cShapePlan::cShapePlan() { // SETUP SPRING CONSTANT: kSpring = 500; // [N/m] } //=========================================================================== // - PUBLIC METHOD - /*! Compute forces when finger interacts with plan. \fn xVector3d cShapePlan::computeForce(xVector3d iFingerPos) \return Return computed force. */ //=========================================================================== xVector3d cShapePlan::computeForce(xVector3d iFingerPos) { } //=========================================================================== // - PUBLIC METHOD - /*! Render shape in OpenGl. \fn void cShapePlan::render() */ //=========================================================================== void cShapePlan::render() { // SET POSITION AND ORIENTATION OF SHAPE: xGLPushMatrixPos(pos); xGLPushMatrixRot(rot); // SET COLOR PROPERTIES: glEnable(GL_COLOR_MATERIAL); glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); glColor4fv( (const float *)&color); // DRAW PLAN: float width = 0.6; glBegin(GL_POLYGON); glNormal3d(0.0, 0.0, 1.0); glVertex3d(-width/2, -width/2, 0.0); glVertex3d( width/2, -width/2, 0.0); glVertex3d( width/2, width/2, 0.0); glVertex3d(-width/2, width/2, 0.0); glEnd(); // POP OPENGL MATRIX xGLPopMatrix(); // pop rotation. xGLPopMatrix(); // pop position. } //=========================================================================== // END OF FILE //===========================================================================
gpl-2.0
teeple/pns_server
work/node_modules/node-cubrid/src/packets/FetchPacket.js
2622
var DATA_TYPES = require('../constants/DataTypes'), Helpers = require('../utils/Helpers'), ErrorMessages = require('../constants/ErrorMessages'), CAS = require('../constants/CASConstants'); module.exports = FetchPacket; /** * Constructor * @param options * @constructor */ function FetchPacket(options) { options = options || {}; this.casInfo = options.casInfo; this.dbVersion = options.dbVersion; this.responseCode = 0; this.errorCode = 0; this.errorMsg = ''; this.resultSet = ''; // ResultSet of the fetch } /** * Write data * @param writer * @param queryPacket */ FetchPacket.prototype.write = function (writer, queryPacket) { writer._writeInt(this.getBufferLength() - DATA_TYPES.DATA_LENGTH_SIZEOF - DATA_TYPES.CAS_INFO_SIZE); writer._writeBytes(DATA_TYPES.CAS_INFO_SIZE, this.casInfo); writer._writeByte(CAS.CASFunctionCode.CAS_FC_FETCH); writer._writeInt(DATA_TYPES.INT_SIZEOF); writer._writeInt(queryPacket.queryHandle); // Query handle writer._writeInt(DATA_TYPES.INT_SIZEOF); writer._writeInt(queryPacket.currentTupleCount + 1); // Start position (= current cursor position + 1) writer._writeInt(DATA_TYPES.INT_SIZEOF); writer._writeInt(100); // Fetch size; 0 = default; recommended = 100 writer._writeInt(DATA_TYPES.BYTE_SIZEOF); writer._writeByte(0); // Is case sensitive writer._writeInt(DATA_TYPES.INT_SIZEOF); writer._writeInt(0); // Is the ResultSet index...? return writer; }; /** * Read data * @param parser * @param queryPacket */ FetchPacket.prototype.parse = function (parser, queryPacket) { var responseLength = parser._parseInt(); this.casInfo = parser._parseBytes(DATA_TYPES.CAS_INFO_SIZE); this.responseCode = parser._parseInt(); if (this.responseCode !== 0) { this.errorCode = parser._parseInt(); this.errorMsg = parser._parseNullTerminatedString(responseLength - 2 * DATA_TYPES.INT_SIZEOF); if (this.errorMsg.length === 0) { this.errorMsg = Helpers._resolveErrorCode(this.errorCode); } } else { this.tupleCount = parser._parseInt(); this.resultSet = JSON.stringify({ColumnValues : queryPacket._getData(parser, this.tupleCount)}); } return this; }; FetchPacket.prototype.getBufferLength = function () { var bufferLength = DATA_TYPES.DATA_LENGTH_SIZEOF + DATA_TYPES.CAS_INFO_SIZE + DATA_TYPES.BYTE_SIZEOF + DATA_TYPES.INT_SIZEOF + DATA_TYPES.INT_SIZEOF + DATA_TYPES.INT_SIZEOF + DATA_TYPES.INT_SIZEOF + DATA_TYPES.INT_SIZEOF + DATA_TYPES.INT_SIZEOF + DATA_TYPES.INT_SIZEOF + DATA_TYPES.BYTE_SIZEOF + DATA_TYPES.INT_SIZEOF + DATA_TYPES.INT_SIZEOF; return bufferLength; };
gpl-2.0
Streamstormer/PanicSim
src/Simulator/Area.cpp
9209
#include "../../include/Simulator/Area.hpp" ClArea::ClArea() { id = 0; time =0; fire_texture.loadFromFile("pictures/fire.png"); } ClArea::~ClArea() { for(unsigned int n=0; n < sobjects.size(); n++) { delete sobjects[n]; } } void ClArea::viewOnStaticObject() { for (int n=0; n<sobjects.size();n++) { if(sobjects[n]->getIsOnFire()== true && sobjects[n]->getIsChecked() == false) // looks for obejcts wich are on fire an not yet checked { for (int m=0; m< sobjects.size(); m++) { if (sobjects[m]->IntersectsRectangle(sobjects[n]->biggerRect())== true&& sobjects[m]->getType() != GATE && sobjects[m]->getType() != FENCE) { sobjects[m]->startToBurn(); } } sobjects[n]->setIsChecked(true); } } for (int n=0; n<sobjects.size();n++) { sobjects[n]->setfirstTime(false); } } float ClArea::addFrameTime(float frameTime) { time = time+frameTime; return time; } void ClArea::update(float frameTime) { if (addFrameTime(frameTime)> 10000 ) { viewOnStaticObject(); time =0; // to reset the counter } } int ClArea::insertStObj(enum staticObjects type, const sf::Vector2f & sizeOfRectangle, const sf::Vector2f & positionOfRectangle, float rotAngle) { id++; sf::RectangleShape *tempRe = new sf::RectangleShape(); tempRe->setPosition(positionOfRectangle); tempRe->setSize(sizeOfRectangle); tempRe->setRotation(rotAngle); if(type == GATE) tempRe->setFillColor(sf::Color::Red); ClStaticObject *tempSt = new ClStaticObject(tempRe, id, type,fire_texture); sobjects.push_back(tempSt); return id; } void ClArea::draw(sf::RenderWindow& window) { for(unsigned int n=0; n < sobjects.size(); n++) { if(sobjects[n] != 0) sobjects[n]->draw(window); } } bool ClArea::validPoint(sf::Vector2f point) { for( unsigned int n=0; n < sobjects.size(); n++) { if(sobjects[n]->getType() != GATE &&sobjects[n]->getType() != FENCE && sobjects[n]->Intersects(point)) { return false; } } return true; } bool ClArea::validPath(sf::Vector2f startPoint, sf::Vector2f endPoint) { for( unsigned int n=0; n < sobjects.size(); n++) { if(sobjects[n]->isValidPath(startPoint, endPoint)) { return false; } } return true; } //changed by Patrick (addaption for Pathfinding, to allow to walk over a Fence in Panik-mode) bool ClArea::isInvalidNode(sf::Vector2f node, int nodeDistance) // ensure that there are no nodes close to staticObjects { for(unsigned int n = 0; n < sobjects.size(); n++) { sf::Rect<float> testRect; testRect.top = node.y - nodeDistance/2; testRect.height = nodeDistance; testRect.left = node.x - nodeDistance/2; testRect.width = nodeDistance; if(sobjects[n]->IntersectsRectangle(testRect) && sobjects[n]->getType() != FENCE) return true; } return false; } bool ClArea::isValidId(int id) { if(this->getObject(id) == NULL) return false; return true; } bool ClArea::getOnFire(int id) { return getObject(id)->getOnFire(); } void ClArea::setOnFire(int id) { time=0; for(unsigned int n = 0; n < sobjects.size(); n++) { if (sobjects[n]->getID() == id) { sobjects[n]->startToBurn(); } } } /// Get Methods for static Object attributes via the id /// for the editor const sf::Vector2f & ClArea::getPosition(int id) { for (unsigned int n = 0; n < sobjects.size();n++) { if (sobjects[n]->getID() == id) { return sobjects[n]->getPosition(); } } } ClStaticObject * ClArea::getObject(int id) { for (unsigned int n = 0; n < sobjects.size();n++) { if (sobjects[n]->getID() == id) { return sobjects[n]; } } return NULL; } bool ClArea::attractionWithHigherId(int lId) { if(getType(lId) <= 2) { return true; } else { if(lId < id) { return this->attractionWithHigherId(lId + 1); } else { return false; } } } const sf::Vector2f ClArea::getClosestExit(const sf::Vector2f & myPosition) { //std::cerr << "Call of closestExit Y: " << myPosition.x << ", Y: " << myPosition.y << " \n"; float distance = INFINITY; sf::Vector2f closestExitPosition; ClStaticObject *closestExit; for(unsigned int n = 0; n < sobjects.size(); n++) { if (sobjects[n]->getType() == GATE) { sf::Vector2f position = sobjects[n]->getCenter(); float testDistance = (myPosition.x - position.x)*(myPosition.x - position.x)+(myPosition.y - position.y)*(myPosition.y - position.y); testDistance = sqrt(testDistance); if (testDistance<distance) { closestExitPosition = position; distance = testDistance; closestExit = sobjects[n]; } } } // std::cerr << "Exit middle: " << closestExitPosition.x << ", " << closestExitPosition.y << "\n"; int numOfExitPoints = closestExit->getSize().x / (EXIT_POINT_DISTANCE + 1); //Big exit with at minimum two exit points: choose nearest if(numOfExitPoints > 1) { ClExitPointSelection myExitSel; return myExitSel.getClosestExitPoint(closestExit, myPosition, numOfExitPoints); } else { //Small exit with just one exit point, so no further checks are necessary return closestExitPosition; } } const sf::Vector2f & ClArea::getSize(int id) { for (unsigned int n = 0; n < sobjects.size();n++) { if (sobjects[n]->getID() == id) { return sobjects[n]->getSize(); } } } float ClArea::getRotation(int id) { for (unsigned int n = 0; n < sobjects.size();n++) { if (sobjects[n]->getID() == id) { return sobjects[n]->getRotation(); } } return -1; } enum staticObjects ClArea::getType(int id) { for (unsigned int n = 0; n < sobjects.size();n++) { if (sobjects[n]->getID() == id) { return sobjects[n]->getType(); } } } int ClArea::getIdByVector(sf::Vector2f mouse) { for( unsigned int n=0; n < sobjects.size(); n++) { if(sobjects[n]->Intersects(mouse)) { return sobjects[n]->getID(); } } return -1; } /// not for the editor const sf::Vector2f & ClArea::getSource(int id) { for (unsigned int n = 0; n < sobjects.size();n++) { if (sobjects[n]->getID() == id) { return sobjects[n]->getCenter(); } } } /// Set Methods for StaticObjects attributes via id and new value /// for the editor void ClArea::setPosition(int id, const sf::Vector2f &position) // sets position of StaticObject via id { for (unsigned int n = 0; n < sobjects.size();n++) { if (sobjects[n]->getID() == id) { sobjects[n]->setPosition(position); } } } void ClArea::setSize(int id, const sf::Vector2f &newSize) // sets size of StaticObject via id { for (unsigned int n = 0; n < sobjects.size();n++) { if (sobjects[n]->getID() == id) { sobjects[n]->setSize(newSize); } } } void ClArea::setRotation(int id, float rotation) // sets rotation of StaticObject via id { for (unsigned int n = 0; n < sobjects.size();n++) { if (sobjects[n]->getID() == id) { sobjects[n]->setRotation(rotation); } } } /// Remove static Object bool ClArea::removeObj(int id) { for (unsigned int n = 0; n < sobjects.size();n++) { if (sobjects[n]->getID() == id){ delete sobjects[n]; sobjects.erase(sobjects.begin()+n); return true; } } return false; }
gpl-2.0
digineo/xt-commerce
admin/validcategories.php
2517
<?php /* ----------------------------------------------------------------------------------------- $Id: validcategories.php 4 2006-11-28 14:38:03Z mzanier $ XT-Commerce - community made shopping http://www.xt-commerce.com Copyright (c) 2003 XT-Commerce ----------------------------------------------------------------------------------------- based on: (c) 2000-2001 The Exchange Project (earlier name of osCommerce) (c) 2002-2003 osCommerce (validcategories.php,v 0.01 2002/08/17); www.oscommerce.com Released under the GNU General Public License ----------------------------------------------------------------------------------------- Third Party contribution: Credit Class/Gift Vouchers/Discount Coupons (Version 5.10) http://www.oscommerce.com/community/contributions,282 Copyright (c) Strider | Strider@oscworks.com Copyright (c Nick Stanko of UkiDev.com, nick@ukidev.com Copyright (c) Andre ambidex@gmx.net Copyright (c) 2001,2002 Ian C Wilson http://www.phesis.org Released under the GNU General Public License ---------------------------------------------------------------------------------------*/ require('includes/application_top.php'); ?> <html> <head> <title>Valid Categories/Products List</title> <link rel="stylesheet" type="text/css" href="includes/stylesheet.css"> <head> <body> <table width="550" cellspacing="1"> <tr> <td class="pageHeading" colspan="3"> <?php echo TEXT_VALID_CATEGORIES_LIST; ?> </td> </tr> <?php echo "<tr><th class=\"dataTableHeadingContent\">" . TEXT_VALID_CATEGORIES_ID . "</th><th class=\"dataTableHeadingContent\">" . TEXT_VALID_CATEGORIES_NAME . "</th></tr><tr>"; $result = xtc_db_query("SELECT * FROM ".TABLE_CATEGORIES." c, ".TABLE_CATEGORIES_DESCRIPTION." cd WHERE c.categories_id = cd.categories_id and cd.language_id = '" . $_SESSION['languages_id'] . "' ORDER BY c.categories_id"); if ($row = xtc_db_fetch_array($result)) { do { echo "<td class=\"dataTableHeadingContent\">".$row["categories_id"]."</td>\n"; echo "<td class=\"dataTableHeadingContent\">".$row["categories_name"]."</td>\n"; echo "</tr>\n"; } while($row = xtc_db_fetch_array($result)); } echo "</table>\n"; ?> <br> <table width="550" border="0" cellspacing="1"> <tr> <td align=middle><input type="button" value="Close Window" onClick="window.close()"></td> </tr></table> </body> </html>
gpl-2.0
mupi/readinweb
course-tool/src/webapp/content/js/dropdown-menu.js
573
$(document).ready(function(){ // Collapse accordion every time dropdown is shown $('#lista_menu_modulos').on('show.bs.dropdown', function (event) { $(this).find('.panel-collapse.in').collapse('hide'); }); // Prevent dropdown to be closed when we click on an accordion link $('#lista_menu_modulos').on('click', 'a[data-toggle="collapse"]', function (event) { event.preventDefault(); event.stopPropagation(); $($(this).data('parent')).find('.panel-collapse.in').collapse('hide'); $($(this).attr('href').substring(1)).collapse('show'); }); });
gpl-2.0
joelbrock/HARVEST_CORE
fannie/src/fpdf/font/Scala-Italic.php
3423
<?php $type='Type1'; $name='Scala-Italic'; $desc=array('Ascent'=>745,'Descent'=>-255,'CapHeight'=>700,'Flags'=>32,'FontBBox'=>'[-174 -256 1200 843]','ItalicAngle'=>0,'StemV'=>77); $up=-166; $ut=37; $cw=array( chr(0)=>600,chr(1)=>600,chr(2)=>600,chr(3)=>600,chr(4)=>600,chr(5)=>600,chr(6)=>600,chr(7)=>600,chr(8)=>600,chr(9)=>600,chr(10)=>600,chr(11)=>600,chr(12)=>600,chr(13)=>600,chr(14)=>600,chr(15)=>600,chr(16)=>600,chr(17)=>600,chr(18)=>600,chr(19)=>600,chr(20)=>600,chr(21)=>600, chr(22)=>600,chr(23)=>600,chr(24)=>600,chr(25)=>600,chr(26)=>600,chr(27)=>600,chr(28)=>600,chr(29)=>600,chr(30)=>600,chr(31)=>600,' '=>250,'!'=>282,'"'=>409,'#'=>650,'$'=>543,'%'=>850,'&'=>589,'\''=>250,'('=>409,')'=>409,'*'=>500,'+'=>550, ','=>250,'-'=>275,'.'=>250,'/'=>409,'0'=>528,'1'=>365,'2'=>429,'3'=>403,'4'=>473,'5'=>417,'6'=>551,'7'=>489,'8'=>510,'9'=>551,':'=>250,';'=>250,'<'=>550,'='=>550,'>'=>550,'?'=>479,'@'=>1000,'A'=>671, 'B'=>635,'C'=>667,'D'=>740,'E'=>581,'F'=>571,'G'=>745,'H'=>835,'I'=>388,'J'=>382,'K'=>653,'L'=>531,'M'=>901,'N'=>737,'O'=>752,'P'=>600,'Q'=>752,'R'=>654,'S'=>562,'T'=>600,'U'=>780,'V'=>661,'W'=>942, 'X'=>623,'Y'=>612,'Z'=>668,'['=>250,'\\'=>409,']'=>250,'^'=>522,'_'=>500,'`'=>258,'a'=>500,'b'=>466,'c'=>377,'d'=>488,'e'=>380,'f'=>256,'g'=>419,'h'=>520,'i'=>281,'j'=>245,'k'=>461,'l'=>243,'m'=>796, 'n'=>540,'o'=>446,'p'=>484,'q'=>451,'r'=>353,'s'=>328,'t'=>292,'u'=>545,'v'=>420,'w'=>652,'x'=>514,'y'=>425,'z'=>488,'{'=>409,'|'=>250,'}'=>409,'~'=>522,chr(127)=>600,chr(128)=>492,chr(129)=>600,chr(130)=>250,chr(131)=>576, chr(132)=>409,chr(133)=>750,chr(134)=>573,chr(135)=>573,chr(136)=>338,chr(137)=>1234,chr(138)=>562,chr(139)=>333,chr(140)=>926,chr(141)=>600,chr(142)=>668,chr(143)=>600,chr(144)=>600,chr(145)=>250,chr(146)=>250,chr(147)=>409,chr(148)=>409,chr(149)=>352,chr(150)=>500,chr(151)=>1000,chr(152)=>454,chr(153)=>1000, chr(154)=>328,chr(155)=>333,chr(156)=>666,chr(157)=>600,chr(158)=>488,chr(159)=>612,chr(160)=>250,chr(161)=>282,chr(162)=>443,chr(163)=>576,chr(164)=>400,chr(165)=>615,chr(166)=>200,chr(167)=>345,chr(168)=>406,chr(169)=>1000,chr(170)=>350,chr(171)=>500,chr(172)=>550,chr(173)=>275,chr(174)=>1000,chr(175)=>406, chr(176)=>333,chr(177)=>550,chr(178)=>300,chr(179)=>282,chr(180)=>333,chr(181)=>545,chr(182)=>644,chr(183)=>333,chr(184)=>417,chr(185)=>255,chr(186)=>350,chr(187)=>500,chr(188)=>769,chr(189)=>769,chr(190)=>769,chr(191)=>479,chr(192)=>672,chr(193)=>672,chr(194)=>672,chr(195)=>672,chr(196)=>672,chr(197)=>672, chr(198)=>871,chr(199)=>667,chr(200)=>581,chr(201)=>581,chr(202)=>581,chr(203)=>581,chr(204)=>372,chr(205)=>372,chr(206)=>372,chr(207)=>372,chr(208)=>740,chr(209)=>737,chr(210)=>752,chr(211)=>752,chr(212)=>752,chr(213)=>752,chr(214)=>752,chr(215)=>522,chr(216)=>749,chr(217)=>780,chr(218)=>780,chr(219)=>780, chr(220)=>780,chr(221)=>612,chr(222)=>600,chr(223)=>550,chr(224)=>500,chr(225)=>500,chr(226)=>500,chr(227)=>500,chr(228)=>500,chr(229)=>500,chr(230)=>657,chr(231)=>377,chr(232)=>380,chr(233)=>380,chr(234)=>380,chr(235)=>380,chr(236)=>281,chr(237)=>281,chr(238)=>281,chr(239)=>281,chr(240)=>470,chr(241)=>540, chr(242)=>446,chr(243)=>446,chr(244)=>446,chr(245)=>446,chr(246)=>446,chr(247)=>550,chr(248)=>443,chr(249)=>545,chr(250)=>545,chr(251)=>545,chr(252)=>545,chr(253)=>425,chr(254)=>484,chr(255)=>425); $enc='cp1252'; $diff=''; $file='Scala-Italic.z'; $size1=755; $size2=36738; ?>
gpl-2.0
RoProducts/rastertheque
RasterLibrary/src/de/rooehler/rastertheque/processing/RasterOp.java
1456
package de.rooehler.rastertheque.processing; import java.io.Serializable; import java.util.Map; import de.rooehler.rastertheque.core.Raster; import de.rooehler.rastertheque.util.Hints; import de.rooehler.rastertheque.util.Hints.Key; import de.rooehler.rastertheque.util.ProgressListener; /** * A RasterOp models an abstract operation on a Raster * * @author Robert Oehler * */ public interface RasterOp { enum Priority{ LOW, NORMAL, HIGH, HIGHEST } /** * default hints for this operation */ Hints getDefaultHints(); /** * default parameters for this operation */ Map<Key,Serializable> getDefaultParams(); /** * validates the map of parameters * @param params the parameters to validate * @return true if the parameters are valid */ boolean validateParameters(Map<Key,Serializable> params); /** * a priority for this operation over other operations of the same name * @return the priority */ Priority getPriority(); /** * the name of this operation * @return the name of this operation */ String getOperationName(); /** * executes the RasterOp, manipulating the raster object * @param raster the raster to work on * @param params the parameters to apply * @param hints the hints to use - can be null * @param listener the listener to report progress - can be null */ void execute(Raster raster, Map <Key,Serializable> params, Hints hints, ProgressListener listener); }
gpl-2.0
panhainan/news
src/com/phn/dao/impl/CommentDaoImpl.java
2162
package com.phn.dao.impl; import java.util.List; import com.phn.dao.ICommentDao; import com.phn.po.Comment; import com.phn.po.News; /** * @author phn * @TODO * @date 2015-4-25 */ public class CommentDaoImpl extends JDBCDaoSupport<Comment> implements ICommentDao { public int save(Comment comment) { String saveSql = "insert into t_comment(commentIP,commentAddress,commentContent,commentPublishTime,commentNewsId) values(?,?,?,?,?)"; return super.executeInsert(saveSql, comment.getCommentIP(),comment.getCommentAddress(),comment.getCommentContent(),comment.getCommentPublishTime(),comment.getCommentNewsId()); } public int delete(int commentId) { String deleteSql ="delete from t_comment where id = ?"; return super.executeUpdateAndDelete(deleteSql, commentId); } public void deleteByNewsId(int newsId) { String deleteSql ="delete from t_comment where commentNewsId = ?"; super.executeUpdateAndDelete(deleteSql, newsId); } public Comment find(int commentId) { String findSql = "select * from t_comment where id =?"; return super.executeGet(findSql, Comment.class, commentId); } public int update(Comment comment) { String updateSql = "update t_comment set commentIP=?,commentAddress=?,commentContent=?,commentPublishTime=?,commentNewsId=? where id=?"; return super.executeUpdateAndDelete(updateSql, comment.getCommentIP(),comment.getCommentAddress(),comment.getCommentContent(),comment.getCommentPublishTime(),comment.getCommentNewsId(),comment.getId()); } public List<Comment> list() { String listSql = "select * from t_comment"; return super.executeList(listSql, Comment.class); } public List<Comment> list(int newsId) { String listSql = "select * from t_comment where commentNewsId=? order by id desc"; return super.executeList(listSql, Comment.class,newsId); } public int countRow() { String getCountSql = "select count(*) from t_comment"; return super.getCountRow(getCountSql); } public List<Comment> list(int startRecord, int pageSize) { String listSql = "select * from t_comment order by id desc limit ?,?"; return super.executeList(listSql,Comment.class,startRecord,pageSize); } }
gpl-2.0
stolosapo/CppPlayground
src/kernel/audio/alsa/exception/AlsaDomainErrorCode.cpp
2118
#include "AlsaDomainErrorCode.h" const DomainErrorCode AlsaDomainErrorCode::ALS0001 = DomainErrorCode("ALS0001", "ALSA feature is not enabled, try to pass the WITH_ALSA=1 param when Make."); const DomainErrorCode AlsaDomainErrorCode::ALS0002 = DomainErrorCode("ALS0002", "Cannot open audio device %s (%s)"); const DomainErrorCode AlsaDomainErrorCode::ALS0003 = DomainErrorCode("ALS0003", "Cannot allocate hardware parameter structure (%s)"); const DomainErrorCode AlsaDomainErrorCode::ALS0004 = DomainErrorCode("ALS0004", "Cannot initialize hardware parameter structure (%s)"); const DomainErrorCode AlsaDomainErrorCode::ALS0005 = DomainErrorCode("ALS0005", "Cannot set access type (%s)"); const DomainErrorCode AlsaDomainErrorCode::ALS0006 = DomainErrorCode("ALS0006", "Cannot set sample format (%s)"); const DomainErrorCode AlsaDomainErrorCode::ALS0007 = DomainErrorCode("ALS0007", "Cannot set sample rate (%s)"); const DomainErrorCode AlsaDomainErrorCode::ALS0008 = DomainErrorCode("ALS0008", "Cannot set channel count (%s)"); const DomainErrorCode AlsaDomainErrorCode::ALS0009 = DomainErrorCode("ALS0009", "Cannot set parameters (%s)"); const DomainErrorCode AlsaDomainErrorCode::ALS0010 = DomainErrorCode("ALS0010", "Cannot allocate software parameters structure (%s)"); const DomainErrorCode AlsaDomainErrorCode::ALS0011 = DomainErrorCode("ALS0011", "Cannot initialize software parameters structure (%s)"); const DomainErrorCode AlsaDomainErrorCode::ALS0012 = DomainErrorCode("ALS0012", "Cannot set minimum available count (%s)"); const DomainErrorCode AlsaDomainErrorCode::ALS0013 = DomainErrorCode("ALS0013", "Cannot set start mode (%s)"); const DomainErrorCode AlsaDomainErrorCode::ALS0014 = DomainErrorCode("ALS0014", "Cannot set software parameters (%s)"); const DomainErrorCode AlsaDomainErrorCode::ALS0015 = DomainErrorCode("ALS0015", "Cannot prepare audio interface for use (%s)"); const DomainErrorCode AlsaDomainErrorCode::ALS0016 = DomainErrorCode("ALS0016", "Read from audio interface failed"); AlsaDomainErrorCode::AlsaDomainErrorCode() { } AlsaDomainErrorCode::~AlsaDomainErrorCode() { }
gpl-2.0
pftaylor61/ctw
inc/jetpack.php
723
<?php /** * Jetpack Compatibility File. * * @link https://jetpack.me/ * * @package ctw */ /** * Add theme support for Infinite Scroll. * See: https://jetpack.me/support/infinite-scroll/ */ function ctw_jetpack_setup() { add_theme_support( 'infinite-scroll', array( 'container' => 'main', 'render' => 'ctw_infinite_scroll_render', 'footer' => 'page', ) ); } // end function ctw_jetpack_setup add_action( 'after_setup_theme', 'ctw_jetpack_setup' ); /** * Custom render function for Infinite Scroll. */ function ctw_infinite_scroll_render() { while ( have_posts() ) { the_post(); get_template_part( 'template-parts/content', get_post_format() ); } } // end function ctw_infinite_scroll_render
gpl-2.0
xbegault/clrh-idf
components/com_joomleague/views/playground/view.html.php
2451
<?php defined( '_JEXEC' ) or die( 'Restricted access' ); jimport( 'joomla.application.component.view'); class JoomleagueViewPlayground extends JLGView { function display( $tpl = null ) { // Get a refrence of the page instance in joomla $document= JFactory::getDocument(); // Set page title $document->setTitle( JText::_( 'COM_JOOMLEAGUE_PLAYGROUND_TITLE' ) ); $model = $this->getModel(); $address_string = $model->getAddressString(); $map_config = $model->getMapConfig(); $config = $model->getTemplateConfig($this->getName()); $games = $model->getNextGames(0, $config['show_referee']); $gamesteams = $model->getTeamsFromMatches( $games ); $playground = $model->getPlayground() ; $teams = $model->getTeams(); $project = $model->getProject(); $overallconfig = $model->getOverallConfig(); $this->assignRef( 'project', $project); $this->assignRef( 'overallconfig', $overallconfig); $this->assignRef( 'config', $config ); $this->assignRef( 'playground', $playground); $this->assignRef( 'teams', $teams ); $this->assignRef( 'games', $games ); $this->assignRef( 'gamesteams', $gamesteams ); $this->assignRef( 'address_string', $address_string); $this->assignRef( 'mapconfig', $map_config ); // Loads the project-template -settings for the GoogleMap $extended = $this->getExtended($this->playground->extended, 'playground'); $this->assignRef( 'extended', $extended ); // Set page title $titleInfo = JoomleagueHelper::createTitleInfo(JText::_('COM_JOOMLEAGUE_PLAYGROUND_PAGE_TITLE')); if (!empty($this->playground->name)) { $titleInfo->playgroundName = $this->playground->name; } if (!empty($this->project)) { $titleInfo->projectName = $this->project->name; $titleInfo->leagueName = $this->project->league_name; $titleInfo->seasonName = $this->project->season_name; } $division = $model->getDivision(JRequest::getInt('division',0)); if (!empty( $division ) && $division->id != 0) { $titleInfo->divisionName = $division->name; } $this->assignRef('pagetitle', JoomleagueHelper::formatTitle($titleInfo, $this->config["page_title_format"])); $document->setTitle($this->pagetitle); $document->addCustomTag( '<meta property="og:title" content="' . $this->playground->name .'"/>' ); $document->addCustomTag( '<meta property="og:street-address" content="' . $this->address_string .'"/>' ); parent::display( $tpl ); } } ?>
gpl-2.0
dl4gbe/kernel
include/data/table_views/cls_view_data_location_34ac07bc_ae71_4158_88ca_2ffc6f998a26.php
4304
<?php if(!defined('kernel_entry') || !kernel_entry) die('Not A Valid Entry Point'); require_once('include/data/cls_table_view_base.php'); class cls_view_data_location_34ac07bc_ae71_4158_88ca_2ffc6f998a26 extends cls_table_view_base { private $p_column_definitions = null; function __construct() { $a = func_get_args(); $i = func_num_args(); if (method_exists($this,$f="__construct".$i)) { call_user_func_array(array($this,$f),$a); } } public function query($search_values,$limit,$offset) { require_once('include/data/table_factory/cls_table_factory.php'); $common_data_location = cls_table_factory::get_common_data_location(); $array_data_location = $common_data_location->get_data_locations($this->get_db_manager(),$this->get_application(),$search_values,$limit,$offset,false); $where = $this->get_distinct_ids_id_location($array_data_location); $data_array_id_location = $this->fill_distinct_id_location($where); $result_array = array(); foreach($array_data_location as $data_location) { $data_location_id = $data_location->get_id(); $result_array[$data_location_id]['data_location.id'] = $data_location->get_id(); $result_array[$data_location_id]['data_location.id_data'] = $data_location->get_id_data(); $link_id = $data_location->get_id_location(); if (empty($link_id)) { $result_array[$data_location_id]['location.no'] = ''; } else { $result_array[$data_location_id]['location.no'] = $data_array_id_location[$link_id]->get_no(); } $link_id = $data_location->get_id_location(); if (empty($link_id)) { $result_array[$data_location_id]['location.unique_credit_identifier'] = ''; } else { $result_array[$data_location_id]['location.unique_credit_identifier'] = $data_array_id_location[$link_id]->get_unique_credit_identifier(); } $link_id = $data_location->get_id_location(); if (empty($link_id)) { $result_array[$data_location_id]['location.ik'] = ''; } else { $result_array[$data_location_id]['location.ik'] = $data_array_id_location[$link_id]->get_ik(); } $link_id = $data_location->get_id_location(); if (empty($link_id)) { $result_array[$data_location_id]['location.taxid'] = ''; } else { $result_array[$data_location_id]['location.taxid'] = $data_array_id_location[$link_id]->get_taxid(); } $result_array[$data_location_id]['data_location.owner'] = $data_location->get_owner(); } return $result_array; } private function get_distinct_ids_id_location($array_data_location) { $ids = array(); foreach ($array_data_location as $data_location) { $id = $data_location->get_id_location(); if (!in_array($id,$ids)) $ids[] = $id; } $i = 0; $in = ""; foreach ($ids as $id) { if (empty($id)) continue; if ($i != 0) $in .= ','; $in .= "'" . $id . "'"; $i++; } if (!empty($in)) $in = ' id in (' . $in . ')'; return $in; } private function fill_distinct_id_location($where) { $data = array(); if (empty($where)) return $data; $sql = 'select id as "location.id",location.no as "location.no",location.unique_credit_identifier as "location.unique_credit_identifier",location.ik as "location.ik",location.taxid as "location.taxid" from location where ' . $where; $db = $this->get_db_manager(); $result = $db->query($sql); while (($row=$db->fetch_by_assoc($result)) !=null) { $location = cls_table_factory::create_instance('location'); $location->fill($row); $data[$row['location.id']] = $location; } return $data; } public function get_column_definitions() { if (!is_null($this->p_column_definitions)) return $this->p_column_definitions; { $this->p_column_definitions = array(); $this->p_column_definitions['data_location.id']['type'] = 'uuid'; $this->p_column_definitions['data_location.id_data']['type'] = 'uuid'; $this->p_column_definitions['location.no']['type'] = 'varchar'; $this->p_column_definitions['location.unique_credit_identifier']['type'] = 'varchar'; $this->p_column_definitions['location.ik']['type'] = 'varchar'; $this->p_column_definitions['location.taxid']['type'] = 'varchar'; $this->p_column_definitions['data_location.owner']['type'] = 'bool'; } return $this->p_column_definitions; } } ?>
gpl-2.0
Engeltj/Time
src/com/tengel/time/Config.java
1546
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.tengel.time; import org.bukkit.configuration.file.YamlConfiguration; import java.io.File; import java.io.IOException; import java.util.logging.Level; /** * * @author Tim */ public class Config extends YamlConfiguration { private final Time plugin; private File configFile; public Config(Time plugin){ this.plugin = plugin; } public Config(Time plugin, String filename){ this.plugin = plugin; configFile = new File(plugin.getDataFolder() + File.separator +filename).getAbsoluteFile(); if (!configFile.exists()){ try { configFile.createNewFile(); } catch (Exception e){ plugin.sendConsole("Error creating "+filename); } } else try{ load(configFile); }catch (Exception ignored){} } public boolean setConfigFile(File configFile){ if (configFile != null){ this.configFile = configFile; return true; } return false; } public File getConfigFile(){ return this.configFile; } public void save() { try{ save(configFile); } catch (IOException e) { plugin.getLogger().log(Level.SEVERE, e.getMessage(), e); } } }
gpl-2.0
stevenzh/tourismwork
src/modules/service/src/main/java/com/opentravelsoft/service/impl/HotelManagerImpl.java
1259
package com.opentravelsoft.service.impl; import java.util.List; import javax.jws.WebService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.opentravelsoft.entity.vacation.Hotel; import com.opentravelsoft.providers.HotelDao; import com.opentravelsoft.service.HotelManager; /** * Implementation of UserManager interface. * */ @Service("hotelManager") @WebService(serviceName = "HotelService", endpointInterface = "com.opentravelsoft.service.HotelManager") public class HotelManagerImpl extends GenericManagerImpl<Hotel, String> implements HotelManager { private HotelDao hotelDao; @Autowired public void setHotelDao(HotelDao hotelDao) { this.dao = hotelDao; this.hotelDao = hotelDao; } @Override public Hotel getHotel(String hotelId) { return hotelDao.get(hotelId); } @Override public void deleteHotel(String hotelId) { hotelDao.remove(hotelId); } @Override public void saveHotel(Hotel hotel) { hotelDao.save(hotel); } @Override public List<Hotel> getHotels(String countryNo, String provinceNo, String cityNo, String hotelName) { return hotelDao.getHotels(countryNo, provinceNo, cityNo, hotelName); } }
gpl-2.0
VisualIdeation/3DVisualizer
Templatized/MultiPolyline.cpp
9919
/*********************************************************************** MultiPolyline - Class to represent multiple arbitrary-length polylines. Copyright (c) 2007-2008 Oliver Kreylos This file is part of the 3D Data Visualizer (Visualizer). The 3D Data Visualizer 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. The 3D Data Visualizer 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 the 3D Data Visualizer; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***********************************************************************/ #define VISUALIZATION_TEMPLATIZED_MULTIPOLYLINE_IMPLEMENTATION #include <Comm/MulticastPipe.h> #include <GL/gl.h> #include <GL/GLVertexArrayParts.h> #define NONSTANDARD_GLVERTEX_TEMPLATES #include <GL/GLVertex.h> #include <GL/GLContextData.h> #include <GL/GLExtensionManager.h> #include <GL/Extensions/GLARBVertexBufferObject.h> #include <Templatized/MultiPolyline.h> namespace Visualization { namespace Templatized { /**************************************** Methods of class MultiPolyline::Polyline: ****************************************/ template <class VertexParam> inline MultiPolyline<VertexParam>::Polyline::~Polyline( void) { /* Delete all vertex buffer chunks: */ while(head!=0) { Chunk* succ=head->succ; delete head; head=succ; } } /**************************************** Methods of class MultiPolyline::DataItem: ****************************************/ template <class VertexParam> inline MultiPolyline<VertexParam>::DataItem::DataItem( unsigned int sNumPolylines) :numPolylines(sNumPolylines), vertexBufferIds(new GLuint[numPolylines]), version(0), numVertices(new size_t[numPolylines]) { if(GLARBVertexBufferObject::isSupported()) { /* Initialize the vertex buffer object extension: */ GLARBVertexBufferObject::initExtension(); /* Create a set of vertex buffer objects: */ glGenBuffersARB(numPolylines,vertexBufferIds); } else vertexBufferIds[0]=0; // Serves as flag for the rest of the buffer /* Initialize polyline storage: */ for(unsigned int i=0;i<numPolylines;++i) numVertices[i]=0; } template <class VertexParam> inline MultiPolyline<VertexParam>::DataItem::~DataItem( void) { if(vertexBufferIds[0]!=0) { /* Delete the vertex buffer objects: */ glDeleteBuffersARB(numPolylines,vertexBufferIds); } delete[] vertexBufferIds; delete[] numVertices; } /****************************** Methods of class MultiPolyline: ******************************/ template <class VertexParam> inline void MultiPolyline<VertexParam>::addNewChunk( unsigned int polylineIndex) { Polyline& p=polylines[polylineIndex]; if(pipe!=0) { /* Check how many vertices in the last chunk need to be sent across the pipe: */ size_t numUnsentVertices; if(p.tail!=0&&(numUnsentVertices=chunkSize-p.tailNumSentVertices)>0) { /* Send unsent vertices in the last chunk across the pipe: */ pipe->write<unsigned int>(polylineIndex); pipe->write<unsigned int>((unsigned int)numUnsentVertices); pipe->write<Vertex>(p.tail->vertices+p.tailNumSentVertices,numUnsentVertices); pipe->finishMessage(); } p.tailNumSentVertices=0; } /* Add a new vertex chunk to the buffer: */ Chunk* newChunk=new Chunk; if(p.tail!=0) p.tail->succ=newChunk; else p.head=newChunk; Chunk* oldTail=p.tail; p.tail=newChunk; /* Set up the vertex pointer: */ p.tailRoomLeft=chunkSize; p.nextVertex=p.tail->vertices; if(newChunk!=p.head) { /* Copy the last vertex of the previous chunk to render a continuous polyline: */ *p.nextVertex=oldTail->vertices[chunkSize-1]; ++p.numVertices; --p.tailRoomLeft; ++p.nextVertex; } } template <class VertexParam> inline MultiPolyline<VertexParam>::MultiPolyline( unsigned int sNumPolylines, Comm::MulticastPipe* sPipe) :numPolylines(sNumPolylines), pipe(sPipe), version(0), polylines(new Polyline[numPolylines]), maxNumVertices(0) { } template <class VertexParam> inline MultiPolyline<VertexParam>::~MultiPolyline( void) { delete[] polylines; } template <class VertexParam> inline void MultiPolyline<VertexParam>::initContext( GLContextData& contextData) const { /* Create a new context data item: */ DataItem* dataItem=new DataItem(numPolylines); contextData.addDataItem(this,dataItem); } template <class VertexParam> inline void MultiPolyline<VertexParam>::clear( void) { ++version; for(unsigned int polylineIndex=0;polylineIndex<numPolylines;++polylineIndex) { Polyline& p=polylines[polylineIndex]; p.numVertices=0; /* Delete all vertex buffer chunks: */ while(p.head!=0) { Chunk* succ=p.head->succ; delete p.head; p.head=succ; } p.tail=0; p.tailRoomLeft=0; p.nextVertex=0; } maxNumVertices=0; } template <class VertexParam> inline void MultiPolyline<VertexParam>::receive( void) { /* Read while the polyline index of the next batch is valid: */ unsigned int polylineIndex; while((polylineIndex=pipe->read<unsigned int>())<numPolylines) { /* Read the number of vertices in the next batch: */ size_t numBatchVertices=pipe->read<unsigned int>(); /* Read the vertex data one chunk at a time: */ Polyline& p=polylines[polylineIndex]; while(numBatchVertices>0) { if(p.tailRoomLeft==0) { /* Add a new vertex chunk to the buffer: */ Chunk* newChunk=new Chunk; if(p.tail!=0) p.tail->succ=newChunk; else p.head=newChunk; p.tail=newChunk; /* Set up the vertex pointer: */ p.tailRoomLeft=chunkSize; p.nextVertex=p.tail->vertices; } /* Receive as many vertices as the current chunk can hold: */ size_t numReadVertices=numBatchVertices; if(numReadVertices>p.tailRoomLeft) numReadVertices=p.tailRoomLeft; pipe->read<Vertex>(p.nextVertex,numReadVertices); numBatchVertices-=numReadVertices; /* Update the vertex storage: */ p.numVertices+=numReadVertices; p.tailRoomLeft-=numReadVertices; p.nextVertex+=numReadVertices; } if(maxNumVertices<p.numVertices) maxNumVertices=p.numVertices; } } template <class VertexParam> inline void MultiPolyline<VertexParam>::flush( void) { if(pipe!=0) { for(unsigned int polylineIndex=0;polylineIndex<numPolylines;++polylineIndex) { Polyline& p=polylines[polylineIndex]; /* Send all unsent vertices across the pipe: */ size_t numUnsentVertices; if(p.tail!=0&&(numUnsentVertices=chunkSize-p.tailRoomLeft-p.tailNumSentVertices)>0) { pipe->write<unsigned int>(polylineIndex); pipe->write<unsigned int>((unsigned int)numUnsentVertices); pipe->write<Vertex>(p.tail->vertices+p.tailNumSentVertices,numUnsentVertices); p.tailNumSentVertices+=numUnsentVertices; } } /* Send a flush signal: */ pipe->write<unsigned int>(numPolylines); pipe->finishMessage(); } } template <class VertexParam> inline void MultiPolyline<VertexParam>::glRenderAction( GLContextData& contextData) const { /* Get the context data item: */ DataItem* dataItem=contextData.template retrieveDataItem<DataItem>(this); GLVertexArrayParts::enable(Vertex::getPartsMask()); if(dataItem->vertexBufferIds[0]!=0) { for(unsigned int polylineIndex=0;polylineIndex<numPolylines;++polylineIndex) { const Polyline& p=polylines[polylineIndex]; /* Save the current number of vertices (for parallel creation and rendering): */ size_t numRenderVertices=p.numVertices; glBindBufferARB(GL_ARRAY_BUFFER_ARB,dataItem->vertexBufferIds[polylineIndex]); /* Check if the vertex buffer is current: */ if(dataItem->version!=version||dataItem->numVertices[polylineIndex]!=numRenderVertices) { /* Upload the vertices to the vertex buffer: */ glBufferDataARB(GL_ARRAY_BUFFER_ARB,numRenderVertices*sizeof(Vertex),0,GL_STATIC_DRAW_ARB); GLintptrARB offset=0; size_t numVerticesLeft=numRenderVertices; for(const Chunk* chPtr=p.head;numVerticesLeft>0;chPtr=chPtr->succ) { /* Calculate the number of vertices in this chunk: */ size_t numChunkVertices=numVerticesLeft; if(numChunkVertices>chunkSize) numChunkVertices=chunkSize; /* Upload the vertices: */ glBufferSubDataARB(GL_ARRAY_BUFFER_ARB,offset,numChunkVertices*sizeof(Vertex),chPtr->vertices); numVerticesLeft-=numChunkVertices; offset+=numChunkVertices*sizeof(Vertex); } dataItem->numVertices[polylineIndex]=numRenderVertices; } /* Render the poly line: */ glVertexPointer(static_cast<const Vertex*>(0)); glDrawArrays(GL_LINE_STRIP,0,numRenderVertices); } glBindBufferARB(GL_ARRAY_BUFFER_ARB,0); dataItem->version=version; } else { for(unsigned int polylineIndex=0;polylineIndex<numPolylines;++polylineIndex) { const Polyline& p=polylines[polylineIndex]; /* Save the current number of vertices (for parallel creation and rendering): */ size_t numRenderVertices=p.numVertices; for(const Chunk* chPtr=p.head;numRenderVertices>0;chPtr=chPtr->succ) { /* Calculate the number of vertices in this chunk: */ size_t numChunkVertices=numRenderVertices; if(numChunkVertices>chunkSize) numChunkVertices=chunkSize; /* Draw the partial polyline: */ glVertexPointer(chPtr->vertices); glDrawArrays(GL_LINE_STRIP,0,numChunkVertices); numRenderVertices-=numChunkVertices; } } } GLVertexArrayParts::disable(Vertex::getPartsMask()); } } }
gpl-2.0
kit0206/DailyWorkReport
DailyWorkReport/DailyWorkReport/Controllers_/CoreController.cs
981
using DailyWorkReportLib.DbAccess; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace DailyWorkReport.Controllers_ { public class CoreController : BaseController { /// <summary> /// 初期化 /// </summary> /// <param name="localDbPath"></param> /// <returns></returns> public bool Initialize( string localDbPath ) { try { Api.Initialize( localDbPath ); } catch( Exception ex ) { var message = string.Format( "Accesser の初期化に失敗しました。\n{0}", ex.Message ); MessageBox.Show( message, "作業日報", MessageBoxButton.OK, MessageBoxImage.Error ); return false; } return true; } /// <summary> /// 再構築 /// </summary> /// <param name="localDbPath"></param> public void Remodeling( string localDbPath ) { Api.Destruction(); Api.Initialize( localDbPath ); Api.CreateTable(); } } }
gpl-2.0
ajv/Offline-Caching
mod/assignment/simpletest/test_assignment_portfolio_callers.php
2125
<?php // $Id$ require_once("$CFG->libdir/simpletest/portfolio_testclass.php"); require_once("$CFG->dirroot/mod/assignment/lib.php"); require_once("$CFG->dirroot/$CFG->admin/generator.php"); Mock::generate('assignment_portfolio_caller', 'mock_caller'); Mock::generate('portfolio_exporter', 'mock_exporter'); class testAssignmentPortfolioCallers extends portfoliolib_test { public static $includecoverage = array('lib/portfoliolib.php', 'mod/assignment/lib.php'); public $module_type = 'assignment'; public $modules = array(); public $entries = array(); public $caller; public function setUp() { global $DB, $USER; parent::setUp(); $assignment_types = new stdClass(); $assignment_types->type = GENERATOR_SEQUENCE; $assignment_types->options = array('online'); $settings = array('quiet' => 1, 'modules_list' => array($this->module_type), 'assignment_grades' => true, 'assignment_type' => $assignment_types, 'number_of_students' => 5, 'students_per_course' => 5, 'number_of_sections' => 1, 'number_of_modules' => 3, 'questions_per_course' => 0); generator_generate_data($settings); $this->modules = $DB->get_records($this->module_type); $first_module = reset($this->modules); $cm = get_coursemodule_from_instance($this->module_type, $first_module->id); $submissions = $DB->get_records('assignment_submissions', array('assignment' => $first_module->id)); $first_submission = reset($submissions); $this->caller = parent::setup_caller('assignment_portfolio_caller', array('id' => $cm->id), $first_submission->userid); } public function tearDown() { parent::tearDown(); } public function test_caller_sha1() { $sha1 = $this->caller->get_sha1(); $this->caller->prepare_package(); $this->assertEqual($sha1, $this->caller->get_sha1()); } public function test_caller_with_plugins() { parent::test_caller_with_plugins(); } } ?>
gpl-2.0
manuelcortez/socializer
src/wxUI/tabs/audio.py
1849
# -*- coding: utf-8 -*- import wx import widgetUtils from .home import homeTab class audioTab(homeTab): def create_list(self): self.lbl = wx.StaticText(self, wx.NewId(), _("Mu&sic")) self.list = widgetUtils.multiselectionList(self, *[_("Title"), _("Artist"), _("Duration")], style=wx.LC_REPORT, name=_("Music")) self.list.set_windows_size(0, 160) self.list.set_windows_size(1, 380) self.list.set_windows_size(2, 80) self.list.set_size() self.list.list.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnKeyDown) def create_post_buttons(self): self.postBox = wx.StaticBoxSizer(parent=self, orient=wx.HORIZONTAL, label=_("Actions")) self.post = wx.Button(self.postBox.GetStaticBox(), -1, _("&Upload audio")) self.post.Enable(False) self.play = wx.Button(self.postBox.GetStaticBox(), -1, _("P&lay")) self.play_all = wx.Button(self.postBox.GetStaticBox(), -1, _("Play &All")) self.postBox.Add(self.post, 0, wx.ALL, 5) self.postBox.Add(self.play, 0, wx.ALL, 5) self.postBox.Add(self.play_all, 0, wx.ALL, 5) def get_file_to_upload(self): openFileDialog = wx.FileDialog(self, _("Select the audio file to be uploaded"), "", "", _("Audio files (*.mp3)|*.mp3"), wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) if openFileDialog.ShowModal() == wx.ID_CANCEL: return None return openFileDialog.GetPath() def get_download_path(self, filename="", multiple=False): if multiple == False: d = wx.FileDialog(self, _("Save this file"), "", filename, _("Audio Files(*.mp3)|*.mp3"), wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) else: d = wx.DirDialog(None, _("Select a folder to save all files")) if d.ShowModal() == wx.ID_OK: return d.GetPath() d.Destroy()
gpl-2.0
ThomasHabets/qpov
pkg/dist/dist_test.go
917
package dist import ( "testing" ) func TestS3Parse(t *testing.T) { for _, test := range []struct { in string bucket, dir, file string err bool }{ {"", "", "", "", true}, {"s3://qpov", "", "", "", true}, {"s3://qpov/", "qpov", "", "", false}, {"s3://qpov/foo.pov", "qpov", "", "foo.pov", false}, {"s3://qpov/foo/bar.pov", "qpov", "foo", "bar.pov", false}, {"s3://qpov/foo.pov/", "qpov", "foo.pov", "", false}, } { bucket, dir, file, err := S3Parse(test.in) if test.err != (err != nil) { t.Errorf("For %q want err %v, got %v", test.in, test.err, err) } if bucket != test.bucket { t.Errorf("For %q want bucket %q, got %q", test.in, test.bucket, bucket) } if dir != test.dir { t.Errorf("For %q want dir %q, got %q", test.in, test.dir, dir) } if file != test.file { t.Errorf("For %q want file %q, got %q", test.in, test.file, file) } } }
gpl-2.0
chisimba/modules
socialweb/resources/socialweb.js
597
/* * Javascript to support socialweb * * Written by Derek Keats derekkeats@gmail.com * STarted on: September 16, 2012, 3:52 pm * * The following parameters need to be set in the * PHP code for this to work: * * @todo * List your parameters here so you won't forget to add them * */ /** * * Put your jQuery code inside this function. * */ jQuery(function() { // Things to do on loading the page. jQuery(document).ready(function() { // Load some demo content into the middle dynamic area. jQuery('body').prepend('<div id="fb-root"></div>'); }); });
gpl-2.0
Firebird1915/mckinleyfirebirds
wp-content/plugins/my-calendar/my-calendar-help.php
26176
<?php if ( ! defined( 'ABSPATH' ) ) { exit; } // Exit if accessed directly function my_calendar_help() { ?> <div class="wrap jd-my-calendar"> <h2><?php _e( 'How to use My Calendar', 'my-calendar' ); ?></h2> <div class="postbox-container jcd-wide"> <div class="metabox-holder"> <div class="ui-sortable meta-box-sortables"> <div class="postbox"> <h3><?php _e( 'My Calendar Help', 'my-calendar' ); ?></h3> <div class="inside"> <?php do_action( 'mc_before_help' ); ?> <ul class="mc-settings checkboxes"> <li><a href="#mc-generator"><?php _e( 'Shortcode Generator', 'my-calendar' ); ?></a></li> <li><a href="#mc-shortcodes"><?php _e( 'Shortcodes', 'my-calendar' ); ?></a></li> <li><a href="#icons"><?php _e( 'Icons', 'my-calendar' ); ?></a></li> <li><a href="#mc-styles"><?php _e( 'Styles', 'my-calendar' ); ?></a></li> <li><a href="#templates"><?php _e( 'Templating', 'my-calendar' ); ?></a></li> <li><a href="#get-support"><?php _e( 'Support Form', 'my-calendar' ); ?></a></li> <li><a href="#notes"><?php _e( 'Helpful Information', 'my-calendar' ); ?></a></li> </ul> </div> </div> </div> <div class="ui-sortable meta-box-sortables" id="get-started"> <div class="postbox"> <h3 id="help"><?php _e( 'Getting Started', 'my-calendar' ); ?></h3> <div class="inside"> <ul> <li><?php _e( 'Add the My Calendar shortcode (<code>[my_calendar]</code>) to a page.', 'my-calendar' ); ?></li> <li><?php _e( 'Add events by clicking on the Add/Edit Events link in the admin or on "Add Events" in the toolbar.', 'my-calendar' ); ?></li> <li><?php _e( 'Select your preferred stylesheet in the Styles Editor', 'my-calendar' ); ?></li> </ul> <p> <?php printf( __( 'Read more help documentation below or <a href="%s">purchase the My Calendar User\'s Guide</a> to learn more -- but the above is all that you need to do to begin using the calendar.', 'my-calendar' ), 'https://www.joedolson.com/my-calendar/users-guide/' ); ?> </p> </div> </div> </div> <div class="ui-sortable meta-box-sortables" id="mc-generator"> <div class="postbox"> <h3 id="help"><?php _e( "My Calendar Shortcode Generator", 'my-calendar' ); ?></h3> <div class="inside mc-tabs"> <?php mc_generate(); ?> <ul class='tabs'> <li><a href='#mc_main'><?php _e( 'Main', 'my-calendar' ); ?></a></li> <li><a href='#mc_upcoming'><?php _e( 'Upcoming', 'my-calendar' ); ?></a></li> <li><a href='#mc_today'><?php _e( 'Today', 'my-calendar' ); ?></a></li> <?php echo apply_filters( 'mc_generator_tabs', '' ); ?> </ul> <div class='wptab mc_main' id='mc_main' aria-live='assertive'> <?php mc_generator( 'main' ); ?> </div> <div class='wptab mc_upcoming' id='mc_upcoming' aria-live='assertive'> <?php mc_generator( 'upcoming' ); ?> </div> <div class='wptab mc_today' id='mc_today' aria-live='assertive'> <?php mc_generator( 'today' ); ?> </div> <?php echo apply_filters( 'mc_generator_tab_content', '' ); ?> </div> </div> </div> <div class="ui-sortable meta-box-sortables"> <div class="postbox" id="mc-shortcodes"> <h3><?php _e( 'Shortcode Syntax', 'my-calendar' ); ?></h3> <div class="inside"> <h4><?php _e( 'Main Calendar Shortcode (List or Grid, Weekly or Monthly view)', 'my-calendar' ); ?></h4> <p class="example"><code>[my_calendar]</code></p> <h4><?php _e( 'Example Customized Shortcode', 'my-calendar' ); ?></h4> <p class="example"><code>[my_calendar format="list" above="nav" below="print" time="week"]</code></p> <p> <?php _e( 'This shortcode shows the one-week view of the calendar on a post or page including all categories and the category key, in a list format. The standard previous/next navigation will be included above the calendar, the link to the print format (if enabled) will be shown below.', 'my-calendar' ); ?> </p> <p> <?php _e( 'Shortcode attributes:', 'my-calendar' ); ?> </p> <ul> <li> <code>category</code>: <?php _e( 'Names or IDs of categories in the calendar, comma or pipe separated.', 'my-calendar' ); ?> </li> <li> <code>format</code>: <?php _e( '"list" or "mini"; exclude or any other value to show a calendar grid.', 'my-calendar' ); ?> </li> <li><code>above</code>, <code>below</code>: <?php _e( "Comma-separated list of navigation to display above or below the calendar. Available: <strong>nav, toggle, jump, print, key, feeds, timeframe</strong>. Order listed determines the order displayed. Defaults in settings will be used if the attribute is blank. Use <em>none</em> to hide all navigation.", 'my-calendar' ); ?> </li> <li> <code>time</code>: <?php _e( 'Set to "week" to show a one week view or to "day" to show a single day view. Any other value will show a month view. (Day view always shows as a list.)', 'my-calendar' ); ?> </li> <li><code>ltype</code>: <?php _e( 'Type of location data to restrict by.', 'my-calendar' ); ?></li> <li><code>lvalue</code>: <?php _e( 'Specific location information to filter to.', 'my-calendar' ); ?> </li> <li> <code>author</code>: <?php _e( 'Author or comma-separated list (usernames or IDs) to show events from.', 'my-calendar' ); ?> </li> <li> <code>host</code>: <?php _e( 'Host or comma-separated list (usernames or IDs) to show events from.', 'my-calendar' ); ?> </li> <li><code>id</code>: <?php _e( 'String to give shortcode a unique ID.', 'my-calendar' ); ?></li> </ul> <p> <em><?php _e( 'The main My Calendar shortcode can be generated from a button in your post and page editor. The mini calendar can also be accessed and configured as a widget.', 'my-calendar' ); ?></em> </p> <h4><?php _e( 'Additional Views (Upcoming events, today\'s events)', 'my-calendar' ); ?></h4> <textarea readonly='readonly'>[my_calendar_upcoming before="3" after="3" type="event" fallback="No events coming up!" category="General" author="1" host="1" template="{title} {date}" order="asc" show_today="yes" skip="0" ltype="" lvalue=""]</textarea> <p> <?php _e( 'Displays the output of the Upcoming Events widget. <code>before</code> and <code>after</code> are numbers; <code>type</code> is either "event" or "days", and <code>category</code> and <code>author</code> work the same as in the main calendar shortcode. Templates use the template codes listed below. <code>fallback</code> provides text if no events meet your criteria. Order sets sort order for the list &ndash; ascending (<code>asc</code>) or descending (<code>desc</code>). <code>show_today</code> indicates whether to include today\'s events in the list. <code>Skip</code> is how many events to skip in the list.', 'my-calendar' ); ?> </p> <textarea readonly='readonly'>[my_calendar_today category="" author="1" host="1" fallback="Nothing today!" template="{title} {date}"]</textarea> <p> <?php _e( 'Displays the output of the Today\'s Events widget, with four configurable attributes: category, author, template and fallback text.', 'my-calendar' ); ?> </p> <p> <em><?php _e( 'Upcoming Events and Today\'s Events can also be configured as widgets.', 'my-calendar' ); ?></em> </p> <textarea readonly='readonly'>[my_calendar_event event="" template="&lt;h3&gt;{title}&lt;/h3&gt;{description}" list="&lt;li&gt;{date}, {time}&lt;/li&gt;" before="&lt;ul&gt;" after="&lt;/ul&gt;"]</textarea> <p> <?php _e( 'Displays a single event and/or all dates for that event. If template is set to a blank value, will only display the list of occurrences. If the list attribute is set blank, will only show the event template', 'my-calendar' ); ?> </p> <h4><?php _e( 'Calendar Filter Shortcodes', 'my-calendar' ); ?></h4> <textarea readonly='readonly'>[mc_filters show="categories,locations"]</textarea> <p> <?php _e( 'Displays all available filters as a single form. The <code>show</code> attribute takes three keywords: categories, locations, and access, to indicate which filters to show and in what order.', 'my-calendar' ); ?> </p> <textarea readonly='readonly'>[my_calendar_locations show="list" type="saved" datatype="name"]</textarea> <p> <?php _e( 'List of event locations, as a list of links or as a select form. <code>show</code> is either <code>list</code> or <code>form</code>, <code>type</code> is <code>saved</code> (to show items from stored locations), or <code>custom</code> (to show options configured in location settings). <code>datatype</code> must be the type of data your limits are using: <code>name</code> (business name), <code>city</code>, <code>state</code>, <code>country</code>, <code>zip</code> (postal code), or <code>region</code>.', 'my-calendar' ); ?> </p> <textarea readonly='readonly'>[my_calendar_categories show="list"]</textarea> <p> <?php _e( 'List of event categories, either as a list of links or as a select dropdown form. The <code>show</code> attribute can either be <code>list</code> or <code>form</code>.', 'my-calendar' ); ?> </p> <textarea readonly='readonly'>[my_calendar_search url='false']</textarea> <p> <?php _e( 'Simple search form to search all events. <code>url</code> attribute to pass a custom search results page, otherwise your My Calendar URL.', 'my-calendar' ); ?> </p> <textarea readonly='readonly'>[my_calendar_access show="list"]</textarea> <p> <?php _e( 'List of filterable accessibility services, either as a list of links or as a select dropdown form. The <code>show</code> attribute can either be <code>list</code> or <code>form</code>.', 'my-calendar' ); ?> </p> <h4><?php _e( 'Information Listing Shortcodes', 'my-calendar' ); ?></h4> <textarea readonly='readonly'>[my_calendar_show_locations datatype="" template=""]</textarea> <p> <?php _e( 'List of locations. <code>datatype</code> is the type of data displayed; all lists include a link to the map to that location. In addition to basic location information as in the above shortcode, you can also use "hcard" to display all available location information.', 'my-calendar' ); ?> <?php _e( 'Use <code>template</code> to show customized data, sorted by the <code>datatype</code> value.', 'my-calendar' ); ?> </p> </div> </div> <div class="ui-sortable meta-box-sortables" id="icons"> <div class="postbox"> <h3><?php _e( 'Category Icons', 'my-calendar' ); ?></h3> <div class="inside"> <p> <?php _e( 'My Calendar is designed to manage multiple calendars. The basis for these calendars are categories; you can setup a calendar page which includes all categories, or you can dedicate separate pages to calendars in each category. For an example, this might be useful for you in managing the tour calendars for multiple bands; event calendars for a variety of locations, etc.', 'my-calendar' ); ?> </p> <p> <?php _e( 'The pre-installed category icons may not be what you need. I assume that you\'ll upload your own icons -- place your custom icons in a folder at "my-calendar-custom" to avoid having them overwritten by upgrades.', 'my-calendar' ); ?> <?php _e( 'You can alternately place icons in:', 'my-calendar' ); ?> <code><?php echo str_replace( '/my-calendar', '', plugin_dir_path( __FILE__ ) ) . 'my-calendar-custom/'; ?></code> </p> </div> </div> </div> <div class="ui-sortable meta-box-sortables" id="mc-styles"> <div class="postbox"> <h3><?php _e( 'Custom Styles', 'my-calendar' ); ?></h3> <div class="inside"> <p> <?php _e( 'My Calendar comes with five default stylesheets. My Calendar will retain your changes to stylesheets, but if you want to add an entirely new stylesheet, you may wish to store it in the My Calendar custom styles directory.', 'my-calendar' ); ?> </p> <ul> <li><?php _e( 'Your custom style directory is', 'my-calendar' ); ?>: <code><?php echo str_replace( '/my-calendar', '', plugin_dir_path( __FILE__ ) ) . 'my-calendar-custom/styles/'; ?></code> </li> </ul> <p> <?php _e( 'You can also add custom styles to your custom directory or your theme directory for print styles, mobile styles, and tablet styles. <code>mc-print.css</code>, <code>mc-mobile.css</code>, and <code>mc-tablet.css</code>.', 'my-calendar' ); ?> </p> </div> </div> </div> <div class="ui-sortable meta-box-sortables" id="templates"> <div class="postbox"> <h3 id="template"><?php _e( 'Template Tags', 'my-calendar' ); ?></h3> <div class="inside"> <p> <?php _e( 'All template tags support two attributes: before="value" and after="value". The values of the attributes will be placed before and after the output value. These attribute values <strong>must</strong> be wrapped in double quotes.', 'my-calendar' ); ?> </p> <p> <?php _e( 'Date/Time template tags support the "format" attribute: format="M, Y", where the value is a PHP formatted date string. Only <code>dtstart</code> and <code>dtend</code> include the full date/time information for formatting.', 'my-calendar' ); ?> </p> <p> <strong><?php _e( 'Example:', 'my-calendar' ); ?></strong> <code>{title before="&lt;h3&gt;" after="&lt;/h3&gt;"}</code> </p> <h4><?php _e( 'Event Template Tags', 'my-calendar' ); ?></h4> <dl> <dt><code>{title}</code></dt> <dd><?php _e( 'Displays the title of the event.', 'my-calendar' ); ?></dd> <dt><code>{link_title}</code></dt> <dd><?php _e( 'Displays title of the event as a link if a URL is present, or the title alone if no URL is available.', 'my-calendar' ); ?></dd> <dt><code>{link_image}</code></dt> <dd><?php _e( 'Displays featured image of the event as a link if a URL is present, or the image alone if no URL is available.', 'my-calendar' ); ?></dd> <dt><code>{time}</code></dt> <dd><?php _e( 'Displays the start time for the event.', 'my-calendar' ); ?></dd> <dt><code>{runtime}</code></dt> <dd><?php _e( 'Human language estimate of how long an event will run.', 'my-calendar' ); ?></dd> <dt><code>{usertime}</code></dt> <dd><?php _e( 'Displays the start time for the event adjusted to the current user\'s time zone settings. Returns <code>{time}</code> if user settings are disabled or if the user has not selected a preferred time zone.', 'my-calendar' ); ?></dd> <dt><code>{endusertime}</code></dt> <dd><?php _e( 'Displays the end time for the event adjusted to the current user\'s time zone settings. Returns <code>{endtime}</code> if user settings are disabled or if the user has not selected a preferred time zone.', 'my-calendar' ); ?></dd> <dt><code>{date}</code></dt> <dd><?php _e( 'Displays the date on which the event begins.', 'my-calendar' ); ?></dd> <dt><code>{began}</code></dt> <dd><?php _e( 'Displays the date on which the series of events began (for recurring events).', 'my-calendar' ); ?></dd> <dt><code>{enddate}</code></dt> <dd><?php _e( 'Displays the date on which the event ends.', 'my-calendar' ); ?></dd> <dt><code>{endtime}</code></dt> <dd><?php _e( 'Displays the time at which the event ends.', 'my-calendar' ); ?></dd> <dt><code>{daterange}</code></dt> <dd><?php _e( 'Displays the beginning date to the end date for events. Does not show end date if same as start date.', 'my-calendar' ); ?></dd> <dt><code>{timerange}</code></dt> <dd><?php _e( 'Displays the beginning and end times for events. Does not show end time if same as start or if marked as hidden.', 'my-calendar' ); ?></dd> <dt><code>{dtstart}</code></dt> <dd><?php _e( 'Timestamp for beginning of event.', 'my-calendar' ); ?></dd> <dt><code>{dtend}</code></dt> <dd><?php _e( 'Timestamp for end of event.', 'my-calendar' ); ?></dd> <dt><code>{multidate}</code></dt> <dd><?php _e( 'For multi-day events displays an unordered list of dates and times for events in this group. Otherwise, beginning date/time.', 'my-calendar' ); ?></dd> <dt><code>{author}</code></dt> <dd><?php _e( 'Displays the WordPress author who posted the event.', 'my-calendar' ); ?></dd> <dt><code>{gravatar}</code></dt> <dd><?php _e( 'Displays the gravatar image for the event author.', 'my-calendar' ); ?></dd> <dt><code>{host}</code></dt> <dd><?php _e( 'Displays the name of the person assigned as host for the event.', 'my-calendar' ); ?></dd> <dt><code>{host_email}</code></dt> <dd><?php _e( 'Displays the email address of the person assigned as host for the event.', 'my-calendar' ); ?></dd> <dt><code>{host_gravatar}</code></dt> <dd><?php _e( 'Displays the gravatar image for the event host.', 'my-calendar' ); ?></dd> <dt><code>{shortdesc}</code></dt> <dd><?php _e( 'Displays the short version of the event description.', 'my-calendar' ); ?></dd> <dt><code>{shortdesc_raw}</code></dt> <dd><?php _e( 'Displays short description without converting paragraphs.', 'my-calendar' ); ?></dd> <dt><code>{shortdesc_stripped}</code></dt> <dd><?php _e( 'Displays short description with any HTML stripped out.', 'my-calendar' ); ?></dd> <dt><code>{excerpt}</code></dt> <dd><?php _e( 'Like <code>the_excerpt();</code> displays shortdesc if provided, otherwise excerpts description.', 'my-calendar' ); ?></dd> <dt><code>{description}</code></dt> <dd><?php _e( 'Displays the description of the event.', 'my-calendar' ); ?></dd> <dt><code>{description_raw}</code></dt> <dd><?php _e( 'Displays description without converting paragraphs.', 'my-calendar' ); ?></dd> <dt><code>{description_stripped}</code></dt> <dd><?php _e( 'Displays description with any HTML stripped out.', 'my-calendar' ); ?></dd> <dt><code>{access}</code></dt> <dd><?php _e( 'Unordered list of accessibility options for this event.', 'my-calendar' ); ?></dd> <dt><code>{image}</code></dt> <dd><?php _e( 'Image associated with the event. (HTMl)', 'my-calendar' ); ?></dd> <dt><code>{image_url}</code></dt> <dd><?php _e( 'Image associated with the event. (image URL only)', 'my-calendar' ); ?></dd> <dt><code>{full}</code></dt> <dd><?php _e( 'Event post thumbnail, full size, full HTML', 'my-calendar' ); ?></dd> <?php $sizes = get_intermediate_image_sizes(); foreach ( $sizes as $size ) { ?> <dt><code>{<?php echo $size; ?>}</code></dt> <dd><?php printf( __( 'Event post thumbnail, %s size, full HTML', 'my-calendar' ), $size ); ?></dd> <?php } ?> <dt><code>{link}</code></dt> <dd><?php _e( 'Displays the URL provided for the event.', 'my-calendar' ); ?></dd> <dt><code>{ical_link}</code></dt> <dd><?php _e( 'Produces the URL to download an iCal formatted record for the event.', 'my-calendar' ); ?></dd> <dt><code>{ical_html}</code></dt> <dd><?php _e( 'Produces a hyperlink to download an iCal formatted record for the event.', 'my-calendar' ); ?></dd> <dt><code>{gcal}</code></dt> <dd><?php _e( 'URL to submit event to Google Calendar', 'my-calendar' ); ?></dd> <dt><code>{gcal_link}</code></dt> <dd><?php _e( 'Link to submit event to Google Calendar, with class "gcal"', 'my-calendar' ); ?></dd> <dt><code>{recurs}</code></dt> <dd><?php _e( 'Shows the recurrence status of the event. (Daily, Weekly, etc.)', 'my-calendar' ); ?></dd> <dt><code>{repeats}</code></dt> <dd><?php _e( 'Shows the number of repetitions of the event.', 'my-calendar' ); ?></dd> <dt><code>{details}</code></dt> <dd><?php _e( 'Provides a link to an auto-generated page containing all information on the given event.', 'my-calendar' ); ?> <strong><?php _e( 'Requires that the site URL has been provided on the Settings page', 'my-calendar' ); ?></strong> <dt><code>{details_link}</code></dt> <dd><?php _e( 'Raw URL for the details link; empty if target URL not defined.', 'my-calendar' ); ?> <dt><code>{linking}</code></dt> <dd><?php _e( 'Provides a link to the defined event URL when present, otherwise the {details} link.', 'my-calendar' ); ?> <strong><?php _e( 'Requires that the site URL has been provided on the Settings page', 'my-calendar' ); ?></strong> <dt><code>{linking_title}</code></dt> <dd><?php _e( 'Like {link_title}, but uses {linking} instead of {link}.', 'my-calendar' ); ?> <dt><code>{event_open}</code></dt> <dd><?php _e( 'Displays text indicating whether registration for the event is currently open or closed; displays nothing if that choice is selected in the event.', 'my-calendar' ); ?></dd> <dt><code>{event_tickets}</code></dt> <dd><?php _e( 'URL to ticketing for event.', 'my-calendar' ); ?></dd> <dt><code>{event_registration}</code></dt> <dd><?php _e( 'Registration information about this event.', 'my-calendar' ); ?></dd> <dt><code>{event_status}</code></dt> <dd><?php _e( 'Displays the current status of the event: either "Published" or "Reserved" - primary used in email templates.', 'my-calendar' ); ?></dd> </dl> <h4><?php _e( 'Location Template Tags', 'my-calendar' ); ?></h4> <dl> <dt><code>{location}</code></dt> <dd><?php _e( 'Displays the name of the location of the event.', 'my-calendar' ); ?></dd> <dt><code>{street}</code></dt> <dd><?php _e( 'Displays the first line of the site address.', 'my-calendar' ); ?></dd> <dt><code>{street2}</code></dt> <dd><?php _e( 'Displays the second line of the site address.', 'my-calendar' ); ?></dd> <dt><code>{city}</code></dt> <dd><?php _e( 'Displays the city for the location.', 'my-calendar' ); ?></dd> <dt><code>{state}</code></dt> <dd><?php _e( 'Displays the state for the location.', 'my-calendar' ); ?></dd> <dt><code>{postcode}</code></dt> <dd><?php _e( 'Displays the postcode for the location.', 'my-calendar' ); ?></dd> <dt><code>{region}</code></dt> <dd><?php _e( 'Shows the custom region entered for the location.', 'my-calendar' ); ?></dd> <dt><code>{country}</code></dt> <dd><?php _e( 'Displays the country for the event location.', 'my-calendar' ); ?></dd> <dt><code>{sitelink}</code></dt> <dd><?php _e( 'Output the URL for the location link.', 'my-calendar' ); ?></dd> <dt><code>{phone}</code></dt> <dd><?php _e( 'Output the stored phone number for the location.', 'my-calendar' ); ?></dd> <dt><code>{sitelink_html}</code></dt> <dd><?php _e( 'Output a hyperlink to the location\'s listed link with default link text.', 'my-calendar' ); ?></dd> <dt><code>{hcard}</code></dt> <dd><?php _e( 'Displays the event address in <a href="http://microformats.org/wiki/hcard">hcard</a> format.', 'my-calendar' ); ?></dd> <dt><code>{link_map}</code></dt> <dd><?php _e( 'Displays a link to a Google Map of the event, if sufficient address information is available. If not, will be empty.', 'my-calendar' ); ?></dd> <dt><code>{map_url}</code></dt> <dd><?php _e( 'Produces the URL for the Google Map for the event location if sufficient address information is available. If not, will be empty.', 'my-calendar' ); ?></dd> <dt><code>{map}</code></dt> <dd><?php _e( 'Output Google Map if sufficient address information is available. If not, will be empty.', 'my-calendar' ); ?></dd> <dt><code>{location_access}</code></dt> <dd><?php _e( 'Unordered list of accessibility options for this location.', 'my-calendar' ); ?></dd> </dl> <h4><?php _e( 'Category Template Tags', 'my-calendar' ); ?></h4> <dl> <dt><code>{category}</code></dt> <dd><?php _e( 'Displays the name of the category the event is in.', 'my-calendar' ); ?></dd> <dt><code>{icon}</code></dt> <dd><?php _e( 'Produces the address of the current event\'s category icon.', 'my-calendar' ); ?></dd> <dt><code>{icon_html}</code></dt> <dd><?php _e( 'Produces the HTML for the current event\'s category icon.', 'my-calendar' ); ?></dd> <dt><code>{color}</code></dt> <dd><?php _e( 'Produces the hex code for the current event\'s category color.', 'my-calendar' ); ?></dd> <dt><code>{cat_id}</code></dt> <dd><?php _e( 'Displays the ID for the category the event is in.', 'my-calendar' ); ?></dd> </dl> <h4><?php _e( 'Special use Template Tags', 'my-calendar' ); ?></h4> <dl> <dt><code>{dateid}</code></dt> <dd><?php _e( 'A unique ID for the current instance of an event.', 'my-calendar' ); ?></dd> <dt><code>{id}</code></dt> <dd><?php _e( 'The ID for the event record associated with the current instance of an event.', 'my-calendar' ); ?></dd> </dl> <?php do_action( 'mc_after_help' ); ?> </div> </div> </div> <div class="ui-sortable meta-box-sortables" id="get-support"> <div class="postbox"> <h3 id="support"><?php _e( 'Get Plug-in Support', 'my-calendar' ); ?></h3> <div class="inside"> <?php if ( current_user_can( 'administrator' ) ) { ?> <?php jcd_get_support_form(); ?> <?php } else { ?> <?php _e( 'My Calendar support requests can only be sent by administrators.', 'my-calendar' ); ?> <?php } ?> </div> </div> <div class="ui-sortable meta-box-sortables" id="notes"> <div class="postbox"> <h3 id="help"><?php _e( 'Helpful Information', 'my-calendar' ); ?></h3> <div class="inside"> <p> <?php _e( '<strong>Uninstalling the plugin</strong>: Although the WordPress standard and expectation is for plug-ins to delete any custom database tables when they\'re uninstalled, My Calendar <em>does not do this</em>. This was a conscious decision on my part -- the data stored in your My Calendar tables is yours; with the sole exception of the "General" category, you added every piece of it yourself. As such, I feel it would be a major disservice to you to delete this information if you uninstall the plug-in. As a result, if you wish to get rid of the plug-in completely, you\'ll need to remove those tables yourself. All your My Calendar settings will be deleted, however.', 'my-calendar' ); ?> </p> <p> <?php _e( '<strong>Donations</strong>: I appreciate anything you can give. $2 may not seem like much, but it can really add up when thousands of people are using the software. Please note that I am not a non-profit organization, and your gifts are not tax deductible. Thank you!', 'my-calendar' ); ?> </p> </div> </div> </div> </div> </div> </div> </div> <?php mc_show_sidebar(); ?> </div> <?php } ?>
gpl-2.0
b4um1/wasserapp
Wasser-App/src/at/fhhgb/mc/wasserapp/parser/WaterlevelJSONParser.java
2454
package at.fhhgb.mc.wasserapp.parser; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import android.util.Log; public class WaterlevelJSONParser { private final String MEASURINGPOINT_ID = "measuringpoint_id"; private final String TIMESTAMP = "time_stamp"; private final String WATERLEVEL = "waterlevel"; private final String LOGTAG = "WaterlevelJSONParser"; /** * Receives an String which is an json encoded array It returns an array of * waterlevels * * @param _jsonResult * @return * @throws ParseException */ public List<HashMap<String, String>> parse(String _jsonResult) throws ParseException { Log.i(LOGTAG, "Parsing-process started"); JSONParser parser = new JSONParser(); Object obj = parser.parse(_jsonResult); JSONArray array = (JSONArray) obj; return getWaterlevels(array); } /** * Returns a List of Hashmaps which represents all the waterlevels * * @param _jArray * @return List<Hashmap<String,String>> */ private List<HashMap<String, String>> getWaterlevels(JSONArray _jArray) { int count = _jArray.size(); List<HashMap<String, String>> waterlevelList = new ArrayList<HashMap<String, String>>(); HashMap<String, String> waterlevel = null; for (int i = 0; i < count; i++) { waterlevel = getWaterlevel((JSONObject) _jArray.get(i)); waterlevelList.add(waterlevel); } return waterlevelList; } /** * Parses the json-object into a Hashmap<Key,value> * * @param _jWaterlevel * @return */ private HashMap<String, String> getWaterlevel(JSONObject _jWaterlevel) { HashMap<String, String> map = new HashMap<String, String>(); String measuringpointId = "-1"; String timestamp = "-1"; String waterlevel = "-1"; if (_jWaterlevel.containsKey(MEASURINGPOINT_ID)) { measuringpointId = "" + _jWaterlevel.get(MEASURINGPOINT_ID); } if (_jWaterlevel.containsKey(TIMESTAMP)) { timestamp = "" + _jWaterlevel.get(TIMESTAMP); } if (_jWaterlevel.containsKey(WATERLEVEL)) { waterlevel = "" + _jWaterlevel.get(WATERLEVEL); } map.put("measuringpointId", measuringpointId); map.put("timestamp", timestamp); map.put("waterlevel", waterlevel); return map; } }
gpl-2.0
Tim-Snow/Sumo
src/Camera.cpp
1121
#include "Camera.h" Camera* Camera::c = 0; Camera::~Camera() { // TODO Auto-generated destructor stub } void Camera::lookAt(const Point3 &eye, const Point3 &point, const Vector3 &up) { camera = new Matrix4(camera->lookAt(eye, point, up)); } void Camera::setCamera(const Matrix4 & m) { Matrix4 * tmp = camera; camera = new Matrix4(m); delete (tmp); } float* Camera::getCamera() { float * f = new float[16]; f[0] = camera->getCol0().getX(); f[4] = camera->getCol0().getY(); f[8] = camera->getCol0().getZ(); f[12] = camera->getCol0().getW(); f[1] = camera->getCol1().getX(); f[5] = camera->getCol1().getY(); f[9] = camera->getCol1().getZ(); f[13] = camera->getCol1().getW(); f[2] = camera->getCol2().getX(); f[6] = camera->getCol2().getY(); f[10] = camera->getCol2().getZ(); f[14] = camera->getCol2().getW(); f[3] = camera->getCol3().getX(); f[7] = camera->getCol3().getY(); f[11] = camera->getCol3().getZ(); f[15] = camera->getCol3().getW(); return f; } Matrix4& Camera::getCameraM() { return *camera; } Camera& Camera::getInstance() { if (0 == c) { c = new Camera(); } return (*c); }
gpl-2.0
imyuka/AFL
crawler_prototype/AFL/frmAge.Designer.cs
4154
namespace AFL { partial class frmAge { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.button2 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 38); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(41, 13); this.label1.TabIndex = 3; this.label1.Text = "Ready."; // // button1 // this.button1.Location = new System.Drawing.Point(12, 12); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 2; this.button1.Text = "Start"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(93, 14); this.textBox1.MaxLength = 3; this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(49, 20); this.textBox1.TabIndex = 4; this.textBox1.Text = "10"; this.textBox1.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // button2 // this.button2.Location = new System.Drawing.Point(247, 12); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(75, 23); this.button2.TabIndex = 5; this.button2.Text = "Close"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); // // frmAge // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(334, 66); this.ControlBox = false; this.Controls.Add(this.button2); this.Controls.Add(this.textBox1); this.Controls.Add(this.label1); this.Controls.Add(this.button1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frmAge"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmAge_FormClosing); this.Load += new System.EventHandler(this.frmAge_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Button button2; } }
gpl-2.0
ruizu/pq-array
types.go
1005
package pqarray import ( "strconv" ) type Int64Slice []int64 func (is *Int64Slice) Scan(value interface{}) error { if value == nil { return nil } val := string(value.([]byte)) parsed := parse(val) converted := []int64{} for _, v := range parsed { pv, err := strconv.ParseInt(v, 10, 64) if err != nil { return nil } converted = append(converted, pv) } (*is) = Int64Slice(converted) return nil } type Float64Slice []float64 func (fs *Float64Slice) Scan(value interface{}) error { if value == nil { return nil } val := string(value.([]byte)) parsed := parse(val) converted := []float64{} for _, v := range parsed { pv, err := strconv.ParseFloat(v, 64) if err != nil { return nil } converted = append(converted, pv) } (*fs) = Float64Slice(converted) return nil } type StringSlice []string func (ss *StringSlice) Scan(value interface{}) error { if value == nil { return nil } val := string(value.([]byte)) (*ss) = StringSlice(parse(val)) return nil }
gpl-2.0
imglib/imglib2-script
src/main/java/net/imglib2/script/color/Hue.java
1691
/* * #%L * ImgLib2: a general-purpose, multidimensional image processing library. * %% * Copyright (C) 2009 - 2016 Tobias Pietzsch, Stephan Preibisch, Stephan Saalfeld, * John Bogovic, Albert Cardona, Barry DeZonia, Christian Dietz, Jan Funke, * Aivar Grislis, Jonathan Hale, Grant Harris, Stefan Helfrich, Mark Hiner, * Martin Horn, Steffen Jaensch, Lee Kamentsky, Larry Lindsey, Melissa Linkert, * Mark Longair, Brian Northan, Nick Perry, Curtis Rueden, Johannes Schindelin, * Jean-Yves Tinevez and Michael Zinsmaier. * %% * 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/gpl-2.0.html>. * #L% */ package net.imglib2.script.color; import net.imglib2.IterableRealInterval; import net.imglib2.script.color.fn.HSBOp; import net.imglib2.type.numeric.ARGBType; /** Extracts the HSB saturation of an RGB pixel. */ /** * TODO * */ public class Hue extends HSBOp { /** Extract the hue component of each pixel, in the range [0, 1]. */ public Hue(final IterableRealInterval<? extends ARGBType> img) { super(img); } @Override protected final int getIndex() { return 0; } }
gpl-2.0
jmayer13/SAlmox
src/uni/uri/salmox/view/DocumentTableModel.java
5510
/*- * Classname: DocumentTableModel.java * * Version information: 1.0 * * Date: 19/03/2013 - 13:31:32 * * author: Jonas Mayer (jmayer13@hotmail.com) * Copyright notice: (informações do método, pra que serve, idéia principal) */ package uni.uri.salmox.view; import java.util.Collections; import java.util.List; import javax.swing.table.AbstractTableModel; import uni.uri.salmox.model.Document; /** * Modelo para tabela de documentos * * @see * @author Jonas Mayer (jmayer13@hotmail.com) */ public class DocumentTableModel extends AbstractTableModel { //lista com documentos na tabela private List<Document> documents; //número de colunas private int COLUMN_NUMBER = 2; //coluna de código dos livros private int COLUMN_CODE = 0; //coluna de título de livro private int COLUMN_TITLE = 1; /** * Construtor com lista de documentos * * @param documents documentos */ public DocumentTableModel(List<Document> documents) { this.documents = documents; order(); fireTableDataChanged(); }//fim do construtor com lista de documentos /** * Retorna número de linhas * * @return <code>Integer</code> número de linhas */ public int getRowCount() { return documents.size(); }//fim do método getRowCount /** * Retorna número de colunas * * @return <code>Integer</code> numero de colunas */ public int getColumnCount() { return COLUMN_NUMBER; }//fim do método getColumnCount /** * Retorna o nome da coluna * * @param columnIndex índice da coluna * @return <code>String</code> com nome da coluna */ @Override public String getColumnName(int columnIndex) { if (columnIndex == COLUMN_CODE) { return "Código"; } else if (columnIndex == COLUMN_TITLE) { return "Título"; } else { return ""; } }//fim do método getColumnName /** * Retorna classe da coluna * * @param columnIndex índice da coluna * @return <code>Class</code> da coluna */ @Override public Class getColumnClass(int columnIndex) { if (columnIndex == COLUMN_CODE) { return Integer.class; } else if (columnIndex == COLUMN_TITLE) { return String.class; } else { return null; } }//fim do método getColumnClass /** * Retorna valor de célula da tabela * * @param rowIndex índice da linha * @param columnIndex índice da coluna * @return <code>Object</code> valor da céluna */ public Object getValueAt(int rowIndex, int columnIndex) { Document document = documents.get(rowIndex); if (columnIndex == COLUMN_CODE) { return document.getCodeDocumentSpecific(); } else if (columnIndex == COLUMN_TITLE) { return document.getTitleDocument(); } else { return ""; } }//fim do método getValueAt /** * Retorna valor indicando se a célula é editavel * * @param rowIndex índice da linha * @param columnIndex índice da coluna * @return <code>Boolean</code> editável */ @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; }//fim do método isCellEditable /** * Retorna documento da linha especificada * * @param rowIndex índice da linha * @return <code>Document</code> documento da linha */ public Document getRow(int rowIndex) { return documents.get(rowIndex); }//fim do método getRow /** * Adiciona um documento a tabela * * @param document documento */ public void addRow(Document document) { documents.add(document); order(); fireTableDataChanged(); }//fim do método addRow /** * Remove um documento da tabela * * @param rowIndex índice da linha */ public void eraseRow(int rowIndex) { documents.remove(rowIndex); order(); fireTableDataChanged(); }//fim do método eraseRow com índice /** * Remove um documento da tabela * * @param document documento */ public void eraseRow(Document document) { documents.remove(document); order(); fireTableDataChanged(); }//fim do método eraseRow com caixa /** * Ordena tabela */ public void order() { Collections.sort(documents, Document.forCategoryCode); }//fim do método order /** * Atualiza tabela * * @param document lista com documentos */ public void refresh(List<Document> documents) { this.documents = documents; order(); fireTableDataChanged(); }//fim do método refresh /** * Obtêm a posição do documemto com código informado * * @param selectedCodeDocument código do documento * @return <code>Integer</code> com posição do documento */ public int getDocumentPosition(int selectedCodeDocument) { order(); for (int i = 0; i < documents.size(); i++) { if (documents.get(i).getCodeDocument() == selectedCodeDocument) { return i; } } return -1; }//fim do método getDocumentPosition }//fim da classe DocumentTableModel
gpl-2.0
oliviernolbert/SEBLOD
administrator/modules/mod_cck_menu/tmpl/default_disabled.php
487
<?php /** * @version SEBLOD 3.x Core ~ $Id: default_disabled.php sebastienheraud $ * @package SEBLOD (App Builder & CCK) // SEBLOD nano (Form Builder) * @url https://www.seblod.com * @editor Octopoos - www.octopoos.com * @copyright Copyright (C) 2009 - 2017 SEBLOD. All Rights Reserved. * @license GNU General Public License version 2 or later; see _LICENSE.php **/ defined( '_JEXEC' ) or die; // Root $menu->addChild( new JMenuNode( $root, NULL, 'disabled' ), true ); ?>
gpl-2.0
georgejhunt/HaitiDictionary.activity
data/words/presan.js
56
showWord(["a. ","ki pa ka tann, ki dwe fèt tousuit." ])
gpl-2.0
alexeyche/snn_sim_old
r_package/Rsnn/src/RPrepLayer.cpp
25
#include "RPrepLayer.h"
gpl-2.0
chisimba/modules
workgroupadmin/templates/content/managenew_tpl.php
1658
<?php //echo '<pre>'; //echo $dump; //echo "TEMPLATE:\n"; //var_dump($members); //echo '</pre>'; $pageTitle = $this->newObject('htmlheading','htmlelements'); $pageTitle->type=1; $pageTitle->align='left'; $pageTitle->str=ucwords($objLanguage->code2Txt("mod_workgroupadmin_workgroup",'workgroupadmin'))." : ".$workgroup['description']; echo $pageTitle->show(); $objForm = $this->newObject('form','htmlelements'); $objForm->name = "form1"; $objForm->action = $this->uri ( array( 'action' => 'processform', 'workgroupId'=>$workgroup['id'] ) ); // Create the selectbox object $objSelectBox = $this->newObject('selectbox','htmlelements'); // Initialise the selectbox. $objSelectBox->create( $objForm, 'leftList[]', ucfirst($objLanguage->code2Txt('mod_workgroupadmin_users_in_course','workgroupadmin')), 'rightList[]', ucfirst($objLanguage->code2Txt('mod_workgroupadmin_members','workgroupadmin')) ); $objSelectBox->objLeftList->extra = ' multiple="1" size="10" style="width:20em;" '; $objSelectBox->objRightList->extra = ' multiple="1" size="10" style="width:20em;" '; // Populate the selectboxes $objSelectBox->insertLeftOptions( $users, 'userid', 'display' ); $objSelectBox->insertRightOptions( $members, 'userid', 'display' ); // Insert the selectbox into the form object. $objForm->addToForm( $objSelectBox->show() ); // Get and insert the save and cancel form buttons $arrFormButtons = $objSelectBox->getFormButtons(); $objForm->addToForm( implode( ' / ', $arrFormButtons ) ); // Show the form echo "<div class='innerwrapper'>".$objForm->show()."</div>"; ?>
gpl-2.0
Chase-C/Agriculture-Tycoon
Sound.js
268
var selectSound = new Audio("audio/select.wav"); selectSound.addEventListener('ended', function(){ this.currentTime = 0; }); var soundtrack = new Audio("audio/soundtrack.mp3"); soundtrack.addEventListener('ended', function(){ this.currentTime = 0; this.play(); });
gpl-2.0
tamviettech/e-par
public_html/apps/r3/modules/record/record_views/print_cancel_request.php
5836
<?php defined('DS') or die(); /* @var $this \View */ $dom_unit_info = simplexml_load_file(SERVER_ROOT . 'public/xml/xml_unit_info.xml'); $dom_data = simplexml_load_string($arr_single_record['C_XML_DATA']); $now = date_create($now); ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>In giấy bàn giao hồ sơ</title> <link rel="stylesheet" href="/lang-giang/public/css/reset.css" type="text/css" media="all" /> <link rel="stylesheet" href="/lang-giang/public/css/text.css" type="text/css" media="screen" /> <link rel="stylesheet" href="/lang-giang/public/css/printer.css" type="text/css" media="all" /> <script src="/lang-giang/public/js/jquery/jquery.min.js" type="text/javascript"></script> </head> <body> <div class="print-button"> <input type="button" value="In trang" onclick="window.print(); return false;"> <input type="button" value="Đóng cửa sổ" onclick="window.parent.hidePopWin(false)"> </div> <div> <!-- header --> <h3><center>CỘNG HÒA XÃ HỘI CHỦ NGHĨA VIỆT NAM</center></h3> <h4> <center>Độc lập - Tự do - Hạnh phúc</center> <center>___________________________</center> </h4> <br/> <h2><center>ĐƠN XIN RÚT HỒ SƠ</center></h2> <p align="center">Kính gửi: <?php echo xpath($dom_unit_info, '//full_name', XPATH_STRING) ?></p> <br/> <table border="0" cellpadding="0" cellspacing="0" width="100%" class=""> <colgroup> <col width="5%"> <col width="95%"> </colgroup> <tbody> <tr> <td>1.</td> <td>Thông tin cơ bản:</td> </tr> <tr> <td>&nbsp;</td> <td class="dots"><label>Họ tên người nộp: </label></td> </tr> <tr> <td>&nbsp;</td> <td class="dots"><label>Địa chỉ: </label></td> </tr> <tr> <td>&nbsp;</td> <td class="dots"><label>Số điện thoại: </label></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>2.</td> <td>Hồ sơ xin rút:</td> </tr> <tr> <td></td> <td class="dots"><label>Mã hồ sơ: <?php echo $arr_single_record['C_RECORD_NO'] ?></label></td> </tr> <tr> <td>&nbsp;</td> <td class="dots">&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td class="">&nbsp;</td> </tr> <tr> <td>3.</td> <td class="dots"><label>Lý do:</label></td> </tr> </tr> <tr> <td>&nbsp;</td> <td class="dots">&nbsp;</td> </tr> </tr> <tr> <td>&nbsp;</td> <td class="dots">&nbsp;</td> </tr> </tbody> </table> <br/> <p align="right"> <?php echo xpath($dom_unit_info, '//name', XPATH_STRING) ?>,&nbsp; ngày <?php echo $now->format('d') ?>&nbsp; tháng <?php echo $now->format('m') ?>&nbsp; năm <?php echo $now->format('Y') ?> </p> <br/> <table border="0" cellpadding="0" cellspacing="0" width="100%" class="tbl-signer"> <tbody> <tr> <td> <strong>NGƯỜI NỘP</strong> <br> <i>(Ký, ghi rõ họ tên)</i> </td> <td style="height: 150px; align:center"> <strong>CÁN BỘ TIẾP NHẬN</strong> <br> <i>(Ký, ghi rõ họ tên)</i> </td> <td style="height: 150px; align:center"> <strong>ĐẠI DIỆN PHÒNG BAN CHUYÊN MÔN</strong><br> <i>(Ký, ghi rõ họ tên)</i> </td> </tr> <tr> <td style="width:33%"> <strong></strong> </td> <td style="height: 150px; align:center;width:33%"> <strong><span style="text-transform: uppercase;"><?php echo Session::get('user_name') ?></span></strong> </td> <td style="height: 150px; align:center;text-transform: uppercase;width:33%"> <strong></strong> </td> </tr> </tbody> </table> </div> </body> </html>
gpl-2.0
JaysonChan/OnlineMall
src/main/java/com/mall/service/category/impl/CategoryService.java
1061
package com.mall.service.category.impl; import com.mall.dao.category.AbstractCategoryDao; import com.mall.orm.category.Category; import com.mall.service.category.ICategoryService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.io.Serializable; import java.util.List; /** * Created by Jayson on 2014/8/11. */ @Service("CategoryService") public class CategoryService implements ICategoryService { @Resource(name = "CategoryDao") private AbstractCategoryDao categoryDao; @Override public Serializable save(Category category) { return categoryDao.save(category); } @Override public List<Category> list() { return categoryDao.list(Category.class); } @Override public Category get(int id) { return categoryDao.get(Category.class , id); } @Override public void delete(Category category) { categoryDao.delete(category); } @Override public void update(Category category) { categoryDao.update(category); } }
gpl-2.0
cholalabs/CholaApps2.0
modules/mod_articles_latest/helper.php
3293
<?php /** * @version $Id: helper.php 20541 2011-02-03 21:12:06Z dextercowley $ * @package Chola.Site * @subpackage mod_articles_latest * @copyright Copyright (C) 2005 - 2011 Cholalabs Software LLP. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ // no direct access defined('_JEXEC') or die; require_once JPATH_SITE.'/components/com_content/helpers/route.php'; jimport('chola.application.component.model'); JModel::addIncludePath(JPATH_SITE.'/components/com_content/models', 'ContentModel'); abstract class modArticlesLatestHelper { public static function getList(&$params) { // Get the dbo $db = JFactory::getDbo(); // Get an instance of the generic articles model $model = JModel::getInstance('Articles', 'ContentModel', array('ignore_request' => true)); // Set application parameters in model $app = JFactory::getApplication(); $appParams = $app->getParams(); $model->setState('params', $appParams); // Set the filters based on the module params $model->setState('list.start', 0); $model->setState('list.limit', (int) $params->get('count', 5)); $model->setState('filter.published', 1); // Access filter $access = !JComponentHelper::getParams('com_content')->get('show_noauth'); $authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id')); $model->setState('filter.access', $access); // Category filter $model->setState('filter.category_id', $params->get('catid', array())); // User filter $userId = JFactory::getUser()->get('id'); switch ($params->get('user_id')) { case 'by_me': $model->setState('filter.author_id', (int) $userId); break; case 'not_me': $model->setState('filter.author_id', $userId); $model->setState('filter.author_id.include', false); break; case '0': break; default: $model->setState('filter.author_id', (int) $params->get('user_id')); break; } // Filter by language $model->setState('filter.language',$app->getLanguageFilter()); // Featured switch switch ($params->get('show_featured')) { case '1': $model->setState('filter.featured', 'only'); break; case '0': $model->setState('filter.featured', 'hide'); break; default: $model->setState('filter.featured', 'show'); break; } // Set ordering $order_map = array( 'm_dsc' => 'a.modified DESC, a.created', 'mc_dsc' => 'CASE WHEN (a.modified = '.$db->quote($db->getNullDate()).') THEN a.created ELSE a.modified END', 'c_dsc' => 'a.created', 'p_dsc' => 'a.publish_up', ); $ordering = JArrayHelper::getValue($order_map, $params->get('ordering'), 'a.publish_up'); $dir = 'DESC'; $model->setState('list.ordering', $ordering); $model->setState('list.direction', $dir); $items = $model->getItems(); foreach ($items as &$item) { $item->slug = $item->id.':'.$item->alias; $item->catslug = $item->catid.':'.$item->category_alias; if ($access || in_array($item->access, $authorised)) { // We know that user has the privilege to view the article $item->link = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catslug)); } else { $item->link = JRoute::_('index.php?option=com_user&view=login'); } } return $items; } }
gpl-2.0