repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
textbookmania/Tomato
app/client/templates/Pages/BanUser/banUser.js
392
/** * Created by mike on 12/5/2015. */ Meteor.subscribe("bannedUsers"); /* submit button for ban user. take value from html and adds name to banned user collection */ Template.banUser.events({ 'submit form': function (e) { e.preventDefault(); var username = $(e.target).find('[id=banuser]').val(); Meteor.call('insertBannedUser', username); Router.go('Home'); } });
gpl-2.0
woakes070048/glpi-bootstrap
inc/ruledictionnaryprintermodel.class.php
2149
<?php /* * @version $Id$ ------------------------------------------------------------------------- GLPI - Gestionnaire Libre de Parc Informatique Copyright (C) 2003-2014 by the INDEPNET Development Team. http://indepnet.net/ http://glpi-project.org ------------------------------------------------------------------------- LICENSE This file is part of GLPI. GLPI 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. GLPI 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 GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief */ class RuleDictionnaryPrinterModel extends RuleDictionnaryDropdown { /** * Constructor **/ function __construct() { parent::__construct('RuleDictionnaryPrinterModel'); } /** * @see Rule::getCriterias() **/ function getCriterias() { static $criterias = array(); if (count($criterias)) { return $criterias; } $criterias['name']['field'] = 'name'; $criterias['name']['name'] = __('Model'); $criterias['name']['table'] = 'glpi_printermodels'; $criterias['manufacturer']['field'] = 'name'; $criterias['manufacturer']['name'] = __('Manufacturer'); $criterias['manufacturer']['table'] = 'glpi_manufacturers'; return $criterias; } /** * @see Rule::getActions() **/ function getActions() { $actions = array(); $actions['name']['name'] = __('Model'); $actions['name']['force_actions'] = array('assign', 'regex_result', 'append_regex_result'); return $actions; } } ?>
gpl-2.0
Vika777/cafe
wp-content/themes/Bistro2/homepage.php
4029
<?php /** * The template for displaying homepage. * Template name: Homepage * * @package fabthemes */ get_header(); ?> <!-- Latest recipes --> <div class="home-section"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="section-title"> <h2> <?php echo _e( 'Последние рецепты', 'fabthemes' );?> </h2> <span> <?php echo _e( 'Наши новые рецепты', 'fabthemes' );?></span> </div> </div> <div class="grid-cover"> <?php $count=6; $args = array( 'posts_per_page' => $count, // Limit count 'post_type' => 'recipe', // Query for the default Post type ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); ?> <div class="col-sm-4"> <div class="grid-box"> <div class="grid-pic"> <div class="gp-overlay"> <?php $thumb = get_post_thumbnail_id(); $img_url = wp_get_attachment_url( $thumb,'full' ); ?> <span class="light"> <a rel="prettyPhoto[pp_gal]" href='<?php echo $img_url?>'> <i class="fa fa-arrows-alt"></i> </a> </span> <span class="hyper"> <a href="<?php the_permalink(); ?>"> <i class="fa fa-cutlery"></i> </a> </span> </div> <?php $thumb = get_post_thumbnail_id(); $img_url = wp_get_attachment_url( $thumb,'full' ); //get full URL to image (use "large" or "medium" if the images too big) $image = aq_resize( $img_url, 720, 480, true,true,true ); //resize & crop the image ?> <?php if($image) : ?> <a href="<?php the_permalink(); ?>"> <img src="<?php echo $image ?>" alt="<?php the_title(); ?>" /></a> <?php endif; ?> </div> <div class="grid-entry"> <h2> <a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a> </h2> <div class="grid-meta"> <span> <?php echo get_the_term_list( $post->ID, 'type', 'Рубрика: ', ', ' ); ?> </span> <span> <?php echo get_the_term_list( $post->ID, 'cuisine', 'Кухня: ', ', ' ); ?></span> </div> </div> </div> </div> <?php endwhile; ?> <?php wp_reset_postdata(); ?> </div> </div></div> </div> <!-- Latest recipes end--> <!-- Latest posts --> <div class="home-section"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="section-title"> <h2> <?php echo _e( 'Последние записи', 'fabthemes' );?> </h2> <span> <?php echo _e( 'Последние записи из нашего блога', 'fabthemes' );?></span> </div> </div> <div class="grid-cover"> <?php $count=3; $args = array( 'posts_per_page' => $count, // Limit count ); $query = new WP_Query( $args ); while ( $query->have_posts() ) : $query->the_post(); ?> <div class="col-sm-4"> <div class="grid-box"> <div class="grid-pic"> <?php $thumb = get_post_thumbnail_id(); $img_url = wp_get_attachment_url( $thumb,'full' ); //get full URL to image (use "large" or "medium" if the images too big) $image = aq_resize( $img_url, 720, 480, true,true,true ); //resize & crop the image ?> <?php if($image) : ?> <a href="<?php the_permalink(); ?>"> <img src="<?php echo $image ?>" alt="<?php the_title(); ?>" /> </a> <?php endif; ?> </div> <div class="grid-entry"> <div class="grid_title"> <h2> <a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a> </h2> <div class="grid-meta"> <span> <?php echo _e( 'Posted in', 'fabthemes' );?> <?php the_category(', '); ?></span> </div> </div> <div class="entry-content"> <p> <?php $excerpt = get_the_excerpt(); echo string_limit_words($excerpt,25); ?> </p> </div> </div> </div> </div> <?php endwhile; ?> <?php wp_reset_postdata(); ?> </div> </div> </div> </div> <!-- Latest Posts end --> <?php get_footer(); ?>
gpl-2.0
NavigateCMS/Navigate-CMS
lib/vendor/voku/portable-ascii/src/voku/helper/data/x086.php
5902
<?php return [ 'Tuo ', // 0x00 'Wu ', // 0x01 'Rui ', // 0x02 'Rui ', // 0x03 'Qi ', // 0x04 'Heng ', // 0x05 'Lu ', // 0x06 'Su ', // 0x07 'Tui ', // 0x08 'Mang ', // 0x09 'Yun ', // 0x0a 'Pin ', // 0x0b 'Yu ', // 0x0c 'Xun ', // 0x0d 'Ji ', // 0x0e 'Jiong ', // 0x0f 'Xian ', // 0x10 'Mo ', // 0x11 'Hagi ', // 0x12 'Su ', // 0x13 'Jiong ', // 0x14 '[?] ', // 0x15 'Nie ', // 0x16 'Bo ', // 0x17 'Rang ', // 0x18 'Yi ', // 0x19 'Xian ', // 0x1a 'Yu ', // 0x1b 'Ju ', // 0x1c 'Lian ', // 0x1d 'Lian ', // 0x1e 'Yin ', // 0x1f 'Qiang ', // 0x20 'Ying ', // 0x21 'Long ', // 0x22 'Tong ', // 0x23 'Wei ', // 0x24 'Yue ', // 0x25 'Ling ', // 0x26 'Qu ', // 0x27 'Yao ', // 0x28 'Fan ', // 0x29 'Mi ', // 0x2a 'Lan ', // 0x2b 'Kui ', // 0x2c 'Lan ', // 0x2d 'Ji ', // 0x2e 'Dang ', // 0x2f 'Katsura ', // 0x30 'Lei ', // 0x31 'Lei ', // 0x32 'Hua ', // 0x33 'Feng ', // 0x34 'Zhi ', // 0x35 'Wei ', // 0x36 'Kui ', // 0x37 'Zhan ', // 0x38 'Huai ', // 0x39 'Li ', // 0x3a 'Ji ', // 0x3b 'Mi ', // 0x3c 'Lei ', // 0x3d 'Huai ', // 0x3e 'Luo ', // 0x3f 'Ji ', // 0x40 'Kui ', // 0x41 'Lu ', // 0x42 'Jian ', // 0x43 'San ', // 0x44 '[?] ', // 0x45 'Lei ', // 0x46 'Quan ', // 0x47 'Xiao ', // 0x48 'Yi ', // 0x49 'Luan ', // 0x4a 'Men ', // 0x4b 'Bie ', // 0x4c 'Hu ', // 0x4d 'Hu ', // 0x4e 'Lu ', // 0x4f 'Nue ', // 0x50 'Lu ', // 0x51 'Si ', // 0x52 'Xiao ', // 0x53 'Qian ', // 0x54 'Chu ', // 0x55 'Hu ', // 0x56 'Xu ', // 0x57 'Cuo ', // 0x58 'Fu ', // 0x59 'Xu ', // 0x5a 'Xu ', // 0x5b 'Lu ', // 0x5c 'Hu ', // 0x5d 'Yu ', // 0x5e 'Hao ', // 0x5f 'Jiao ', // 0x60 'Ju ', // 0x61 'Guo ', // 0x62 'Bao ', // 0x63 'Yan ', // 0x64 'Zhan ', // 0x65 'Zhan ', // 0x66 'Kui ', // 0x67 'Ban ', // 0x68 'Xi ', // 0x69 'Shu ', // 0x6a 'Chong ', // 0x6b 'Qiu ', // 0x6c 'Diao ', // 0x6d 'Ji ', // 0x6e 'Qiu ', // 0x6f 'Cheng ', // 0x70 'Shi ', // 0x71 '[?] ', // 0x72 'Di ', // 0x73 'Zhe ', // 0x74 'She ', // 0x75 'Yu ', // 0x76 'Gan ', // 0x77 'Zi ', // 0x78 'Hong ', // 0x79 'Hui ', // 0x7a 'Meng ', // 0x7b 'Ge ', // 0x7c 'Sui ', // 0x7d 'Xia ', // 0x7e 'Chai ', // 0x7f 'Shi ', // 0x80 'Yi ', // 0x81 'Ma ', // 0x82 'Xiang ', // 0x83 'Fang ', // 0x84 'E ', // 0x85 'Pa ', // 0x86 'Chi ', // 0x87 'Qian ', // 0x88 'Wen ', // 0x89 'Wen ', // 0x8a 'Rui ', // 0x8b 'Bang ', // 0x8c 'Bi ', // 0x8d 'Yue ', // 0x8e 'Yue ', // 0x8f 'Jun ', // 0x90 'Qi ', // 0x91 'Ran ', // 0x92 'Yin ', // 0x93 'Qi ', // 0x94 'Tian ', // 0x95 'Yuan ', // 0x96 'Jue ', // 0x97 'Hui ', // 0x98 'Qin ', // 0x99 'Qi ', // 0x9a 'Zhong ', // 0x9b 'Ya ', // 0x9c 'Ci ', // 0x9d 'Mu ', // 0x9e 'Wang ', // 0x9f 'Fen ', // 0xa0 'Fen ', // 0xa1 'Hang ', // 0xa2 'Gong ', // 0xa3 'Zao ', // 0xa4 'Fu ', // 0xa5 'Ran ', // 0xa6 'Jie ', // 0xa7 'Fu ', // 0xa8 'Chi ', // 0xa9 'Dou ', // 0xaa 'Piao ', // 0xab 'Xian ', // 0xac 'Ni ', // 0xad 'Te ', // 0xae 'Qiu ', // 0xaf 'You ', // 0xb0 'Zha ', // 0xb1 'Ping ', // 0xb2 'Chi ', // 0xb3 'You ', // 0xb4 'He ', // 0xb5 'Han ', // 0xb6 'Ju ', // 0xb7 'Li ', // 0xb8 'Fu ', // 0xb9 'Ran ', // 0xba 'Zha ', // 0xbb 'Gou ', // 0xbc 'Pi ', // 0xbd 'Bo ', // 0xbe 'Xian ', // 0xbf 'Zhu ', // 0xc0 'Diao ', // 0xc1 'Bie ', // 0xc2 'Bing ', // 0xc3 'Gu ', // 0xc4 'Ran ', // 0xc5 'Qu ', // 0xc6 'She ', // 0xc7 'Tie ', // 0xc8 'Ling ', // 0xc9 'Gu ', // 0xca 'Dan ', // 0xcb 'Gu ', // 0xcc 'Ying ', // 0xcd 'Li ', // 0xce 'Cheng ', // 0xcf 'Qu ', // 0xd0 'Mou ', // 0xd1 'Ge ', // 0xd2 'Ci ', // 0xd3 'Hui ', // 0xd4 'Hui ', // 0xd5 'Mang ', // 0xd6 'Fu ', // 0xd7 'Yang ', // 0xd8 'Wa ', // 0xd9 'Lie ', // 0xda 'Zhu ', // 0xdb 'Yi ', // 0xdc 'Xian ', // 0xdd 'Kuo ', // 0xde 'Jiao ', // 0xdf 'Li ', // 0xe0 'Yi ', // 0xe1 'Ping ', // 0xe2 'Ji ', // 0xe3 'Ha ', // 0xe4 'She ', // 0xe5 'Yi ', // 0xe6 'Wang ', // 0xe7 'Mo ', // 0xe8 'Qiong ', // 0xe9 'Qie ', // 0xea 'Gui ', // 0xeb 'Gong ', // 0xec 'Zhi ', // 0xed 'Man ', // 0xee 'Ebi ', // 0xef 'Zhi ', // 0xf0 'Jia ', // 0xf1 'Rao ', // 0xf2 'Si ', // 0xf3 'Qi ', // 0xf4 'Xing ', // 0xf5 'Lie ', // 0xf6 'Qiu ', // 0xf7 'Shao ', // 0xf8 'Yong ', // 0xf9 'Jia ', // 0xfa 'Shui ', // 0xfb 'Che ', // 0xfc 'Bai ', // 0xfd 'E ', // 0xfe 'Han ', // 0xff ];
gpl-2.0
sbaldwin24/Helps
wp-content/plugins/updraftplus/oc/rs/lib/OpenCloud/Queues/Exception/MessageException.php
393
<?php /** * PHP OpenCloud library. * * @copyright 2013 Rackspace Hosting, Inc. See LICENSE for information. * @license https://www.apache.org/licenses/LICENSE-2.0 * @author Glen Campbell <glen.campbell@rackspace.com> * @author Jamie Hannaford <jamie.hannaford@rackspace.com> */ namespace OpenCloud\Queues\Exception; class MessageException extends \Exception { }
gpl-2.0
cisco-sas/kitty
kitty/data/__init__.py
818
# Copyright (C) 2016 Cisco Systems, Inc. and/or its affiliates. All rights reserved. # # This file is part of Kitty. # # Kitty 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. # # Kitty 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 Kitty. If not, see <http://www.gnu.org/licenses/>. ''' This package contains class for managing data related to the fuzzing session. '''
gpl-2.0
sacooper/ECSE-429-Project-Group1
ca.mcgill.sel.core/src/ca/mcgill/sel/core/impl/COREConcernImpl.java
12702
/** */ package ca.mcgill.sel.core.impl; import ca.mcgill.sel.core.COREConcern; import ca.mcgill.sel.core.COREFeatureModel; import ca.mcgill.sel.core.COREImpactModel; import ca.mcgill.sel.core.COREInterface; import ca.mcgill.sel.core.COREModel; import ca.mcgill.sel.core.CorePackage; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>CORE Concern</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link ca.mcgill.sel.core.impl.COREConcernImpl#getModels <em>Models</em>}</li> * <li>{@link ca.mcgill.sel.core.impl.COREConcernImpl#getInterface <em>Interface</em>}</li> * <li>{@link ca.mcgill.sel.core.impl.COREConcernImpl#getFeatureModel <em>Feature Model</em>}</li> * <li>{@link ca.mcgill.sel.core.impl.COREConcernImpl#getImpactModel <em>Impact Model</em>}</li> * </ul> * * @generated */ public class COREConcernImpl extends CORENamedElementImpl implements COREConcern { /** * The cached value of the '{@link #getModels() <em>Models</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getModels() * @generated * @ordered */ protected EList<COREModel> models; /** * The cached value of the '{@link #getInterface() <em>Interface</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getInterface() * @generated * @ordered */ protected COREInterface interface_; /** * The cached value of the '{@link #getFeatureModel() <em>Feature Model</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFeatureModel() * @generated * @ordered */ protected COREFeatureModel featureModel; /** * The cached value of the '{@link #getImpactModel() <em>Impact Model</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getImpactModel() * @generated * @ordered */ protected COREImpactModel impactModel; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected COREConcernImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return CorePackage.Literals.CORE_CONCERN; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<COREModel> getModels() { if (models == null) { models = new EObjectWithInverseResolvingEList<COREModel>(COREModel.class, this, CorePackage.CORE_CONCERN__MODELS, CorePackage.CORE_MODEL__CORE_CONCERN); } return models; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public COREInterface getInterface() { return interface_; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetInterface(COREInterface newInterface, NotificationChain msgs) { COREInterface oldInterface = interface_; interface_ = newInterface; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, CorePackage.CORE_CONCERN__INTERFACE, oldInterface, newInterface); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setInterface(COREInterface newInterface) { if (newInterface != interface_) { NotificationChain msgs = null; if (interface_ != null) msgs = ((InternalEObject)interface_).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - CorePackage.CORE_CONCERN__INTERFACE, null, msgs); if (newInterface != null) msgs = ((InternalEObject)newInterface).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - CorePackage.CORE_CONCERN__INTERFACE, null, msgs); msgs = basicSetInterface(newInterface, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, CorePackage.CORE_CONCERN__INTERFACE, newInterface, newInterface)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public COREFeatureModel getFeatureModel() { return featureModel; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetFeatureModel(COREFeatureModel newFeatureModel, NotificationChain msgs) { COREFeatureModel oldFeatureModel = featureModel; featureModel = newFeatureModel; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, CorePackage.CORE_CONCERN__FEATURE_MODEL, oldFeatureModel, newFeatureModel); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFeatureModel(COREFeatureModel newFeatureModel) { if (newFeatureModel != featureModel) { NotificationChain msgs = null; if (featureModel != null) msgs = ((InternalEObject)featureModel).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - CorePackage.CORE_CONCERN__FEATURE_MODEL, null, msgs); if (newFeatureModel != null) msgs = ((InternalEObject)newFeatureModel).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - CorePackage.CORE_CONCERN__FEATURE_MODEL, null, msgs); msgs = basicSetFeatureModel(newFeatureModel, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, CorePackage.CORE_CONCERN__FEATURE_MODEL, newFeatureModel, newFeatureModel)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public COREImpactModel getImpactModel() { return impactModel; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetImpactModel(COREImpactModel newImpactModel, NotificationChain msgs) { COREImpactModel oldImpactModel = impactModel; impactModel = newImpactModel; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, CorePackage.CORE_CONCERN__IMPACT_MODEL, oldImpactModel, newImpactModel); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setImpactModel(COREImpactModel newImpactModel) { if (newImpactModel != impactModel) { NotificationChain msgs = null; if (impactModel != null) msgs = ((InternalEObject)impactModel).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - CorePackage.CORE_CONCERN__IMPACT_MODEL, null, msgs); if (newImpactModel != null) msgs = ((InternalEObject)newImpactModel).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - CorePackage.CORE_CONCERN__IMPACT_MODEL, null, msgs); msgs = basicSetImpactModel(newImpactModel, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, CorePackage.CORE_CONCERN__IMPACT_MODEL, newImpactModel, newImpactModel)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case CorePackage.CORE_CONCERN__MODELS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getModels()).basicAdd(otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case CorePackage.CORE_CONCERN__MODELS: return ((InternalEList<?>)getModels()).basicRemove(otherEnd, msgs); case CorePackage.CORE_CONCERN__INTERFACE: return basicSetInterface(null, msgs); case CorePackage.CORE_CONCERN__FEATURE_MODEL: return basicSetFeatureModel(null, msgs); case CorePackage.CORE_CONCERN__IMPACT_MODEL: return basicSetImpactModel(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case CorePackage.CORE_CONCERN__MODELS: return getModels(); case CorePackage.CORE_CONCERN__INTERFACE: return getInterface(); case CorePackage.CORE_CONCERN__FEATURE_MODEL: return getFeatureModel(); case CorePackage.CORE_CONCERN__IMPACT_MODEL: return getImpactModel(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case CorePackage.CORE_CONCERN__MODELS: getModels().clear(); getModels().addAll((Collection<? extends COREModel>)newValue); return; case CorePackage.CORE_CONCERN__INTERFACE: setInterface((COREInterface)newValue); return; case CorePackage.CORE_CONCERN__FEATURE_MODEL: setFeatureModel((COREFeatureModel)newValue); return; case CorePackage.CORE_CONCERN__IMPACT_MODEL: setImpactModel((COREImpactModel)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case CorePackage.CORE_CONCERN__MODELS: getModels().clear(); return; case CorePackage.CORE_CONCERN__INTERFACE: setInterface((COREInterface)null); return; case CorePackage.CORE_CONCERN__FEATURE_MODEL: setFeatureModel((COREFeatureModel)null); return; case CorePackage.CORE_CONCERN__IMPACT_MODEL: setImpactModel((COREImpactModel)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case CorePackage.CORE_CONCERN__MODELS: return models != null && !models.isEmpty(); case CorePackage.CORE_CONCERN__INTERFACE: return interface_ != null; case CorePackage.CORE_CONCERN__FEATURE_MODEL: return featureModel != null; case CorePackage.CORE_CONCERN__IMPACT_MODEL: return impactModel != null; } return super.eIsSet(featureID); } } //COREConcernImpl
gpl-2.0
Qwaz/solved-hacking-problem
holyshield/2016/mobile_sound_meter/source_original/android/support/v7/widget/am.java
1490
package android.support.v7.widget; import android.content.Context; import android.util.AttributeSet; import android.widget.CheckedTextView; import android.widget.TextView; public class am extends CheckedTextView { private static final int[] f1295a; private ao f1296b; private bn f1297c; static { f1295a = new int[]{16843016}; } public am(Context context, AttributeSet attributeSet) { this(context, attributeSet, 16843720); } public am(Context context, AttributeSet attributeSet, int i) { super(de.m2707a(context), attributeSet, i); this.f1297c = bn.m2593a((TextView) this); this.f1297c.m2598a(attributeSet, i); this.f1297c.m2595a(); this.f1296b = ao.m2497a(); dh a = dh.m2710a(getContext(), attributeSet, f1295a, i, 0); setCheckMarkDrawable(a.m2713a(0)); a.m2714a(); } protected void drawableStateChanged() { super.drawableStateChanged(); if (this.f1297c != null) { this.f1297c.m2595a(); } } public void setCheckMarkDrawable(int i) { if (this.f1296b != null) { setCheckMarkDrawable(this.f1296b.m2520a(getContext(), i)); } else { super.setCheckMarkDrawable(i); } } public void setTextAppearance(Context context, int i) { super.setTextAppearance(context, i); if (this.f1297c != null) { this.f1297c.m2596a(context, i); } } }
gpl-2.0
lostdj/Jaklin-OpenJFX
modules/web/src/main/native/Source/WebCore/platform/graphics/ca/mac/LayerFlushSchedulerMac.cpp
3782
/* * Copyright (C) 2011 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "LayerFlushScheduler.h" #include <wtf/AutodrainedPool.h> #if PLATFORM(IOS) #include "RuntimeApplicationChecksIOS.h" #include <CoreFoundation/CFBundle.h> #include <WebCore/WebCoreThread.h> #endif namespace WebCore { static const CFIndex CoreAnimationRunLoopOrder = 2000000; static const CFIndex LayerFlushRunLoopOrder = CoreAnimationRunLoopOrder - 1; static CFRunLoopRef currentRunLoop() { #if PLATFORM(IOS) // A race condition during WebView deallocation can lead to a crash if the layer sync run loop // observer is added to the main run loop <rdar://problem/9798550>. However, for responsiveness, // we still allow this, see <rdar://problem/7403328>. Since the race condition and subsequent // crash are especially troublesome for iBooks, we never allow the observer to be added to the // main run loop in iBooks. if (applicationIsIBooksOnIOS()) return WebThreadRunLoop(); #endif return CFRunLoopGetCurrent(); } LayerFlushScheduler::LayerFlushScheduler(LayerFlushSchedulerClient* client) : m_isSuspended(false) , m_client(client) { ASSERT_ARG(client, client); } LayerFlushScheduler::~LayerFlushScheduler() { ASSERT(!m_runLoopObserver); } void LayerFlushScheduler::runLoopObserverCallback(CFRunLoopObserverRef, CFRunLoopActivity, void* context) { static_cast<LayerFlushScheduler*>(context)->runLoopObserverCallback(); } void LayerFlushScheduler::runLoopObserverCallback() { ASSERT(m_runLoopObserver); ASSERT(!m_isSuspended); AutodrainedPool pool; if (m_client->flushLayers()) invalidate(); } void LayerFlushScheduler::schedule() { if (m_isSuspended) return; CFRunLoopRef runLoop = currentRunLoop(); // Make sure we wake up the loop or the observer could be delayed until some other source fires. CFRunLoopWakeUp(runLoop); if (m_runLoopObserver) return; CFRunLoopObserverContext context = { 0, this, 0, 0, 0 }; m_runLoopObserver = adoptCF(CFRunLoopObserverCreate(0, kCFRunLoopBeforeWaiting | kCFRunLoopExit, true, LayerFlushRunLoopOrder, runLoopObserverCallback, &context)); CFRunLoopAddObserver(runLoop, m_runLoopObserver.get(), kCFRunLoopCommonModes); } void LayerFlushScheduler::invalidate() { if (m_runLoopObserver) { CFRunLoopObserverInvalidate(m_runLoopObserver.get()); m_runLoopObserver = nullptr; } } } // namespace WebCore
gpl-2.0
EquilibriumGames/Flounder-Engine
src/flounder/fonts/TextObject.java
7519
package flounder.fonts; import flounder.framework.*; import flounder.guis.*; import flounder.loaders.*; import flounder.maths.*; import flounder.maths.vectors.*; import flounder.visual.*; /** * A object the represents a text in a GUI. */ public class TextObject extends ScreenObject { private String textString; private GuiAlign textAlign; private String newText; private int textMeshVao; private int vertexCount; private float lineMaxSize; private int numberOfLines; private FontType font; private Colour colour; private Colour borderColour; private boolean solidBorder; private boolean glowBorder; private ValueDriver glowDriver; private float glowSize; private ValueDriver borderDriver; private float borderSize; /** * Creates a new ext object. * * @param parent The objects parent. * @param position The objects position relative to the parents. * @param text The text that will be set to this object. * @param fontSize The initial size of the font (1 is the default). * @param font The font type to be used in this text. * @param maxLineLength The longest line length before the text is wrapped, 1.0 being 100% of the screen width when font size = 1. * @param align How the text will align if wrapped. */ public TextObject(ScreenObject parent, Vector2f position, String text, float fontSize, FontType font, float maxLineLength, GuiAlign align) { super(parent, position, new Vector2f(1.0f, 1.0f)); super.setMeshSize(new Vector2f()); super.setScaleDriver(new ConstantDriver(fontSize)); this.textString = text; this.textAlign = align; this.newText = null; this.textMeshVao = -1; this.vertexCount = -1; this.lineMaxSize = maxLineLength; this.numberOfLines = -1; this.font = font; this.colour = new Colour(0.0f, 0.0f, 0.0f, 1.0f); this.borderColour = new Colour(1.0f, 1.0f, 1.0f, 1.0f); this.solidBorder = false; this.glowBorder = false; this.glowDriver = new ConstantDriver(0.0f); this.glowSize = 0.0f; this.borderDriver = new ConstantDriver(0.0f); this.borderSize = 0.0f; font.loadText(this); } @Override public void updateObject() { if (isLoaded() && newText != null) { delete(); textString = newText; font.loadText(this); newText = null; } switch (textAlign) { case LEFT: getPositionOffsets().set(getMeshSize().x * getScreenDimensions().x, 0.0f); break; case CENTRE: getPositionOffsets().set(0.0f, 0.0f); break; case RIGHT: getPositionOffsets().set(-getMeshSize().x * getScreenDimensions().x, 0.0f); break; } glowSize = glowDriver.update(Framework.get().getDelta()); borderSize = borderDriver.update(Framework.get().getDelta()); } /** * Gets the string of text represented. * * @return The string of text. */ public String getTextString() { return textString; } /** * Changed the current string in this text. * * @param newText The new text, */ public void setText(String newText) { if (!textString.equals(newText)) { this.newText = newText; } } /** * Gets how the text should align. * * @return How the text should align. */ public GuiAlign getTextAlign() { return textAlign; } /** * Gets the ID of the text's VAO, which contains all the vertex data for the quads on which the text will be rendered. * * @return The ID of the text's VAO. */ public int getMesh() { return textMeshVao; } /** * Gets the total number of vertices of all the text's quads. * * @return The vertices count in the text's VAO. */ public int getVertexCount() { return this.vertexCount; } /** * Sets the loaded mesh data for the text. * * @param vao The mesh VAO id. * @param verticesCount The mesh vertex count. */ protected void setMeshInfo(int vao, int verticesCount) { this.textMeshVao = vao; this.vertexCount = verticesCount; } /** * Gets the maximum length of a line of this text. * * @return The maximum length of a line. */ protected float getMaxLineSize() { return lineMaxSize; } /** * Gets the number of lines of text. This is determined when the text is loaded, based on the length of the text and the max line length that is set. * * @return The number of lines of text */ public int getNumberOfLines() { return numberOfLines; } /** * Sets the number of lines that this text covers (method used only in loading). * * @param number The new number of lines. */ protected void setNumberOfLines(int number) { this.numberOfLines = number; } /** * Gets the font used by this text. * * @return The font used by this text. */ public FontType getFont() { return font; } /** * Gets the colour of the text. * * @return The colour of the text. */ public Colour getColour() { return colour; } /** * Sets the colour of the text. * * @param colour The new colour of the text. */ public void setColour(Colour colour) { this.colour.set(colour); } /** * Gets the border colour of the text. This is used with border and glow drivers. * * @return The border colour of the text. */ public Colour getBorderColour() { return borderColour; } /** * Sets the border colour of the text. This is used with border and glow drivers. * * @param borderColour The new border colour of the text. */ public void setBorderColour(Colour borderColour) { this.borderColour.set(borderColour); } /** * Sets a new border driver, will disable glowing. * * @param driver The new border driver. */ public void setBorder(ValueDriver driver) { this.borderDriver = driver; this.solidBorder = true; this.glowBorder = false; } /** * Sets a new glow driver, will disable solid borders. * * @param driver The new glow driver. */ public void setGlowing(ValueDriver driver) { this.glowDriver = driver; this.solidBorder = false; this.glowBorder = true; } /** * Disables both solid borders and glow borders. */ public void removeBorder() { this.solidBorder = false; this.glowBorder = false; } /** * Gets the calculated border size. * * @return The border size. */ protected float getTotalBorderSize() { if (solidBorder) { if (borderSize == 0.0f) { return 0.0f; } else { return calculateEdgeStart() + borderSize; } } else if (glowBorder) { return calculateEdgeStart(); } else { return 0.0f; } } /** * Gets the size of the glow. * * @return The glow size. */ protected float getGlowSize() { if (solidBorder) { return calculateAntialiasSize(); } else if (glowBorder) { return glowSize; } else { return 0.0f; } } /** * Gets the distance field edge before antialias. * * @return The distance field edge. */ protected float calculateEdgeStart() { float size = super.getScale(); return 1.0f / 300.0f * size + 137.0f / 300.0f; } /** * Gets the distance field antialias distance. * * @return The distance field antialias distance. */ protected float calculateAntialiasSize() { float size = super.getScale(); size = (size - 1.0f) / (1.0f + size / 4.0f) + 1.0f; return 0.1f / size; } /** * Gets if the text has been loaded to OpenGL. * * @return If the text has been loaded to OpenGL. */ public boolean isLoaded() { return !textString.isEmpty() && textMeshVao != -1 && vertexCount != -1; } @Override public void deleteObject() { if (isLoaded()) { FlounderLoader.get().deleteVAOFromCache(textMeshVao); textMeshVao = -1; vertexCount = -1; } } }
gpl-3.0
MTK6580/walkie-talkie
ALPS.L1.MP6.V2_HEXING6580_WE_L/alps/device/generic/goldfish/opengl/system/renderControl_enc/renderControl_entry.cpp
5774
// Generated Code - DO NOT EDIT !! // generated by 'emugen' #include <stdio.h> #include <stdlib.h> #include "renderControl_client_context.h" #ifndef GL_TRUE extern "C" { GLint rcGetRendererVersion(); EGLint rcGetEGLVersion(EGLint* major, EGLint* minor); EGLint rcQueryEGLString(EGLenum name, void* buffer, EGLint bufferSize); EGLint rcGetGLString(EGLenum name, void* buffer, EGLint bufferSize); EGLint rcGetNumConfigs(uint32_t* numAttribs); EGLint rcGetConfigs(uint32_t bufSize, GLuint* buffer); EGLint rcChooseConfig(EGLint* attribs, uint32_t attribs_size, uint32_t* configs, uint32_t configs_size); EGLint rcGetFBParam(EGLint param); uint32_t rcCreateContext(uint32_t config, uint32_t share, uint32_t glVersion); void rcDestroyContext(uint32_t context); uint32_t rcCreateWindowSurface(uint32_t config, uint32_t width, uint32_t height); void rcDestroyWindowSurface(uint32_t windowSurface); uint32_t rcCreateColorBuffer(uint32_t width, uint32_t height, GLenum internalFormat); void rcOpenColorBuffer(uint32_t colorbuffer); void rcCloseColorBuffer(uint32_t colorbuffer); void rcSetWindowColorBuffer(uint32_t windowSurface, uint32_t colorBuffer); int rcFlushWindowColorBuffer(uint32_t windowSurface); EGLint rcMakeCurrent(uint32_t context, uint32_t drawSurf, uint32_t readSurf); void rcFBPost(uint32_t colorBuffer); void rcFBSetSwapInterval(EGLint interval); void rcBindTexture(uint32_t colorBuffer); void rcBindRenderbuffer(uint32_t colorBuffer); EGLint rcColorBufferCacheFlush(uint32_t colorbuffer, EGLint postCount, int forRead); void rcReadColorBuffer(uint32_t colorbuffer, GLint x, GLint y, GLint width, GLint height, GLenum format, GLenum type, void* pixels); int rcUpdateColorBuffer(uint32_t colorbuffer, GLint x, GLint y, GLint width, GLint height, GLenum format, GLenum type, void* pixels); int rcOpenColorBuffer2(uint32_t colorbuffer); }; #endif #ifndef GET_CONTEXT static renderControl_client_context_t::CONTEXT_ACCESSOR_TYPE *getCurrentContext = NULL; void renderControl_client_context_t::setContextAccessor(CONTEXT_ACCESSOR_TYPE *f) { getCurrentContext = f; } #define GET_CONTEXT renderControl_client_context_t * ctx = getCurrentContext() #endif GLint rcGetRendererVersion() { GET_CONTEXT; return ctx->rcGetRendererVersion(ctx); } EGLint rcGetEGLVersion(EGLint* major, EGLint* minor) { GET_CONTEXT; return ctx->rcGetEGLVersion(ctx, major, minor); } EGLint rcQueryEGLString(EGLenum name, void* buffer, EGLint bufferSize) { GET_CONTEXT; return ctx->rcQueryEGLString(ctx, name, buffer, bufferSize); } EGLint rcGetGLString(EGLenum name, void* buffer, EGLint bufferSize) { GET_CONTEXT; return ctx->rcGetGLString(ctx, name, buffer, bufferSize); } EGLint rcGetNumConfigs(uint32_t* numAttribs) { GET_CONTEXT; return ctx->rcGetNumConfigs(ctx, numAttribs); } EGLint rcGetConfigs(uint32_t bufSize, GLuint* buffer) { GET_CONTEXT; return ctx->rcGetConfigs(ctx, bufSize, buffer); } EGLint rcChooseConfig(EGLint* attribs, uint32_t attribs_size, uint32_t* configs, uint32_t configs_size) { GET_CONTEXT; return ctx->rcChooseConfig(ctx, attribs, attribs_size, configs, configs_size); } EGLint rcGetFBParam(EGLint param) { GET_CONTEXT; return ctx->rcGetFBParam(ctx, param); } uint32_t rcCreateContext(uint32_t config, uint32_t share, uint32_t glVersion) { GET_CONTEXT; return ctx->rcCreateContext(ctx, config, share, glVersion); } void rcDestroyContext(uint32_t context) { GET_CONTEXT; ctx->rcDestroyContext(ctx, context); } uint32_t rcCreateWindowSurface(uint32_t config, uint32_t width, uint32_t height) { GET_CONTEXT; return ctx->rcCreateWindowSurface(ctx, config, width, height); } void rcDestroyWindowSurface(uint32_t windowSurface) { GET_CONTEXT; ctx->rcDestroyWindowSurface(ctx, windowSurface); } uint32_t rcCreateColorBuffer(uint32_t width, uint32_t height, GLenum internalFormat) { GET_CONTEXT; return ctx->rcCreateColorBuffer(ctx, width, height, internalFormat); } void rcOpenColorBuffer(uint32_t colorbuffer) { GET_CONTEXT; ctx->rcOpenColorBuffer(ctx, colorbuffer); } void rcCloseColorBuffer(uint32_t colorbuffer) { GET_CONTEXT; ctx->rcCloseColorBuffer(ctx, colorbuffer); } void rcSetWindowColorBuffer(uint32_t windowSurface, uint32_t colorBuffer) { GET_CONTEXT; ctx->rcSetWindowColorBuffer(ctx, windowSurface, colorBuffer); } int rcFlushWindowColorBuffer(uint32_t windowSurface) { GET_CONTEXT; return ctx->rcFlushWindowColorBuffer(ctx, windowSurface); } EGLint rcMakeCurrent(uint32_t context, uint32_t drawSurf, uint32_t readSurf) { GET_CONTEXT; return ctx->rcMakeCurrent(ctx, context, drawSurf, readSurf); } void rcFBPost(uint32_t colorBuffer) { GET_CONTEXT; ctx->rcFBPost(ctx, colorBuffer); } void rcFBSetSwapInterval(EGLint interval) { GET_CONTEXT; ctx->rcFBSetSwapInterval(ctx, interval); } void rcBindTexture(uint32_t colorBuffer) { GET_CONTEXT; ctx->rcBindTexture(ctx, colorBuffer); } void rcBindRenderbuffer(uint32_t colorBuffer) { GET_CONTEXT; ctx->rcBindRenderbuffer(ctx, colorBuffer); } EGLint rcColorBufferCacheFlush(uint32_t colorbuffer, EGLint postCount, int forRead) { GET_CONTEXT; return ctx->rcColorBufferCacheFlush(ctx, colorbuffer, postCount, forRead); } void rcReadColorBuffer(uint32_t colorbuffer, GLint x, GLint y, GLint width, GLint height, GLenum format, GLenum type, void* pixels) { GET_CONTEXT; ctx->rcReadColorBuffer(ctx, colorbuffer, x, y, width, height, format, type, pixels); } int rcUpdateColorBuffer(uint32_t colorbuffer, GLint x, GLint y, GLint width, GLint height, GLenum format, GLenum type, void* pixels) { GET_CONTEXT; return ctx->rcUpdateColorBuffer(ctx, colorbuffer, x, y, width, height, format, type, pixels); } int rcOpenColorBuffer2(uint32_t colorbuffer) { GET_CONTEXT; return ctx->rcOpenColorBuffer2(ctx, colorbuffer); }
gpl-3.0
radekp/NeronGPS
src/tracesegment.cpp
2000
/* * Copyright 2009, 2010 Thierry Vuillaume * * This file is part of NeronGPS. * * NeronGPS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NeronGPS 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 NeronGPS. If not, see <http://www.gnu.org/licenses/>. * */ #include <QtGlobal> #include <QtDebug> #include <QMessageBox> #include "include/tracesegment.h" #include "include/converter.h" TTraceSegment::TTraceSegment() { _size = 0; } TTraceSegment::~TTraceSegment() { } void TTraceSegment::addSample(int x, int y) { if(_size < SEGMENT_SIZE) { _data[_size].x = x; _data[_size].y = y; _size ++; if(x < _xmin) { _xmin = x; } else if(x > _xmax) { _xmax = x; } if(y < _ymin) { _ymin = y; } else if(y > _ymax) { _ymax = y; } } else { qDebug() << "Attempt to add sample to segment full" ; } } bool TTraceSegment::isFull() { return (_size == SEGMENT_SIZE); } void TTraceSegment::draw(TTracePainter *multi, int translatX, int translatY, int zoom) { int i; for (i = 0; i < _size; i++) { multi->nextPoint(TConverter::convert(_data[i].x, zoom) + translatX, TConverter::convert(_data[i].y, zoom) + translatY); } } void TTraceSegment::drawEndPoints(TTracePainter *multi, int translatX, int translatY, int zoom) { if(_size > 0) { multi->nextPoint(TConverter::convert(_data[0].x, zoom) + translatX, TConverter::convert(_data[0].y, zoom) + translatY); } if(_size > 1) { multi->nextPoint(TConverter::convert(_data[_size - 1].x, zoom) + translatX, TConverter::convert(_data[_size - 1].y, zoom) + translatY); } }
gpl-3.0
axis/axiscommerce
app/code/Axis/Sitemap/controllers/IndexController.php
7286
<?php /** * Axis * * This file is part of Axis. * * Axis is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Axis 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 Axis. If not, see <http://www.gnu.org/licenses/>. * * @category Axis * @package Axis_Sitemap * @subpackage Axis_Sitemap_Controller * @copyright Copyright 2008-2012 Axis * @license GNU Public License V3.0 */ /** * * @category Axis * @package Axis_Sitemap * @subpackage Axis_Sitemap_Controller * @author Axis Core Team <core@axiscommerce.com> */ class Axis_Sitemap_IndexController extends Axis_Core_Controller_Front { public function init() { parent::init(); $this->_helper->breadcrumbs(array( 'label' => Axis::translate('sitemap')->__('Sitemap'), 'route' => 'sitemap' )); } public function getAllCategoriesAction() { $this->setTitle(Axis::translate('sitemap')->__( 'Site Map Categories' )); $categories = Axis::single('catalog/category')->select('*') ->addName(Axis_Locale::getLanguageId()) ->addKeyWord() ->order('cc.lft') ->addSiteFilter(Axis::getSiteId()) ->addDisabledFilter() ->fetchAll(); $menu = $_container = new Zend_Navigation(); $lvl = 0; foreach ($categories as $_category) { $uri = $this->view->hurl(array( 'cat' => array( 'value' => $_category['id'], 'seo' => $_category['key_word'] ), 'controller' => 'catalog', 'action' => 'view' ), false, true); $class = 'nav-' . str_replace('.', '-', $_category['key_word']); $page = new Zend_Navigation_Page_Uri(array( 'label' => $_category['name'], 'title' => $_category['name'], 'uri' => $uri, 'order' => $_category['lft'], 'class' => $class, 'visible' => ('enabled' === $_category['status']) ? true : false )); $lvl = $lvl - $_category['lvl'] + 1; for ($i = 0; $i < $lvl; $i++) { $_container = $_container->getParent(); } $lvl = $_category['lvl']; $_container->addPage($page); $_container = $page; } $this->view->menu = $menu; $this->render('categories'); } public function getAllProductsAction() { $this->setTitle( Axis::translate('sitemap')->__( 'Site Map All Products' )); $products = Axis::single('catalog/product_category')->select() ->distinct() ->from('catalog_product_category', array()) ->joinLeft('catalog_product', 'cp.id = cpc.product_id', array('id')) ->addName(Axis_Locale::getLanguageId()) ->addKeyWord() ->addActiveFilter() ->addDateAvailableFilter() ->addSiteFilter(Axis::getSiteId()) ->order('cpd.name') ->fetchAll(); $menu = new Zend_Navigation(); foreach ($products as $_product) { $uri = $this->view->hurl(array( 'cat' => array( 'value' => $_product['id'], 'seo' => $_product['key_word'] ), 'controller' => 'catalog', 'action' => 'view' ), false, true); $class = 'nav-' . str_replace('.', '-', $_product['key_word']); $page = new Zend_Navigation_Page_Uri(array( 'label' => $_product['name'], 'title' => $_product['name'], 'uri' => $uri, 'class' => $class )); $menu->addPage($page); } $this->view->menu = $menu; $this->render('products'); } public function getAllPagesAction() { $this->setTitle(Axis::translate('sitemap')->__('Site Map All Pages')); $result = array(); $categories = Axis::single('cms/category')->select(array('id', 'parent_id')) ->addCategoryContentTable() ->columns(array('ccc.link', 'ccc.title')) ->addActiveFilter() ->addSiteFilter(Axis::getSiteId()) ->addLanguageIdFilter(Axis_Locale::getLanguageId()) ->order('cc.parent_id') ->where('ccc.link IS NOT NULL') ->fetchAssoc(); $menu = new Zend_Navigation(); foreach ($categories as $_category) { $title = empty($_category['title']) ? $_category['link'] : $_category['title']; $page = new Zend_Navigation_Page_Mvc(array( 'category_id' => $_category['id'], 'label' => $title, 'title' => $title, 'route' => 'cms_category', 'params' => array('cat' => $_category['link']), 'class' => 'icon-folder' )); $_container = $menu->findBy('category_id', $_category['parent_id']); if (null === $_container) { $_container = $menu; } $_container->addPage($page); } if (Axis::config('sitemap/cms/showPages') && !empty ($categories)) { $pages = Axis::single('cms/page')->select(array('id', 'name')) ->join(array('cpca' => 'cms_page_category'), 'cp.id = cpca.cms_page_id', 'cms_category_id') ->join('cms_page_content', 'cp.id = cpc.cms_page_id', array('link', 'title')) ->where('cp.is_active = 1') ->where('cpc.language_id = ?', Axis_Locale::getLanguageId()) ->where('cpca.cms_category_id IN (?)', array_keys($categories)) ->order('cpca.cms_category_id') ->fetchAssoc(); foreach($pages as $_page) { $title = empty($_page['title']) ? $_page['link'] : $_page['title']; $page = new Zend_Navigation_Page_Mvc(array( 'label' => $title, 'title' => $title, 'route' => 'cms_page', 'params' => array('page' => $_page['link']), 'class' => 'icon-page' )); $_container = $menu->findBy('category_id', $_page['cms_category_id']); $_container->addPage($page); } } $this->view->menu = $menu; $this->render('pages'); } }
gpl-3.0
OpenQBMM/OpenQBMM-dev
src/quadratureMethods/populationBalanceModels/populationBalanceSubModels/breakupKernels/AyaziShamlou/AyaziShamlou.C
4212
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | OpenQBMM - www.openqbmm.org \\/ M anipulation | ------------------------------------------------------------------------------- Code created 2015-2018 by Alberto Passalacqua Contributed 2018-07-31 to the OpenFOAM Foundation Copyright (C) 2018 OpenFOAM Foundation Copyright (C) 2019-2020 Alberto Passalacqua ------------------------------------------------------------------------------- License This file is derivative work of OpenFOAM. OpenFOAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "AyaziShamlou.H" #include "addToRunTimeSelectionTable.H" // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * // namespace Foam { namespace populationBalanceSubModels { namespace breakupKernels { defineTypeNameAndDebug(AyaziShamlou, 0); addToRunTimeSelectionTable ( breakupKernel, AyaziShamlou, dictionary ); } } } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // Foam::populationBalanceSubModels::breakupKernels::AyaziShamlou ::AyaziShamlou ( const dictionary& dict, const fvMesh& mesh ) : breakupKernel(dict, mesh), continuousPhase_(dict.lookupOrDefault("continuousPhase", word::null)), A_("A", dimEnergy, dict), df_("df", dimless, dict), H0_("H0", dimLength, dict), primarySize_("primarySize", dimLength, dict), flTurb_ ( mesh_.lookupObject<turbulenceModel> ( IOobject::groupName ( turbulenceModel::propertiesName, continuousPhase_ ) ) ), epsilon_(flTurb_.epsilon()), mu_ ( dict.found("mu") ? mesh.lookupObject<volScalarField>(dict.get<word>("mu")) : mesh.lookupObject<volScalarField> ( IOobject::groupName("thermo:mu", continuousPhase_) ) ), rho_ ( dict.found("rho") ? mesh.lookupObject<volScalarField>(dict.get<word>("rho")) : mesh.lookupObject<volScalarField> ( IOobject::groupName("rho", continuousPhase_) ) ) {} // * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * // Foam::populationBalanceSubModels::breakupKernels::AyaziShamlou::~AyaziShamlou() {} // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // Foam::scalar Foam::populationBalanceSubModels::breakupKernels::AyaziShamlou::Kb ( const scalar& abscissa, const label celli, const label environment ) const { // Interparticle force scalar F = A_.value()*primarySize_.value()/(12.0*sqr(H0_.value())); // Coefficient of volume fraction (Vanni, 2000) scalar C = 0.41*df_.value() - 0.211; // Volume fraction of solid within aggregates scalar phiL = C*pow(abscissa/primarySize_.value(), df_.value() - 3.0); // Coordination number scalar kc = 15.0*pow(phiL, 1.2); // Aggregation strength scalar sigma = 9.0*kc*phiL*F/(8.0*sqr(primarySize_.value()) *Foam::constant::mathematical::pi); scalar epsilonByNu = epsilon_[celli]*rho_[celli]/mu_[celli]; scalar tau = mu_[celli]*sqrt(epsilonByNu); return sqrt(epsilonByNu/15.0)*exp(-sigma/tau); } // ************************************************************************* //
gpl-3.0
brimzi/jeromq
src/test/java/zmq/TestYQueue.java
1771
/* Copyright (c) 2007-2014 Contributors as noted in the AUTHORS file This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package zmq; import org.junit.Test; import static org.junit.Assert.assertThat; import static org.hamcrest.CoreMatchers.is; public class TestYQueue { @Test public void testReuse() { // yqueue has a first empty entry YQueue<Msg> p = new YQueue<Msg>(3); Msg m1 = new Msg(1); Msg m2 = new Msg(2); Msg m3 = new Msg(3); Msg m4 = new Msg(4); Msg m5 = new Msg(5); Msg m6 = new Msg(6); Msg m7 = new Msg(7); m7.put("1234567".getBytes(ZMQ.CHARSET)); p.push(m1); assertThat(p.back_pos(), is(1)); p.push(m2); // might allocated new chunk p.push(m3); assertThat(p.back_pos(), is(3)); assertThat(p.front_pos(), is(0)); p.pop(); p.pop(); p.pop(); // offer the old chunk assertThat(p.front_pos(), is(3)); p.push(m4); p.push(m5); // might reuse the old chunk p.push(m6); assertThat(p.back_pos(), is(0)); } }
gpl-3.0
grandgeorg/omeka-ddb
themes/Deco-master/deco/common/footer.php
3976
</div><!-- end content --> <div id="footer"> <?php echo public_nav_main();?> <p>&copy; <?php echo date('Y');?> <?php echo html_escape(option('author'));?> <br/>Powered by <a href="http://omeka.org">Omeka</a><?php echo deco_display_theme_credit();?> <?php echo ($footertext=get_theme_option('custom_footer')) ? '<br>'.$footertext : '';?></p> <script type="text/javascript"> jQuery(document).ready(function() { var $window = jQuery(window); // exists? function jQuery.fn.exists = function(){return this.length>0;} // Function to handle changes to style classes based on window width // Also swaps in thumbnails for larger views where user can utilize Fancybox image viewer // Also swaps #hero images in items/show header function checkWidth() { var breakpoint = 625; if ($window.width() < breakpoint) { jQuery('body').removeClass('big').addClass('small'); // menu button if (jQuery("body").hasClass('small')){ jQuery('#mobile-menu-button').show(); jQuery(function() { jQuery('#primary-nav').hide(); }); } } if ($window.width() >= breakpoint) { jQuery('body').removeClass('small').addClass('big'); if (jQuery("body").hasClass('big')){ jQuery('#primary-nav').show(); jQuery('#mobile-menu-button').hide(); } } } // Execute on load checkWidth(); // Bind event listener jQuery($window).resize(checkWidth); }); // resizable site title jQuery("#site-title").fitText(2, { minFontSize: '25px', maxFontSize: '45px' }); jQuery("body#home #content h2").fitText(0, { minFontSize: '23px', maxFontSize: '27px' }); // create slideshow on home window.mySwipe = new Swipe(document.getElementById('slider'), { startSlide: 0, speed: 300, auto: 5000, continuous: true, disableScroll: false, stopPropagation: false, callback: function(index, elem) {}, transitionEnd: function(index, elem) {} }); // create the dropdown select (function(jQuery) { jQuery(function() { var jQueryselect = jQuery('<select>') .appendTo('#exhibit-pages'); jQuery('nav#exhibit-pages li').each(function() { var jQueryli = jQuery(this), jQuerya = jQueryli.find('> a'), jQueryp = jQueryli.parents('li'), prefix = new Array(jQueryp.length + 1).join('-'); var jQueryoption = jQuery('<option>') .text(prefix + ' ' + jQuerya.text()) .val(jQuerya.attr('href')) .appendTo(jQueryselect); if (jQueryli.hasClass('current')) { jQueryoption.attr('selected', 'selected'); } }); });})(jQuery); // Bind dropdown select to change the page jQuery(function(){ // bind change event to select jQuery('nav#exhibit-pages select').bind('change', function () { var url = jQuery(this).val(); // get selected value if (url) { // require a URL window.location = url; // redirect } return false; }); }); // Get the link to the first section page and place link on summary page jQuery('<a class="view-exhibit" href="">View Exhibit&nbsp;&rarr;</a>').appendTo("#exhibit-start"); jQuery(function() { var url = jQuery("nav#exhibit-pages ul li:first-child a").attr("href"); jQuery("#exhibit-start a.view-exhibit").attr("href", ''+url+'' ); }); // Mobile Menu button jQuery('#mobile-menu-button').click( function() { jQuery('#primary-nav').slideToggle('fast', function(){ if (jQuery('#primary-nav').is(':visible')) { jQuery('#mobile-menu-button a').text('Hide Menu') } else { jQuery('#mobile-menu-button a').text('Show Menu') } }); }); </script> </script> </div><!-- end footer --> </div><!-- end wrap --> </body> </html>
gpl-3.0
OpenFOAM/OpenFOAM-5.x
src/lagrangian/intermediate/parcels/Templates/ReactingMultiphaseParcel/ReactingMultiphaseParcel.C
18624
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2011-2016 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "ReactingMultiphaseParcel.H" #include "mathematicalConstants.H" using namespace Foam::constant::mathematical; // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * // template<class ParcelType> const Foam::label Foam::ReactingMultiphaseParcel<ParcelType>::GAS(0); template<class ParcelType> const Foam::label Foam::ReactingMultiphaseParcel<ParcelType>::LIQ(1); template<class ParcelType> const Foam::label Foam::ReactingMultiphaseParcel<ParcelType>::SLD(2); // * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * * // template<class ParcelType> template<class TrackData> Foam::scalar Foam::ReactingMultiphaseParcel<ParcelType>::CpEff ( TrackData& td, const scalar p, const scalar T, const label idG, const label idL, const label idS ) const { return this->Y_[GAS]*td.cloud().composition().Cp(idG, YGas_, p, T) + this->Y_[LIQ]*td.cloud().composition().Cp(idL, YLiquid_, p, T) + this->Y_[SLD]*td.cloud().composition().Cp(idS, YSolid_, p, T); } template<class ParcelType> template<class TrackData> Foam::scalar Foam::ReactingMultiphaseParcel<ParcelType>::HsEff ( TrackData& td, const scalar p, const scalar T, const label idG, const label idL, const label idS ) const { return this->Y_[GAS]*td.cloud().composition().Hs(idG, YGas_, p, T) + this->Y_[LIQ]*td.cloud().composition().Hs(idL, YLiquid_, p, T) + this->Y_[SLD]*td.cloud().composition().Hs(idS, YSolid_, p, T); } template<class ParcelType> template<class TrackData> Foam::scalar Foam::ReactingMultiphaseParcel<ParcelType>::LEff ( TrackData& td, const scalar p, const scalar T, const label idG, const label idL, const label idS ) const { return this->Y_[GAS]*td.cloud().composition().L(idG, YGas_, p, T) + this->Y_[LIQ]*td.cloud().composition().L(idL, YLiquid_, p, T) + this->Y_[SLD]*td.cloud().composition().L(idS, YSolid_, p, T); } template<class ParcelType> Foam::scalar Foam::ReactingMultiphaseParcel<ParcelType>::updateMassFractions ( const scalar mass0, const scalarField& dMassGas, const scalarField& dMassLiquid, const scalarField& dMassSolid ) { scalarField& YMix = this->Y_; scalar massGas = this->updateMassFraction(mass0*YMix[GAS], dMassGas, YGas_); scalar massLiquid = this->updateMassFraction(mass0*YMix[LIQ], dMassLiquid, YLiquid_); scalar massSolid = this->updateMassFraction(mass0*YMix[SLD], dMassSolid, YSolid_); scalar massNew = max(massGas + massLiquid + massSolid, ROOTVSMALL); YMix[GAS] = massGas/massNew; YMix[LIQ] = massLiquid/massNew; YMix[SLD] = 1.0 - YMix[GAS] - YMix[LIQ]; return massNew; } // * * * * * * * * * * * Protected Member Functions * * * * * * * * * * * * // template<class ParcelType> template<class TrackData> void Foam::ReactingMultiphaseParcel<ParcelType>::setCellValues ( TrackData& td, const scalar dt, const label celli ) { ParcelType::setCellValues(td, dt, celli); } template<class ParcelType> template<class TrackData> void Foam::ReactingMultiphaseParcel<ParcelType>::cellValueSourceCorrection ( TrackData& td, const scalar dt, const label celli ) { // Re-use correction from reacting parcel ParcelType::cellValueSourceCorrection(td, dt, celli); } template<class ParcelType> template<class TrackData> void Foam::ReactingMultiphaseParcel<ParcelType>::calc ( TrackData& td, const scalar dt, const label celli ) { typedef typename TrackData::cloudType::reactingCloudType reactingCloudType; const CompositionModel<reactingCloudType>& composition = td.cloud().composition(); // Define local properties at beginning of timestep // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ const scalar np0 = this->nParticle_; const scalar d0 = this->d_; const vector& U0 = this->U_; const scalar T0 = this->T_; const scalar mass0 = this->mass(); const scalar pc = this->pc_; const scalarField& YMix = this->Y_; const label idG = composition.idGas(); const label idL = composition.idLiquid(); const label idS = composition.idSolid(); // Calc surface values scalar Ts, rhos, mus, Prs, kappas; this->calcSurfaceValues(td, celli, T0, Ts, rhos, mus, Prs, kappas); scalar Res = this->Re(U0, d0, rhos, mus); // Sources //~~~~~~~~ // Explicit momentum source for particle vector Su = Zero; // Linearised momentum source coefficient scalar Spu = 0.0; // Momentum transfer from the particle to the carrier phase vector dUTrans = Zero; // Explicit enthalpy source for particle scalar Sh = 0.0; // Linearised enthalpy source coefficient scalar Sph = 0.0; // Sensible enthalpy transfer from the particle to the carrier phase scalar dhsTrans = 0.0; // 1. Compute models that contribute to mass transfer - U, T held constant // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Phase change in liquid phase // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Mass transfer due to phase change scalarField dMassPC(YLiquid_.size(), 0.0); // Molar flux of species emitted from the particle (kmol/m^2/s) scalar Ne = 0.0; // Sum Ni*Cpi*Wi of emission species scalar NCpW = 0.0; // Surface concentrations of emitted species scalarField Cs(composition.carrier().species().size(), 0.0); // Calc mass and enthalpy transfer due to phase change this->calcPhaseChange ( td, dt, celli, Res, Prs, Ts, mus/rhos, d0, T0, mass0, idL, YMix[LIQ], YLiquid_, dMassPC, Sh, Ne, NCpW, Cs ); // Devolatilisation // ~~~~~~~~~~~~~~~~ // Mass transfer due to devolatilisation scalarField dMassDV(YGas_.size(), 0.0); // Calc mass and enthalpy transfer due to devolatilisation calcDevolatilisation ( td, dt, this->age_, Ts, d0, T0, mass0, this->mass0_, YMix[GAS]*YGas_, YMix[LIQ]*YLiquid_, YMix[SLD]*YSolid_, canCombust_, dMassDV, Sh, Ne, NCpW, Cs ); // Surface reactions // ~~~~~~~~~~~~~~~~~ // Change in carrier phase composition due to surface reactions scalarField dMassSRGas(YGas_.size(), 0.0); scalarField dMassSRLiquid(YLiquid_.size(), 0.0); scalarField dMassSRSolid(YSolid_.size(), 0.0); scalarField dMassSRCarrier(composition.carrier().species().size(), 0.0); // Calc mass and enthalpy transfer due to surface reactions calcSurfaceReactions ( td, dt, celli, d0, T0, mass0, canCombust_, Ne, YMix, YGas_, YLiquid_, YSolid_, dMassSRGas, dMassSRLiquid, dMassSRSolid, dMassSRCarrier, Sh, dhsTrans ); // 2. Update the parcel properties due to change in mass // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ scalarField dMassGas(dMassDV + dMassSRGas); scalarField dMassLiquid(dMassPC + dMassSRLiquid); scalarField dMassSolid(dMassSRSolid); scalar mass1 = updateMassFractions(mass0, dMassGas, dMassLiquid, dMassSolid); this->Cp_ = CpEff(td, pc, T0, idG, idL, idS); // Update particle density or diameter if (td.cloud().constProps().constantVolume()) { this->rho_ = mass1/this->volume(); } else { this->d_ = cbrt(mass1/this->rho_*6.0/pi); } // Remove the particle when mass falls below minimum threshold if (np0*mass1 < td.cloud().constProps().minParcelMass()) { td.keepParticle = false; if (td.cloud().solution().coupled()) { scalar dm = np0*mass0; // Absorb parcel into carrier phase forAll(YGas_, i) { label gid = composition.localToCarrierId(GAS, i); td.cloud().rhoTrans(gid)[celli] += dm*YMix[GAS]*YGas_[i]; } forAll(YLiquid_, i) { label gid = composition.localToCarrierId(LIQ, i); td.cloud().rhoTrans(gid)[celli] += dm*YMix[LIQ]*YLiquid_[i]; } // No mapping between solid components and carrier phase /* forAll(YSolid_, i) { label gid = composition.localToCarrierId(SLD, i); td.cloud().rhoTrans(gid)[celli] += dm*YMix[SLD]*YSolid_[i]; } */ td.cloud().UTrans()[celli] += dm*U0; td.cloud().hsTrans()[celli] += dm*HsEff(td, pc, T0, idG, idL, idS); td.cloud().phaseChange().addToPhaseChangeMass(np0*mass1); } return; } // Correct surface values due to emitted species this->correctSurfaceValues(td, celli, Ts, Cs, rhos, mus, Prs, kappas); Res = this->Re(U0, this->d_, rhos, mus); // 3. Compute heat- and momentum transfers // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Heat transfer // ~~~~~~~~~~~~~ // Calculate new particle temperature this->T_ = this->calcHeatTransfer ( td, dt, celli, Res, Prs, kappas, NCpW, Sh, dhsTrans, Sph ); this->Cp_ = CpEff(td, pc, this->T_, idG, idL, idS); // Motion // ~~~~~~ // Calculate new particle velocity this->U_ = this->calcVelocity(td, dt, celli, Res, mus, mass1, Su, dUTrans, Spu); // 4. Accumulate carrier phase source terms // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if (td.cloud().solution().coupled()) { // Transfer mass lost to carrier mass, momentum and enthalpy sources forAll(YGas_, i) { scalar dm = np0*dMassGas[i]; label gid = composition.localToCarrierId(GAS, i); scalar hs = composition.carrier().Hs(gid, pc, T0); td.cloud().rhoTrans(gid)[celli] += dm; td.cloud().UTrans()[celli] += dm*U0; td.cloud().hsTrans()[celli] += dm*hs; } forAll(YLiquid_, i) { scalar dm = np0*dMassLiquid[i]; label gid = composition.localToCarrierId(LIQ, i); scalar hs = composition.carrier().Hs(gid, pc, T0); td.cloud().rhoTrans(gid)[celli] += dm; td.cloud().UTrans()[celli] += dm*U0; td.cloud().hsTrans()[celli] += dm*hs; } // No mapping between solid components and carrier phase /* forAll(YSolid_, i) { scalar dm = np0*dMassSolid[i]; label gid = composition.localToCarrierId(SLD, i); scalar hs = composition.carrier().Hs(gid, pc, T0); td.cloud().rhoTrans(gid)[celli] += dm; td.cloud().UTrans()[celli] += dm*U0; td.cloud().hsTrans()[celli] += dm*hs; } */ forAll(dMassSRCarrier, i) { scalar dm = np0*dMassSRCarrier[i]; scalar hs = composition.carrier().Hs(i, pc, T0); td.cloud().rhoTrans(i)[celli] += dm; td.cloud().UTrans()[celli] += dm*U0; td.cloud().hsTrans()[celli] += dm*hs; } // Update momentum transfer td.cloud().UTrans()[celli] += np0*dUTrans; td.cloud().UCoeff()[celli] += np0*Spu; // Update sensible enthalpy transfer td.cloud().hsTrans()[celli] += np0*dhsTrans; td.cloud().hsCoeff()[celli] += np0*Sph; // Update radiation fields if (td.cloud().radiation()) { const scalar ap = this->areaP(); const scalar T4 = pow4(T0); td.cloud().radAreaP()[celli] += dt*np0*ap; td.cloud().radT4()[celli] += dt*np0*T4; td.cloud().radAreaPT4()[celli] += dt*np0*ap*T4; } } } // * * * * * * * * * * * * Protected Member Functions * * * * * * * * * * * // template<class ParcelType> template<class TrackData> void Foam::ReactingMultiphaseParcel<ParcelType>::calcDevolatilisation ( TrackData& td, const scalar dt, const scalar age, const scalar Ts, const scalar d, const scalar T, const scalar mass, const scalar mass0, const scalarField& YGasEff, const scalarField& YLiquidEff, const scalarField& YSolidEff, label& canCombust, scalarField& dMassDV, scalar& Sh, scalar& N, scalar& NCpW, scalarField& Cs ) const { // Check that model is active if (!td.cloud().devolatilisation().active()) { return; } // Initialise demand-driven constants (void)td.cloud().constProps().TDevol(); (void)td.cloud().constProps().LDevol(); // Check that the parcel temperature is within necessary limits for // devolatilisation to occur if (T < td.cloud().constProps().TDevol() || canCombust == -1) { return; } typedef typename TrackData::cloudType::reactingCloudType reactingCloudType; const CompositionModel<reactingCloudType>& composition = td.cloud().composition(); // Total mass of volatiles evolved td.cloud().devolatilisation().calculate ( dt, age, mass0, mass, T, YGasEff, YLiquidEff, YSolidEff, canCombust, dMassDV ); scalar dMassTot = sum(dMassDV); td.cloud().devolatilisation().addToDevolatilisationMass ( this->nParticle_*dMassTot ); Sh -= dMassTot*td.cloud().constProps().LDevol()/dt; // Update molar emissions if (td.cloud().heatTransfer().BirdCorrection()) { // Molar average molecular weight of carrier mix const scalar Wc = max(SMALL, this->rhoc_*RR*this->Tc_/this->pc_); // Note: hardcoded gaseous diffusivities for now // TODO: add to carrier thermo const scalar beta = sqr(cbrt(15.0) + cbrt(15.0)); forAll(dMassDV, i) { const label id = composition.localToCarrierId(GAS, i); const scalar Cp = composition.carrier().Cp(id, this->pc_, Ts); const scalar W = composition.carrier().W(id); const scalar Ni = dMassDV[i]/(this->areaS(d)*dt*W); // Dab calc'd using API vapour mass diffusivity function const scalar Dab = 3.6059e-3*(pow(1.8*Ts, 1.75)) *sqrt(1.0/W + 1.0/Wc) /(this->pc_*beta); N += Ni; NCpW += Ni*Cp*W; Cs[id] += Ni*d/(2.0*Dab); } } } template<class ParcelType> template<class TrackData> void Foam::ReactingMultiphaseParcel<ParcelType>::calcSurfaceReactions ( TrackData& td, const scalar dt, const label celli, const scalar d, const scalar T, const scalar mass, const label canCombust, const scalar N, const scalarField& YMix, const scalarField& YGas, const scalarField& YLiquid, const scalarField& YSolid, scalarField& dMassSRGas, scalarField& dMassSRLiquid, scalarField& dMassSRSolid, scalarField& dMassSRCarrier, scalar& Sh, scalar& dhsTrans ) const { // Check that model is active if (!td.cloud().surfaceReaction().active()) { return; } // Initialise demand-driven constants (void)td.cloud().constProps().hRetentionCoeff(); (void)td.cloud().constProps().TMax(); // Check that model is active if (canCombust != 1) { return; } // Update surface reactions const scalar hReaction = td.cloud().surfaceReaction().calculate ( dt, celli, d, T, this->Tc_, this->pc_, this->rhoc_, mass, YGas, YLiquid, YSolid, YMix, N, dMassSRGas, dMassSRLiquid, dMassSRSolid, dMassSRCarrier ); td.cloud().surfaceReaction().addToSurfaceReactionMass ( this->nParticle_ *(sum(dMassSRGas) + sum(dMassSRLiquid) + sum(dMassSRSolid)) ); const scalar xsi = min(T/td.cloud().constProps().TMax(), 1.0); const scalar coeff = (1.0 - xsi*xsi)*td.cloud().constProps().hRetentionCoeff(); Sh += coeff*hReaction/dt; dhsTrans += (1.0 - coeff)*hReaction; } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // template<class ParcelType> Foam::ReactingMultiphaseParcel<ParcelType>::ReactingMultiphaseParcel ( const ReactingMultiphaseParcel<ParcelType>& p ) : ParcelType(p), YGas_(p.YGas_), YLiquid_(p.YLiquid_), YSolid_(p.YSolid_), canCombust_(p.canCombust_) {} template<class ParcelType> Foam::ReactingMultiphaseParcel<ParcelType>::ReactingMultiphaseParcel ( const ReactingMultiphaseParcel<ParcelType>& p, const polyMesh& mesh ) : ParcelType(p, mesh), YGas_(p.YGas_), YLiquid_(p.YLiquid_), YSolid_(p.YSolid_), canCombust_(p.canCombust_) {} // * * * * * * * * * * * * * * IOStream operators * * * * * * * * * * * * * // #include "ReactingMultiphaseParcelIO.C" // ************************************************************************* //
gpl-3.0
idega/se.idega.idegaweb.commune.care
src/java/se/idega/idegaweb/commune/care/business/AccountingSessionHomeImpl.java
369
package se.idega.idegaweb.commune.care.business; public class AccountingSessionHomeImpl extends com.idega.business.IBOHomeImpl implements AccountingSessionHome { protected Class getBeanInterfaceClass(){ return AccountingSession.class; } public AccountingSession create() throws javax.ejb.CreateException{ return (AccountingSession) super.createIBO(); } }
gpl-3.0
terraframe/geodashboard
geoprism-web/src/main/webapp/3rd-party/mapbox/mapboxgl/mapbox-gl-js-0.34.0/test/unit/source/source_cache.test.js
29567
'use strict'; const test = require('mapbox-gl-js-test').test; const SourceCache = require('../../../src/source/source_cache'); const AnimationLoop = require('../../../src/style/animation_loop'); const Source = require('../../../src/source/source'); const Tile = require('../../../src/source/tile'); const TileCoord = require('../../../src/source/tile_coord'); const Transform = require('../../../src/geo/transform'); const LngLat = require('../../../src/geo/lng_lat'); const Coordinate = require('../../../src/geo/coordinate'); const Evented = require('../../../src/util/evented'); const util = require('../../../src/util/util'); // Add a mocked source type for use in these tests function MockSourceType(id, sourceOptions, _dispatcher, eventedParent) { // allow tests to override mocked methods/properties by providing // them in the source definition object that's given to Source.create() class SourceMock extends Evented { constructor() { super(); this.id = id; this.minzoom = 0; this.maxzoom = 22; util.extend(this, sourceOptions); this.setEventedParent(eventedParent); } loadTile(tile, callback) { if (sourceOptions.expires) { tile.setExpiryData({ expires: sourceOptions.expires }); } setTimeout(callback, 0); } onAdd() { if (sourceOptions.noLoad) return; if (sourceOptions.error) { this.fire('error', { error: sourceOptions.error }); } else { this.fire('data', {dataType: 'source', sourceDataType: 'metadata'}); } } abortTile() {} unloadTile() {} serialize() {} } const source = new SourceMock(); return source; } Source.setType('mock-source-type', MockSourceType); function createSourceCache(options, used) { const sc = new SourceCache('id', util.extend({ tileSize: 512, minzoom: 0, maxzoom: 14, type: 'mock-source-type' }, options), /* dispatcher */ {}); sc.used = typeof used === 'boolean' ? used : true; return sc; } test('SourceCache#addTile', (t) => { t.test('loads tile when uncached', (t) => { const coord = new TileCoord(0, 0, 0); const sourceCache = createSourceCache({ loadTile: function(tile) { t.deepEqual(tile.coord, coord); t.equal(tile.uses, 0); t.end(); } }); sourceCache.onAdd(); sourceCache.addTile(coord); }); t.test('adds tile when uncached', (t) => { const coord = new TileCoord(0, 0, 0); const sourceCache = createSourceCache({}) .on('dataloading', (data) => { t.deepEqual(data.tile.coord, coord); t.equal(data.tile.uses, 1); t.end(); }); sourceCache.onAdd(); sourceCache.addTile(coord); }); t.test('uses cached tile', (t) => { const coord = new TileCoord(0, 0, 0); let load = 0, add = 0; const sourceCache = createSourceCache({ loadTile: function(tile, callback) { tile.state = 'loaded'; load++; callback(); } }) .on('dataloading', () => { add++; }); const tr = new Transform(); tr.width = 512; tr.height = 512; sourceCache.updateCacheSize(tr); sourceCache.addTile(coord); sourceCache.removeTile(coord.id); sourceCache.addTile(coord); t.equal(load, 1); t.equal(add, 1); t.end(); }); t.test('moves timers when adding tile from cache', (t) => { const coord = new TileCoord(0, 0, 0); const time = new Date(); time.setSeconds(time.getSeconds() + 5); const sourceCache = createSourceCache(); sourceCache._setTileReloadTimer = (id) => { sourceCache._timers[id] = setTimeout(() => {}, 0); }; sourceCache._setCacheInvalidationTimer = (id) => { sourceCache._cacheTimers[id] = setTimeout(() => {}, 0); }; sourceCache.loadTile = (tile, callback) => { tile.state = 'loaded'; tile.getExpiryTimeout = () => time; sourceCache._setTileReloadTimer(coord.id, tile); callback(); }; const tr = new Transform(); tr.width = 512; tr.height = 512; sourceCache.updateCacheSize(tr); const id = coord.id; t.notOk(sourceCache._timers[id]); t.notOk(sourceCache._cacheTimers[id]); sourceCache.addTile(coord); t.ok(sourceCache._timers[id]); t.notOk(sourceCache._cacheTimers[id]); sourceCache.removeTile(coord.id); t.notOk(sourceCache._timers[id]); t.ok(sourceCache._cacheTimers[id]); sourceCache.addTile(coord); t.ok(sourceCache._timers[id]); t.notOk(sourceCache._cacheTimers[id]); t.end(); }); t.test('reuses wrapped tile', (t) => { const coord = new TileCoord(0, 0, 0); let load = 0, add = 0; const sourceCache = createSourceCache({ loadTile: function(tile, callback) { tile.state = 'loaded'; load++; callback(); } }) .on('dataloading', () => { add++; }); const t1 = sourceCache.addTile(coord); const t2 = sourceCache.addTile(new TileCoord(0, 0, 0, 1)); t.equal(load, 1); t.equal(add, 1); t.equal(t1, t2); t.end(); }); t.end(); }); test('SourceCache#removeTile', (t) => { t.test('removes tile', (t) => { const coord = new TileCoord(0, 0, 0); const sourceCache = createSourceCache({}); sourceCache.addTile(coord); sourceCache.on('data', ()=> { sourceCache.removeTile(coord.id); t.notOk(sourceCache._tiles[coord.id]); t.end(); }); }); t.test('caches (does not unload) loaded tile', (t) => { const coord = new TileCoord(0, 0, 0); const sourceCache = createSourceCache({ loadTile: function(tile) { tile.state = 'loaded'; }, unloadTile: function() { t.fail(); } }); const tr = new Transform(); tr.width = 512; tr.height = 512; sourceCache.updateCacheSize(tr); sourceCache.addTile(coord); sourceCache.removeTile(coord.id); t.end(); }); t.test('aborts and unloads unfinished tile', (t) => { const coord = new TileCoord(0, 0, 0); let abort = 0, unload = 0; const sourceCache = createSourceCache({ abortTile: function(tile) { t.deepEqual(tile.coord, coord); abort++; }, unloadTile: function(tile) { t.deepEqual(tile.coord, coord); unload++; } }); sourceCache.addTile(coord); sourceCache.removeTile(coord.id); t.equal(abort, 1); t.equal(unload, 1); t.end(); }); t.end(); }); test('SourceCache / Source lifecycle', (t) => { t.test('does not fire load or change before source load event', (t) => { const sourceCache = createSourceCache({noLoad: true}) .on('data', t.fail); sourceCache.onAdd(); setTimeout(t.end, 1); }); t.test('forward load event', (t) => { const sourceCache = createSourceCache({}).on('data', (e)=>{ if (e.sourceDataType === 'metadata') t.end(); }); sourceCache.onAdd(); }); t.test('forward change event', (t) => { const sourceCache = createSourceCache().on('data', (e)=>{ if (e.sourceDataType === 'metadata') t.end(); }); sourceCache.onAdd(); sourceCache.getSource().fire('data'); }); t.test('forward error event', (t) => { const sourceCache = createSourceCache({ error: 'Error loading source' }) .on('error', (err) => { t.equal(err.error, 'Error loading source'); t.end(); }); sourceCache.onAdd(); }); t.test('loaded() true after source error', (t) => { const sourceCache = createSourceCache({ error: 'Error loading source' }) .on('error', () => { t.ok(sourceCache.loaded()); t.end(); }); sourceCache.onAdd(); }); t.test('loaded() true after tile error', (t)=>{ const transform = new Transform(); transform.resize(511, 511); transform.zoom = 0; const sourceCache = createSourceCache({ loadTile: function (tile, callback) { callback("error"); } }).on('data', (e)=>{ if (e.dataType === 'source' && e.sourceDataType === 'metadata') { sourceCache.update(transform); } }).on('error', ()=>{ t.true(sourceCache.loaded()); t.end(); }); sourceCache.onAdd(); }); t.test('reloads tiles after a data event where source is updated', (t) => { const transform = new Transform(); transform.resize(511, 511); transform.zoom = 0; const expected = [ new TileCoord(0, 0, 0).id, new TileCoord(0, 0, 0).id ]; t.plan(expected.length); const sourceCache = createSourceCache({ loadTile: function (tile, callback) { t.equal(tile.coord.id, expected.shift()); tile.loaded = true; callback(); } }); sourceCache.on('data', (e) => { if (e.dataType === 'source' && e.sourceDataType === 'metadata') { sourceCache.update(transform); sourceCache.getSource().fire('data', {dataType: 'source', sourceDataType: 'content'}); } }); sourceCache.onAdd(); }); t.end(); }); test('SourceCache#update', (t) => { t.test('loads no tiles if used is false', (t) => { const transform = new Transform(); transform.resize(512, 512); transform.zoom = 0; const sourceCache = createSourceCache({}, false); sourceCache.on('data', (e) => { if (e.sourceDataType === 'metadata') { sourceCache.update(transform); t.deepEqual(sourceCache.getIds(), []); t.end(); } }); sourceCache.onAdd(); }); t.test('loads covering tiles', (t) => { const transform = new Transform(); transform.resize(511, 511); transform.zoom = 0; const sourceCache = createSourceCache({}); sourceCache.on('data', (e) => { if (e.sourceDataType === 'metadata') { sourceCache.update(transform); t.deepEqual(sourceCache.getIds(), [new TileCoord(0, 0, 0).id]); t.end(); } }); sourceCache.onAdd(); }); t.test('removes unused tiles', (t) => { const transform = new Transform(); transform.resize(511, 511); transform.zoom = 0; const sourceCache = createSourceCache({}); sourceCache.on('data', (e) => { if (e.sourceDataType === 'metadata') { sourceCache.update(transform); t.deepEqual(sourceCache.getIds(), [new TileCoord(0, 0, 0).id]); transform.zoom = 1; sourceCache.update(transform); t.deepEqual(sourceCache.getIds(), [ new TileCoord(1, 0, 0).id, new TileCoord(1, 1, 0).id, new TileCoord(1, 0, 1).id, new TileCoord(1, 1, 1).id ]); t.end(); } }); sourceCache.onAdd(); }); t.test('retains parent tiles for pending children', (t) => { const transform = new Transform(); transform._test = 'retains'; transform.resize(511, 511); transform.zoom = 0; const sourceCache = createSourceCache({ loadTile: function(tile, callback) { tile.state = (tile.coord.id === new TileCoord(0, 0, 0).id) ? 'loaded' : 'loading'; callback(); } }); sourceCache.on('data', (e) => { if (e.sourceDataType === 'metadata') { sourceCache.update(transform); t.deepEqual(sourceCache.getIds(), [new TileCoord(0, 0, 0).id]); transform.zoom = 1; sourceCache.update(transform); t.deepEqual(sourceCache.getIds(), [ new TileCoord(0, 0, 0).id, new TileCoord(1, 0, 0).id, new TileCoord(1, 1, 0).id, new TileCoord(1, 0, 1).id, new TileCoord(1, 1, 1).id ]); t.end(); } }); sourceCache.onAdd(); }); t.test('retains parent tiles for pending children (wrapped)', (t) => { const transform = new Transform(); transform.resize(511, 511); transform.zoom = 0; transform.center = new LngLat(360, 0); const sourceCache = createSourceCache({ loadTile: function(tile, callback) { tile.state = (tile.coord.id === new TileCoord(0, 0, 0).id) ? 'loaded' : 'loading'; callback(); } }); sourceCache.on('data', (e) => { if (e.sourceDataType === 'metadata') { sourceCache.update(transform); t.deepEqual(sourceCache.getIds(), [new TileCoord(0, 0, 0, 1).id]); transform.zoom = 1; sourceCache.update(transform); t.deepEqual(sourceCache.getIds(), [ new TileCoord(0, 0, 0, 1).id, new TileCoord(1, 0, 0, 1).id, new TileCoord(1, 1, 0, 1).id, new TileCoord(1, 0, 1, 1).id, new TileCoord(1, 1, 1, 1).id ]); t.end(); } }); sourceCache.onAdd(); }); t.test('retains covered child tiles while parent tile is fading in', (t) => { const transform = new Transform(); transform.resize(511, 511); transform.zoom = 2; const animationLoop = new AnimationLoop(); const sourceCache = createSourceCache({ loadTile: function(tile, callback) { tile.timeAdded = Infinity; tile.state = 'loaded'; tile.registerFadeDuration(animationLoop, 100); callback(); } }); sourceCache._source.type = 'raster'; sourceCache.on('data', (e) => { if (e.sourceDataType === 'metadata') { sourceCache.update(transform); t.deepEqual(sourceCache.getIds(), [ new TileCoord(2, 1, 1).id, new TileCoord(2, 2, 1).id, new TileCoord(2, 1, 2).id, new TileCoord(2, 2, 2).id ]); transform.zoom = 0; sourceCache.update(transform); t.deepEqual(sourceCache.getRenderableIds().length, 5); t.end(); } }); sourceCache.onAdd(); }); t.test('retains a parent tile for fading even if a tile is partially covered by children', (t) => { const transform = new Transform(); transform.resize(511, 511); transform.zoom = 0; const animationLoop = new AnimationLoop(); const sourceCache = createSourceCache({ loadTile: function(tile, callback) { tile.timeAdded = Infinity; tile.state = 'loaded'; tile.registerFadeDuration(animationLoop, 100); callback(); } }); sourceCache._source.type = 'raster'; sourceCache.on('data', (e) => { if (e.sourceDataType === 'metadata') { sourceCache.update(transform); transform.zoom = 2; sourceCache.update(transform); transform.zoom = 1; sourceCache.update(transform); t.equal(sourceCache._coveredTiles[(new TileCoord(0, 0, 0).id)], true); t.end(); } }); sourceCache.onAdd(); }); t.test('retains children for fading when tile.fadeEndTime is not set', (t) => { const transform = new Transform(); transform.resize(511, 511); transform.zoom = 1; const sourceCache = createSourceCache({ loadTile: function(tile, callback) { tile.timeAdded = Date.now(); tile.state = 'loaded'; callback(); } }); sourceCache._source.type = 'raster'; sourceCache.on('data', (e) => { if (e.sourceDataType === 'metadata') { sourceCache.update(transform); transform.zoom = 0; sourceCache.update(transform); t.equal(sourceCache.getRenderableIds().length, 5, 'retains 0/0/0 and its four children'); t.end(); } }); sourceCache.onAdd(); }); t.test('retains children when tile.fadeEndTime is in the future', (t) => { const transform = new Transform(); transform.resize(511, 511); transform.zoom = 1; const sourceCache = createSourceCache({ loadTile: function(tile, callback) { tile.timeAdded = Date.now(); tile.state = 'loaded'; tile.fadeEndTime = Date.now() + 100; callback(); } }); sourceCache._source.type = 'raster'; sourceCache.on('data', (e) => { if (e.sourceDataType === 'metadata') { sourceCache.update(transform); transform.zoom = 0; sourceCache.update(transform); t.equal(sourceCache.getRenderableIds().length, 5, 'retains 0/0/0 and its four children'); setTimeout(() => { sourceCache.update(transform); t.equal(sourceCache.getRenderableIds().length, 1, 'drops children after fading is complete'); t.end(); }, 100); } }); sourceCache.onAdd(); }); t.test('retains overscaled loaded children', (t) => { const transform = new Transform(); transform.resize(511, 511); transform.zoom = 16; // use slightly offset center so that sort order is better defined transform.center = new LngLat(-0.001, 0.001); const sourceCache = createSourceCache({ reparseOverscaled: true, loadTile: function(tile, callback) { tile.state = tile.coord.z === 16 ? 'loaded' : 'loading'; callback(); } }); sourceCache.on('data', (e) => { if (e.sourceDataType === 'metadata') { sourceCache.update(transform); t.deepEqual(sourceCache.getRenderableIds(), [ new TileCoord(16, 8191, 8191, 0).id, new TileCoord(16, 8192, 8191, 0).id, new TileCoord(16, 8191, 8192, 0).id, new TileCoord(16, 8192, 8192, 0).id ]); transform.zoom = 15; sourceCache.update(transform); t.deepEqual(sourceCache.getRenderableIds(), [ new TileCoord(16, 8191, 8191, 0).id, new TileCoord(16, 8192, 8191, 0).id, new TileCoord(16, 8191, 8192, 0).id, new TileCoord(16, 8192, 8192, 0).id ]); t.end(); } }); sourceCache.onAdd(); }); t.end(); }); test('SourceCache#clearTiles', (t) => { t.test('unloads tiles', (t) => { const coord = new TileCoord(0, 0, 0); let abort = 0, unload = 0; const sourceCache = createSourceCache({ abortTile: function(tile) { t.deepEqual(tile.coord, coord); abort++; }, unloadTile: function(tile) { t.deepEqual(tile.coord, coord); unload++; } }); sourceCache.onAdd(); sourceCache.addTile(coord); sourceCache.clearTiles(); t.equal(abort, 1); t.equal(unload, 1); t.end(); }); t.end(); }); test('SourceCache#tilesIn', (t) => { t.test('graceful response before source loaded', (t) => { const sourceCache = createSourceCache({ noLoad: true }); sourceCache.onAdd(); t.same(sourceCache.tilesIn([ new Coordinate(0.5, 0.25, 1), new Coordinate(1.5, 0.75, 1) ]), []); t.end(); }); t.test('regular tiles', (t) => { const transform = new Transform(); transform.resize(511, 511); transform.zoom = 1; const sourceCache = createSourceCache({ loadTile: function(tile, callback) { tile.state = 'loaded'; callback(); } }); sourceCache.on('data', (e) => { if (e.sourceDataType === 'metadata') { sourceCache.update(transform); t.deepEqual(sourceCache.getIds(), [ new TileCoord(1, 0, 0).id, new TileCoord(1, 1, 0).id, new TileCoord(1, 0, 1).id, new TileCoord(1, 1, 1).id ]); const tiles = sourceCache.tilesIn([ new Coordinate(0.5, 0.25, 1), new Coordinate(1.5, 0.75, 1) ]); tiles.sort((a, b) => { return a.tile.coord.x - b.tile.coord.x; }); tiles.forEach((result) => { delete result.tile.uid; }); t.equal(tiles[0].tile.coord.id, 1); t.equal(tiles[0].tile.tileSize, 512); t.equal(tiles[0].scale, 1); t.deepEqual(tiles[0].queryGeometry, [[{x: 4096, y: 2048}, {x:12288, y: 6144}]]); t.equal(tiles[1].tile.coord.id, 33); t.equal(tiles[1].tile.tileSize, 512); t.equal(tiles[1].scale, 1); t.deepEqual(tiles[1].queryGeometry, [[{x: -4096, y: 2048}, {x: 4096, y: 6144}]]); t.end(); } }); sourceCache.onAdd(); }); t.test('reparsed overscaled tiles', (t) => { const sourceCache = createSourceCache({ loadTile: function(tile, callback) { tile.state = 'loaded'; callback(); }, reparseOverscaled: true, minzoom: 1, maxzoom: 1, tileSize: 512 }); sourceCache.on('data', (e) => { if (e.sourceDataType === 'metadata') { const transform = new Transform(); transform.resize(512, 512); transform.zoom = 2.0; sourceCache.update(transform); t.deepEqual(sourceCache.getIds(), [ new TileCoord(2, 0, 0).id, new TileCoord(2, 1, 0).id, new TileCoord(2, 0, 1).id, new TileCoord(2, 1, 1).id ]); const tiles = sourceCache.tilesIn([ new Coordinate(0.5, 0.25, 1), new Coordinate(1.5, 0.75, 1) ]); tiles.sort((a, b) => { return a.tile.coord.x - b.tile.coord.x; }); tiles.forEach((result) => { delete result.tile.uid; }); t.equal(tiles[0].tile.coord.id, 2); t.equal(tiles[0].tile.tileSize, 1024); t.equal(tiles[0].scale, 1); t.deepEqual(tiles[0].queryGeometry, [[{x: 4096, y: 2048}, {x:12288, y: 6144}]]); t.equal(tiles[1].tile.coord.id, 34); t.equal(tiles[1].tile.tileSize, 1024); t.equal(tiles[1].scale, 1); t.deepEqual(tiles[1].queryGeometry, [[{x: -4096, y: 2048}, {x: 4096, y: 6144}]]); t.end(); } }); sourceCache.onAdd(); }); t.test('overscaled tiles', (t) => { const sourceCache = createSourceCache({ loadTile: function(tile, callback) { tile.state = 'loaded'; callback(); }, reparseOverscaled: false, minzoom: 1, maxzoom: 1, tileSize: 512 }); sourceCache.on('data', (e) => { if (e.sourceDataType === 'metadata') { const transform = new Transform(); transform.resize(512, 512); transform.zoom = 2.0; sourceCache.update(transform); t.end(); } }); sourceCache.onAdd(); }); t.end(); }); test('SourceCache#loaded (no errors)', (t) => { const sourceCache = createSourceCache({ loadTile: function(tile, callback) { tile.state = 'loaded'; callback(); } }); sourceCache.on('data', (e) => { if (e.sourceDataType === 'metadata') { const coord = new TileCoord(0, 0, 0); sourceCache.addTile(coord); t.ok(sourceCache.loaded()); t.end(); } }); sourceCache.onAdd(); }); test('SourceCache#loaded (with errors)', (t) => { const sourceCache = createSourceCache({ loadTile: function(tile) { tile.state = 'errored'; } }); sourceCache.on('data', (e) => { if (e.sourceDataType === 'metadata') { const coord = new TileCoord(0, 0, 0); sourceCache.addTile(coord); t.ok(sourceCache.loaded()); t.end(); } }); sourceCache.onAdd(); }); test('SourceCache#getIds (ascending order by zoom level)', (t) => { const ids = [ new TileCoord(0, 0, 0), new TileCoord(3, 0, 0), new TileCoord(1, 0, 0), new TileCoord(2, 0, 0) ]; const sourceCache = createSourceCache({}); for (let i = 0; i < ids.length; i++) { sourceCache._tiles[ids[i].id] = {}; } t.deepEqual(sourceCache.getIds(), [ new TileCoord(0, 0, 0).id, new TileCoord(1, 0, 0).id, new TileCoord(2, 0, 0).id, new TileCoord(3, 0, 0).id ]); t.end(); sourceCache.onAdd(); }); test('SourceCache#findLoadedParent', (t) => { t.test('adds from previously used tiles (sourceCache._tiles)', (t) => { const sourceCache = createSourceCache({}); sourceCache.onAdd(); const tr = new Transform(); tr.width = 512; tr.height = 512; sourceCache.updateCacheSize(tr); const tile = { coord: new TileCoord(1, 0, 0), hasData: function() { return true; } }; sourceCache._tiles[tile.coord.id] = tile; const retain = {}; const expectedRetain = {}; expectedRetain[tile.coord.id] = true; t.equal(sourceCache.findLoadedParent(new TileCoord(2, 3, 3), 0, retain), undefined); t.deepEqual(sourceCache.findLoadedParent(new TileCoord(2, 0, 0), 0, retain), tile); t.deepEqual(retain, expectedRetain); t.end(); }); t.test('retains parents', (t) => { const sourceCache = createSourceCache({}); sourceCache.onAdd(); const tr = new Transform(); tr.width = 512; tr.height = 512; sourceCache.updateCacheSize(tr); const tile = new Tile(new TileCoord(1, 0, 0), 512, 22); sourceCache._cache.add(tile.coord.id, tile); const retain = {}; const expectedRetain = {}; expectedRetain[tile.coord.id] = true; t.equal(sourceCache.findLoadedParent(new TileCoord(2, 3, 3), 0, retain), undefined); t.equal(sourceCache.findLoadedParent(new TileCoord(2, 0, 0), 0, retain), tile); t.deepEqual(retain, expectedRetain); t.equal(sourceCache._cache.order.length, 1); t.end(); }); t.end(); }); test('SourceCache#reload', (t) => { t.test('before loaded', (t) => { const sourceCache = createSourceCache({ noLoad: true }); sourceCache.onAdd(); t.doesNotThrow(() => { sourceCache.reload(); }, null, 'reload ignored gracefully'); t.end(); }); t.end(); }); test('SourceCache reloads expiring tiles', (t) => { t.test('calls reloadTile when tile expires', (t) => { const coord = new TileCoord(1, 0, 0); const expiryDate = new Date(); expiryDate.setMilliseconds(expiryDate.getMilliseconds() + 50); const sourceCache = createSourceCache({ expires: expiryDate }); sourceCache.reloadTile = (id, state) => { t.equal(state, 'expired'); t.end(); }; sourceCache.addTile(coord); }); t.end(); });
gpl-3.0
ManifoldScholar/manifold
client/src/reader/components/notation/viewer/Fader.js
1052
import React, { PureComponent } from "react"; import PropTypes from "prop-types"; import classNames from "classnames"; export default class NotationFader extends PureComponent { static displayName = "NotationViewer.Fader"; static propTypes = { children: PropTypes.element.isRequired }; constructor(props) { super(props); this.state = { visible: true }; } componentDidUpdate() { if (!this.wrapper) return; const rect = this.wrapper.getBoundingClientRect(); const visible = rect.top > 75 && rect.top + rect.height / 2 < window.innerHeight; // eslint-disable-next-line react/no-did-update-set-state this.setState({ visible }); } render() { const { children } = this.props; const classes = classNames("notation-preview-fader", { "transition-out": !this.state.visible, "transition-in": this.state.visible }); return ( <div className={classes} ref={r => { this.wrapper = r; }} > {children} </div> ); } }
gpl-3.0
asiapacificforum/nhridocs
vendor/gems/complaint_reporter/lib/complaint_reporter/version.rb
49
module ComplaintReporter VERSION = "0.0.1" end
gpl-3.0
samszo/open-edition
plugins-dist/compagnon/lang/compagnon_pt_br.php
4184
<?php // This is a SPIP language file -- Ceci est un fichier langue de SPIP // extrait automatiquement de http://trad.spip.net/tradlang_module/compagnon?lang_cible=pt_br // ** ne pas modifier le fichier ** if (!defined('_ECRIRE_INC_VERSION')) { return; } $GLOBALS[$GLOBALS['idx_lang']] = array( // C 'c_accueil_bienvenue' => 'Bem vindo @nom@!', 'c_accueil_configurer_site' => 'Configurar o seu site', 'c_accueil_configurer_site_texte' => 'Uma das primeiras coisas a fazer é dar um nome ao seu site. Atualmente, ele se chama « @nom@ ». O nome do site é exibido no alto desta página.Clicando abaixo, você poderá alterar o seu nome, bem como definir um logo e um slogan.', 'c_accueil_publication' => 'Publicar!', 'c_accueil_publication_texte' => 'Para publicar uma página, você precisa criar uma matéria. Para isso, é necessário que você crie pelo menos uma seção. Você pode fazê-lo no menu « Edição », clicando em « Seções ».', 'c_accueil_texte' => 'Você acaba de entrar na área privada do SPIP.', 'c_accueil_texte_revenir' => 'Esta página exibe a atividade editorial recente no seu site. Você pode voltar a esta página a qualquer momento clicando no ícone da casa, no cabeçalho, sob o seu nome.', # MODIF 'c_article_redaction' => 'A matéria está em fase de redação', 'c_article_redaction_redacteur' => 'A matéria está em fase de redação', 'c_article_redaction_redacteur_texte' => 'Para propor a sua matéria aos administradores do site e aos outros redatores, no box ao lado, altere «em fase de redação» por «proposta para publicação».', 'c_article_redaction_texte' => 'Para publicar esta matéria na área pública, é necessário alterar o seu status. No box ao lado mude de «em fase de redação» para «publicado online»', 'c_articles_creer' => 'Como criar uma matéria?', 'c_articles_creer_texte' => 'Você só poderá criar uma matéria a partir desta página após ter criado uma seção no seu site. Você pode criá-la a partir do menu « Edição » e, em seguida « Seções ».', 'c_job' => 'As tarefas a executar…', 'c_job_texte' => 'Esta página lista as próximas tarefas de manutenção que o SPIP deve efetuar. Estas tarefas são executadas em intervalos regulares, ou pontualmente para os procedimentos pesados solicitados pelos plugins, tais como o envio em massa de e-mails.', 'c_rubrique_publier' => 'Crie uma matéria', 'c_rubrique_publier_texte' => 'Uma seção só é exibida na área pública a partir do momento em que ela contenha pelo menos um conteúdo publicado. Crie então uma matéria. Você pode fazê-lo a partir desta página, abaixo da descrição da sua seção.', 'c_rubriques_creer' => 'Crie uma primeira seção!', 'c_rubriques_creer_texte' => 'As seções são a estrutura básica do site; você pode criar matérias em cada uma delas. Comece criando uma primeira seção.', 'c_sites_creer' => 'Como criar ou importar um site?', 'c_sites_creer_texte' => 'Você só poderá criar ou importar um site a partir desta página a partir do momento em que exista uma seção no seu site. Você poderá criá-la a partir do menu «Edição», na opção «Seções».', // E 'explication_activer_compagnon' => 'O companheiro inclui comentários em certas páginas da área restrita para ajudar a se familiarizar com o SPIP. Você quer ativá-lo?', 'explication_reinitialiser_compagnon' => 'As mensagens já vistas por um autor não são mais exibidas. Você quer reinicializar essas mensagens?', // L 'label_activer_compagnon' => 'Ativar o companheiro?', 'label_reinitialiser_compagnon' => 'Reinicializar as mensagens do companheiro?', // O 'ok' => 'OK', 'ok_bien' => 'Bom!', 'ok_jai_compris' => 'Entendido!', 'ok_merci' => 'Obrigado', 'ok_parfait' => 'Perfeito!', // R 'reinitialisation' => 'Reinicialização', 'reinitialisation_ok' => 'A reinicialização foi efetuada.', 'reinitialiser' => 'Reinicializar', 'reinitialiser_moi' => 'Sim, apenas as que eu já li', 'reinitialiser_tous' => 'Sim, para qualquer autor', // T 'titre_compagnon' => 'O Companheiro', 'titre_page_configurer_compagnon' => 'Configurar o Companheiro' ); ?>
gpl-3.0
tranleduy2000/javaide
jdk-1_7/src/main/java/javax/lang/model/util/AbstractTypeVisitor6.java
3814
/* * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.lang.model.util; import javax.lang.model.type.*; /** * A skeletal visitor of types with default behavior appropriate for * the {@link javax.lang.model.SourceVersion#RELEASE_6 RELEASE_6} * source version. * * <p> <b>WARNING:</b> The {@code TypeVisitor} interface implemented * by this class may have methods added to it in the future to * accommodate new, currently unknown, language structures added to * future versions of the Java&trade; programming language. * Therefore, methods whose names begin with {@code "visit"} may be * added to this class in the future; to avoid incompatibilities, * classes which extend this class should not declare any instance * methods with names beginning with {@code "visit"}. * * <p>When such a new visit method is added, the default * implementation in this class will be to call the {@link * #visitUnknown visitUnknown} method. A new abstract type visitor * class will also be introduced to correspond to the new language * level; this visitor will have different default behavior for the * visit method in question. When the new visitor is introduced, all * or portions of this visitor may be deprecated. * * @param <R> the return type of this visitor's methods. Use {@link * Void} for visitors that do not need to return results. * @param <P> the type of the additional parameter to this visitor's * methods. Use {@code Void} for visitors that do not need an * additional parameter. * * @author Joseph D. Darcy * @author Scott Seligman * @author Peter von der Ah&eacute; * * @see AbstractTypeVisitor7 * @since 1.6 */ public abstract class AbstractTypeVisitor6<R, P> implements TypeVisitor<R, P> { /** * Constructor for concrete subclasses to call. */ protected AbstractTypeVisitor6() {} /** * Visits any type mirror as if by passing itself to that type * mirror's {@link TypeMirror#accept accept} method. The * invocation {@code v.visit(t, p)} is equivalent to {@code * t.accept(v, p)}. * * @param t the type to visit * @param p a visitor-specified parameter * @return a visitor-specified result */ public final R visit(TypeMirror t, P p) { return t.accept(this, p); } /** * Visits any type mirror as if by passing itself to that type * mirror's {@link TypeMirror#accept accept} method and passing * {@code null} for the additional parameter. The invocation * {@code v.visit(t)} is equivalent to {@code t.accept(v, null)}. * * @param t the type to visit * @return a visitor-specified result */ public final R visit(TypeMirror t) { return t.accept(this, null); } /** * Visits a {@code UnionType} element by calling {@code * visitUnknown}. * @param t {@inheritDoc} * @param p {@inheritDoc} * @return the result of {@code visitUnknown} * * @since 1.7 */ public R visitUnion(UnionType t, P p) { return visitUnknown(t, p); } /** * {@inheritDoc} * * <p> The default implementation of this method in {@code * AbstractTypeVisitor6} will always throw {@code * UnknownTypeException}. This behavior is not required of a * subclass. * * @param t the type to visit * @return a visitor-specified result * @throws UnknownTypeException * a visitor implementation may optionally throw this exception */ public R visitUnknown(TypeMirror t, P p) { throw new UnknownTypeException(t, p); } }
gpl-3.0
Fatalerror66/ffxi-a
scripts/globals/items/bowl_of_stamina_soup.lua
1487
----------------------------------------- -- ID: 4337 -- Item: bowl_of_stamina_soup -- Food Effect: 4Hrs, All Races ----------------------------------------- -- HP % 10 -- Dexterity 4 -- Vitality 6 -- Mind -3 -- HP Recovered While Healing 10 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,4337); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 10); target:addMod(MOD_FOOD_HP_CAP, 999); target:addMod(MOD_DEX, 4); target:addMod(MOD_VIT, 6); target:addMod(MOD_MND, -3); target:addMod(MOD_HPHEAL, 10); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 10); target:delMod(MOD_FOOD_HP_CAP, 999); target:delMod(MOD_DEX, 4); target:delMod(MOD_VIT, 6); target:delMod(MOD_MND, -3); target:delMod(MOD_HPHEAL, 10); end;
gpl-3.0
censam/open_cart
multilanguage/OC-Europa-1-5-1-3-9.part01 (2)/upload/admin/language/polski/feed/google_base.php
1042
<?php /** * OpenCart 1.5.1.1 Polskie Tłumaczenie * * This script is protected by copyright. It's use, copying, modification * and distribution without written consent of the author is prohibited. * * * @category OpenCart * @package OpenCart * @author Krzysztof Kardasz <krzysztof.kardasz@gmail.com> * @copyright Copyright (c) 2011 Krzysztof Kardasz * @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU Lesser General Public * @version 1.5.1.1 $Id: google_base.php 3 2011-08-29 11:09:52Z krzysztof.kardasz $ * @link http://opencart-polish.googlecode.com * @link http://opencart-polish.googlecode.com/svn/branches/1.5.x/ */ // Heading $_['heading_title'] = 'Google Base'; // Text $_['text_feed'] = 'Kanał produktu'; $_['text_success'] = 'Sukces: Zmiany Google Base zapisane!'; // Entry $_['entry_status'] = 'Status:'; $_['entry_data_feed'] = 'Adres url danych kanału:'; // Error $_['error_permission'] = 'Uwaga: Nie masz uprawnień do modyfikacji Google Base!'; ?>
gpl-3.0
tectronics/magicgrove
source/Grove/UserInterface/Battlefield/ViewModel.cs
3974
namespace Grove.UserInterface.Battlefield { using System; using System.Linq; using Events; using Infrastructure; public class ViewModel : ViewModelBase, IReceive<AttachmentAttachedEvent>, IReceive<AttachmentDetachedEvent>, IDisposable { private readonly Player _owner; private readonly Row[] _rows = new[] { new Row( LandSlot(), LandSlot(), LandSlot(), LandSlot(), LandSlot(), LandSlot(), LandSlot()), new Row( CreatureSlot(), CreatureSlot(), CreatureSlot(), CreatureSlot(), CreatureSlot(), MiscSlot(), MiscSlot() ), }; public ViewModel(Player owner) { _owner = owner; } public Row Row1 { get { return SwitchRows ? _rows[1] : _rows[0]; } } public Row Row2 { get { return SwitchRows ? _rows[0] : _rows[1]; } } public bool SwitchRows { get { return _owner == Players.Player2; } } public void Dispose() { foreach (var row in _rows) { row.Dispose(); } } public void Receive(AttachmentAttachedEvent message) { if (message.Attachment.Controller == _owner && message.Attachment.Is().Equipment) { Attach(message.Attachment); } } public void Receive(AttachmentDetachedEvent message) { if (message.Attachment.Controller == _owner && message.Attachment.Zone == Zone.Battlefield) { Detach(message.Attachment); } } public override void Initialize() { foreach (var card in _owner.Battlefield.Where(x => !x.IsAttached)) { AddCard(card); } foreach (var card in _owner.Battlefield.Where(x => x.IsAttached)) { AddCard(card); } _owner.Battlefield.CardAdded += OnCardAdded; _owner.Battlefield.CardRemoved += OnCardRemoved; } private void OnCardRemoved(object sender, ZoneChangedEventArgs e) { var viewModel = GetPermanent(e.Card); viewModel.OnPermanentLeftBattlefield(); ViewModels.Permanent.Destroy(viewModel); Remove(viewModel); } private void OnCardAdded(object sender, ZoneChangedEventArgs e) { AddCard(e.Card); } private static Slot CreatureSlot() { return new Slot(vm => vm.Card.Is().Creature); } private static Slot LandSlot() { return new Slot(vm => vm.Card.Is().Land); } private static Slot MiscSlot() { return new Slot(vm => !vm.Card.Is().Creature && !vm.Card.Is().Land); } private void AddCard(Card card) { var viewModel = ViewModels.Permanent.Create(card); Add(viewModel); } private void Add(UserInterface.Permanent.ViewModel viewModel) { var row = _rows.First(r => r.CanAdd(viewModel)); row.Add(viewModel); } private void Attach(Card attachment) { var viewModel = GetPermanent(attachment); Remove(viewModel); foreach (var row in _rows) { if (row.ContainsAttachmentTarget(attachment)) { row.Add(viewModel); break; } } } private void Detach(Card equipment) { var viewModel = GetPermanent(equipment); if (viewModel != null) { Remove(viewModel); Add(viewModel); } } private UserInterface.Permanent.ViewModel GetPermanent(Card card) { foreach (var row in _rows) { var viewModel = row.GetPermanent(card); if (viewModel != null) { return viewModel; } } return null; } private void Remove(UserInterface.Permanent.ViewModel permanent) { foreach (var row in _rows) { var removed = row.Remove(permanent); if (removed) break; } } public interface IFactory { ViewModel Create(Player owner); } } }
gpl-3.0
SickGear/SickGear
lib/tornado_py2/autoreload.py
13459
# # Copyright 2009 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Automatically restart the server when a source file is modified. Most applications should not access this module directly. Instead, pass the keyword argument ``autoreload=True`` to the `tornado.web.Application` constructor (or ``debug=True``, which enables this setting and several others). This will enable autoreload mode as well as checking for changes to templates and static resources. Note that restarting is a destructive operation and any requests in progress will be aborted when the process restarts. (If you want to disable autoreload while using other debug-mode features, pass both ``debug=True`` and ``autoreload=False``). This module can also be used as a command-line wrapper around scripts such as unit test runners. See the `main` method for details. The command-line wrapper and Application debug modes can be used together. This combination is encouraged as the wrapper catches syntax errors and other import-time failures, while debug mode catches changes once the server has started. This module depends on `.IOLoop`, so it will not work in WSGI applications and Google App Engine. It also will not work correctly when `.HTTPServer`'s multi-process mode is used. Reloading loses any Python interpreter command-line arguments (e.g. ``-u``) because it re-executes Python using ``sys.executable`` and ``sys.argv``. Additionally, modifying these variables will cause reloading to behave incorrectly. """ from __future__ import absolute_import, division, print_function import os import sys # sys.path handling # ----------------- # # If a module is run with "python -m", the current directory (i.e. "") # is automatically prepended to sys.path, but not if it is run as # "path/to/file.py". The processing for "-m" rewrites the former to # the latter, so subsequent executions won't have the same path as the # original. # # Conversely, when run as path/to/file.py, the directory containing # file.py gets added to the path, which can cause confusion as imports # may become relative in spite of the future import. # # We address the former problem by reconstructing the original command # line (Python >= 3.4) or by setting the $PYTHONPATH environment # variable (Python < 3.4) before re-execution so the new process will # see the correct path. We attempt to address the latter problem when # tornado.autoreload is run as __main__. if __name__ == "__main__": # This sys.path manipulation must come before our imports (as much # as possible - if we introduced a tornado.sys or tornado.os # module we'd be in trouble), or else our imports would become # relative again despite the future import. # # There is a separate __main__ block at the end of the file to call main(). if sys.path[0] == os.path.dirname(__file__): del sys.path[0] import functools import logging import os import pkgutil # type: ignore import sys import traceback import types import subprocess import weakref from tornado_py2 import ioloop from tornado_py2.log import gen_log from tornado_py2 import process from tornado_py2.util import exec_in try: import signal except ImportError: signal = None # os.execv is broken on Windows and can't properly parse command line # arguments and executable name if they contain whitespaces. subprocess # fixes that behavior. _has_execv = sys.platform != 'win32' _watched_files = set() _reload_hooks = [] _reload_attempted = False _io_loops = weakref.WeakKeyDictionary() # type: ignore _autoreload_is_main = False _original_argv = None _original_spec = None def start(check_time=500): """Begins watching source files for changes. .. versionchanged:: 5.0 The ``io_loop`` argument (deprecated since version 4.1) has been removed. """ io_loop = ioloop.IOLoop.current() if io_loop in _io_loops: return _io_loops[io_loop] = True if len(_io_loops) > 1: gen_log.warning("tornado.autoreload started more than once in the same process") modify_times = {} callback = functools.partial(_reload_on_update, modify_times) scheduler = ioloop.PeriodicCallback(callback, check_time) scheduler.start() def wait(): """Wait for a watched file to change, then restart the process. Intended to be used at the end of scripts like unit test runners, to run the tests again after any source file changes (but see also the command-line interface in `main`) """ io_loop = ioloop.IOLoop() io_loop.add_callback(start) io_loop.start() def watch(filename): """Add a file to the watch list. All imported modules are watched by default. """ _watched_files.add(filename) def add_reload_hook(fn): """Add a function to be called before reloading the process. Note that for open file and socket handles it is generally preferable to set the ``FD_CLOEXEC`` flag (using `fcntl` or ``tornado.platform.auto.set_close_exec``) instead of using a reload hook to close them. """ _reload_hooks.append(fn) def _reload_on_update(modify_times): if _reload_attempted: # We already tried to reload and it didn't work, so don't try again. return if process.task_id() is not None: # We're in a child process created by fork_processes. If child # processes restarted themselves, they'd all restart and then # all call fork_processes again. return for module in list(sys.modules.values()): # Some modules play games with sys.modules (e.g. email/__init__.py # in the standard library), and occasionally this can cause strange # failures in getattr. Just ignore anything that's not an ordinary # module. if not isinstance(module, types.ModuleType): continue path = getattr(module, "__file__", None) if not path: continue if path.endswith(".pyc") or path.endswith(".pyo"): path = path[:-1] _check_file(modify_times, path) for path in _watched_files: _check_file(modify_times, path) def _check_file(modify_times, path): try: modified = os.stat(path).st_mtime except Exception: return if path not in modify_times: modify_times[path] = modified return if modify_times[path] != modified: gen_log.info("%s modified; restarting server", path) _reload() def _reload(): global _reload_attempted _reload_attempted = True for fn in _reload_hooks: fn() if hasattr(signal, "setitimer"): # Clear the alarm signal set by # ioloop.set_blocking_log_threshold so it doesn't fire # after the exec. signal.setitimer(signal.ITIMER_REAL, 0, 0) # sys.path fixes: see comments at top of file. If __main__.__spec__ # exists, we were invoked with -m and the effective path is about to # change on re-exec. Reconstruct the original command line to # ensure that the new process sees the same path we did. If # __spec__ is not available (Python < 3.4), check instead if # sys.path[0] is an empty string and add the current directory to # $PYTHONPATH. if _autoreload_is_main: spec = _original_spec argv = _original_argv else: spec = getattr(sys.modules['__main__'], '__spec__', None) argv = sys.argv if spec: argv = ['-m', spec.name] + argv[1:] else: path_prefix = '.' + os.pathsep if (sys.path[0] == '' and not os.environ.get("PYTHONPATH", "").startswith(path_prefix)): os.environ["PYTHONPATH"] = (path_prefix + os.environ.get("PYTHONPATH", "")) if not _has_execv: subprocess.Popen([sys.executable] + argv) os._exit(0) else: try: os.execv(sys.executable, [sys.executable] + argv) except OSError: # Mac OS X versions prior to 10.6 do not support execv in # a process that contains multiple threads. Instead of # re-executing in the current process, start a new one # and cause the current process to exit. This isn't # ideal since the new process is detached from the parent # terminal and thus cannot easily be killed with ctrl-C, # but it's better than not being able to autoreload at # all. # Unfortunately the errno returned in this case does not # appear to be consistent, so we can't easily check for # this error specifically. os.spawnv(os.P_NOWAIT, sys.executable, [sys.executable] + argv) # At this point the IOLoop has been closed and finally # blocks will experience errors if we allow the stack to # unwind, so just exit uncleanly. os._exit(0) _USAGE = """\ Usage: python -m tornado.autoreload -m module.to.run [args...] python -m tornado.autoreload path/to/script.py [args...] """ def main(): """Command-line wrapper to re-run a script whenever its source changes. Scripts may be specified by filename or module name:: python -m tornado.autoreload -m tornado.test.runtests python -m tornado.autoreload tornado/test/runtests.py Running a script with this wrapper is similar to calling `tornado.autoreload.wait` at the end of the script, but this wrapper can catch import-time problems like syntax errors that would otherwise prevent the script from reaching its call to `wait`. """ # Remember that we were launched with autoreload as main. # The main module can be tricky; set the variables both in our globals # (which may be __main__) and the real importable version. import tornado_py2.autoreload global _autoreload_is_main global _original_argv, _original_spec tornado_py2.autoreload._autoreload_is_main = _autoreload_is_main = True original_argv = sys.argv tornado_py2.autoreload._original_argv = _original_argv = original_argv original_spec = getattr(sys.modules['__main__'], '__spec__', None) tornado_py2.autoreload._original_spec = _original_spec = original_spec sys.argv = sys.argv[:] if len(sys.argv) >= 3 and sys.argv[1] == "-m": mode = "module" module = sys.argv[2] del sys.argv[1:3] elif len(sys.argv) >= 2: mode = "script" script = sys.argv[1] sys.argv = sys.argv[1:] else: print(_USAGE, file=sys.stderr) sys.exit(1) try: if mode == "module": import runpy runpy.run_module(module, run_name="__main__", alter_sys=True) elif mode == "script": with open(script) as f: # Execute the script in our namespace instead of creating # a new one so that something that tries to import __main__ # (e.g. the unittest module) will see names defined in the # script instead of just those defined in this module. global __file__ __file__ = script # If __package__ is defined, imports may be incorrectly # interpreted as relative to this module. global __package__ del __package__ exec_in(f.read(), globals(), globals()) except SystemExit as e: logging.basicConfig() gen_log.info("Script exited with status %s", e.code) except Exception as e: logging.basicConfig() gen_log.warning("Script exited with uncaught exception", exc_info=True) # If an exception occurred at import time, the file with the error # never made it into sys.modules and so we won't know to watch it. # Just to make sure we've covered everything, walk the stack trace # from the exception and watch every file. for (filename, lineno, name, line) in traceback.extract_tb(sys.exc_info()[2]): watch(filename) if isinstance(e, SyntaxError): # SyntaxErrors are special: their innermost stack frame is fake # so extract_tb won't see it and we have to get the filename # from the exception object. watch(e.filename) else: logging.basicConfig() gen_log.info("Script exited normally") # restore sys.argv so subsequent executions will include autoreload sys.argv = original_argv if mode == 'module': # runpy did a fake import of the module as __main__, but now it's # no longer in sys.modules. Figure out where it is and watch it. loader = pkgutil.get_loader(module) if loader is not None: watch(loader.get_filename()) wait() if __name__ == "__main__": # See also the other __main__ block at the top of the file, which modifies # sys.path before our imports main()
gpl-3.0
structr/structr
structr-db-driver-api/src/main/java/org/structr/api/config/IntegerChoiceSetting.java
2128
/* * Copyright (C) 2010-2021 Structr GmbH * * This file is part of Structr <http://structr.org>. * * Structr is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Structr 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 Structr. If not, see <http://www.gnu.org/licenses/>. */ package org.structr.api.config; import java.util.LinkedHashMap; import java.util.Map; import org.structr.api.util.html.Attr; import org.structr.api.util.html.Tag; /** * A configuration setting with a key and a type. */ public class IntegerChoiceSetting extends IntegerSetting { private final Map<Integer, String> choices = new LinkedHashMap<>(); public IntegerChoiceSetting(final SettingsGroup group, final String groupName, final String key, final Integer value, final Map<Integer, String> choices) { this(group, groupName, key, value, choices, null); } public IntegerChoiceSetting(final SettingsGroup group, final String groupName, final String key, final Integer value, final Map<Integer, String> choices, final String comment) { super(group, groupName, key, value, comment); this.choices.putAll(choices); } @Override public void render(final Tag parent) { final Tag group = parent.block("div").css("form-group"); renderLabel(group); final Tag select = group.block("select").attr(new Attr("name", getKey())); for (final Map.Entry<Integer, String> entry : choices.entrySet()) { final Tag option = select.block("option").text(entry.getValue()); option.attr(new Attr("value", entry.getKey())); // selected? if (entry.getKey().equals(getValue())) { option.attr(new Attr("selected", "selected")); } } renderResetButton(group); } }
gpl-3.0
smarthit/openemr
interface/super/edit_layout.php
72500
<?php /** * Copyright (C) 2014 Rod Roark <rod@sunsetsystems.com> * * LICENSE: 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://opensource.org/licenses/gpl-license.php>. * * @package OpenEMR * @author Rod Roark <rod@sunsetsystems.com> * @link http://www.open-emr.org */ require_once("../globals.php"); require_once("$srcdir/acl.inc"); require_once("$srcdir/log.inc"); require_once("$srcdir/formdata.inc.php"); $layouts = array( 'DEM' => xl('Demographics'), 'HIS' => xl('History'), 'REF' => xl('Referrals'), 'FACUSR' => xl('Facility Specific User Information') ); if ($GLOBALS['ippf_specific']) { $layouts['GCA'] = xl('Abortion Issues'); $layouts['CON'] = xl('Contraception Issues'); // $layouts['SRH'] = xl('SRH Visit Form'); } // Include Layout Based Encounter Forms. $lres = sqlStatement("SELECT * FROM list_options " . "WHERE list_id = 'lbfnames' ORDER BY seq, title"); while ($lrow = sqlFetchArray($lres)) { $layouts[$lrow['option_id']] = $lrow['title']; } // array of the data_types of the fields $datatypes = array( "1" => xl("List box"), "2" => xl("Textbox"), "3" => xl("Textarea"), "4" => xl("Text-date"), "10" => xl("Providers"), "11" => xl("Providers NPI"), "12" => xl("Pharmacies"), "13" => xl("Squads"), "14" => xl("Organizations"), "15" => xl("Billing codes"), "16" => xl("Insurances"), "18" => xl("Visit Categories"), "21" => xl("Checkbox list"), "22" => xl("Textbox list"), "23" => xl("Exam results"), "24" => xl("Patient allergies"), "25" => xl("Checkbox w/text"), "26" => xl("List box w/add"), "27" => xl("Radio buttons"), "28" => xl("Lifestyle status"), "31" => xl("Static Text"), "32" => xl("Smoking Status"), "33" => xl("Race and Ethnicity"), "34" => xl("NationNotes"), "35" => xl("Facilities"), "36" => xl("Multiple Select List") ); $sources = array( 'F' => xl('Form'), 'D' => xl('Patient'), 'H' => xl('History'), 'E' => xl('Visit'), 'V' => xl('VisForm'), ); function nextGroupOrder($order) { if ($order == '9') $order = 'A'; else if ($order == 'Z') $order = 'a'; else $order = chr(ord($order) + 1); return $order; } // Check authorization. $thisauth = acl_check('admin', 'super'); if (!$thisauth) die(xl('Not authorized')); // The layout ID identifies the layout to be edited. $layout_id = empty($_REQUEST['layout_id']) ? '' : $_REQUEST['layout_id']; // Tag style for stuff to hide if not an LBF layout. $lbfonly = substr($layout_id,0,3) == 'LBF' ? "" : "style='display:none;'"; // Handle the Form actions if ($_POST['formaction'] == "save" && $layout_id) { // If we are saving, then save. $fld = $_POST['fld']; for ($lino = 1; isset($fld[$lino]['id']); ++$lino) { $iter = $fld[$lino]; $field_id = formTrim($iter['id']); $data_type = formTrim($iter['data_type']); $listval = $data_type == 34 ? formTrim($iter['contextName']) : formTrim($iter['list_id']); // Skip conditions for the line are stored as a serialized array. $condarr = array(); for ($cix = 0; !empty($iter['condition_id'][$cix]); ++$cix) { $andor = empty($iter['condition_andor'][$cix]) ? '' : $iter['condition_andor'][$cix]; $condarr[$cix] = array( 'id' => strip_escape_custom($iter['condition_id' ][$cix]), 'itemid' => strip_escape_custom($iter['condition_itemid' ][$cix]), 'operator' => strip_escape_custom($iter['condition_operator'][$cix]), 'value' => strip_escape_custom($iter['condition_value' ][$cix]), 'andor' => strip_escape_custom($andor), ); } $conditions = empty($condarr) ? '' : serialize($condarr); if ($field_id) { sqlStatement("UPDATE layout_options SET " . "source = '" . formTrim($iter['source']) . "', " . "title = '" . formTrim($iter['title']) . "', " . "group_name = '" . formTrim($iter['group']) . "', " . "seq = '" . formTrim($iter['seq']) . "', " . "uor = '" . formTrim($iter['uor']) . "', " . "fld_length = '" . formTrim($iter['lengthWidth']) . "', " . "fld_rows = '" . formTrim($iter['lengthHeight']) . "', " . "max_length = '" . formTrim($iter['maxSize']) . "', " . "titlecols = '" . formTrim($iter['titlecols']) . "', " . "datacols = '" . formTrim($iter['datacols']) . "', " . "data_type= '$data_type', " . "list_id= '" . $listval . "', " . "list_backup_id= '" . formTrim($iter['list_backup_id']) . "', " . "edit_options = '" . formTrim($iter['edit_options']) . "', " . "default_value = '" . formTrim($iter['default']) . "', " . "description = '" . formTrim($iter['desc']) . "', " . "conditions = '" . add_escape_custom($conditions) . "' " . "WHERE form_id = '$layout_id' AND field_id = '$field_id'"); } } } else if ($_POST['formaction'] == "addfield" && $layout_id) { // Add a new field to a specific group $data_type = formTrim($_POST['newdatatype']); $max_length = $data_type == 3 ? 3 : 255; $listval = $data_type == 34 ? formTrim($_POST['contextName']) : formTrim($_POST['newlistid']); sqlStatement("INSERT INTO layout_options (" . " form_id, source, field_id, title, group_name, seq, uor, fld_length, fld_rows" . ", titlecols, datacols, data_type, edit_options, default_value, description" . ", max_length, list_id, list_backup_id " . ") VALUES ( " . "'" . formTrim($_POST['layout_id'] ) . "'" . ",'" . formTrim($_POST['newsource'] ) . "'" . ",'" . formTrim($_POST['newid'] ) . "'" . ",'" . formTrim($_POST['newtitle'] ) . "'" . ",'" . formTrim($_POST['newfieldgroupid']) . "'" . ",'" . formTrim($_POST['newseq'] ) . "'" . ",'" . formTrim($_POST['newuor'] ) . "'" . ",'" . formTrim($_POST['newlengthWidth'] ) . "'" . ",'" . formTrim($_POST['newlengthHeight'] ) . "'" . ",'" . formTrim($_POST['newtitlecols'] ) . "'" . ",'" . formTrim($_POST['newdatacols'] ) . "'" . ",'$data_type'" . ",'" . formTrim($_POST['newedit_options']) . "'" . ",'" . formTrim($_POST['newdefault'] ) . "'" . ",'" . formTrim($_POST['newdesc'] ) . "'" . ",'" . formTrim($_POST['newmaxSize']) . "'" . ",'" . $listval . "'" . ",'" . formTrim($_POST['newbackuplistid']) . "'" . " )"); if (substr($layout_id,0,3) != 'LBF' && $layout_id != "FACUSR") { // Add the field to the table too (this is critical) if ($layout_id == "DEM") { $tablename = "patient_data"; } else if ($layout_id == "HIS") { $tablename = "history_data"; } else if ($layout_id == "REF") { $tablename = "transactions"; } else if ($layout_id == "SRH") { $tablename = "lists_ippf_srh"; } else if ($layout_id == "CON") { $tablename = "lists_ippf_con"; } else if ($layout_id == "GCA") { $tablename = "lists_ippf_gcac"; } sqlStatement("ALTER TABLE `" . $tablename . "` ADD ". "`" . formTrim($_POST['newid']) . "`" . " TEXT NOT NULL"); newEvent("alter_table", $_SESSION['authUser'], $_SESSION['authProvider'], 1, $tablename . " ADD " . formTrim($_POST['newid'])); } } else if ($_POST['formaction'] == "movefields" && $layout_id) { // Move field(s) to a new group in the layout $sqlstmt = "UPDATE layout_options SET ". " group_name='". $_POST['targetgroup']."' ". " WHERE ". " form_id = '".$_POST['layout_id']."' ". " AND field_id IN ("; $comma = ""; foreach (explode(" ", $_POST['selectedfields']) as $onefield) { $sqlstmt .= $comma."'".$onefield."'"; $comma = ", "; } $sqlstmt .= ")"; //echo $sqlstmt; sqlStatement($sqlstmt); } else if ($_POST['formaction'] == "deletefields" && $layout_id) { // Delete a field from a specific group $sqlstmt = "DELETE FROM layout_options WHERE ". " form_id = '".$_POST['layout_id']."' ". " AND field_id IN ("; $comma = ""; foreach (explode(" ", $_POST['selectedfields']) as $onefield) { $sqlstmt .= $comma."'".$onefield."'"; $comma = ", "; } $sqlstmt .= ")"; sqlStatement($sqlstmt); if (substr($layout_id,0,3) != 'LBF' && $layout_id != "FACUSR") { // drop the field from the table too (this is critical) if ($layout_id == "DEM") { $tablename = "patient_data"; } else if ($layout_id == "HIS") { $tablename = "history_data"; } else if ($layout_id == "REF") { $tablename = "transactions"; } else if ($layout_id == "SRH") { $tablename = "lists_ippf_srh"; } else if ($layout_id == "CON") { $tablename = "lists_ippf_con"; } else if ($layout_id == "GCA") { $tablename = "lists_ippf_gcac"; } foreach (explode(" ", $_POST['selectedfields']) as $onefield) { sqlStatement("ALTER TABLE `".$tablename."` DROP `".$onefield."`"); newEvent("alter_table", $_SESSION['authUser'], $_SESSION['authProvider'], 1, $tablename." DROP ".$onefield); } } } else if ($_POST['formaction'] == "addgroup" && $layout_id) { // all group names are prefixed with a number indicating their display order // this new group is prefixed with the net highest number given the // layout_id $results = sqlStatement("select distinct(group_name) as gname ". " from layout_options where ". " form_id = '".$_POST['layout_id']."'" ); $maxnum = '1'; while ($result = sqlFetchArray($results)) { $tmp = substr($result['gname'], 0, 1); if ($tmp >= $maxnum) $maxnum = nextGroupOrder($tmp); } $data_type = formTrim($_POST['gnewdatatype']); $max_length = $data_type == 3 ? 3 : 255; $listval = $data_type == 34 ? formTrim($_POST['gcontextName']) : formTrim($_POST['gnewlistid']); // add a new group to the layout, with the defined field sqlStatement("INSERT INTO layout_options (" . " form_id, source, field_id, title, group_name, seq, uor, fld_length, fld_rows" . ", titlecols, datacols, data_type, edit_options, default_value, description" . ", max_length, list_id, list_backup_id " . ") VALUES ( " . "'" . formTrim($_POST['layout_id'] ) . "'" . ",'" . formTrim($_POST['gnewsource'] ) . "'" . ",'" . formTrim($_POST['gnewid'] ) . "'" . ",'" . formTrim($_POST['gnewtitle'] ) . "'" . ",'" . formTrim($maxnum . $_POST['newgroupname']) . "'" . ",'" . formTrim($_POST['gnewseq'] ) . "'" . ",'" . formTrim($_POST['gnewuor'] ) . "'" . ",'" . formTrim($_POST['gnewlengthWidth'] ) . "'" . ",'" . formTrim($_POST['gnewlengthHeight'] ) . "'" . ",'" . formTrim($_POST['gnewtitlecols'] ) . "'" . ",'" . formTrim($_POST['gnewdatacols'] ) . "'" . ",'$data_type'" . ",'" . formTrim($_POST['gnewedit_options']) . "'" . ",'" . formTrim($_POST['gnewdefault'] ) . "'" . ",'" . formTrim($_POST['gnewdesc'] ) . "'" . ",'" . formTrim($_POST['gnewmaxSize']) . "'" . ",'" . $listval . "'" . ",'" . formTrim($_POST['gnewbackuplistid'] ) . "'" . " )"); if (substr($layout_id,0,3) != 'LBF' && $layout_id != "FACUSR") { // Add the field to the table too (this is critical) if ($layout_id == "DEM") { $tablename = "patient_data"; } else if ($layout_id == "HIS") { $tablename = "history_data"; } else if ($layout_id == "REF") { $tablename = "transactions"; } else if ($layout_id == "SRH") { $tablename = "lists_ippf_srh"; } else if ($layout_id == "CON") { $tablename = "lists_ippf_con"; } else if ($layout_id == "GCA") { $tablename = "lists_ippf_gcac"; } sqlStatement("ALTER TABLE `" . $tablename . "` ADD ". "`" . formTrim($_POST['gnewid']) . "`" . " TEXT NOT NULL"); newEvent("alter_table", $_SESSION['authUser'], $_SESSION['authProvider'], 1, $tablename . " ADD " . formTrim($_POST['gnewid'])); } } else if ($_POST['formaction'] == "deletegroup" && $layout_id) { // drop the fields from the related table (this is critical) if (substr($layout_id,0,3) != 'LBF' && $layout_id != "FACUSR") { $res = sqlStatement("SELECT field_id FROM layout_options WHERE " . " form_id = '".$_POST['layout_id']."' ". " AND group_name = '".$_POST['deletegroupname']."'" ); while ($row = sqlFetchArray($res)) { // drop the field from the table too (this is critical) if ($layout_id == "DEM") { $tablename = "patient_data"; } else if ($layout_id == "HIS") { $tablename = "history_data"; } else if ($layout_id == "REF") { $tablename = "transactions"; } else if ($layout_id == "SRH") { $tablename = "lists_ippf_srh"; } else if ($layout_id == "CON") { $tablename = "lists_ippf_con"; } else if ($layout_id == "GCA") { $tablename = "lists_ippf_gcac"; } sqlStatement("ALTER TABLE `".$tablename."` DROP `".$row['field_id']."`"); newEvent("alter_table", $_SESSION['authUser'], $_SESSION['authProvider'], 1, $tablename." DROP ".trim($row['field_id'])); } } // Delete an entire group from the form sqlStatement("DELETE FROM layout_options WHERE ". " form_id = '".$_POST['layout_id']."' ". " AND group_name = '".$_POST['deletegroupname']."'" ); } else if ($_POST['formaction'] == "movegroup" && $layout_id) { $results = sqlStatement("SELECT DISTINCT(group_name) AS gname " . "FROM layout_options WHERE form_id = '$layout_id' " . "ORDER BY gname"); $garray = array(); $i = 0; while ($result = sqlFetchArray($results)) { if ($result['gname'] == $_POST['movegroupname']) { if ($_POST['movedirection'] == 'up') { // moving up if ($i > 0) { $garray[$i] = $garray[$i - 1]; $garray[$i - 1] = $result['gname']; $i++; } else { $garray[$i++] = $result['gname']; } } else { // moving down $garray[$i++] = ''; $garray[$i++] = $result['gname']; } } else if ($i > 1 && $garray[$i - 2] == '') { $garray[$i - 2] = $result['gname']; } else { $garray[$i++] = $result['gname']; } } $nextord = '1'; foreach ($garray as $value) { if ($value === '') continue; $newname = $nextord . substr($value, 1); sqlStatement("UPDATE layout_options SET " . "group_name = '$newname' WHERE " . "form_id = '$layout_id' AND " . "group_name = '$value'"); $nextord = nextGroupOrder($nextord); } } else if ($_POST['formaction'] == "renamegroup" && $layout_id) { $currpos = substr($_POST['renameoldgroupname'], 0, 1); // update the database rows sqlStatement("UPDATE layout_options SET " . "group_name = '" . $currpos . $_POST['renamegroupname'] . "' ". "WHERE form_id = '$layout_id' AND ". "group_name = '" . $_POST['renameoldgroupname'] . "'"); } // Get the selected form's elements. if ($layout_id) { $res = sqlStatement("SELECT * FROM layout_options WHERE " . "form_id = '$layout_id' ORDER BY group_name, seq"); } // global counter for field numbers $fld_line_no = 0; $extra_html = ''; // This is called to generate a select option list for fields within this form. // Used for selecting a field for testing in a skip condition. // function genFieldOptionList($current='') { global $layout_id; $option_list = "<option value=''>-- " . xlt('Please Select') . " --</option>"; if ($layout_id) { $query = "SELECT field_id FROM layout_options WHERE form_id = ? ORDER BY group_name, seq"; $res = sqlStatement($query, array($layout_id)); while ($row = sqlFetchArray($res)) { $field_id = $row['field_id']; $option_list .= "<option value='" . attr($field_id) . "'"; if ($field_id == $current) $option_list .= " selected"; $option_list .= ">" . text($field_id) . "</option>"; } } return $option_list; } // Write one option line to the form. // function writeFieldLine($linedata) { global $fld_line_no, $sources, $lbfonly, $extra_html; ++$fld_line_no; $checked = $linedata['default_value'] ? " checked" : ""; //echo " <tr bgcolor='$bgcolor'>\n"; echo " <tr id='fld[$fld_line_no]' class='".($fld_line_no % 2 ? 'even' : 'odd')."'>\n"; echo " <td class='optcell' style='width:4%' nowrap>"; // tuck the group_name INPUT in here echo "<input type='hidden' name='fld[$fld_line_no][group]' value='" . htmlspecialchars($linedata['group_name'], ENT_QUOTES) . "' class='optin' />"; echo "<input type='checkbox' class='selectfield' ". "name='".$linedata['group_name']."~".$linedata['field_id']."' ". "id='".$linedata['group_name']."~".$linedata['field_id']."' ". "title='".htmlspecialchars(xl('Select field', ENT_QUOTES))."'>"; echo "<input type='text' name='fld[$fld_line_no][seq]' id='fld[$fld_line_no][seq]' value='" . htmlspecialchars($linedata['seq'], ENT_QUOTES) . "' size='2' maxlength='3' " . "class='optin' style='width:36pt' />"; echo "</td>\n"; echo " <td align='center' class='optcell' $lbfonly style='width:3%'>"; echo "<select name='fld[$fld_line_no][source]' class='optin noselect' $lbfonly>"; foreach ($sources as $key => $value) { echo "<option value='" . attr($key) . "'"; if ($key == $linedata['source']) echo " selected"; echo ">" . text($value) . "</option>\n"; } echo "</select>"; echo "</td>\n"; echo " <td align='left' class='optcell' style='width:10%'>"; echo "<input type='text' name='fld[$fld_line_no][id]' value='" . htmlspecialchars($linedata['field_id'], ENT_QUOTES) . "' size='15' maxlength='63' class='optin noselect' style='width:100%' />"; // class='optin noselect' onclick='FieldIDClicked(this)' />"; /* echo "<input type='hidden' name='fld[$fld_line_no][id]' value='" . htmlspecialchars($linedata['field_id'], ENT_QUOTES) . "' />"; echo htmlspecialchars($linedata['field_id'], ENT_QUOTES); */ echo "</td>\n"; echo " <td align='center' class='optcell' style='width:12%'>"; echo "<input type='text' id='fld[$fld_line_no][title]' name='fld[$fld_line_no][title]' value='" . htmlspecialchars($linedata['title'], ENT_QUOTES) . "' size='15' maxlength='63' class='optin' style='width:100%' />"; echo "</td>\n"; // if not english and set to translate layout labels, then show the translation if ($GLOBALS['translate_layout'] && $_SESSION['language_choice'] > 1) { echo "<td align='center' class='translation' style='width:10%'>" . htmlspecialchars(xl($linedata['title']), ENT_QUOTES) . "</td>\n"; } echo " <td align='center' class='optcell' style='width:4%'>"; echo "<select name='fld[$fld_line_no][uor]' class='optin'>"; foreach (array(0 =>xl('Unused'), 1 =>xl('Optional'), 2 =>xl('Required')) as $key => $value) { echo "<option value='$key'"; if ($key == $linedata['uor']) echo " selected"; echo ">$value</option>\n"; } echo "</select>"; echo "</td>\n"; echo " <td align='center' class='optcell' style='width:8%'>"; echo "<select name='fld[$fld_line_no][data_type]' id='fld[$fld_line_no][data_type]' onchange=NationNotesContext('".$fld_line_no."',this.value)>"; echo "<option value=''></option>"; GLOBAL $datatypes; foreach ($datatypes as $key=>$value) { if ($linedata['data_type'] == $key) echo "<option value='$key' selected>$value</option>"; else echo "<option value='$key'>$value</option>"; } echo "</select>"; echo " </td>"; echo " <td align='center' class='optcell' style='width:4%'>"; if ($linedata['data_type'] == 2 || $linedata['data_type'] == 3 || $linedata['data_type'] == 21 || $linedata['data_type'] == 22 || $linedata['data_type'] == 23 || $linedata['data_type'] == 25 || $linedata['data_type'] == 27 || $linedata['data_type'] == 28 || $linedata['data_type'] == 32) { // Show the width field echo "<input type='text' name='fld[$fld_line_no][lengthWidth]' value='" . htmlspecialchars($linedata['fld_length'], ENT_QUOTES) . "' size='1' maxlength='10' class='optin' title='" . xla('Width') . "' />"; if ($linedata['data_type'] == 3) { // Show the height field echo "<input type='text' name='fld[$fld_line_no][lengthHeight]' value='" . htmlspecialchars($linedata['fld_rows'], ENT_QUOTES) . "' size='1' maxlength='10' class='optin' title='" . xla('Height') . "' />"; } else { // Hide the height field echo "<input type='hidden' name='fld[$fld_line_no][lengthHeight]' value=''>"; } } else { // all other data_types (hide both the width and height fields echo "<input type='hidden' name='fld[$fld_line_no][lengthWidth]' value=''>"; echo "<input type='hidden' name='fld[$fld_line_no][lengthHeight]' value=''>"; } echo "</td>\n"; echo " <td align='center' class='optcell' style='width:4%'>"; echo "<input type='text' name='fld[$fld_line_no][maxSize]' value='" . htmlspecialchars($linedata['max_length'], ENT_QUOTES) . "' size='1' maxlength='10' class='optin' style='width:100%' " . "title='" . xla('Maximum Size (entering 0 will allow any size)') . "' />"; echo "</td>\n"; echo " <td align='center' class='optcell' style='width:8%'>"; if ($linedata['data_type'] == 1 || $linedata['data_type'] == 21 || $linedata['data_type'] == 22 || $linedata['data_type'] == 23 || $linedata['data_type'] == 25 || $linedata['data_type'] == 26 || $linedata['data_type'] == 27 || $linedata['data_type'] == 32 || $linedata['data_type'] == 33 || $linedata['data_type'] == 34 || $linedata['data_type'] == 36) { $type = ""; $disp = "style='display:none'"; if($linedata['data_type'] == 34){ $type = "style='display:none'"; $disp = ""; } echo "<input type='text' name='fld[$fld_line_no][list_id]' id='fld[$fld_line_no][list_id]' value='" . htmlspecialchars($linedata['list_id'], ENT_QUOTES) . "'".$type. " size='6' maxlength='30' class='optin listid' style='width:100%;cursor:pointer'". "title='". xl('Choose list') . "' />"; echo "<select name='fld[$fld_line_no][contextName]' id='fld[$fld_line_no][contextName]' ".$disp.">"; $res = sqlStatement("SELECT * FROM customlists WHERE cl_list_type=2 AND cl_deleted=0"); while($row = sqlFetchArray($res)){ $sel = ''; if ($linedata['list_id'] == $row['cl_list_item_long']) $sel = 'selected'; echo "<option value='".htmlspecialchars($row['cl_list_item_long'],ENT_QUOTES)."' ".$sel.">".htmlspecialchars($row['cl_list_item_long'],ENT_QUOTES)."</option>"; } echo "</select>"; } else { // all other data_types echo "<input type='hidden' name='fld[$fld_line_no][list_id]' value=''>"; } echo "</td>\n"; //Backup List Begin echo " <td align='center' class='optcell' style='width:4%'>"; if ($linedata['data_type'] == 1 || $linedata['data_type'] == 26 || $linedata['data_type'] == 33 || $linedata['data_type'] == 36) { echo "<input type='text' name='fld[$fld_line_no][list_backup_id]' value='" . htmlspecialchars($linedata['list_backup_id'], ENT_QUOTES) . "' size='3' maxlength='10' class='optin listid' style='cursor:pointer; width:100%' />"; } else { echo "<input type='hidden' name='fld[$fld_line_no][list_backup_id]' value=''>"; } echo "</td>\n"; //Backup List End echo " <td align='center' class='optcell' style='width:4%'>"; echo "<input type='text' name='fld[$fld_line_no][titlecols]' value='" . htmlspecialchars($linedata['titlecols'], ENT_QUOTES) . "' size='3' maxlength='10' class='optin' style='width:100%' />"; echo "</td>\n"; echo " <td align='center' class='optcell' style='width:4%'>"; echo "<input type='text' name='fld[$fld_line_no][datacols]' value='" . htmlspecialchars($linedata['datacols'], ENT_QUOTES) . "' size='3' maxlength='10' class='optin' style='width:100%' />"; echo "</td>\n"; echo " <td align='center' class='optcell' style='width:5%' title='" . "A = " . xla('Age') . ", B = " . xla('Gestational Age') . ", C = " . xla('Capitalize') . ", D = " . xla('Dup Check') . ", G = " . xla('Graphable') . ", L = " . xla('Lab Order') . ", N = " . xla('New Patient Form') . ", O = " . xla('Order Processor') . ", P = " . xla('Default to previous value') . ", R = " . xla('Distributor') . ", T = " . xla('Description is default text') . ", U = " . xla('Capitalize all') . ", V = " . xla('Vendor') . ", 0 = " . xla('Read Only') . ", 1 = " . xla('Write Once') . ", 2 = " . xla('Billing Code Descriptions') . "'>"; echo "<input type='text' name='fld[$fld_line_no][edit_options]' value='" . htmlspecialchars($linedata['edit_options'], ENT_QUOTES) . "' size='3' " . "maxlength='36' class='optin' style='width:100%' />"; echo "</td>\n"; /***************************************************************** echo " <td align='center' class='optcell'>"; if ($linedata['data_type'] == 2) { echo "<input type='text' name='fld[$fld_line_no][default]' value='" . htmlspecialchars($linedata['default_value'], ENT_QUOTES) . "' size='10' maxlength='63' class='optin' />"; } else { echo "&nbsp;"; } echo "</td>\n"; echo " <td align='center' class='optcell'>"; echo "<input type='text' name='fld[$fld_line_no][desc]' value='" . htmlspecialchars($linedata['description'], ENT_QUOTES) . "' size='20' maxlength='63' class='optin' />"; echo "</td>\n"; // if not english and showing layout labels, then show the translation of Description if ($GLOBALS['translate_layout'] && $_SESSION['language_choice'] > 1) { echo "<td align='center' class='translation'>" . htmlspecialchars(xl($linedata['description']), ENT_QUOTES) . "</td>\n"; } *****************************************************************/ if ($linedata['data_type'] == 31) { echo " <td align='center' class='optcell' style='width:24%'>"; echo "<textarea name='fld[$fld_line_no][desc]' rows='3' cols='35' class='optin' style='width:100%'>" . $linedata['description'] . "</textarea>"; echo "<input type='hidden' name='fld[$fld_line_no][default]' value='" . htmlspecialchars($linedata['default_value'], ENT_QUOTES) . "' />"; echo "</td>\n"; } else { echo " <td align='center' class='optcell' style='width:24%'>"; echo "<input type='text' name='fld[$fld_line_no][desc]' value='" . htmlspecialchars($linedata['description'], ENT_QUOTES) . "' size='30' maxlength='63' class='optin' style='width:100%' />"; echo "<input type='hidden' name='fld[$fld_line_no][default]' value='" . htmlspecialchars($linedata['default_value'], ENT_QUOTES) . "' />"; echo "</td>\n"; // if not english and showing layout labels, then show the translation of Description if ($GLOBALS['translate_layout'] && $_SESSION['language_choice'] > 1) { echo "<td align='center' class='translation' style='width:10%'>" . htmlspecialchars(xl($linedata['description']), ENT_QUOTES) . "</td>\n"; } } // The "?" to click on for yet more field attributes. echo " <td class='bold' id='querytd_$fld_line_no' style='cursor:pointer;"; if (!empty($linedata['conditions'])) echo "background-color:#77ff77;"; echo "' onclick='extShow($fld_line_no, this)' align='center' "; echo "title='" . xla('Click here to view/edit more details') . "'>"; echo "&nbsp;?&nbsp;"; echo "</td>\n"; echo " </tr>\n"; // Create a floating div for the additional attributes of this field. $conditions = empty($linedata['conditions']) ? array(0 => array('id' => '', 'itemid' => '', 'operator' => '', 'value' => '')) : unserialize($linedata['conditions']); // $extra_html .= "<div id='ext_$fld_line_no' " . "style='position:absolute;width:750px;border:1px solid black;" . "padding:2px;background-color:#cccccc;visibility:hidden;" . "z-index:1000;left:-1000px;top:0px;font-size:9pt;'>\n" . "<table width='100%'>\n" . " <tr>\n" . " <th colspan='3' align='left' class='bold'>\"" . text($linedata['field_id']) . "\" " . xlt('will be hidden if') . ":</th>\n" . " <th colspan='2' align='right' class='text'><input type='button' " . "value='" . xla('Close') . "' onclick='extShow($fld_line_no, false)' />&nbsp;</th>\n" . " </tr>\n" . " <tr>\n" . " <th align='left' class='bold'>" . xlt('Field ID') . "</th>\n" . " <th align='left' class='bold'>" . xlt('List item ID') . "</th>\n" . " <th align='left' class='bold'>" . xlt('Operator') . "</th>\n" . " <th align='left' class='bold'>" . xlt('Value if comparing') . "</th>\n" . " <th align='left' class='bold'>&nbsp;</th>\n" . " </tr>\n"; // There may be multiple condition lines for each field. foreach ($conditions as $i => $condition) { $extra_html .= " <tr>\n" . " <td align='left'>\n" . " <select name='fld[$fld_line_no][condition_id][$i]' onchange='cidChanged($fld_line_no, $i)'>" . genFieldOptionList($condition['id']) . " </select>\n" . " </td>\n" . " <td align='left'>\n" . // List item choices are populated on the client side but will need the current value, // so we insert a temporary option here to hold that value. " <select name='fld[$fld_line_no][condition_itemid][$i]'><option value='" . attr($condition['itemid']) . "'>...</option></select>\n" . " </td>\n" . " <td align='left'>\n" . " <select name='fld[$fld_line_no][condition_operator][$i]'>\n"; foreach (array( 'eq' => xl('Equals' ), 'ne' => xl('Does not equal' ), 'se' => xl('Is selected' ), 'ns' => xl('Is not selected'), ) as $key => $value) { $extra_html .= " <option value='$key'"; if ($key == $condition['operator']) $extra_html .= " selected"; $extra_html .= ">" . text($value) . "</option>\n"; } $extra_html .= " </select>\n" . " </td>\n" . " <td align='left' title='" . xla('Only for comparisons') . "'>\n" . " <input type='text' name='fld[$fld_line_no][condition_value][$i]' value='" . attr($condition['value']) . "' size='15' maxlength='63' />\n" . " </td>\n"; if (count($conditions) == $i + 1) { $extra_html .= " <td align='right' title='" . xla('Add a condition') . "'>\n" . " <input type='button' value='+' onclick='extAddCondition($fld_line_no,this)' />\n" . " </td>\n"; } else { $extra_html .= " <td align='right'>\n" . " <select name='fld[$fld_line_no][condition_andor][$i]'>\n"; foreach (array( 'and' => xl('And'), 'or' => xl('Or' ), ) as $key => $value) { $extra_html .= " <option value='$key'"; if ($key == $condition['andor']) $extra_html .= " selected"; $extra_html .= ">" . text($value) . "</option>\n"; } $extra_html .= " </select>\n" . " </td>\n"; } $extra_html .= " </tr>\n"; } $extra_html .= "</table>\n" . "</div>\n"; } ?> <html> <head> <?php html_header_show();?> <!-- supporting javascript code --> <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/js/jquery.js"></script> <link rel="stylesheet" href='<?php echo $css_header ?>' type='text/css'> <title><?php xl('Layout Editor','e'); ?></title> <style> tr.head { font-size:10pt; background-color:#cccccc; } tr.detail { font-size:10pt; } td { font-size:10pt; } input { font-size:10pt; } a, a:visited, a:hover { color:#0000cc; } .optcell { } .optin { background: transparent; } .group { margin: 0pt 0pt 8pt 0pt; padding: 0; width: 100%; } .group table { border-collapse: collapse; width: 100%; } .odd td { background-color: #ddddff; padding: 3px 0px 3px 0px; } .even td { background-color: #ffdddd; padding: 3px 0px 3px 0px; } .help { cursor: help; } .layouts_title { font-size: 110%; } .translation { color: green; font-size:10pt; } .highlight * { border: 2px solid blue; background-color: yellow; color: black; } </style> <script language="JavaScript"> // Helper functions for positioning the floating divs. function extGetX(elem) { var x = 0; while(elem != null) { x += elem.offsetLeft; elem = elem.offsetParent; } return x; } function extGetY(elem) { var y = 0; while(elem != null) { y += elem.offsetTop; elem = elem.offsetParent; } return y; } // Show or hide the "extras" div for a row. var extdiv = null; function extShow(lino, show) { var thisdiv = document.getElementById("ext_" + lino); if (extdiv) { extdiv.style.visibility = 'hidden'; extdiv.style.left = '-1000px'; extdiv.style.top = '0px'; } if (show && thisdiv != extdiv) { extdiv = thisdiv; var dw = window.innerWidth ? window.innerWidth - 20 : document.body.clientWidth; x = dw - extdiv.offsetWidth; if (x < 0) x = 0; var y = extGetY(show) + show.offsetHeight; extdiv.style.left = x; extdiv.style.top = y; extdiv.style.visibility = 'visible'; } else { extdiv = null; } } // Add an extra condition line for the given row. function extAddCondition(lino, btnelem) { var f = document.forms[0]; var i = 0; // Get index of next condition line. while (f['fld[' + lino + '][condition_id][' + i + ']']) ++i; if (i == 0) alert('f["fld[' + lino + '][condition_id][' + i + ']"] <?php echo xls('not found') ?>'); // Get containing <td>, <tr> and <table> nodes of the "+" button. var tdplus = btnelem.parentNode; var trelem = tdplus.parentNode; var telem = trelem.parentNode; // Replace contents of the tdplus cell. tdplus.innerHTML = "<select name='fld[" + lino + "][condition_andor][" + i + "]'>" + "<option value='and'><?php echo xls('And') ?></option>" + "<option value='or' ><?php echo xls('Or' ) ?></option>" + "</select>"; // Add the new row. var newtrelem = telem.insertRow(i+2); newtrelem.innerHTML = "<td align='left'>" + "<select name='fld[" + lino + "][condition_id][" + i + "]' onchange='cidChanged(" + lino + "," + i + ")'>" + "<?php echo addslashes(genFieldOptionList()) ?>" + "</select>" + "</td>" + "<td align='left'>" + "<select name='fld[" + lino + "][condition_itemid][" + i + "]' style='display:none' />" + "</td>" + "<td align='left'>" + "<select name='fld[" + lino + "][condition_operator][" + i + "]'>" + "<option value='eq'><?php echo xls('Equals' ) ?></option>" + "<option value='ne'><?php echo xls('Does not equal' ) ?></option>" + "<option value='se'><?php echo xls('Is selected' ) ?></option>" + "<option value='ns'><?php echo xls('Is not selected') ?></option>" + "</select>" + "</td>" + "<td align='left'>" + "<input type='text' name='fld[" + lino + "][condition_value][" + i + "]' value='' size='15' maxlength='63' />" + "</td>" + "<td align='right'>" + "<input type='button' value='+' onclick='extAddCondition(" + lino + ",this)' />" + "</td>"; } // This is called when a field ID is chosen for testing within a skip condition. // It checks to see if a corresponding list item must also be chosen for the test, and // if so then inserts the dropdown for selecting an item from the appropriate list. function setListItemOptions(lino, seq, init) { var f = document.forms[0]; var target = 'fld[' + lino + '][condition_itemid][' + seq + ']'; // field_id is the ID of the field that the condition will test. var field_id = f['fld[' + lino + '][condition_id][' + seq + ']'].value; if (!field_id) { f[target].options.length = 0; f[target].style.display = 'none'; return; } // Find the occurrence of that field in the layout. var i = 1; while (true) { var idname = 'fld[' + i + '][id]'; if (!f[idname]) { alert('<?php echo xls('Condition field not found') ?>: ' + field_id); return; } if (f[idname].value == field_id) break; ++i; } // If this is startup initialization then preserve the current value. var current = init ? f[target].value : ''; f[target].options.length = 0; // Get the corresponding data type and list ID. var data_type = f['fld[' + i + '][data_type]'].value; var list_id = f['fld[' + i + '][list_id]'].value; // WARNING: If new data types are defined the following test may need enhancing. // We're getting out if the type does not generate multiple fields with different names. if (data_type != '21' && data_type != '22' && data_type != '23' && data_type != '25') { f[target].style.display = 'none'; return; } // OK, list item IDs do apply so go get 'em. // This happens asynchronously so the generated code needs to stand alone. f[target].style.display = ''; $.getScript('layout_listitems_ajax.php' + '?listid=' + encodeURIComponent(list_id) + '&target=' + encodeURIComponent(target) + '&current=' + encodeURIComponent(current)); } // This is called whenever a condition's field ID selection is changed. function cidChanged(lino, seq) { var thisid = document.forms[0]['fld[' + lino + '][condition_id][0]'].value; var thistd = document.getElementById("querytd_" + lino); thistd.style.backgroundColor = thisid ? '#77ff77' : ''; setListItemOptions(lino, seq, false); } </script> </head> <body class="body_top"> <form method='post' name='theform' id='theform' action='edit_layout.php'> <input type="hidden" name="formaction" id="formaction" value=""> <!-- elements used to identify a field to delete --> <input type="hidden" name="deletefieldid" id="deletefieldid" value=""> <input type="hidden" name="deletefieldgroup" id="deletefieldgroup" value=""> <!-- elements used to identify a group to delete --> <input type="hidden" name="deletegroupname" id="deletegroupname" value=""> <!-- elements used to change the group order --> <input type="hidden" name="movegroupname" id="movegroupname" value=""> <input type="hidden" name="movedirection" id="movedirection" value=""> <!-- elements used to select more than one field --> <input type="hidden" name="selectedfields" id="selectedfields" value=""> <input type="hidden" id="targetgroup" name="targetgroup" value=""> <p><b><?php xl('Edit layout','e'); ?>:</b>&nbsp; <select name='layout_id' id='layout_id'> <option value=''>-- <?php echo xl('Select') ?> --</option> <?php foreach ($layouts as $key => $value) { echo " <option value='$key'"; if ($key == $layout_id) echo " selected"; echo ">$value</option>\n"; } ?> </select></p> <?php if ($layout_id) { ?> <div style='margin: 0 0 8pt 0;'> <input type='button' class='addgroup' id='addgroup' value=<?php xl('Add Group','e','\'','\''); ?>/> </div> <?php } ?> <?php $prevgroup = "!@#asdf1234"; // an unlikely group name $firstgroup = true; // flag indicates it's the first group to be displayed while ($row = sqlFetchArray($res)) { if ($row['group_name'] != $prevgroup) { if ($firstgroup == false) { echo "</tbody></table></div>\n"; } echo "<div id='".$row['group_name']."' class='group'>"; echo "<div class='text bold layouts_title' style='position:relative; background-color: #eef'>"; // echo preg_replace("/^\d+/", "", $row['group_name']); echo substr($row['group_name'], 1); echo "&nbsp; "; // if not english and set to translate layout labels, then show the translation of group name if ($GLOBALS['translate_layout'] && $_SESSION['language_choice'] > 1) { // echo "<span class='translation'>>>&nbsp; " . xl(preg_replace("/^\d+/", "", $row['group_name'])) . "</span>"; echo "<span class='translation'>>>&nbsp; " . xl(substr($row['group_name'], 1)) . "</span>"; echo "&nbsp; "; } echo "&nbsp; "; echo " <input type='button' class='addfield' id='addto~".$row['group_name']."' value='" . xl('Add Field') . "'/>"; echo "&nbsp; &nbsp; "; echo " <input type='button' class='renamegroup' id='".$row['group_name']."' value='" . xl('Rename Group') . "'/>"; echo "&nbsp; &nbsp; "; echo " <input type='button' class='deletegroup' id='".$row['group_name']."' value='" . xl('Delete Group') . "'/>"; echo "&nbsp; &nbsp; "; echo " <input type='button' class='movegroup' id='".$row['group_name']."~up' value='" . xl('Move Up') . "'/>"; echo "&nbsp; &nbsp; "; echo " <input type='button' class='movegroup' id='".$row['group_name']."~down' value='" . xl('Move Down') . "'/>"; echo "</div>"; $firstgroup = false; ?> <table> <thead> <tr class='head'> <th><?php xl('Order','e'); ?></th> <th<?php echo " $lbfonly"; ?>><?php xl('Source','e'); ?></th> <th><?php xl('ID','e'); ?>&nbsp;<span class="help" title=<?php xl('A unique value to identify this field, not visible to the user','e','\'','\''); ?> >(?)</span></th> <th><?php xl('Label','e'); ?>&nbsp;<span class="help" title=<?php xl('The label that appears to the user on the form','e','\'','\''); ?> >(?)</span></th> <?php // if not english and showing layout label translations, then show translation header for title if ($GLOBALS['translate_layout'] && $_SESSION['language_choice'] > 1) { echo "<th>" . xl('Translation')."<span class='help' title='" . xl('The translated label that will appear on the form in current language') . "'>&nbsp;(?)</span></th>"; } ?> <th><?php xl('UOR','e'); ?></th> <th><?php xl('Data Type','e'); ?></th> <th><?php xl('Size','e'); ?></th> <th><?php xl('Max Size','e'); ?></th> <th><?php xl('List','e'); ?></th> <th><?php xl('Backup List','e'); ?></th> <th><?php xl('Label Cols','e'); ?></th> <th><?php xl('Data Cols','e'); ?></th> <th><?php xl('Options','e'); ?></th> <th><?php xl('Description','e'); ?></th> <?php // if not english and showing layout label translations, then show translation header for description if ($GLOBALS['translate_layout'] && $_SESSION['language_choice'] > 1) { echo "<th>" . xl('Translation')."<span class='help' title='" . xl('The translation of description in current language')."'>&nbsp;(?)</span></th>"; } ?> <th><?php echo xlt('?'); ?></th> </tr> </thead> <tbody> <?php } // end if-group_name writeFieldLine($row); $prevgroup = $row['group_name']; } // end while loop ?> </tbody> </table></div> <?php echo $extra_html; ?> <?php if ($layout_id) { ?> <span style="font-size:90%"> <?php xl('With selected:', 'e');?> <input type='button' name='deletefields' id='deletefields' value='<?php xl('Delete','e'); ?>' style="font-size:90%" disabled="disabled" /> <input type='button' name='movefields' id='movefields' value='<?php xl('Move to...','e'); ?>' style="font-size:90%" disabled="disabled" /> </span> <p> <input type='button' name='save' id='save' value='<?php xl('Save Changes','e'); ?>' /> </p> <?php } ?> </form> <!-- template DIV that appears when user chooses to rename an existing group --> <div id="renamegroupdetail" style="border: 1px solid black; padding: 3px; display: none; visibility: hidden; background-color: lightgrey;"> <input type="hidden" name="renameoldgroupname" id="renameoldgroupname" value=""> <?php xl('Group Name','e'); ?>: <input type="textbox" size="20" maxlength="30" name="renamegroupname" id="renamegroupname"> <br> <input type="button" class="saverenamegroup" value=<?php xl('Rename Group','e','\'','\''); ?>> <input type="button" class="cancelrenamegroup" value=<?php xl('Cancel','e','\'','\''); ?>> </div> <!-- template DIV that appears when user chooses to add a new group --> <div id="groupdetail" style="border: 1px solid black; padding: 3px; display: none; visibility: hidden; background-color: lightgrey;"> <span class='bold'> <?php xl('Group Name','e'); ?>: <input type="textbox" size="20" maxlength="30" name="newgroupname" id="newgroupname"> <br> <table style="border-collapse: collapse; margin-top: 5px;"> <thead> <tr class='head'> <th><?php xl('Order','e'); ?></th> <th<?php echo " $lbfonly"; ?>><?php xl('Source','e'); ?></th> <th><?php xl('ID','e'); ?>&nbsp;<span class="help" title=<?php xl('A unique value to identify this field, not visible to the user','e','\'','\''); ?> >(?)</span></th> <th><?php xl('Label','e'); ?>&nbsp;<span class="help" title=<?php xl('The label that appears to the user on the form','e','\'','\''); ?> >(?)</span></th> <th><?php xl('UOR','e'); ?></th> <th><?php xl('Data Type','e'); ?></th> <th><?php xl('Size','e'); ?></th> <th><?php xl('Max Size','e'); ?></th> <th><?php xl('List','e'); ?></th> <th><?php xl('Backup List','e'); ?></th> <th><?php xl('Label Cols','e'); ?></th> <th><?php xl('Data Cols','e'); ?></th> <th><?php xl('Options','e'); ?></th> <th><?php xl('Description','e'); ?></th> </tr> </thead> <tbody> <tr class='center'> <td ><input type="textbox" name="gnewseq" id="gnewseq" value="" size="2" maxlength="3"> </td> <td<?php echo " $lbfonly"; ?>> <select name='gnewsource' id='gnewsource'> <?php foreach ($sources as $key => $value) { echo "<option value='" . attr($key) . "'>" . text($value) . "</option>\n"; } ?> </select> </td> <td><input type="textbox" name="gnewid" id="gnewid" value="" size="10" maxlength="20" onclick='FieldIDClicked(this)'> </td> <td><input type="textbox" name="gnewtitle" id="gnewtitle" value="" size="20" maxlength="63"> </td> <td> <select name="gnewuor" id="gnewuor"> <option value="0"><?php xl('Unused','e'); ?></option> <option value="1" selected><?php xl('Optional','e'); ?></option> <option value="2"><?php xl('Required','e'); ?></option> </select> </td> <td align='center'> <select name='gnewdatatype' id='gnewdatatype'> <option value=''></option> <?php global $datatypes; foreach ($datatypes as $key=>$value) { echo "<option value='$key'>$value</option>"; } ?> </select> </td> <td><input type="textbox" name="gnewlengthWidth" id="gnewlengthWidth" value="" size="1" maxlength="3" title="<?php echo xla('Width'); ?>"> <input type="textbox" name="gnewlengthHeight" id="gnewlengthHeight" value="" size="1" maxlength="3" title="<?php echo xla('Height'); ?>"></td> <td><input type="textbox" name="gnewmaxSize" id="gnewmaxSize" value="" size="1" maxlength="3" title="<?php echo xla('Maximum Size (entering 0 will allow any size)'); ?>"></td> <td><input type="textbox" name="gnewlistid" id="gnewlistid" value="" size="8" maxlength="31" class="listid"> <select name='gcontextName' id='gcontextName' style='display:none'> <?php $res = sqlStatement("SELECT * FROM customlists WHERE cl_list_type=2 AND cl_deleted=0"); while($row = sqlFetchArray($res)){ echo "<option value='".htmlspecialchars($row['cl_list_item_long'],ENT_QUOTES)."'>".htmlspecialchars($row['cl_list_item_long'],ENT_QUOTES)."</option>"; } ?> </select> </td> <td><input type="textbox" name="gnewbackuplistid" id="gnewbackuplistid" value="" size="8" maxlength="31" class="listid"></td> <td><input type="textbox" name="gnewtitlecols" id="gnewtitlecols" value="" size="3" maxlength="3"> </td> <td><input type="textbox" name="gnewdatacols" id="gnewdatacols" value="" size="3" maxlength="3"> </td> <td><input type="textbox" name="gnewedit_options" id="gnewedit_options" value="" size="3" maxlength="36"> <input type="hidden" name="gnewdefault" id="gnewdefault" value="" /> </td> <td><input type="textbox" name="gnewdesc" id="gnewdesc" value="" size="30" maxlength="63"> </td> </tr> </tbody> </table> <br> <input type="button" class="savenewgroup" value=<?php xl('Save New Group','e','\'','\''); ?>> <input type="button" class="cancelnewgroup" value=<?php xl('Cancel','e','\'','\''); ?>> </span> </div> <!-- template DIV that appears when user chooses to add a new field to a group --> <div id="fielddetail" class="fielddetail" style="display: none; visibility: hidden"> <input type="hidden" name="newfieldgroupid" id="newfieldgroupid" value=""> <table style="border-collapse: collapse;"> <thead> <tr class='head'> <th><?php xl('Order','e'); ?></th> <th<?php echo " $lbfonly"; ?>><?php xl('Source','e'); ?></th> <th><?php xl('ID','e'); ?>&nbsp;<span class="help" title=<?php xl('A unique value to identify this field, not visible to the user','e','\'','\''); ?> >(?)</span></th> <th><?php xl('Label','e'); ?>&nbsp;<span class="help" title=<?php xl('The label that appears to the user on the form','e','\'','\''); ?> >(?)</span></th> <th><?php xl('UOR','e'); ?></th> <th><?php xl('Data Type','e'); ?></th> <th><?php xl('Size','e'); ?></th> <th><?php xl('Max Size','e'); ?></th> <th><?php xl('List','e'); ?></th> <th><?php xl('Backup List','e'); ?></th> <th><?php xl('Label Cols','e'); ?></th> <th><?php xl('Data Cols','e'); ?></th> <th><?php xl('Options','e'); ?></th> <th><?php xl('Description','e'); ?></th> </tr> </thead> <tbody> <tr class='center'> <td ><input type="textbox" name="newseq" id="newseq" value="" size="2" maxlength="3"> </td> <td<?php echo " $lbfonly"; ?>> <select name='newsource' id='newsource'> <?php foreach ($sources as $key => $value) { echo " <option value='" . attr($key) . "'>" . text($value) . "</option>\n"; } ?> </select> </td> <td ><input type="textbox" name="newid" id="newid" value="" size="10" maxlength="20" onclick='FieldIDClicked(this)'> </td> <td><input type="textbox" name="newtitle" id="newtitle" value="" size="20" maxlength="63"> </td> <td> <select name="newuor" id="newuor"> <option value="0"><?php xl('Unused','e'); ?></option> <option value="1" selected><?php xl('Optional','e'); ?></option> <option value="2"><?php xl('Required','e'); ?></option> </select> </td> <td align='center'> <select name='newdatatype' id='newdatatype'> <option value=''></option> <?php global $datatypes; foreach ($datatypes as $key=>$value) { echo " <option value='$key'>$value</option>\n"; } ?> </select> </td> <td><input type="textbox" name="newlengthWidth" id="newlengthWidth" value="" size="1" maxlength="3" title="<?php echo xla('Width'); ?>"> <input type="textbox" name="newlengthHeight" id="newlengthHeight" value="" size="1" maxlength="3" title="<?php echo xla('Height'); ?>"></td> <td><input type="textbox" name="newmaxSize" id="newmaxSize" value="" size="1" maxlength="3" title="<?php echo xla('Maximum Size (entering 0 will allow any size)'); ?>"></td> <td><input type="textbox" name="newlistid" id="newlistid" value="" size="8" maxlength="31" class="listid"> <select name='contextName' id='contextName' style='display:none'> <?php $res = sqlStatement("SELECT * FROM customlists WHERE cl_list_type=2 AND cl_deleted=0"); while($row = sqlFetchArray($res)){ echo "<option value='".htmlspecialchars($row['cl_list_item_long'],ENT_QUOTES)."'>".htmlspecialchars($row['cl_list_item_long'],ENT_QUOTES)."</option>"; } ?> </select> </td> <td><input type="textbox" name="newbackuplistid" id="newbackuplistid" value="" size="8" maxlength="31" class="listid"></td> <td><input type="textbox" name="newtitlecols" id="newtitlecols" value="" size="3" maxlength="3"> </td> <td><input type="textbox" name="newdatacols" id="newdatacols" value="" size="3" maxlength="3"> </td> <td><input type="textbox" name="newedit_options" id="newedit_options" value="" size="3" maxlength="36"> <input type="hidden" name="newdefault" id="newdefault" value="" /> </td> <td><input type="textbox" name="newdesc" id="newdesc" value="" size="30" maxlength="63"> </td> </tr> <tr> <td colspan="9"> <input type="button" class="savenewfield" value=<?php xl('Save New Field','e','\'','\''); ?>> <input type="button" class="cancelnewfield" value=<?php xl('Cancel','e','\'','\''); ?>> </td> </tr> </tbody> </table> </div> </body> <script language="javascript"> // used when selecting a list-name for a field var selectedfield; // Get the next logical sequence number for a field in the specified group. // Note it guesses and uses the existing increment value. function getNextSeq(group) { var f = document.forms[0]; var seq = 0; var delta = 10; for (var i = 1; true; ++i) { var gelem = f['fld[' + i + '][group]']; if (!gelem) break; if (gelem.value != group) continue; var tmp = parseInt(f['fld[' + i + '][seq]'].value); if (isNaN(tmp)) continue; if (tmp <= seq) continue; delta = tmp - seq; seq = tmp; } return seq + delta; } // jQuery stuff to make the page a little easier to use $(document).ready(function(){ $("#save").click(function() { SaveChanges(); }); $("#layout_id").change(function() { $('#theform').submit(); }); $(".addgroup").click(function() { AddGroup(this); }); $(".savenewgroup").click(function() { SaveNewGroup(this); }); $(".deletegroup").click(function() { DeleteGroup(this); }); $(".cancelnewgroup").click(function() { CancelNewGroup(this); }); $(".movegroup").click(function() { MoveGroup(this); }); $(".renamegroup").click(function() { RenameGroup(this); }); $(".saverenamegroup").click(function() { SaveRenameGroup(this); }); $(".cancelrenamegroup").click(function() { CancelRenameGroup(this); }); $(".addfield").click(function() { AddField(this); }); $("#deletefields").click(function() { DeleteFields(this); }); $(".selectfield").click(function() { var TRparent = $(this).parent().parent(); $(TRparent).children("td").toggleClass("highlight"); // disable the delete-move buttons $("#deletefields").attr("disabled", "disabled"); $("#movefields").attr("disabled", "disabled"); $(".selectfield").each(function(i) { // if any field is selected, enable the delete-move buttons if ($(this).attr("checked") == true) { $("#deletefields").removeAttr("disabled"); $("#movefields").removeAttr("disabled"); } }); }); $("#movefields").click(function() { ShowGroups(this); }); $(".savenewfield").click(function() { SaveNewField(this); }); $(".cancelnewfield").click(function() { CancelNewField(this); }); $("#newtitle").blur(function() { if ($("#newid").val() == "") $("#newid").val($("#newtitle").val()); }); $("#newdatatype").change(function() { ChangeList(this.value);}); $("#gnewdatatype").change(function() { ChangeListg(this.value);}); $(".listid").click(function() { ShowLists(this); }); // special class that skips the element $(".noselect").focus(function() { $(this).blur(); }); // Save the changes made to the form var SaveChanges = function () { $("#formaction").val("save"); $("#theform").submit(); } /****************************************************/ /************ Group functions ***********************/ /****************************************************/ // display the 'new group' DIV var AddGroup = function(btnObj) { // show the field details DIV $('#groupdetail').css('visibility', 'visible'); $('#groupdetail').css('display', 'block'); $(btnObj).parent().append($("#groupdetail")); $('#groupdetail > #newgroupname').focus(); // Assign a sensible default sequence number. $('#gnewseq').val(10); }; // save the new group to the form var SaveNewGroup = function(btnObj) { // the group name field can only have letters, numbers, spaces and underscores // AND it cannot start with a number if ($("#newgroupname").val() == "") { alert("<?php xl('Group names cannot be blank', 'e'); ?>"); return false; } if ($("#newgroupname").val().match(/^(\d+|\s+)/)) { alert("<?php xl('Group names cannot start with numbers or spaces.','e'); ?>"); return false; } var validname = $("#newgroupname").val().replace(/[^A-za-z0-9 ]/g, "_"); // match any non-word characters and replace them $("#newgroupname").val(validname); // now, check the first group field values // seq must be numeric and less than 999 if (! IsNumeric($("#gnewseq").val(), 0, 999)) { alert("<?php xl('Order must be a number between 1 and 999','e'); ?>"); return false; } // length must be numeric and less than 999 if (! IsNumeric($("#gnewlengthWidth").val(), 0, 999)) { alert("<?php xl('Size must be a number between 1 and 999','e'); ?>"); return false; } // titlecols must be numeric and less than 100 if (! IsNumeric($("#gnewtitlecols").val(), 0, 999)) { alert("<?php xl('LabelCols must be a number between 1 and 999','e'); ?>"); return false; } // datacols must be numeric and less than 100 if (! IsNumeric($("#gnewdatacols").val(), 0, 999)) { alert("<?php xl('DataCols must be a number between 1 and 999','e'); ?>"); return false; } // some fields cannot be blank if ($("#gnewtitle").val() == "") { alert("<?php xl('Label cannot be blank','e'); ?>"); return false; } // the id field can only have letters, numbers and underscores if ($("#gnewid").val() == "") { alert("<?php xl('ID cannot be blank', 'e'); ?>"); return false; } var validid = $("#gnewid").val().replace(/(\s|\W)/g, "_"); // match any non-word characters and replace them $("#gnewid").val(validid); // similarly with the listid field validid = $("#gnewlistid").val().replace(/(\s|\W)/g, "_"); $("#gnewlistid").val(validid); // similarly with the backuplistid field validid = $("#gnewbackuplistid").val().replace(/(\s|\W)/g, "_"); $("#gnewbackuplistid").val(validid); // submit the form to add a new field to a specific group $("#formaction").val("addgroup"); $("#theform").submit(); } // actually delete an entire group from the database var DeleteGroup = function(btnObj) { var parts = $(btnObj).attr("id"); var groupname = parts.replace(/^\d+/, ""); if (confirm("<?php xl('WARNING','e','',' - ') . xl('This action cannot be undone.','e','','\n') . xl('Are you sure you wish to delete the entire group named','e','',' '); ?>'"+groupname+"'?")) { // submit the form to add a new field to a specific group $("#formaction").val("deletegroup"); $("#deletegroupname").val(parts); $("#theform").submit(); } }; // just hide the new field DIV var CancelNewGroup = function(btnObj) { // hide the field details DIV $('#groupdetail').css('visibility', 'hidden'); $('#groupdetail').css('display', 'none'); // reset the new group values to a default $('#groupdetail > #newgroupname').val(""); }; // display the 'new field' DIV var MoveGroup = function(btnObj) { var btnid = $(btnObj).attr("id"); var parts = btnid.split("~"); var groupid = parts[0]; var direction = parts[1]; // submit the form to change group order $("#formaction").val("movegroup"); $("#movegroupname").val(groupid); $("#movedirection").val(direction); $("#theform").submit(); } // show the rename group DIV var RenameGroup = function(btnObj) { $('#renamegroupdetail').css('visibility', 'visible'); $('#renamegroupdetail').css('display', 'block'); $(btnObj).parent().append($("#renamegroupdetail")); $('#renameoldgroupname').val($(btnObj).attr("id")); $('#renamegroupname').val($(btnObj).attr("id").replace(/^\d+/, "")); } // save the new group to the form var SaveRenameGroup = function(btnObj) { // the group name field can only have letters, numbers, spaces and underscores // AND it cannot start with a number if ($("#renamegroupname").val().match(/^\d+/)) { alert("<?php xl('Group names cannot start with numbers.','e'); ?>"); return false; } var validname = $("#renamegroupname").val().replace(/[^A-za-z0-9 ]/g, "_"); // match any non-word characters and replace them $("#renamegroupname").val(validname); // submit the form to add a new field to a specific group $("#formaction").val("renamegroup"); $("#theform").submit(); } // just hide the new field DIV var CancelRenameGroup = function(btnObj) { // hide the field details DIV $('#renamegroupdetail').css('visibility', 'hidden'); $('#renamegroupdetail').css('display', 'none'); // reset the rename group values to a default $('#renameoldgroupname').val(""); $('#renamegroupname').val(""); }; /****************************************************/ /************ Field functions ***********************/ /****************************************************/ // display the 'new field' DIV var AddField = function(btnObj) { // update the fieldgroup value to be the groupid var btnid = $(btnObj).attr("id"); var parts = btnid.split("~"); var groupid = parts[1]; $('#fielddetail > #newfieldgroupid').attr('value', groupid); // show the field details DIV $('#fielddetail').css('visibility', 'visible'); $('#fielddetail').css('display', 'block'); $(btnObj).parent().append($("#fielddetail")); // Assign a sensible default sequence number. $('#newseq').val(getNextSeq(groupid)); }; var DeleteFields = function(btnObj) { if (confirm("<?php xl('WARNING','e','',' - ') . xl('This action cannot be undone.','e','','\n') . xl('Are you sure you wish to delete the selected fields?','e'); ?>")) { var delim = ""; $(".selectfield").each(function(i) { // build a list of selected field names to be moved if ($(this).attr("checked") == true) { var parts = this.id.split("~"); var currval = $("#selectedfields").val(); $("#selectedfields").val(currval+delim+parts[1]); delim = " "; } }); // submit the form to delete the field(s) $("#formaction").val("deletefields"); $("#theform").submit(); } }; // save the new field to the form var SaveNewField = function(btnObj) { // check the new field values for correct formatting // seq must be numeric and less than 999 if (! IsNumeric($("#newseq").val(), 0, 999)) { alert("<?php xl('Order must be a number between 1 and 999','e'); ?>"); return false; } // length must be numeric and less than 999 if (! IsNumeric($("#newlengthWidth").val(), 0, 999)) { alert("<?php xl('Size must be a number between 1 and 999','e'); ?>"); return false; } // titlecols must be numeric and less than 100 if (! IsNumeric($("#newtitlecols").val(), 0, 999)) { alert("<?php xl('LabelCols must be a number between 1 and 999','e'); ?>"); return false; } // datacols must be numeric and less than 100 if (! IsNumeric($("#newdatacols").val(), 0, 999)) { alert("<?php xl('DataCols must be a number between 1 and 999','e'); ?>"); return false; } // some fields cannot be blank if ($("#newtitle").val() == "") { alert("<?php xl('Label cannot be blank','e'); ?>"); return false; } // the id field can only have letters, numbers and underscores var validid = $("#newid").val().replace(/(\s|\W)/g, "_"); // match any non-word characters and replace them $("#newid").val(validid); // similarly with the listid field validid = $("#newlistid").val().replace(/(\s|\W)/g, "_"); $("#newlistid").val(validid); // similarly with the backuplistid field validid = $("#newbackuplistid").val().replace(/(\s|\W)/g, "_"); $("#newbackuplistid").val(validid); // submit the form to add a new field to a specific group $("#formaction").val("addfield"); $("#theform").submit(); }; // just hide the new field DIV var CancelNewField = function(btnObj) { // hide the field details DIV $('#fielddetail').css('visibility', 'hidden'); $('#fielddetail').css('display', 'none'); // reset the new field values to a default ResetNewFieldValues(); }; // show the popup choice of lists var ShowLists = function(btnObj) { window.open("./show_lists_popup.php", "lists", "width=300,height=500,scrollbars=yes"); selectedfield = btnObj; }; // show the popup choice of groups var ShowGroups = function(btnObj) { window.open("./show_groups_popup.php?layout_id=<?php echo $layout_id;?>", "groups", "width=300,height=300,scrollbars=yes"); }; // Show context DD for NationNotes var ChangeList = function(btnObj){ if(btnObj==34){ $('#newlistid').hide(); $('#contextName').show(); } else{ $('#newlistid').show(); $('#contextName').hide(); } }; var ChangeListg = function(btnObj){ if(btnObj==34){ $('#gnewlistid').hide(); $('#gcontextName').show(); } else{ $('#gnewlistid').show(); $('#gcontextName').hide(); } }; // Initialize the list item selectors in skip conditions. var f = document.forms[0]; for (var lino = 1; f['fld[' + lino + '][id]']; ++lino) { for (var seq = 0; f['fld[' + lino + '][condition_itemid][' + seq + ']']; ++seq) { setListItemOptions(lino, seq, true); } } }); function NationNotesContext(lineitem,val){ if(val==34){ document.getElementById("fld["+lineitem+"][contextName]").style.display=''; document.getElementById("fld["+lineitem+"][list_id]").style.display='none'; document.getElementById("fld["+lineitem+"][list_id]").value=''; } else{ document.getElementById("fld["+lineitem+"][list_id]").style.display=''; document.getElementById("fld["+lineitem+"][contextName]").style.display='none'; document.getElementById("fld["+lineitem+"][list_id]").value=''; } } function SetList(listid) { $(selectedfield).val(listid); } ////////////////////////////////////////////////////////////////////// // The following supports the field ID selection pop-up. ////////////////////////////////////////////////////////////////////// var fieldselectfield; function elemFromPart(part) { var ename = fieldselectfield.name; // ename is like one of the following: // fld[$fld_line_no][id] // gnewid // newid // and "part" is what we substitute for the "id" part. var i = ename.lastIndexOf('id'); ename = ename.substr(0, i) + part + ename.substr(i+2); return document.forms[0][ename]; } function FieldIDClicked(elem) { <?php if (substr($layout_id,0,3) == 'LBF') { ?> fieldselectfield = elem; var srcval = elemFromPart('source').value; // If the field ID is for the local form, allow direct entry. if (srcval == 'F') return; // Otherwise pop up the selection window. window.open('./field_id_popup.php?source=' + srcval, 'fields', 'width=600,height=600,scrollbars=yes'); <?php } ?> } function SetField(field_id, title, data_type, uor, fld_length, max_length, list_id, titlecols, datacols, edit_options, description, fld_rows) { fieldselectfield.value = field_id; elemFromPart('title' ).value = title; elemFromPart('datatype' ).value = data_type; elemFromPart('uor' ).value = uor; elemFromPart('lengthWidth' ).value = fld_length; elemFromPart('maxSize' ).value = max_length; elemFromPart('listid' ).value = list_id; elemFromPart('titlecols' ).value = titlecols; elemFromPart('datacols' ).value = datacols; elemFromPart('edit_options').value = edit_options; elemFromPart('desc' ).value = description; elemFromPart('lengthHeight').value = fld_rows; } ////////////////////////////////////////////////////////////////////// // End code for field ID selection pop-up. ////////////////////////////////////////////////////////////////////// /* this is called after the user chooses a new group from the popup window * it will submit the page so the selected fields can be moved into * the target group */ function MoveFields(targetgroup) { $("#targetgroup").val(targetgroup); var delim = ""; $(".selectfield").each(function(i) { // build a list of selected field names to be moved if ($(this).attr("checked") == true) { var parts = this.id.split("~"); var currval = $("#selectedfields").val(); $("#selectedfields").val(currval+delim+parts[1]); delim = " "; } }); $("#formaction").val("movefields"); $("#theform").submit(); }; // set the new-field values to a default state function ResetNewFieldValues () { $("#newseq").val(""); $("#newsource").val(""); $("#newid").val(""); $("#newtitle").val(""); $("#newuor").val(1); $("#newlengthWidth").val(""); $("#newlengthHeight").val(""); $("#newmaxSize").val(""); $("#newdatatype").val(""); $("#newlistid").val(""); $("#newbackuplistid").val(""); $("#newtitlecols").val(""); $("#newdatacols").val(""); $("#newedit_options").val(""); $("#newdefault").val(""); $("#newdesc").val(""); } // is value an integer and between min and max function IsNumeric(value, min, max) { if (value == "" || value == null) return false; if (! IsN(value) || parseInt(value) < min || parseInt(value) > max) return false; return true; } /****************************************************/ /****************************************************/ /****************************************************/ // tell if num is an Integer function IsN(num) { return !/\D/.test(num); } </script> </html>
gpl-3.0
letsgoING/ArduBlock
Source/ardublock-master/ardublock-master/src/main/java/com/ardublock/translator/block/letsgoING/WaitBlock.java
1093
package com.ardublock.translator.block.letsgoING; import com.ardublock.translator.Translator; import com.ardublock.translator.block.TranslatorBlock; import com.ardublock.translator.block.exception.SocketNullException; import com.ardublock.translator.block.exception.SubroutineNotDeclaredException; public class WaitBlock extends TranslatorBlock { public WaitBlock (Long blockId, Translator translator, String codePrefix, String codeSuffix, String label) { super(blockId, translator, codePrefix, codeSuffix, label); } public String toCode() throws SocketNullException, SubroutineNotDeclaredException { String ret = "long current=millis();\nwhile(current+"; TranslatorBlock translatorBlock = this.getRequiredTranslatorBlockAtSocket(0); ret = ret + translatorBlock.toCode(); ret = ret + ">millis())\n{"; translatorBlock = getTranslatorBlockAtSocket(1); while (translatorBlock != null) { ret = ret + "\t"+translatorBlock.toCode(); translatorBlock = translatorBlock.nextTranslatorBlock(); } ret = ret + "}\n"; return ret; } }
gpl-3.0
rranz/javalego
javalego/javalego_ui/src/main/java/com/javalego/ui/field/impl/ReferenceFieldModel.java
814
package com.javalego.ui.field.impl; /** * Obtener la configuración de un campo de otra Entidad a modo de referencia. El * tipo de campo es indiferente y sólo se pueden sobreescribir alguna de las * propieaddes que son comunes a todos los campos. * * @author ROBERTO RANZ */ public class ReferenceFieldModel extends AbstractFieldModel { private static final long serialVersionUID = 7639611051958307409L; private String viewName; private String fieldName; public ReferenceFieldModel() { } public String getViewName() { return viewName; } public void setViewName(String viewName) { this.viewName = viewName; } public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } }
gpl-3.0
nerdiabet/webSPELL
languages/hu/awards.php
2460
<?php /* ########################################################################## # # # Version 4 / / / # # -----------__---/__---__------__----__---/---/- # # | /| / /___) / ) (_ ` / ) /___) / / # # _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ # # Free Content / Management System # # / # # # # # # Copyright 2005-2015 by webspell.org # # # # visit webSPELL.org, webspell.info to get webSPELL for free # # - Script runs under the GNU GENERAL PUBLIC LICENSE # # - It's NOT allowed to remove this copyright-tag # # -- http://www.fsf.org/licensing/licenses/gpl.html # # # # Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), # # Far Development by Development Team - webspell.org # # # # visit webspell.org # # # ########################################################################## */ $language_array = array( /* do not edit above this line */ 'award' => 'Díjak', 'awards' => 'díjak', 'date' => 'Dátum', 'delete' => 'Törlés', 'edit' => 'Szerkesztés', 'edit_award' => 'Díj szerkesztése', 'enter_text' => 'Meg kell adnod szöveget', 'enter_title' => 'Megg kell adnod a címet!', 'event' => 'Esemény', 'homepage' => 'Honlap', 'info' => 'Információ', 'new_award' => 'Új díj létrehozása', 'no_access' => 'Nincs hozzáférhetőség!', 'no_entries' => 'Nincs elérhető díj', 'ranking' => 'Helyezés', 'save_award' => 'Díj mentése', 'sort' => 'Rendezés', 'squad' => 'Squad', 'update_award' => 'Díj frissítése' );
gpl-3.0
myjyby/unmilleniumgoals
static/js/clear.functions.js
3350
function rm(selector){ return d3.selectAll(selector).remove(); } function rm_check_countrylabel(parent,conditionnode,condition){ if(!condition){ if(parent.select(".ctr-label-text")[0][0]){ return rm_countrylabel(parent); }else{ return null; } }else{ if(conditionnode.classed(condition) === true){ return null; }else{ if(parent.select(".ctr-label-text")[0][0]){ return rm_countrylabel(parent); }else{ return null; } } } } function rm_force_countrylabel(parent){ if(!parent){ d3.selectAll(".ctr-label-text").remove(); d3.selectAll(".ctr-label-contour").remove(); d3.selectAll(".ctr-label-line").remove(); }else{ parent.select(".ctr-label-text").remove(); parent.select(".ctr-label-contour").remove(); parent.select(".ctr-label-line").remove(); } } function rm_countrylabel(parent){ var label_pos = determine_bubble_position(parent); var text = parent.select("text") .transition() .duration(_main_transition.fast_duration) .ease("elastic-in") .attr("x",0) .attr("y",0) .style("opacity",0) .each("end",function(){ d3.select(this).remove(); }); var bbox = text.node().getBBox(); var contour = parent.select("rect") .transition() .duration(_main_transition.fast_duration) .ease(_main_transition.ease) .attr("x",0) .attr("y",0) .attr("width",0) .attr("height",0) .style("opacity",0) .each("end",function(){ d3.select(this).remove(); }); var line = parent.select("line") .transition() .duration(_main_transition.very_fast_duration) .ease(_main_transition.ease) .attr("x2",function(){ if(label_pos[0] === "left"){ return -parent.select(".main-bubble").attr("r"); }else if(label_pos[0] === "right"){ return parent.select(".main-bubble").attr("r"); }else if(label_pos[0] === "center"){ return 0; } }) .attr("y2",function(){ if(label_pos[1] === "top"){ return -parent.select(".main-bubble").attr("r"); }else if(label_pos[1] === "bottom"){ return parent.select(".main-bubble").attr("r"); }else if(label_pos[1] === "middle"){ return 0; } }) .each("end",function(){ d3.select(this).remove(); }); /*setTimeout(function(){ text.remove(); contour.remove(); line.remove(); },_main_transition.duration)*/ } function rm_temporalline(idx){ if(!idx){ return d3.selectAll(".ts").remove(); }else{ return d3.selectAll(".ts-" + idx).remove(); } } function rm_all_bubbles(){ return d3.selectAll(".bubble").remove(); } function rm_big_feedback_icon(){ return d3.select(".fo-body.feedback") .select(".huge") .transition() .duration(_main_transition.duration) .ease(_main_transition.ease) .style("opacity",0) .each("end",function(){ d3.selectAll(".big-feedback").remove(); }); } function rm_force_big_feedback_icon(){ return d3.selectAll(".fo-body.feedback").remove(); } function rm_force_variability(){ return d3.selectAll(".variability").remove(); } function rm_variability_styling(){ return d3.selectAll(".bubble").classed("err-bar",false); } function rm_goal_line(){ return d3.selectAll(".target-val").remove(); } function rm_stat_lines(){ return d3.selectAll(".stat").remove(); } function rm_correlation_line(){ return d3.selectAll(".correlation").remove(); } function rm_stat_bubbtons(){ return d3.select(".stat-picker-menu").remove(); }
gpl-3.0
treejames/madsonic-5.5
src/github/madmarty/madsonic/util/SubtitleConverter/TimedTextObject.java
3873
package github.madmarty.madsonic.util.SubtitleConverter; import java.util.Hashtable; import java.util.Iterator; import java.util.TreeMap; /** * These objects can (should) only be created through the implementations of parseFile() in the {@link TimedTextFileFormat} interface * They are an object representation of a subtitle file and contain all the captions and associated styles. * <br><br> * Copyright (c) 2012 J. David Requejo <br> * j[dot]david[dot]requejo[at] Gmail * <br><br> * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following conditions: * <br><br> * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * <br><br> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * @author J. David Requejo * */ public class TimedTextObject { /* * Attributes * */ //meta info public String title = ""; public String description = ""; public String copyrigth = ""; public String author = ""; public String fileName = ""; public String language = ""; //list of styles (id, reference) public Hashtable<String, Style> styling; //list of layouts (id, reference) public Hashtable<String, Region> layout; //list of captions (begin time, reference) //represented by a tree map to maintain order public TreeMap<Integer, Caption> captions; //to store non fatal errors produced during parsing public String warnings; //**** OPTIONS ***** //to know whether file should be saved as .ASS or .SSA public boolean useASSInsteadOfSSA = true; //to delay or advance the subtitles, parsed into +/- milliseconds public int offset = 0; //to know if a parsing method has been applied public boolean built = false; /** * Protected constructor so it can't be created from outside */ protected TimedTextObject(){ styling = new Hashtable<String, Style>(); layout = new Hashtable<String, Region>(); captions = new TreeMap<Integer, Caption>(); warnings = "List of non fatal errors produced during parsing:\n\n"; } /* * PROTECTED METHODS * */ /** * This method simply checks the style list and eliminate any style not referenced by any caption * This might come useful when default styles get created and cover too much. * It require a unique iteration through all captions. * */ protected void cleanUnusedStyles(){ //here all used styles will be stored Hashtable<String, Style> usedStyles = new Hashtable<String, Style>(); //we iterate over the captions Iterator<Caption> itrC = captions.values().iterator(); while(itrC.hasNext()){ //new caption Caption current = itrC.next(); //if it has a style if(current.style != null){ String iD = current.style.iD; //if we haven't saved it yet if(!usedStyles.containsKey(iD)) usedStyles.put(iD, current.style); } } //we saved the used styles this.styling = usedStyles; } }
gpl-3.0
springernature/bandiera
config/puma.rb
897
APP_ROOT = File.expand_path(File.dirname(File.dirname(__FILE__))) $LOAD_PATH.unshift File.join(APP_ROOT, 'lib') require 'bandiera' port = Integer(ENV['PORT'] || 5000) unix_socket = ENV['SOCKET'] || '/tmp/bandiera.sock' no_of_processes = Integer(ENV['PROCESSES'] || 1) min_no_of_threads = Integer(ENV['MIN_THREADS'] || 8) max_no_of_threads = Integer(ENV['MAX_THREADS'] || 32) tag 'bandiera' environment ENV['RACK_ENV'] || 'production' daemonize false worker_timeout 15 pidfile ENV['PID_FILE'] if ENV['PID_FILE'] state_path ENV['STATE_FILE'] if ENV['STATE_FILE'] threads min_no_of_threads, max_no_of_threads workers no_of_processes bind "tcp://0.0.0.0:#{port}" bind "unix://#{unix_socket}" preload_app! on_worker_boot do Bandiera::Db.disconnect Bandiera::Db.connect end
gpl-3.0
mlohbihler/BACnet4J
src/main/java/com/serotonin/bacnet4j/util/sero/SerialPortException.java
1682
/* * ============================================================================ * GNU General Public License * ============================================================================ * * Copyright (C) 2015 Infinite Automation Software. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * When signing a commercial license with Infinite Automation Software, * the following extension to GPL is made. A special exception to the GPL is * included to allow you to distribute a combined work that includes BAcnet4J * without being obliged to provide the source code for any proprietary components. * * See www.infiniteautomation.com for commercial license options. * * @author Matthew Lohbihler */ package com.serotonin.bacnet4j.util.sero; /** * @author Matthew Lohbihler */ public class SerialPortException extends Exception { private static final long serialVersionUID = -1; public SerialPortException(String message) { super(message); } public SerialPortException(Throwable cause) { super(cause); } }
gpl-3.0
gohdan/DFC
known_files/hashes/sys-temp/updates/core/libs/vendor/guzzle/service/Guzzle/Service/Command/LocationVisitor/Response/StatusCodeVisitor.php
46
UMI.CMS 15 = 4df70de665603ecde9d54127bc589e84
gpl-3.0
woakes070048/crm-php
htdocs/langs/de_DE/donations.lang.php
2134
<?php /* Copyright (C) 2012 Regis Houssin <regis.houssin@capnetworks.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ $donations = array( 'CHARSET' => 'UTF-8', 'Donation' => 'Spende', 'Donations' => 'Spenden', 'DonationRef' => 'Donation ref.', 'Donor' => 'Spender', 'Donors' => 'Spender', 'AddDonation' => 'Spende hinzufügen', 'NewDonation' => 'Neue Spende', 'DonationPromise' => 'Zugesagte Spende', 'PromisesNotValid' => 'Ungültige Zusage', 'PromisesValid' => 'Gültige Zusage', 'DonationsPaid' => 'Bezahlte Spenden', 'DonationsReceived' => 'Erhaltene Spenden', 'PublicDonation' => 'Öffentliche Spenden', 'DonationsNumber' => 'Spendenanzahl', 'DonationsArea' => 'Spendenübersicht', 'DonationStatusPromiseNotValidated' => 'Zugesagt (nicht freigegeben)', 'DonationStatusPromiseValidated' => 'Zugesagt (freigegeben)', 'DonationStatusPaid' => 'Spende bezahlt', 'DonationStatusPromiseNotValidatedShort' => 'Entwurf', 'DonationStatusPromiseValidatedShort' => 'Freigegeben', 'DonationStatusPaidShort' => 'Bezahlt', 'ValidPromess' => 'Zusage freigeben', 'DonationReceipt' => 'Donation receipt', 'BuildDonationReceipt' => 'Erzeuge Spendenbeleg', 'DonationsModels' => 'Spendenvorlagen', 'LastModifiedDonations' => 'Letzten %s geänderten Spenden', 'SearchADonation' => 'Spende suchen', 'DonationRecipient' => 'Donation recipient', 'ThankYou' => 'Thank You', 'IConfirmDonationReception' => 'The recipient declare reception, as a donation, of the following amount' ); ?>
gpl-3.0
crm-js/crm-php
htdocs/langs/hu_HU/externalsite.lang.php
887
<?php /* Copyright (C) 2012 Regis Houssin <regis.houssin@capnetworks.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ $externalsite = array( 'CHARSET' => 'UTF-8', 'ExternalSiteSetup' => 'Beállítás linket külső weboldal', 'ExternalSiteURL' => 'Külső oldal URL' ); ?>
gpl-3.0
Backfeed/Backfeed-Protocol-Service
tester/value_distributer.py
6665
from protocol_function import BidInfo,FIn,ProtocolFunctionV1 import classes as cls from operator import attrgetter class ValueDistributerBase(object): def process_bid(self,current_bid,session,logger = None): pass class ValueDistributer(ValueDistributerBase): def __init__(self,logger = None): self.logger = logger self.error_occured = False self.error_code = None def log(self,messsage,level = 'info'): if(self.logger): self.logger.info(messsage) return True def getHighestEval(self,bids): maxValue = max(bids, key=attrgetter('contribution_value_after_bid')).contribution_value_after_bid return maxValue def isBidderFirstBid(self,bids, current_bid): self.log('\n\n *** isBidderFirstBid: ***:\n') for bid in bids: if bid.owner == current_bid.owner: self.log('is not bidders first bid.') return False self.log('is bidders first bid.') return True def validateBid(self,bids, current_bid): self.log('\n\n *** validateBid: ***:\n') Wi = 0; users = self.usersDict current_bidder = users[current_bid.owner] rep = current_bid.reputation #check how much reputation has been engaged by current_bidder, for bid in bids: if bid.owner == current_bidder.user_id: Wi += bid.reputation self.log('amount of reputation which has been engaged by the current_bidder:'+str(Wi)) #check if something has to be trimmed if current_bidder.org_reputation - Wi < rep: if current_bidder.org_reputation > Wi: current_bid.reputation = current_bidder.org_reputation - Wi self.log("trimmed reputation to : "+str(current_bid.reputation)) else: self.log("bidder has no more reputation to spare for current bid. exit.") return None; elif(not current_bidder.org_reputation): self.log("bidder has no more reputation to spare for current bid. exit.") return None; self.log("current_bid.stake = " + str(current_bid.stake) + " and current_bid.rep = " + str(current_bid.reputation)) if current_bid.stake > current_bid.reputation: self.log("bidder has put more stake than he has reputation - reducing stake to bidder's reputation.") current_bid.stake = current_bid.reputation self.log( "bidder reputation: "+ str(current_bidder.org_reputation) + ", bidder total weight = " + str(Wi) + "Appending current bid reputation:" + str(current_bid.reputation)) self.log('\n\n') return current_bid; def debug_state(self): self.log('\n\n *** current state ***:\n') self.log('previous highest eval:'+str(self.highest_eval)) self.log('total system reputation:'+str(self.total_system_reputation)) # get state : users Dict which is a dict of (key : value) userId:userOrgenization object ,also calc total_system_reputation and highest_eval: def getCurrentState(self,contributionObject,session): usersDict = {} total_system_reputation = 0 # get users: user_org = contributionObject.userOrganization userOrgObjects = session.query(cls.UserOrganization).filter(cls.UserOrganization.organization_id == user_org.organization_id).all() for userOrg in userOrgObjects: usersDict[userOrg.user_id] = userOrg total_system_reputation = total_system_reputation + userOrg.org_reputation self.highest_eval = 0 if(contributionObject.bids and len(contributionObject.bids)): self.highest_eval = self.getHighestEval(contributionObject.bids) self.total_system_reputation = total_system_reputation self.usersDict = usersDict self.debug_state() def debug_bid(self,current_bid): self.log('\n\n *** processing bid - info: ***\n') self.log('stake (risk):'+str(current_bid.stake)) self.log('reputation (weight):'+str(current_bid.reputation)) self.log('tokens (eval):'+str(current_bid.tokens)) def process_current_evaluation(self,current_eval,contributers,session): eval_delta = current_eval - self.highest_eval if (eval_delta > 0): # Issue tokens and reputation to collaborators: for contributer in contributers: user = self.usersDict[contributer.contributer_id] tokens_to_add = ( eval_delta * contributer.contributer_percentage ) / 100 user.org_tokens += tokens_to_add user.org_reputation += tokens_to_add session.add(user) def distribute_rep(self,bids_distribution, current_bid,session): users = self.usersDict current_bidder = users[current_bid.owner] if(not current_bid.stake): self.log('stake is null --> stake is set to entire bid reputation:'+str(current_bid.reputation)) current_bid.stake = current_bid.reputation #kill the stake of the current_bidder current_bidder.org_reputation -= current_bid.stake session.add(current_bidder) #reallocate reputation for ownerId in bids_distribution: user = users[int(ownerId)] self.log("\n\nrealocating reputation for bidder Id:" + str(ownerId)) self.log("OLD REP === " + str(user.org_reputation)) user.org_reputation += bids_distribution[ownerId] self.log("NEW REP === " + str(user.org_reputation)) session.add(user) def set_error(self,message): self.log('Error:'+message) self.error_occured = True self.error_code = message def process_bid(self,current_bid,session,logger = None): self.debug_bid(current_bid) # get current state data: contributionObject = session.query(cls.Contribution).filter(cls.Contribution.id == current_bid.contribution_id).first() self.getCurrentState(contributionObject,session) # validate is First Bid: if(not self.isBidderFirstBid(contributionObject.bids, current_bid)): self.set_error('is Not bidders first bid, (we currently do not allow several bids per contribution.)') return None # validate Bid: current_bid = self.validateBid(contributionObject.bids, current_bid) if(not current_bid): self.set_error('bid not valid.') return None # add current bid to bids: bids = contributionObject.bids bids.append(current_bid); # prepare protocol function Input: bidsInfo = [] for bid in bids: bidsInfo.append( BidInfo(bid.tokens,bid.reputation,bid.stake,bid.owner) ) current_bid_info = bidsInfo[-1] fin = FIn(bidsInfo,current_bid_info,self.total_system_reputation) # protocol function calc: f = ProtocolFunctionV1(logger) result = f.execute(fin) if(result.error_occured): self.set_error(result.error_code) return None # success: handle result: self.distribute_rep(result.rep_distributions, current_bid,session) self.process_current_evaluation(result.evaluation, contributionObject.contributionContributers,session) # add current bid and commit DB session: current_bid.contribution_value_after_bid = result.evaluation session.add(current_bid) session.commit() return current_bid
gpl-3.0
felipearimateia/zum-android
app/src/main/java/com/hotmart/dragonfly/authenticator/service/AccountAuthenticatorService.java
1193
/* * This file is part of Zum. * * Zum is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Zum 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 Zum. If not, see <http://www.gnu.org/licenses/>. */ package com.hotmart.dragonfly.authenticator.service; import android.app.Service; import android.content.Intent; import android.os.IBinder; import com.hotmart.dragonfly.authenticator.AccountAuthenticator; public class AccountAuthenticatorService extends Service { private AccountAuthenticator mAuthenticator; @Override public void onCreate() { mAuthenticator = new AccountAuthenticator(this); } @Override public IBinder onBind(Intent intent) { return mAuthenticator.getIBinder(); } }
gpl-3.0
SmithsModding/Tiny-Storage
src/main/java/com/smithsmodding/tinystorage/util/common/IKeyBound.java
312
package com.smithsmodding.tinystorage.util.common; import com.smithsmodding.tinystorage.common.reference.Key; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; public interface IKeyBound { void doKeyBindingAction(EntityPlayer entityPlayer, ItemStack itemStack, Key key); }
gpl-3.0
44kia244/MWFramework
demo/shop_demo/core/DBengine.class.php
2669
<?php /**************************************************************************** * This file is part of MWFramework. * * * * MWFramework is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * MWFramework 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 MWFramework. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ ?> <?php class DBengine extends MySQLi { /** Class Construct : Connect to MySQL */ public function __construct() { parent::__construct(BaseConfiguration::$MySQL["host"], BaseConfiguration::$MySQL["user"], BaseConfiguration::$MySQL["pass"], BaseConfiguration::$MySQL["db"]); } /** Class Destruct (End Of Process) : Close Connection */ public function __destruct() { $this->close(); } /** $SQLquery SQL Query String without parameter (use ? to mark parameter) Ex. SELECT * FROM `users` WHERE `username` = ? AND `password` = ? $SQLparam SQL Parameter as 2D Array Ex. array( array("s", "admin"), array("s", "P4$sw0rd") ) */ public function query($SQLquery, $SQLparam = array()) { if ($this->connect_errno) return FALSE; if($stmt = $this->prepare($SQLquery)) { $type = ""; $param = array("Initialize"); for($i=0;$i<count($SQLparam);$i++) { $type .= $SQLparam[$i][0]; $param[] = &$SQLparam[$i][1]; } $param[0] = $type; if(count($SQLparam) > 0) call_user_func_array(array($stmt,"bind_param"),$param); $exec_res = $stmt->execute(); $result = $stmt->get_result(); if($result == FALSE) return array(array($exec_res)); else { $return = array(); while ($row = $result->fetch_assoc()) { $return[] = $row; } return $return; } } else return FALSE; } } ?>
gpl-3.0
phase/compiler
src/org/sugarj/driver/transformations/renaming/$Dyn$Rule$Id_1_0.java
1339
package org.sugarj.driver.transformations.renaming; import org.strategoxt.stratego_lib.*; import org.strategoxt.lang.*; import org.spoofax.interpreter.terms.*; import static org.strategoxt.lang.Term.*; import org.spoofax.interpreter.library.AbstractPrimitive; import java.util.ArrayList; import java.lang.ref.WeakReference; @SuppressWarnings("all") public class $Dyn$Rule$Id_1_0 extends Strategy { public static $Dyn$Rule$Id_1_0 instance = new $Dyn$Rule$Id_1_0(); @Override public IStrategoTerm invoke(Context context, IStrategoTerm term, Strategy j_10) { ITermFactory termFactory = context.getFactory(); context.push("DynRuleId_1_0"); Fail15: { IStrategoTerm l_90 = null; IStrategoTerm j_90 = null; if(term.getTermType() != IStrategoTerm.APPL || out._consDynRuleId_1 != ((IStrategoAppl)term).getConstructor()) break Fail15; j_90 = term.getSubterm(0); IStrategoList annos6 = term.getAnnotations(); l_90 = annos6; term = j_10.invoke(context, j_90); if(term == null) break Fail15; term = termFactory.annotateTerm(termFactory.makeAppl(out._consDynRuleId_1, new IStrategoTerm[]{term}), checkListAnnos(termFactory, l_90)); context.popOnSuccess(); if(true) return term; } context.popOnFailure(); return null; } }
gpl-3.0
chriskmanx/qmole
QMOLEDEV/llvm-2.8/tools/llvmc/examples/Skeleton/Main.cpp
561
//===--- Main.cpp - The LLVM Compiler Driver -------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open // Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Just include CompilerDriver/Main.inc and AutoGenerated.inc. // //===----------------------------------------------------------------------===// #include "llvm/CompilerDriver/Main.inc" #include "AutoGenerated.inc"
gpl-3.0
nipunn1313/parity
js/src/modals/DappPermissions/dappPermissions.spec.js
1512
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. import { shallow } from 'enzyme'; import React from 'react'; import DappPermissions from './'; let component; function renderShallow (permissionStore = {}) { component = shallow( <DappPermissions permissionStore={ permissionStore } /> ); return component; } describe('modals/DappPermissions', () => { describe('rendering', () => { it('renders defaults', () => { expect(renderShallow()).to.be.ok; }); it('does not render the modal with modalOpen = false', () => { expect( renderShallow({ modalOpen: false }).find('Portal') ).to.have.length(0); }); it('does render the modal with modalOpen = true', () => { expect( renderShallow({ modalOpen: true, accounts: [] }).find('Portal') ).to.have.length(1); }); }); });
gpl-3.0
nmenon/predict2
src/PredictII/network/networkAnalyzerServer.java
3540
/* * Copyright (C) 2001-2008 Nishanth Menon <menon.nishanth at gmail dot com> * * Part of the predict two project done during NITC Final year. * Predict2: http://code.google.com/p/predict2/ * NITC: http://web.nitc.ac.in/~cse/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 US */ /* This Is a Copy Lefted Software (CL) 2001 Spetember By Nishanth 'Lazarus' Menon Calicut Regional Engineering College Calicut */ package network; import java.lang.*; import java.io.*; import java.util.*; import java.net.*; /** * The Network Analyser Server works with the Client. * This is basiically meant for the sending a specified umber of packets and analysing the network * Info at the end of the transmission. * */ public class networkAnalyzerServer extends networkAnalyzer { long CurrT = System.currentTimeMillis (); private static long histime; private static long mytime; private static long mytimeD; public networkAnalyzerServer (DataInputStream in, DataOutputStream out, int numberofSends) throws Exception { int count = 0; int c = in.readInt (); // << READ Number of reads // System.out.println ("TOLD TO READ " + c); if (c != numberofSends) throw (new Exception ("Client Requests more number of transmits than what i was told to do" + c + " " + numberofSends)); // Start the Stuff... mytimeD = System.currentTimeMillis (); CurrT = System.currentTimeMillis (); while (count < numberofSends + 1) { // sleep (10000); histime = in.readLong (); // <<<<<Reading Data mytimeD = System.currentTimeMillis (); // System.out.println (count + ": Time is :" + // System.currentTimeMillis ()); addTime (mytime, mytimeD, histime); // *****Adding Time mytime = System.currentTimeMillis (); // sleep (10000); out.writeLong (mytime); // >>>>>>Sending Data count++; } // End of While analyse (); } public static void main (String[]args) throws Exception { ServerSocket s = new ServerSocket (8909); Socket cli = s.accept (); DataOutputStream out = new DataOutputStream (cli.getOutputStream ()); DataInputStream in = new DataInputStream (cli.getInputStream ()); // The Number 30 is excellent for most Statistical reasons... networkAnalyzerServer a = new networkAnalyzerServer (in, out, 30); // System.out.println ("RESULT= OneWayTIME=" + a.getOneWayTime () + // "\n Differenceintim=" + a.getDifferenceInTime ()); cli.close (); } } // End of networkAnalyzerServer
gpl-3.0
nuttynb/darts-project
src/main/java/hu/nutty/darts/model/package-info.java
192
/** * Model - Model represents an object or JAVA POJO carrying data. * It can also have logic to update controller if its data changes. * @author nutty * */ package hu.nutty.darts.model;
gpl-3.0
4n6g4/gtsdm
malra/bo/module/mutasi_masa_kerja_penyesuaian/response/DoUpdateMutasiMasaKerjaPenyesuaian.html.class.php
681
<?php require_once GTFWConfiguration::GetValue( 'application', 'docroot') . 'module/mutasi_masa_kerja_penyesuaian/response/ProcessMutasiMasaKerjaPenyesuaian.proc.class.php'; class DoUpdateMutasiMasaKerjaPenyesuaian extends HtmlResponse { function TemplateModule() { } function ProcessRequest() { //echo "<pre>";print_r($_GET);echo "</pre>";exit(); $ret = "html"; $obj = new Process($ret); //set post $obj->SetPost($_POST); $urlRedirect = $obj->InputData(); $this->RedirectTo($urlRedirect) ; return NULL; } function ParseTemplate($data = NULL) { } } ?>
gpl-3.0
ingochris/InfinityEncryption
python/printcoor.py
11429
#!/usr/bin/python # Python-based HTTP server for requesting sensor data # # To run: # python server.py [port] # where port defaults to 8080. # # Connect to the server via HTTP to receive latest images in JSON # format. For example, http://127.0.0.1:8080 # Requires: # FTDI D2XX driver for your OS (http://www.ftdichip.com/Drivers/D2XX.htm) # PyWin32 on Windows # # Tested with Python 2.7, 3.4 on Windows (32-bit), Mac OS X (10.10), # and Ubuntu Linux 15.04. # # On Mac OS X, make sure the USB serial driver is unloaded. For # example: # # sudo kextunload /System/Library/Extensions/IOUSBFamily.kext/Contents/PlugIns/AppleUSBFTDI.kext/ # # On Linux, make sure the ftdi_sio and usbserial modules are unloaded: # # sudo rmmod ftdi_sio # sudo rmmod usbserial # # Also, make sure you have permission to write to the USB device: # # lsusb -d 0403:6010 -> get bus and device number # sudo chmod ugo+rw /dev/bus/usb/<bus number>/<device number> # This web server is single threaded because the Sensor class is not # thread-safe. You can serve multiple clients from it, but not at high # speeds. If you want to use multiple clients, spawn a worker thread # that polls the Sensor for more images, then share those images with # the other threads. # # Also, the server only returns the *last* image. This is because the # web browser demo code can't handle more than 10-20 frames per # second. However, the sensor class itself can deliver data at 80 Hz # or more if the downstream code is consuming it fast enough. from __future__ import print_function import ftd2xx as FT import win32api import time import sys try: import BaseHTTPServer as httpServer except: import http.server as httpServer crcTable = [ 0x0000,0x1021,0x2042,0x3063,0x4084,0x50A5,0x60C6,0x70E7, 0x8108,0x9129,0xA14A,0xB16B,0xC18C,0xD1AD,0xE1CE,0xF1EF, 0x1231,0x0210,0x3273,0x2252,0x52B5,0x4294,0x72F7,0x62D6, 0x9339,0x8318,0xB37B,0xA35A,0xD3BD,0xC39C,0xF3FF,0xE3DE, 0x2462,0x3443,0x0420,0x1401,0x64E6,0x74C7,0x44A4,0x5485, 0xA56A,0xB54B,0x8528,0x9509,0xE5EE,0xF5CF,0xC5AC,0xD58D, 0x3653,0x2672,0x1611,0x0630,0x76D7,0x66F6,0x5695,0x46B4, 0xB75B,0xA77A,0x9719,0x8738,0xF7DF,0xE7FE,0xD79D,0xC7BC, 0x48C4,0x58E5,0x6886,0x78A7,0x0840,0x1861,0x2802,0x3823, 0xC9CC,0xD9ED,0xE98E,0xF9AF,0x8948,0x9969,0xA90A,0xB92B, 0x5AF5,0x4AD4,0x7AB7,0x6A96,0x1A71,0x0A50,0x3A33,0x2A12, 0xDBFD,0xCBDC,0xFBBF,0xEB9E,0x9B79,0x8B58,0xBB3B,0xAB1A, 0x6CA6,0x7C87,0x4CE4,0x5CC5,0x2C22,0x3C03,0x0C60,0x1C41, 0xEDAE,0xFD8F,0xCDEC,0xDDCD,0xAD2A,0xBD0B,0x8D68,0x9D49, 0x7E97,0x6EB6,0x5ED5,0x4EF4,0x3E13,0x2E32,0x1E51,0x0E70, 0xFF9F,0xEFBE,0xDFDD,0xCFFC,0xBF1B,0xAF3A,0x9F59,0x8F78, 0x9188,0x81A9,0xB1CA,0xA1EB,0xD10C,0xC12D,0xF14E,0xE16F, 0x1080,0x00A1,0x30C2,0x20E3,0x5004,0x4025,0x7046,0x6067, 0x83B9,0x9398,0xA3FB,0xB3DA,0xC33D,0xD31C,0xE37F,0xF35E, 0x02B1,0x1290,0x22F3,0x32D2,0x4235,0x5214,0x6277,0x7256, 0xB5EA,0xA5CB,0x95A8,0x8589,0xF56E,0xE54F,0xD52C,0xC50D, 0x34E2,0x24C3,0x14A0,0x0481,0x7466,0x6447,0x5424,0x4405, 0xA7DB,0xB7FA,0x8799,0x97B8,0xE75F,0xF77E,0xC71D,0xD73C, 0x26D3,0x36F2,0x0691,0x16B0,0x6657,0x7676,0x4615,0x5634, 0xD94C,0xC96D,0xF90E,0xE92F,0x99C8,0x89E9,0xB98A,0xA9AB, 0x5844,0x4865,0x7806,0x6827,0x18C0,0x08E1,0x3882,0x28A3, 0xCB7D,0xDB5C,0xEB3F,0xFB1E,0x8BF9,0x9BD8,0xABBB,0xBB9A, 0x4A75,0x5A54,0x6A37,0x7A16,0x0AF1,0x1AD0,0x2AB3,0x3A92, 0xFD2E,0xED0F,0xDD6C,0xCD4D,0xBDAA,0xAD8B,0x9DE8,0x8DC9, 0x7C26,0x6C07,0x5C64,0x4C45,0x3CA2,0x2C83,0x1CE0,0x0CC1, 0xEF1F,0xFF3E,0xCF5D,0xDF7C,0xAF9B,0xBFBA,0x8FD9,0x9FF8, 0x6E17,0x7E36,0x4E55,0x5E74,0x2E93,0x3EB2,0x0ED1,0x1EF0, ] def crc16(packet): rem = 0 for p in packet: #print("%04X %02X %04X" % (rem,p,crcTable[(rem>>8) ^ p])) rem = (rem << 8) ^ crcTable[(rem>>8) ^ p] rem = rem & 0xFFFF return rem class SensorInterface(object): def __init__(self): self.sensor = None self.buffer = [] def connect(self, id=None): """Connects to a sensor Use the optional id argument to specify a non-default sensor""" if id == None: id = 0; try: self.sensor = FT.open(id) except FT.DeviceError: print("Error: Device not found") raise self.sensor.setUSBParameters(8192) self.sensor.setLatencyTimer(2) def close(self): "Closes the connection to the sensor" if self.sensor: self.sensor.close() self.sensor = None def getAllImages(self): "Returns a list of all images found in the FTDI buffer" self.readBuffer() images = [] while True: p = self.getPacket() if not p: return images if p[0] == 2: # image packet rows = p[14] cols = p[15] imgBuf = p[16:] pixels = [] for i in range(rows): pixels.append(imgBuf[(i*cols):((i+1)*cols)]) img = { 'timeStamp' : p[5] + (p[6] << 16), 'sequence' : p[10], 'rows' : rows, 'cols' : cols, 'image' : pixels } images.append(img) def getPacket(self): while True: if len(self.buffer) == 0: return None # find BOM: 7 FFs followed by A5 ffCount = 0 while len(self.buffer) > 0: b = self.buffer.pop(0) if b == 0xFF: ffCount += 1 #if ffCount == 15: # print("Warning: Sensor buffer overflow") elif ffCount >= 7 and b == 0xA5: break else: ffCount == 0 # Read length word if len(self.buffer) < 2: #print("Discarded packet because buffer is empty") continue length = self.buffer[1] + (self.buffer[0] << 8) if length > len(self.buffer): # Allow this packet to be processed next time self.buffer.insert(0, 0xA5) for i in range(7): self.buffer.insert(0, 0xFF) return None if length < 32: #print("Discarded packet shorter than minimum (%d bytes vs 32 bytes)" % (length)) continue # packet is shorter than minimum size packet = self.buffer[0:length] calcCrc = crc16(packet[4:]) txCrc = packet[3] + (packet[2] << 8) if calcCrc != txCrc: #print("Warning: Transmitted CRC %04X != %04X Calculated" % (txCrc, calcCrc)) continue packet = self.removeEscapedFFs(packet) # convert packet to words from bytes lo = packet[5::2] hi = packet[4::2] packet = [lo[i] + (hi[i] << 8) for i in range(len(lo))] # accept the packet, remove it from buffer self.buffer[0:length] = [] #print("Accepting packet, %d bytes long" % length) return packet def removeEscapedFFs(self, packet): # packets have 00 bytes inserted after each 4 FFs because # strings of FFs are used by hardware for signaling purposes i = 4 while i < len(packet)-4: if packet[i] != 0xFF or packet[i+1] != 0xFF or packet[i+2] != 0xFF or packet[i+3] != 0xFF: i += 1 continue #print(packet[i+4]) #if packet[i+4] != 0: #print("Warning, saw incorrect escape in FF sequence: %d" % packet[i+4]) del packet[i+4] i += 1 return packet def readBuffer(self): if not self.sensor: return # flush out buffer so we don't get old images rx = 65536 while rx == 65536: (rx, tx, stat) = self.sensor.getStatus() buf = self.sensor.read(rx) #print("Read %d bytes" % len(buf)) #if rx == 65536: # print("Discarding buffer...") if sys.version_info[0] < 3: buf = [ord(x) for x in buf] self.buffer.extend(buf) class MyHttpHandler(httpServer.BaseHTTPRequestHandler): def imageToJSON(self, image): # JSON requires double-quotes around dict keys, Python's standard # __str__ gives single-quotes. Also it annotates long integers. So # here's a method to create actual JSON. self.writeStr("{") keys = list(image.keys()) for j in range(len(keys)): k = keys[j] self.writeStr('"%s":%s' % (k, image[k])) if j != len(keys)-1: self.writeStr(",") self.writeStr("}") def writeStr(self, s): self.wfile.write(s.encode("utf-8")) def send_sensorData(self): global sensor self.send_response(200) self.send_header("Content-type", "application/json") self.end_headers() images = sensor.getAllImages() if len(images) > 0: self.imageToJSON(images[-1]) else: print("Warning: no image available") self.writeStr("{}") def send_file(self, file): f = open(file) self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() for line in f: self.writeStr(line) f.close() def do_GET(self): files = ['index.html', 'jquery-1.11.3.js'] if self.path == '/': self.path = '/index.html' if self.path == '/sensorData': self.send_sensorData() elif self.path[1:] in files: self.send_file(self.path[1:]) else: self.send_response(404) self.send_header("Content-type", "text/html") self.end_headers() self.writeStr("<html><head><title>Not Found</title></head>") self.writeStr("<body><h1>Not Found</h1></body></html>") def FindFinger(sensor, baseline): imgs = sensor.getAllImages() if len(imgs) == 0: return None img = imgs[-1] imgmax = -9000 maxcoor = None for r in range(len(img['image'])): for c in range(len(img['image'][r])): img['image'][r][c] = baseline[r][c] - img['image'][r][c] for r in range(len(img['image'])): for c in range(len(img['image'][r])): if img['image'][r][c] > imgmax: imgmax = img['image'][r][c] maxcoor = (r,c) if imgmax < 20: return None return maxcoor def Main(port): global sensor sensor = SensorInterface() try: sensor.connect() except: print("Error connecting to sensor") raise return bl = None while bl == None: imgs = sensor.getAllImages() if len(imgs) > 0: #print(imgs[-1]) bl = imgs[-1]['image'] time.sleep(.005) while True: print(FindFinger(sensor,bl)) time.sleep(.005) #server = httpServer.HTTPServer(('', port), MyHttpHandler) # try: # server.serve_forever() # except KeyboardInterrupt: # pass sensor.close() if __name__ == '__main__': port = 8080 if len(sys.argv) > 1: port = int(sys.argv[1]) Main(port)
gpl-3.0
jesuscript/parity
js/src/views/Settings/Proxy/index.js
743
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. export default from './proxy';
gpl-3.0
nrizzio/Signal-Desktop
libtextsecure/test/websocket_test.js
1997
// Copyright 2015-2020 Signal Messenger, LLC // SPDX-License-Identifier: AGPL-3.0-only /* global TextSecureWebSocket */ describe('TextSecureWebSocket', () => { const RealWebSocket = window.WebSocket; before(() => { window.WebSocket = MockSocket; }); after(() => { window.WebSocket = RealWebSocket; }); it('connects and disconnects', done => { const mockServer = new MockServer('ws://localhost:8080'); mockServer.on('connection', server => { socket.close(); server.close(); done(); }); const socket = new TextSecureWebSocket('ws://localhost:8080'); }); it('sends and receives', done => { const mockServer = new MockServer('ws://localhost:8080'); mockServer.on('connection', server => { server.on('message', () => { server.send('ack'); server.close(); }); }); const socket = new TextSecureWebSocket('ws://localhost:8080'); socket.onmessage = response => { assert.strictEqual(response.data, 'ack'); socket.close(); done(); }; socket.send('syn'); }); it('exposes the socket status', done => { const mockServer = new MockServer('ws://localhost:8082'); mockServer.on('connection', server => { assert.strictEqual(socket.getStatus(), WebSocket.OPEN); server.close(); socket.close(); }); const socket = new TextSecureWebSocket('ws://localhost:8082'); socket.onclose = () => { assert.strictEqual(socket.getStatus(), WebSocket.CLOSING); done(); }; }); it('reconnects', function thisNeeded(done) { this.timeout(60000); const mockServer = new MockServer('ws://localhost:8082'); const socket = new TextSecureWebSocket('ws://localhost:8082'); socket.onclose = () => { const secondServer = new MockServer('ws://localhost:8082'); secondServer.on('connection', server => { socket.close(); server.close(); done(); }); }; mockServer.close(); }); });
gpl-3.0
mailcow/mailcow-dockerized
data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Converter.php
15771
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Carbon\Exceptions\UnitException; use Closure; use DateTime; use DateTimeImmutable; use ReturnTypeWillChange; /** * Trait Converter. * * Change date into different string formats and types and * handle the string cast. * * Depends on the following methods: * * @method static copy() */ trait Converter { /** * Format to use for __toString method when type juggling occurs. * * @var string|Closure|null */ protected static $toStringFormat; /** * Reset the format used to the default when type juggling a Carbon instance to a string * * @return void */ public static function resetToStringFormat() { static::setToStringFormat(null); } /** * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. * You should rather let Carbon object being casted to string with DEFAULT_TO_STRING_FORMAT, and * use other method or custom format passed to format() method if you need to dump an other string * format. * * Set the default format used when type juggling a Carbon instance to a string * * @param string|Closure|null $format * * @return void */ public static function setToStringFormat($format) { static::$toStringFormat = $format; } /** * Returns the formatted date string on success or FALSE on failure. * * @see https://php.net/manual/en/datetime.format.php * * @param string $format * * @return string */ #[ReturnTypeWillChange] public function format($format) { $function = $this->localFormatFunction ?: static::$formatFunction; if (!$function) { return $this->rawFormat($format); } if (\is_string($function) && method_exists($this, $function)) { $function = [$this, $function]; } return $function(...\func_get_args()); } /** * @see https://php.net/manual/en/datetime.format.php * * @param string $format * * @return string */ public function rawFormat($format) { return parent::format($format); } /** * Format the instance as a string using the set format * * @example * ``` * echo Carbon::now(); // Carbon instances can be casted to string * ``` * * @return string */ public function __toString() { $format = $this->localToStringFormat ?? static::$toStringFormat; return $format instanceof Closure ? $format($this) : $this->rawFormat($format ?: ( \defined('static::DEFAULT_TO_STRING_FORMAT') ? static::DEFAULT_TO_STRING_FORMAT : CarbonInterface::DEFAULT_TO_STRING_FORMAT )); } /** * Format the instance as date * * @example * ``` * echo Carbon::now()->toDateString(); * ``` * * @return string */ public function toDateString() { return $this->rawFormat('Y-m-d'); } /** * Format the instance as a readable date * * @example * ``` * echo Carbon::now()->toFormattedDateString(); * ``` * * @return string */ public function toFormattedDateString() { return $this->rawFormat('M j, Y'); } /** * Format the instance as time * * @example * ``` * echo Carbon::now()->toTimeString(); * ``` * * @param string $unitPrecision * * @return string */ public function toTimeString($unitPrecision = 'second') { return $this->rawFormat(static::getTimeFormatByPrecision($unitPrecision)); } /** * Format the instance as date and time * * @example * ``` * echo Carbon::now()->toDateTimeString(); * ``` * * @param string $unitPrecision * * @return string */ public function toDateTimeString($unitPrecision = 'second') { return $this->rawFormat('Y-m-d '.static::getTimeFormatByPrecision($unitPrecision)); } /** * Return a format from H:i to H:i:s.u according to given unit precision. * * @param string $unitPrecision "minute", "second", "millisecond" or "microsecond" * * @return string */ public static function getTimeFormatByPrecision($unitPrecision) { switch (static::singularUnit($unitPrecision)) { case 'minute': return 'H:i'; case 'second': return 'H:i:s'; case 'm': case 'millisecond': return 'H:i:s.v'; case 'µ': case 'microsecond': return 'H:i:s.u'; } throw new UnitException('Precision unit expected among: minute, second, millisecond and microsecond.'); } /** * Format the instance as date and time T-separated with no timezone * * @example * ``` * echo Carbon::now()->toDateTimeLocalString(); * echo "\n"; * echo Carbon::now()->toDateTimeLocalString('minute'); // You can specify precision among: minute, second, millisecond and microsecond * ``` * * @param string $unitPrecision * * @return string */ public function toDateTimeLocalString($unitPrecision = 'second') { return $this->rawFormat('Y-m-d\T'.static::getTimeFormatByPrecision($unitPrecision)); } /** * Format the instance with day, date and time * * @example * ``` * echo Carbon::now()->toDayDateTimeString(); * ``` * * @return string */ public function toDayDateTimeString() { return $this->rawFormat('D, M j, Y g:i A'); } /** * Format the instance as ATOM * * @example * ``` * echo Carbon::now()->toAtomString(); * ``` * * @return string */ public function toAtomString() { return $this->rawFormat(DateTime::ATOM); } /** * Format the instance as COOKIE * * @example * ``` * echo Carbon::now()->toCookieString(); * ``` * * @return string */ public function toCookieString() { return $this->rawFormat(DateTime::COOKIE); } /** * Format the instance as ISO8601 * * @example * ``` * echo Carbon::now()->toIso8601String(); * ``` * * @return string */ public function toIso8601String() { return $this->toAtomString(); } /** * Format the instance as RFC822 * * @example * ``` * echo Carbon::now()->toRfc822String(); * ``` * * @return string */ public function toRfc822String() { return $this->rawFormat(DateTime::RFC822); } /** * Convert the instance to UTC and return as Zulu ISO8601 * * @example * ``` * echo Carbon::now()->toIso8601ZuluString(); * ``` * * @param string $unitPrecision * * @return string */ public function toIso8601ZuluString($unitPrecision = 'second') { return $this->avoidMutation() ->utc() ->rawFormat('Y-m-d\T'.static::getTimeFormatByPrecision($unitPrecision).'\Z'); } /** * Format the instance as RFC850 * * @example * ``` * echo Carbon::now()->toRfc850String(); * ``` * * @return string */ public function toRfc850String() { return $this->rawFormat(DateTime::RFC850); } /** * Format the instance as RFC1036 * * @example * ``` * echo Carbon::now()->toRfc1036String(); * ``` * * @return string */ public function toRfc1036String() { return $this->rawFormat(DateTime::RFC1036); } /** * Format the instance as RFC1123 * * @example * ``` * echo Carbon::now()->toRfc1123String(); * ``` * * @return string */ public function toRfc1123String() { return $this->rawFormat(DateTime::RFC1123); } /** * Format the instance as RFC2822 * * @example * ``` * echo Carbon::now()->toRfc2822String(); * ``` * * @return string */ public function toRfc2822String() { return $this->rawFormat(DateTime::RFC2822); } /** * Format the instance as RFC3339 * * @param bool $extended * * @example * ``` * echo Carbon::now()->toRfc3339String() . "\n"; * echo Carbon::now()->toRfc3339String(true) . "\n"; * ``` * * @return string */ public function toRfc3339String($extended = false) { $format = DateTime::RFC3339; if ($extended) { $format = DateTime::RFC3339_EXTENDED; } return $this->rawFormat($format); } /** * Format the instance as RSS * * @example * ``` * echo Carbon::now()->toRssString(); * ``` * * @return string */ public function toRssString() { return $this->rawFormat(DateTime::RSS); } /** * Format the instance as W3C * * @example * ``` * echo Carbon::now()->toW3cString(); * ``` * * @return string */ public function toW3cString() { return $this->rawFormat(DateTime::W3C); } /** * Format the instance as RFC7231 * * @example * ``` * echo Carbon::now()->toRfc7231String(); * ``` * * @return string */ public function toRfc7231String() { return $this->avoidMutation() ->setTimezone('GMT') ->rawFormat(\defined('static::RFC7231_FORMAT') ? static::RFC7231_FORMAT : CarbonInterface::RFC7231_FORMAT); } /** * Get default array representation. * * @example * ``` * var_dump(Carbon::now()->toArray()); * ``` * * @return array */ public function toArray() { return [ 'year' => $this->year, 'month' => $this->month, 'day' => $this->day, 'dayOfWeek' => $this->dayOfWeek, 'dayOfYear' => $this->dayOfYear, 'hour' => $this->hour, 'minute' => $this->minute, 'second' => $this->second, 'micro' => $this->micro, 'timestamp' => $this->timestamp, 'formatted' => $this->rawFormat(\defined('static::DEFAULT_TO_STRING_FORMAT') ? static::DEFAULT_TO_STRING_FORMAT : CarbonInterface::DEFAULT_TO_STRING_FORMAT), 'timezone' => $this->timezone, ]; } /** * Get default object representation. * * @example * ``` * var_dump(Carbon::now()->toObject()); * ``` * * @return object */ public function toObject() { return (object) $this->toArray(); } /** * Returns english human readable complete date string. * * @example * ``` * echo Carbon::now()->toString(); * ``` * * @return string */ public function toString() { return $this->avoidMutation()->locale('en')->isoFormat('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); } /** * Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z, if $keepOffset truthy, offset will be kept: * 1977-04-22T01:00:00-05:00). * * @example * ``` * echo Carbon::now('America/Toronto')->toISOString() . "\n"; * echo Carbon::now('America/Toronto')->toISOString(true) . "\n"; * ``` * * @param bool $keepOffset Pass true to keep the date offset. Else forced to UTC. * * @return null|string */ public function toISOString($keepOffset = false) { if (!$this->isValid()) { return null; } $yearFormat = $this->year < 0 || $this->year > 9999 ? 'YYYYYY' : 'YYYY'; $tzFormat = $keepOffset ? 'Z' : '[Z]'; $date = $keepOffset ? $this : $this->avoidMutation()->utc(); return $date->isoFormat("$yearFormat-MM-DD[T]HH:mm:ss.SSSSSS$tzFormat"); } /** * Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z) with UTC timezone. * * @example * ``` * echo Carbon::now('America/Toronto')->toJSON(); * ``` * * @return null|string */ public function toJSON() { return $this->toISOString(); } /** * Return native DateTime PHP object matching the current instance. * * @example * ``` * var_dump(Carbon::now()->toDateTime()); * ``` * * @return DateTime */ public function toDateTime() { return new DateTime($this->rawFormat('Y-m-d H:i:s.u'), $this->getTimezone()); } /** * Return native toDateTimeImmutable PHP object matching the current instance. * * @example * ``` * var_dump(Carbon::now()->toDateTimeImmutable()); * ``` * * @return DateTimeImmutable */ public function toDateTimeImmutable() { return new DateTimeImmutable($this->rawFormat('Y-m-d H:i:s.u'), $this->getTimezone()); } /** * @alias toDateTime * * Return native DateTime PHP object matching the current instance. * * @example * ``` * var_dump(Carbon::now()->toDate()); * ``` * * @return DateTime */ public function toDate() { return $this->toDateTime(); } /** * Create a iterable CarbonPeriod object from current date to a given end date (and optional interval). * * @param \DateTimeInterface|Carbon|CarbonImmutable|int|null $end period end date or recurrences count if int * @param int|\DateInterval|string|null $interval period default interval or number of the given $unit * @param string|null $unit if specified, $interval must be an integer * * @return CarbonPeriod */ public function toPeriod($end = null, $interval = null, $unit = null) { if ($unit) { $interval = CarbonInterval::make("$interval ".static::pluralUnit($unit)); } $period = (new CarbonPeriod())->setDateClass(static::class)->setStartDate($this); if ($interval) { $period->setDateInterval($interval); } if (\is_int($end) || \is_string($end) && ctype_digit($end)) { $period->setRecurrences($end); } elseif ($end) { $period->setEndDate($end); } return $period; } /** * Create a iterable CarbonPeriod object from current date to a given end date (and optional interval). * * @param \DateTimeInterface|Carbon|CarbonImmutable|null $end period end date * @param int|\DateInterval|string|null $interval period default interval or number of the given $unit * @param string|null $unit if specified, $interval must be an integer * * @return CarbonPeriod */ public function range($end = null, $interval = null, $unit = null) { return $this->toPeriod($end, $interval, $unit); } }
gpl-3.0
csbernath/DataCommander
Foundation/.Net-5.0/Diagnostics/WindowsVersionInfo.cs
1151
using Microsoft.Win32; namespace Foundation.Diagnostics; public sealed class WindowsVersionInfo { public readonly string ProductName; public readonly string DisplayVersion; public readonly string ReleaseId; public readonly string CurrentBuild; public WindowsVersionInfo(string productName, string displayVersion, string releaseId, string currentBuild) { ProductName = productName; DisplayVersion = displayVersion; ReleaseId = releaseId; CurrentBuild = currentBuild; } public static WindowsVersionInfo Get() { #pragma warning disable CA1416 using (var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion")) { var productName = (string)key.GetValue("ProductName"); var displayVersion = (string)key.GetValue("DisplayVersion"); var releaseId = (string)key.GetValue("ReleaseId"); var currentBuild = (string)key.GetValue("CurrentBuild"); return new WindowsVersionInfo(productName, displayVersion, releaseId, currentBuild); } #pragma warning restore CA1416 } }
gpl-3.0
Yoon-jae/Algorithm_BOJ
problem/10826/10826.py
120
n = input() a = 1 b = 0 c = 0 for i in range(2,n+1): c = a + b b = a a = c if n==0: print '0' else: print a
gpl-3.0
jesuscript/parity
js/src/redux/providers/walletActions.js
14867
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. import { isEqual, uniq } from 'lodash'; import Contract from '~/api/contract'; import { bytesToHex, toHex } from '~/api/util/format'; import { ERROR_CODES } from '~/api/transport/error'; import { wallet as WALLET_ABI } from '~/contracts/abi'; import { MAX_GAS_ESTIMATION } from '~/util/constants'; import WalletsUtils from '~/util/wallets'; import { newError } from '~/ui/Errors/actions'; const UPDATE_OWNERS = 'owners'; const UPDATE_REQUIRE = 'require'; const UPDATE_DAILYLIMIT = 'dailylimit'; const UPDATE_TRANSACTIONS = 'transactions'; const UPDATE_CONFIRMATIONS = 'confirmations'; export function confirmOperation (address, owner, operation) { return modifyOperation('confirm', address, owner, operation); } export function revokeOperation (address, owner, operation) { return modifyOperation('revoke', address, owner, operation); } function modifyOperation (method, address, owner, operation) { return (dispatch, getState) => { const { api } = getState(); const contract = new Contract(api, WALLET_ABI).at(address); const options = { from: owner, gas: MAX_GAS_ESTIMATION }; const values = [ operation ]; dispatch(setOperationPendingState(address, operation, true)); contract.instance[method] .estimateGas(options, values) .then((gas) => { options.gas = gas.mul(1.2); return contract.instance[method].postTransaction(options, values); }) .then((requestId) => { return api .pollMethod('parity_checkRequest', requestId) .catch((e) => { dispatch(setOperationPendingState(address, operation, false)); if (e.code === ERROR_CODES.REQUEST_REJECTED) { return; } throw e; }); }) .catch((error) => { dispatch(setOperationPendingState(address, operation, false)); dispatch(newError(error)); }); }; } export function attachWallets (_wallets) { return (dispatch, getState) => { const { wallet, api } = getState(); const prevAddresses = wallet.walletsAddresses; const nextAddresses = Object.keys(_wallets).map((a) => a.toLowerCase()).sort(); if (isEqual(prevAddresses, nextAddresses)) { return; } if (wallet.filterSubId) { api.eth.uninstallFilter(wallet.filterSubId); } if (nextAddresses.length === 0) { return dispatch(updateWallets({ wallets: {}, walletsAddresses: [], filterSubId: null })); } const filterOptions = { fromBlock: 0, toBlock: 'latest', address: nextAddresses }; api.eth .newFilter(filterOptions) .then((filterId) => { dispatch(updateWallets({ wallets: _wallets, walletsAddresses: nextAddresses, filterSubId: filterId })); }) .catch((error) => { if (process.env.NODE_ENV === 'production') { console.error('walletActions::attachWallets', error); } else { throw error; } }); fetchWalletsInfo(Object.keys(_wallets))(dispatch, getState); }; } export function load (api) { return (dispatch, getState) => { const contract = new Contract(api, WALLET_ABI); dispatch(setWalletContract(contract)); api.subscribe('eth_blockNumber', (error) => { if (error) { if (process.env.NODE_ENV === 'production') { return console.error('[eth_blockNumber] walletActions::load', error); } else { throw error; } } const { filterSubId } = getState().wallet; if (!filterSubId) { return; } api.eth .getFilterChanges(filterSubId) .then((logs) => contract.parseEventLogs(logs)) .then((logs) => { parseLogs(logs)(dispatch, getState); }) .catch((error) => { if (process.env.NODE_ENV === 'production') { return console.error('[getFilterChanges] walletActions::load', error); } else { throw error; } }); }); }; } function fetchWalletsInfo (updates) { return (dispatch, getState) => { if (Array.isArray(updates)) { const _updates = updates.reduce((updates, address) => { updates[address] = { [ UPDATE_OWNERS ]: true, [ UPDATE_REQUIRE ]: true, [ UPDATE_DAILYLIMIT ]: true, [ UPDATE_CONFIRMATIONS ]: true, [ UPDATE_TRANSACTIONS ]: true, address }; return updates; }, {}); return fetchWalletsInfo(_updates)(dispatch, getState); } const { api } = getState(); const _updates = Object.values(updates); Promise .all(_updates.map((update) => { const contract = new Contract(api, WALLET_ABI).at(update.address); return fetchWalletInfo(contract, update, getState); })) .then((updates) => { dispatch(updateWalletsDetails(updates)); }) .catch((error) => { if (process.env.NODE_ENV === 'production') { return console.error('walletAction::fetchWalletsInfo', error); } else { throw error; } }); }; } function fetchWalletInfo (contract, update, getState) { const promises = []; if (update[UPDATE_OWNERS]) { promises.push(fetchWalletOwners(contract)); } if (update[UPDATE_REQUIRE]) { promises.push(fetchWalletRequire(contract)); } if (update[UPDATE_DAILYLIMIT]) { promises.push(fetchWalletDailylimit(contract)); } if (update[UPDATE_TRANSACTIONS]) { promises.push(fetchWalletTransactions(contract)); } return Promise .all(promises) .then((updates) => { if (update[UPDATE_CONFIRMATIONS]) { const ownersUpdate = updates.find((u) => u.key === UPDATE_OWNERS); const transactionsUpdate = updates.find((u) => u.key === UPDATE_TRANSACTIONS); const owners = ownersUpdate && ownersUpdate.value || null; const transactions = transactionsUpdate && transactionsUpdate.value || null; return fetchWalletConfirmations(contract, update[UPDATE_CONFIRMATIONS], owners, transactions, getState) .then((update) => { updates.push(update); return updates; }); } return updates; }) .then((updates) => { const wallet = { address: update.address }; updates.forEach((update) => { wallet[update.key] = update.value; }); return wallet; }); } function fetchWalletTransactions (contract) { return WalletsUtils .fetchTransactions(contract) .then((transactions) => { return { key: UPDATE_TRANSACTIONS, value: transactions }; }); } function fetchWalletOwners (contract) { return WalletsUtils .fetchOwners(contract) .then((value) => { return { key: UPDATE_OWNERS, value }; }); } function fetchWalletRequire (contract) { return WalletsUtils .fetchRequire(contract) .then((value) => { return { key: UPDATE_REQUIRE, value }; }); } function fetchWalletDailylimit (contract) { return WalletsUtils .fetchDailylimit(contract) .then((value) => { return { key: UPDATE_DAILYLIMIT, value }; }); } function fetchWalletConfirmations (contract, _operations, _owners = null, _transactions = null, getState) { const walletInstance = contract.instance; const wallet = getState().wallet.wallets[contract.address]; const owners = _owners || (wallet && wallet.owners) || null; const transactions = _transactions || (wallet && wallet.transactions) || null; // Full load if no operations given, or if the one given aren't loaded yet const fullLoad = !Array.isArray(_operations) || _operations .filter((op) => !wallet.confirmations.find((conf) => conf.operation === op)) .length > 0; let promise; if (fullLoad) { promise = walletInstance .ConfirmationNeeded .getAllLogs() .then((logs) => { return logs.map((log) => ({ initiator: log.params.initiator.value, to: log.params.to.value, data: log.params.data.value, value: log.params.value.value, operation: bytesToHex(log.params.operation.value), transactionIndex: log.transactionIndex, transactionHash: log.transactionHash, blockNumber: log.blockNumber, confirmedBy: [] })); }) .then((logs) => { return logs.sort((logA, logB) => { const comp = logA.blockNumber.comparedTo(logB.blockNumber); if (comp !== 0) { return comp; } return logA.transactionIndex.comparedTo(logB.transactionIndex); }); }) .then((confirmations) => { if (confirmations.length === 0) { return confirmations; } // Only fetch confirmations for operations not // yet confirmed (ie. not yet a transaction) if (transactions) { const operations = transactions .filter((t) => t.operation) .map((t) => t.operation); return confirmations.filter((confirmation) => { return !operations.includes(confirmation.operation); }); } return confirmations; }); } else { const { confirmations } = wallet; const nextConfirmations = confirmations .filter((conf) => _operations.includes(conf.operation)); promise = Promise.resolve(nextConfirmations); } return promise .then((confirmations) => { if (confirmations.length === 0) { return confirmations; } const uniqConfirmations = Object.values( confirmations.reduce((confirmations, confirmation) => { confirmations[confirmation.operation] = confirmation; return confirmations; }, {}) ); const operations = uniqConfirmations.map((conf) => conf.operation); return Promise .all(operations.map((op) => fetchOperationConfirmations(contract, op, owners))) .then((confirmedBys) => { uniqConfirmations.forEach((_, index) => { uniqConfirmations[index].confirmedBy = confirmedBys[index]; }); return uniqConfirmations; }); }) .then((confirmations) => { const prevConfirmations = wallet.confirmations || []; const nextConfirmations = prevConfirmations .filter((conA) => !confirmations.find((conB) => conB.operation === conA.operation)) .concat(confirmations) .map((conf) => ({ ...conf, pending: false })); return { key: UPDATE_CONFIRMATIONS, value: nextConfirmations }; }); } function fetchOperationConfirmations (contract, operation, owners = null) { if (!owners) { console.warn('[fetchOperationConfirmations] try to provide the owners for the Wallet', contract.address); } const walletInstance = contract.instance; const promise = owners ? Promise.resolve({ value: owners }) : fetchWalletOwners(contract); return promise .then((result) => { const owners = result.value; return Promise .all(owners.map((owner) => walletInstance.hasConfirmed.call({}, [ operation, owner ]))) .then((data) => { return owners.filter((owner, index) => data[index]); }); }); } function parseLogs (logs) { return (dispatch, getState) => { if (!logs || logs.length === 0) { return; } const { wallet } = getState(); const { contract } = wallet; const walletInstance = contract.instance; const signatures = { OwnerChanged: toHex(walletInstance.OwnerChanged.signature), OwnerAdded: toHex(walletInstance.OwnerAdded.signature), OwnerRemoved: toHex(walletInstance.OwnerRemoved.signature), RequirementChanged: toHex(walletInstance.RequirementChanged.signature), Confirmation: toHex(walletInstance.Confirmation.signature), Revoke: toHex(walletInstance.Revoke.signature), Deposit: toHex(walletInstance.Deposit.signature), SingleTransact: toHex(walletInstance.SingleTransact.signature), MultiTransact: toHex(walletInstance.MultiTransact.signature), ConfirmationNeeded: toHex(walletInstance.ConfirmationNeeded.signature) }; const updates = {}; logs.forEach((log) => { const { address, topics } = log; const eventSignature = toHex(topics[0]); const prev = updates[address] || { [ UPDATE_DAILYLIMIT ]: true, address }; switch (eventSignature) { case signatures.OwnerChanged: case signatures.OwnerAdded: case signatures.OwnerRemoved: updates[address] = { ...prev, [ UPDATE_OWNERS ]: true }; return; case signatures.RequirementChanged: updates[address] = { ...prev, [ UPDATE_REQUIRE ]: true }; return; case signatures.ConfirmationNeeded: case signatures.Confirmation: case signatures.Revoke: const operation = bytesToHex(log.params.operation.value); updates[address] = { ...prev, [ UPDATE_CONFIRMATIONS ]: uniq( (prev[UPDATE_CONFIRMATIONS] || []).concat(operation) ) }; return; case signatures.Deposit: case signatures.SingleTransact: case signatures.MultiTransact: updates[address] = { ...prev, [ UPDATE_TRANSACTIONS ]: true }; return; } }); fetchWalletsInfo(updates)(dispatch, getState); }; } function setOperationPendingState (address, operation, isPending) { return { type: 'setOperationPendingState', address, operation, isPending }; } function updateWalletsDetails (wallets) { return { type: 'updateWalletsDetails', wallets }; } function setWalletContract (contract) { return { type: 'setWalletContract', contract }; } function updateWallets (data) { return { type: 'updateWallets', ...data }; }
gpl-3.0
aitoralmeida/c4a_data_repository
RestApiInterface/src/packControllers/__init__.py
79
# -*- coding: utf-8 -*- import ar_post_orm import sr_post_orm import post_orm
gpl-3.0
atkv/atkv.github.io
doc/search/all_12.js
311
var searchData= [ ['v',['v',['../structAtPQueueU64.html#aa27f8fee7776c2bc7cb76258d09284d4',1,'AtPQueueU64']]], ['value',['value',['../structAtListU64.html#a11759f4a7cc962de68a912d3656eb202',1,'AtListU64']]], ['vp',['vp',['../structAtPQueueU64.html#a3466a22e0db9044bf148bde2a9b7eb1e',1,'AtPQueueU64']]] ];
gpl-3.0
DanielReid/addis-core
src/main/java/org/drugis/addis/analyses/controller/AnalysisArchiveCommand.java
352
package org.drugis.addis.analyses.controller; /** * Created by joris on 9-1-17. */ public class AnalysisArchiveCommand { private Boolean isArchived; public AnalysisArchiveCommand() { } public AnalysisArchiveCommand(Boolean isArchived){ this.isArchived = isArchived; } public Boolean getIsArchived() { return isArchived; } }
gpl-3.0
nurv/lirec
scenarios/MyFriend/MyPleo/workspace/viPleoShivaModule/Resources/Scripts/MyPleoAI_State_LowEnergy_onLeave.lua
693
-------------------------------------------------------------------------------- -- State............ : LowEnergy -- Author........... : Tiago Paiva -- Description...... : -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function MyPleoAI.LowEnergy_onLeave ( ) -------------------------------------------------------------------------------- sound.stop( this.hBody ( ), 3) this.gotstate (false ) -------------------------------------------------------------------------------- end --------------------------------------------------------------------------------
gpl-3.0
dtrip/weevely3
modules/file/upload2web.py
4955
from core.vectors import PhpCode, ShellCmd, ModuleExec, Os from core.module import Module from core import modules from core import messages from core.loggers import log import urlparse import os class Upload2web(Module): """Upload file automatically to a web folder and get corresponding URL.""" def init(self): self.register_info( { 'author': [ 'Emilio Pinna' ], 'license': 'GPLv3' } ) self.register_arguments([ { 'name' : 'lpath', 'help' : 'Local file path. Set remote file name when used with -content.' }, { 'name' : 'rpath', 'help' : 'Remote path. If it is a folder find the first writable folder in it', 'default' : '.', 'nargs' : '?' }, { 'name' : '-content', 'help' : 'Optionally specify the file content'}, { 'name' : '-simulate', 'help' : 'Just return the positions without uploading any content', 'action' : 'store_true', 'default' : False }, ]) def _get_env_info(self, script_url): script_folder = ModuleExec('system_info', [ '-info', 'script_folder' ]).load_result_or_run('script_folder') if not script_folder: return script_url_splitted = urlparse.urlsplit(script_url) script_url_path_folder, script_url_path_filename = os.path.split( script_url_splitted.path) url_folder_pieces = script_url_path_folder.split(os.sep) folder_pieces = script_folder.split(os.sep) for pieceurl, piecefolder in zip(reversed(url_folder_pieces), reversed(folder_pieces)): if pieceurl == piecefolder: folder_pieces.pop() url_folder_pieces.pop() else: break base_url_path_folder = os.sep.join(url_folder_pieces) self.base_folder_url = urlparse.urlunsplit( script_url_splitted[:2] + (base_url_path_folder, ) + script_url_splitted[3:]) self.base_folder_path = os.sep.join(folder_pieces) def _map_folder2web(self, relative_path_folder='.'): absolute_path = ModuleExec('file_check', [ relative_path_folder, 'abspath' ]).run() if not absolute_path: log.warn(messages.module_file_upload2web.failed_resolve_path) return None, None if not absolute_path.startswith(self.base_folder_path.rstrip('/')): log.warn(messages.module_file_upload2web.error_s_not_under_webroot_s % ( absolute_path, self.base_folder_path.rstrip('/')) ) return None, None relative_to_webroot_path = absolute_path.replace( self.base_folder_path, '' ) url_folder = '%s/%s' % (self.base_folder_url.rstrip('/'), relative_to_webroot_path.lstrip('/')) return absolute_path, url_folder def _map_file2web(self, relative_path_file): relative_path_folder, filename = os.path.split(relative_path_file) if not relative_path_folder: relative_path_folder = './' absolute_path_folder, url_folder = self._map_folder2web( relative_path_folder) if not absolute_path_folder or not url_folder: return None, None absolute_path_file = os.path.join(absolute_path_folder, filename) url_file = os.path.join(url_folder, filename) return absolute_path_file, url_file def run(self): file_upload_args = [ self.args['rpath'] ] content = self.args.get('content') lpath = self.args.get('lpath') self._get_env_info(self.session['url']) if not self.base_folder_url or not self.base_folder_path: log.warn(messages.module_file_upload2web.failed_retrieve_info) # If remote path is a folder, get first writable folder if ModuleExec("file_check", [ self.args['rpath'], 'dir' ]).run(): folders = ModuleExec("file_find", [ '-writable', '-quit', self.args['rpath'] ]).run() if not folders or not folders[0]: log.warn(messages.module_file_upload2web.failed_search_writable_starting_s % self.args['rpath']) return None, None # Get remote file name from lpath lfolder, rname = os.path.split(lpath) # TODO: all the paths should be joined with remote OS_SEP from system_info. self.args['rpath'] = os.path.join(folders[0], rname) file_upload_args = [ lpath, self.args['rpath'] ] if content: file_upload_args += [ '-content', content ] if self.args.get('simulate') or ModuleExec("file_upload", file_upload_args).run(): # Guess URL from rpath return [ self._map_file2web(self.args['rpath']) ]
gpl-3.0
jonathankablan/prestashop-1.6
prestashop_1.7/classes/Carrier.php
62085
<?php /** * 2007-2016 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@prestashop.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <contact@prestashop.com> * @copyright 2007-2016 PrestaShop SA * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ class CarrierCore extends ObjectModel { /** * getCarriers method filter. */ const PS_CARRIERS_ONLY = 1; const CARRIERS_MODULE = 2; const CARRIERS_MODULE_NEED_RANGE = 3; const PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE = 4; const ALL_CARRIERS = 5; const SHIPPING_METHOD_DEFAULT = 0; const SHIPPING_METHOD_WEIGHT = 1; const SHIPPING_METHOD_PRICE = 2; const SHIPPING_METHOD_FREE = 3; const SHIPPING_PRICE_EXCEPTION = 0; const SHIPPING_WEIGHT_EXCEPTION = 1; const SHIPPING_SIZE_EXCEPTION = 2; const SORT_BY_PRICE = 0; const SORT_BY_POSITION = 1; const SORT_BY_ASC = 0; const SORT_BY_DESC = 1; /** @var int common id for carrier historization */ public $id_reference; /** @var string Name */ public $name; /** @var string URL with a '@' for */ public $url; /** @var string Delay needed to deliver customer */ public $delay; /** @var bool Carrier statuts */ public $active = true; /** @var bool True if carrier has been deleted (staying in database as deleted) */ public $deleted = 0; /** @var bool Active or not the shipping handling */ public $shipping_handling = true; /** @var int Behavior taken for unknown range */ public $range_behavior; /** @var bool Carrier module */ public $is_module; /** @var bool Free carrier */ public $is_free = false; /** @var int shipping behavior: by weight or by price */ public $shipping_method = 0; /** @var bool Shipping external */ public $shipping_external = 0; /** @var string Shipping external */ public $external_module_name = null; /** @var bool Need Range */ public $need_range = 0; /** @var int Position */ public $position; /** @var int maximum package width managed by the transporter */ public $max_width; /** @var int maximum package height managed by the transporter */ public $max_height; /** @var int maximum package deep managed by the transporter */ public $max_depth; /** @var int maximum package weight managed by the transporter */ public $max_weight; /** @var int grade of the shipping delay (0 for longest, 9 for shortest) */ public $grade; /** * @see ObjectModel::$definition */ public static $definition = array( 'table' => 'carrier', 'primary' => 'id_carrier', 'multilang' => true, 'multilang_shop' => true, 'fields' => array( /* Classic fields */ 'id_reference' => array('type' => self::TYPE_INT), 'name' => array('type' => self::TYPE_STRING, 'validate' => 'isCarrierName', 'required' => true, 'size' => 64), 'active' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool', 'required' => true), 'is_free' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'), 'url' => array('type' => self::TYPE_STRING, 'validate' => 'isAbsoluteUrl'), 'shipping_handling' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'), 'shipping_external' => array('type' => self::TYPE_BOOL), 'range_behavior' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'), 'shipping_method' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), 'max_width' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), 'max_height' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), 'max_depth' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), 'max_weight' => array('type' => self::TYPE_FLOAT, 'validate' => 'isFloat'), 'grade' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'size' => 1), 'external_module_name' => array('type' => self::TYPE_STRING, 'size' => 64), 'is_module' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'), 'need_range' => array('type' => self::TYPE_BOOL), 'position' => array('type' => self::TYPE_INT), 'deleted' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'), /* Lang fields */ 'delay' => array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'required' => true, 'size' => 128), ), ); protected static $price_by_weight = array(); protected static $price_by_weight2 = array(); protected static $price_by_price = array(); protected static $price_by_price2 = array(); protected static $cache_tax_rule = array(); protected $webserviceParameters = array( 'fields' => array( 'deleted' => array(), 'is_module' => array(), 'id_tax_rules_group' => array( 'getter' => 'getIdTaxRulesGroup', 'setter' => 'setTaxRulesGroup', 'xlink_resource' => array( 'resourceName' => 'tax_rule_groups', ), ), ), ); /** * CarrierCore constructor. * * @param int|null $id Carrier ID * @param int|null $id_lang Language ID */ public function __construct($id = null, $id_lang = null) { parent::__construct($id, $id_lang); /* * keep retrocompatibility SHIPPING_METHOD_DEFAULT * @deprecated 1.5.5 */ if ($this->shipping_method == Carrier::SHIPPING_METHOD_DEFAULT) { $this->shipping_method = ((int) Configuration::get('PS_SHIPPING_METHOD') ? Carrier::SHIPPING_METHOD_WEIGHT : Carrier::SHIPPING_METHOD_PRICE); } if ($this->name == '0') { $this->name = Carrier::getCarrierNameFromShopName(); } $this->image_dir = _PS_SHIP_IMG_DIR_; } /** * Adds current Carrier as a new Object to the database. * * @param bool $autoDate Automatically set `date_upd` and `date_add` columns * @param bool $nullValues Whether we want to use NULL values instead of empty quotes values * * @return bool Whether the Carrier has been successfully added * * @throws PrestaShopDatabaseException * @throws PrestaShopException */ public function add($autoDate = true, $nullValues = false) { if ($this->position <= 0) { $this->position = Carrier::getHigherPosition() + 1; } if (!parent::add($autoDate, $nullValues) || !Validate::isLoadedObject($this)) { return false; } if (!$count = Db::getInstance()->getValue('SELECT count(`id_carrier`) FROM `'._DB_PREFIX_.$this->def['table'].'` WHERE `deleted` = 0')) { return false; } if ($count == 1) { Configuration::updateValue('PS_CARRIER_DEFAULT', (int) $this->id); } // Register reference Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.$this->def['table'].'` SET `id_reference` = '. (int) $this->id.' WHERE `id_carrier` = '.(int) $this->id ); foreach (Shop::getContextListShopID() as $shopId) { foreach (Module::getPaymentModules() as $module) { Db::getInstance()->execute(' INSERT INTO `'._DB_PREFIX_.'module_'.bqSQL('carrier').'` (`id_module`, `id_shop`, `id_'.bqSQL('reference').'`) VALUES ('.(int) $module['id_module'].','.(int) $shopId.','.(int) $this->id.')' ); } } return true; } /** * @since 1.5.0 * @see ObjectModel::delete() */ public function delete() { if (!parent::delete()) { return false; } Carrier::cleanPositions(); return Db::getInstance()->delete('cart_rule_carrier', 'id_carrier = '.(int) $this->id) && Db::getInstance()->delete('module_carrier', 'id_reference = '.(int) $this->id_reference) && $this->deleteTaxRulesGroup(Shop::getShops(true, null, true)); } /** * Change carrier id in delivery prices when updating a carrier. * * @param int $id_old Old Carrier ID */ public function setConfiguration($id_old) { Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.'delivery` SET `id_carrier` = '.(int) $this->id.' WHERE `id_carrier` = '.(int) $id_old); } /** * Get delivery price for a given order. * * @param float $total_weight Total order weight * @param int $id_zone Zone ID (for customer delivery address) * * @return float|bool Delivery price, false if not possible */ public function getDeliveryPriceByWeight($total_weight, $id_zone) { $id_carrier = (int) $this->id; $cache_key = $id_carrier.'_'.$total_weight.'_'.$id_zone; if (!isset(self::$price_by_weight[$cache_key])) { $sql = 'SELECT d.`price` FROM `'._DB_PREFIX_.'delivery` d LEFT JOIN `'._DB_PREFIX_.'range_weight` w ON (d.`id_range_weight` = w.`id_range_weight`) WHERE d.`id_zone` = '.(int) $id_zone.' AND '.(float) $total_weight.' >= w.`delimiter1` AND '.(float) $total_weight.' < w.`delimiter2` AND d.`id_carrier` = '.$id_carrier.' '.Carrier::sqlDeliveryRangeShop('range_weight').' ORDER BY w.`delimiter1` ASC'; $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql); if (!isset($result['price'])) { self::$price_by_weight[$cache_key] = $this->getMaxDeliveryPriceByWeight($id_zone); } else { self::$price_by_weight[$cache_key] = $result['price']; } } $price_by_weight = Hook::exec('actionDeliveryPriceByWeight', array('id_carrier' => $id_carrier, 'total_weight' => $total_weight, 'id_zone' => $id_zone)); if (is_numeric($price_by_weight)) { self::$price_by_weight[$cache_key] = $price_by_weight; } return self::$price_by_weight[$cache_key]; } /** * Get delivery price by total weight. * * @param int $id_carrier Carrier ID * @param float $total_weight Total weight * @param int $id_zone Zone ID * * @return float|bool Delivery price, false if not possible */ public static function checkDeliveryPriceByWeight($id_carrier, $total_weight, $id_zone) { $id_carrier = (int) $id_carrier; $cache_key = $id_carrier.'_'.$total_weight.'_'.$id_zone; if (!isset(self::$price_by_weight2[$cache_key])) { $sql = 'SELECT d.`price` FROM `'._DB_PREFIX_.'delivery` d LEFT JOIN `'._DB_PREFIX_.'range_weight` w ON d.`id_range_weight` = w.`id_range_weight` WHERE d.`id_zone` = '.(int) $id_zone.' AND '.(float) $total_weight.' >= w.`delimiter1` AND '.(float) $total_weight.' < w.`delimiter2` AND d.`id_carrier` = '.$id_carrier.' '.Carrier::sqlDeliveryRangeShop('range_weight').' ORDER BY w.`delimiter1` ASC'; $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql); self::$price_by_weight2[$cache_key] = (isset($result['price'])); } $price_by_weight = Hook::exec('actionDeliveryPriceByWeight', array('id_carrier' => $id_carrier, 'total_weight' => $total_weight, 'id_zone' => $id_zone)); if (is_numeric($price_by_weight)) { self::$price_by_weight2[$cache_key] = $price_by_weight; } return self::$price_by_weight2[$cache_key]; } /** * Get maximum delivery price when range weight is used. * * @param int $id_zone Zone ID * * @return false|null|string Maximum delivery price */ public function getMaxDeliveryPriceByWeight($id_zone) { $cache_id = 'Carrier::getMaxDeliveryPriceByWeight_'.(int) $this->id.'-'.(int) $id_zone; if (!Cache::isStored($cache_id)) { $sql = 'SELECT d.`price` FROM `'._DB_PREFIX_.'delivery` d INNER JOIN `'._DB_PREFIX_.'range_weight` w ON d.`id_range_weight` = w.`id_range_weight` WHERE d.`id_zone` = '.(int) $id_zone.' AND d.`id_carrier` = '.(int) $this->id.' '.Carrier::sqlDeliveryRangeShop('range_weight').' ORDER BY w.`delimiter2` DESC'; $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql); Cache::store($cache_id, $result); return $result; } return Cache::retrieve($cache_id); } /** * Get delivery price for a given order by total order price MINUS shipping costs. * * @param float $order_total Order total to pay * @param int $id_zone Zone id (for customer delivery address) * @param int|null $id_currency Currency ID * * @return float Maximum delivery price */ public function getDeliveryPriceByPrice($order_total, $id_zone, $id_currency = null) { $id_carrier = (int) $this->id; $cache_key = $this->id.'_'.$order_total.'_'.$id_zone.'_'.$id_currency; if (!isset(self::$price_by_price[$cache_key])) { if (!empty($id_currency)) { $order_total = Tools::convertPrice($order_total, $id_currency, false); } $sql = 'SELECT d.`price` FROM `'._DB_PREFIX_.'delivery` d LEFT JOIN `'._DB_PREFIX_.'range_price` r ON d.`id_range_price` = r.`id_range_price` WHERE d.`id_zone` = '.(int) $id_zone.' AND '.(float) $order_total.' >= r.`delimiter1` AND '.(float) $order_total.' < r.`delimiter2` AND d.`id_carrier` = '.$id_carrier.' '.Carrier::sqlDeliveryRangeShop('range_price').' ORDER BY r.`delimiter1` ASC'; $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql); if (!isset($result['price'])) { self::$price_by_price[$cache_key] = $this->getMaxDeliveryPriceByPrice($id_zone); } else { self::$price_by_price[$cache_key] = $result['price']; } } $price_by_price = Hook::exec('actionDeliveryPriceByPrice', array('id_carrier' => $id_carrier, 'order_total' => $order_total, 'id_zone' => $id_zone)); if (is_numeric($price_by_price)) { self::$price_by_price[$cache_key] = $price_by_price; } return self::$price_by_price[$cache_key]; } /** * Get delivery price for a given order. * * @param int $id_carrier Carrier ID * @param float $order_total Order total to pay * @param int $id_zone Zone id (for customer delivery address) * @param int|null $id_currency Currency ID * * @return float Delivery price */ public static function checkDeliveryPriceByPrice($id_carrier, $order_total, $id_zone, $id_currency = null) { $id_carrier = (int) $id_carrier; $cache_key = $id_carrier.'_'.$order_total.'_'.$id_zone.'_'.$id_currency; if (!isset(self::$price_by_price2[$cache_key])) { if (!empty($id_currency)) { $order_total = Tools::convertPrice($order_total, $id_currency, false); } $sql = 'SELECT d.`price` FROM `'._DB_PREFIX_.'delivery` d LEFT JOIN `'._DB_PREFIX_.'range_price` r ON d.`id_range_price` = r.`id_range_price` WHERE d.`id_zone` = '.(int) $id_zone.' AND '.(float) $order_total.' >= r.`delimiter1` AND '.(float) $order_total.' < r.`delimiter2` AND d.`id_carrier` = '.$id_carrier.' '.Carrier::sqlDeliveryRangeShop('range_price').' ORDER BY r.`delimiter1` ASC'; $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql); self::$price_by_price2[$cache_key] = (isset($result['price'])); } $price_by_price = Hook::exec('actionDeliveryPriceByPrice', array('id_carrier' => $id_carrier, 'order_total' => $order_total, 'id_zone' => $id_zone)); if (is_numeric($price_by_price)) { self::$price_by_price2[$cache_key] = $price_by_price; } return self::$price_by_price2[$cache_key]; } /** * Get maximum delivery price by order total MINUS shipping costs. * * @param int $id_zone Zone ID * * @return float Maximum delivery price */ public function getMaxDeliveryPriceByPrice($id_zone) { $cache_id = 'Carrier::getMaxDeliveryPriceByPrice_'.(int) $this->id.'-'.(int) $id_zone; if (!Cache::isStored($cache_id)) { $sql = 'SELECT d.`price` FROM `'._DB_PREFIX_.'delivery` d INNER JOIN `'._DB_PREFIX_.'range_price` r ON d.`id_range_price` = r.`id_range_price` WHERE d.`id_zone` = '.(int) $id_zone.' AND d.`id_carrier` = '.(int) $this->id.' '.Carrier::sqlDeliveryRangeShop('range_price').' ORDER BY r.`delimiter2` DESC'; $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql); Cache::store($cache_id, $result); } return Cache::retrieve($cache_id); } /** * Get delivery prices for a given shipping method (price/weight). * * @param string $range_table Table name (price or weight) * @param int $id_carrier Carrier ID * * @return array Delivery prices */ public static function getDeliveryPriceByRanges($range_table, $id_carrier) { $sql = 'SELECT d.`id_'.bqSQL($range_table).'`, d.id_carrier, d.id_zone, d.price FROM '._DB_PREFIX_.'delivery d LEFT JOIN `'._DB_PREFIX_.bqSQL($range_table).'` r ON r.`id_'.bqSQL($range_table).'` = d.`id_'.bqSQL($range_table).'` WHERE d.id_carrier = '.(int) $id_carrier.' AND d.`id_'.bqSQL($range_table).'` IS NOT NULL AND d.`id_'.bqSQL($range_table).'` != 0 '.Carrier::sqlDeliveryRangeShop($range_table).' ORDER BY r.delimiter1'; return Db::getInstance()->executeS($sql); } /** * Get all carriers in a given language. * * @param int $id_lang Language id * @param int $modules_filters Possible values: * - PS_CARRIERS_ONLY * - CARRIERS_MODULE * - CARRIERS_MODULE_NEED_RANGE * - PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE * - ALL_CARRIERS * @param bool $active Returns only active carriers when true * * @return array Carriers */ public static function getCarriers($id_lang, $active = false, $delete = false, $id_zone = false, $ids_group = null, $modules_filters = self::PS_CARRIERS_ONLY) { // Filter by groups and no groups => return empty array if ($ids_group && (!is_array($ids_group) || !count($ids_group))) { return array(); } $sql = ' SELECT c.*, cl.delay FROM `'._DB_PREFIX_.'carrier` c LEFT JOIN `'._DB_PREFIX_.'carrier_lang` cl ON (c.`id_carrier` = cl.`id_carrier` AND cl.`id_lang` = '.(int) $id_lang.Shop::addSqlRestrictionOnLang('cl').') LEFT JOIN `'._DB_PREFIX_.'carrier_zone` cz ON (cz.`id_carrier` = c.`id_carrier`)'. ($id_zone ? 'LEFT JOIN `'._DB_PREFIX_.'zone` z ON (z.`id_zone` = '.(int) $id_zone.')' : '').' '.Shop::addSqlAssociation('carrier', 'c').' WHERE c.`deleted` = '.($delete ? '1' : '0'); if ($active) { $sql .= ' AND c.`active` = 1 '; } if ($id_zone) { $sql .= ' AND cz.`id_zone` = '.(int) $id_zone.' AND z.`active` = 1 '; } if ($ids_group) { $sql .= ' AND EXISTS (SELECT 1 FROM '._DB_PREFIX_.'carrier_group WHERE '._DB_PREFIX_.'carrier_group.id_carrier = c.id_carrier AND id_group IN ('.implode(',', array_map('intval', $ids_group)).')) '; } switch ($modules_filters) { case 1: $sql .= ' AND c.is_module = 0 '; break; case 2: $sql .= ' AND c.is_module = 1 '; break; case 3: $sql .= ' AND c.is_module = 1 AND c.need_range = 1 '; break; case 4: $sql .= ' AND (c.is_module = 0 OR c.need_range = 1) '; break; } $sql .= ' GROUP BY c.`id_carrier` ORDER BY c.`position` ASC'; $cache_id = 'Carrier::getCarriers_'.md5($sql); if (!Cache::isStored($cache_id)) { $carriers = Db::getInstance()->executeS($sql); Cache::store($cache_id, $carriers); } else { $carriers = Cache::retrieve($cache_id); } foreach ($carriers as $key => $carrier) { if ($carrier['name'] == '0') { $carriers[$key]['name'] = Carrier::getCarrierNameFromShopName(); } } return $carriers; } /** * Get most used Tax rules group. * * @return false|null|string Most used Tax rules group ID */ public static function getIdTaxRulesGroupMostUsed() { return Db::getInstance()->getValue(' SELECT id_tax_rules_group FROM ( SELECT COUNT(*) n, c.id_tax_rules_group FROM '._DB_PREFIX_.'carrier c JOIN '._DB_PREFIX_.'tax_rules_group trg ON (c.id_tax_rules_group = trg.id_tax_rules_group) WHERE trg.active = 1 AND trg.deleted = 0 GROUP BY c.id_tax_rules_group ORDER BY n DESC LIMIT 1 ) most_used' ); } /** * Get the countries to which can be delivered. * * @param int $id_lang Language ID * @param bool $active_countries Only return active countries when true * @param bool $active_carriers Only return active carriers when true * @param null $contain_states Only return countries with states * * @return array Countries to which can be delivered */ public static function getDeliveredCountries($id_lang, $active_countries = false, $active_carriers = false, $contain_states = null) { if (!Validate::isBool($active_countries) || !Validate::isBool($active_carriers)) { die(Tools::displayError()); } $states = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' SELECT s.* FROM `'._DB_PREFIX_.'state` s ORDER BY s.`name` ASC'); $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' SELECT cl.*,c.*, cl.`name` AS country, zz.`name` AS zone FROM `'._DB_PREFIX_.'country` c'. Shop::addSqlAssociation('country', 'c').' LEFT JOIN `'._DB_PREFIX_.'country_lang` cl ON (c.`id_country` = cl.`id_country` AND cl.`id_lang` = '.(int) $id_lang.') INNER JOIN (`'._DB_PREFIX_.'carrier_zone` cz INNER JOIN `'._DB_PREFIX_.'carrier` cr ON ( cr.id_carrier = cz.id_carrier AND cr.deleted = 0 '. ($active_carriers ? 'AND cr.active = 1) ' : ') ').' LEFT JOIN `'._DB_PREFIX_.'zone` zz ON cz.id_zone = zz.id_zone) ON zz.`id_zone` = c.`id_zone` WHERE 1 '.($active_countries ? 'AND c.active = 1' : '').' '.(!is_null($contain_states) ? 'AND c.`contains_states` = '.(int) $contain_states : '').' ORDER BY cl.name ASC'); $countries = array(); foreach ($result as &$country) { $countries[$country['id_country']] = $country; } foreach ($states as &$state) { if (isset($countries[$state['id_country']])) { /* Does not keep the state if its country has been disabled and not selected */ if ($state['active'] == 1) { $countries[$state['id_country']]['states'][] = $state; } } } return $countries; } /** * Return the default carrier to use. * * @param array $carriers Carriers * @param int $default_carrier The last selected Carrier ID * * @return number the id of the default carrier */ public static function getDefaultCarrierSelection($carriers, $default_carrier = 0) { if (empty($carriers)) { return 0; } if ((int) $default_carrier != 0) { foreach ($carriers as $carrier) { if ($carrier['id_carrier'] == (int) $default_carrier) { return (int) $carrier['id_carrier']; } } } foreach ($carriers as $carrier) { if ($carrier['id_carrier'] == (int) Configuration::get('PS_CARRIER_DEFAULT')) { return (int) $carrier['id_carrier']; } } return (int) $carriers[0]['id_carrier']; } /** * Get available Carriers for Order. * * @param int $id_zone Zone ID * @param array $groups Group of the Customer * @param Cart|null $cart Optional Cart object * @param array &$error Contains an error message if an error occurs * * @return array Carriers for the order */ public static function getCarriersForOrder($id_zone, $groups = null, $cart = null, &$error = array()) { $context = Context::getContext(); $id_lang = $context->language->id; if (is_null($cart)) { $cart = $context->cart; } if (isset($context->currency)) { $id_currency = $context->currency->id; } if (is_array($groups) && !empty($groups)) { $result = Carrier::getCarriers($id_lang, true, false, (int) $id_zone, $groups, self::PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE); } else { $result = Carrier::getCarriers($id_lang, true, false, (int) $id_zone, array(Configuration::get('PS_UNIDENTIFIED_GROUP')), self::PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE); } $results_array = array(); foreach ($result as $k => $row) { $carrier = new Carrier((int) $row['id_carrier']); $shipping_method = $carrier->getShippingMethod(); if ($shipping_method != Carrier::SHIPPING_METHOD_FREE) { // Get only carriers that are compliant with shipping method if (($shipping_method == Carrier::SHIPPING_METHOD_WEIGHT && $carrier->getMaxDeliveryPriceByWeight($id_zone) === false)) { $error[$carrier->id] = Carrier::SHIPPING_WEIGHT_EXCEPTION; unset($result[$k]); continue; } if (($shipping_method == Carrier::SHIPPING_METHOD_PRICE && $carrier->getMaxDeliveryPriceByPrice($id_zone) === false)) { $error[$carrier->id] = Carrier::SHIPPING_PRICE_EXCEPTION; unset($result[$k]); continue; } // If out-of-range behavior carrier is set to "Deactivate carrier" if ($row['range_behavior']) { // Get id zone if (!$id_zone) { $id_zone = (int) Country::getIdZone(Country::getDefaultCountryId()); } // Get only carriers that have a range compatible with cart if ($shipping_method == Carrier::SHIPPING_METHOD_WEIGHT && (!Carrier::checkDeliveryPriceByWeight($row['id_carrier'], $cart->getTotalWeight(), $id_zone))) { $error[$carrier->id] = Carrier::SHIPPING_WEIGHT_EXCEPTION; unset($result[$k]); continue; } if ($shipping_method == Carrier::SHIPPING_METHOD_PRICE && (!Carrier::checkDeliveryPriceByPrice($row['id_carrier'], $cart->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING), $id_zone, $id_currency))) { $error[$carrier->id] = Carrier::SHIPPING_PRICE_EXCEPTION; unset($result[$k]); continue; } } } $row['name'] = (strval($row['name']) != '0' ? $row['name'] : Carrier::getCarrierNameFromShopName()); $row['price'] = (($shipping_method == Carrier::SHIPPING_METHOD_FREE) ? 0 : $cart->getPackageShippingCost((int) $row['id_carrier'], true, null, null, $id_zone)); $row['price_tax_exc'] = (($shipping_method == Carrier::SHIPPING_METHOD_FREE) ? 0 : $cart->getPackageShippingCost((int) $row['id_carrier'], false, null, null, $id_zone)); $row['img'] = file_exists(_PS_SHIP_IMG_DIR_.(int) $row['id_carrier'].'.jpg') ? _THEME_SHIP_DIR_.(int) $row['id_carrier'].'.jpg' : ''; // If price is false, then the carrier is unavailable (carrier module) if ($row['price'] === false) { unset($result[$k]); continue; } $results_array[] = $row; } // if we have to sort carriers by price $prices = array(); if (Configuration::get('PS_CARRIER_DEFAULT_SORT') == Carrier::SORT_BY_PRICE) { foreach ($results_array as $r) { $prices[] = $r['price']; } if (Configuration::get('PS_CARRIER_DEFAULT_ORDER') == Carrier::SORT_BY_ASC) { array_multisort($prices, SORT_ASC, SORT_NUMERIC, $results_array); } else { array_multisort($prices, SORT_DESC, SORT_NUMERIC, $results_array); } } return $results_array; } public static function checkCarrierZone($id_carrier, $id_zone) { $cache_id = 'Carrier::checkCarrierZone_'.(int) $id_carrier.'-'.(int) $id_zone; if (!Cache::isStored($cache_id)) { $sql = 'SELECT c.`id_carrier` FROM `'._DB_PREFIX_.'carrier` c LEFT JOIN `'._DB_PREFIX_.'carrier_zone` cz ON (cz.`id_carrier` = c.`id_carrier`) LEFT JOIN `'._DB_PREFIX_.'zone` z ON (z.`id_zone` = '.(int) $id_zone.') WHERE c.`id_carrier` = '.(int) $id_carrier.' AND c.`deleted` = 0 AND c.`active` = 1 AND cz.`id_zone` = '.(int) $id_zone.' AND z.`active` = 1'; $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql); Cache::store($cache_id, $result); } return Cache::retrieve($cache_id); } /** * Get all zones. * * @return array Zones */ public function getZones() { return Db::getInstance()->executeS(' SELECT * FROM `'._DB_PREFIX_.'carrier_zone` cz LEFT JOIN `'._DB_PREFIX_.'zone` z ON cz.`id_zone` = z.`id_zone` WHERE cz.`id_carrier` = '.(int) $this->id); } /** * Get a specific zones. * * @return array Zone */ public function getZone($id_zone) { return Db::getInstance()->executeS(' SELECT * FROM `'._DB_PREFIX_.'carrier_zone` WHERE `id_carrier` = '.(int) $this->id.' AND `id_zone` = '.(int) $id_zone); } /** * Add zone. */ public function addZone($id_zone) { if (Db::getInstance()->execute(' INSERT INTO `'._DB_PREFIX_.'carrier_zone` (`id_carrier` , `id_zone`) VALUES ('.(int) $this->id.', '.(int) $id_zone.') ')) { // Get all ranges for this carrier $ranges_price = RangePrice::getRanges($this->id); $ranges_weight = RangeWeight::getRanges($this->id); // Create row in ps_delivery table if (count($ranges_price) || count($ranges_weight)) { $sql = 'INSERT INTO `'._DB_PREFIX_.'delivery` (`id_carrier`, `id_range_price`, `id_range_weight`, `id_zone`, `price`) VALUES '; if (count($ranges_price)) { foreach ($ranges_price as $range) { $sql .= '('.(int) $this->id.', '.(int) $range['id_range_price'].', 0, '.(int) $id_zone.', 0),'; } } if (count($ranges_weight)) { foreach ($ranges_weight as $range) { $sql .= '('.(int) $this->id.', 0, '.(int) $range['id_range_weight'].', '.(int) $id_zone.', 0),'; } } $sql = rtrim($sql, ','); return Db::getInstance()->execute($sql); } return true; } return false; } /** * Delete zone. */ public function deleteZone($id_zone) { if (Db::getInstance()->execute(' DELETE FROM `'._DB_PREFIX_.'carrier_zone` WHERE `id_carrier` = '.(int) $this->id.' AND `id_zone` = '.(int) $id_zone.' LIMIT 1 ')) { return Db::getInstance()->execute(' DELETE FROM `'._DB_PREFIX_.'delivery` WHERE `id_carrier` = '.(int) $this->id.' AND `id_zone` = '.(int) $id_zone); } return false; } /** * Gets a specific group. * * @since 1.5.0 * * @return array Group */ public function getGroups() { return Db::getInstance()->executeS(' SELECT id_group FROM '._DB_PREFIX_.'carrier_group WHERE id_carrier='.(int) $this->id); } /** * Clean delivery prices (weight/price). * * @param string $rangeTable Table name to clean (weight or price according to shipping method) * * @return bool Deletion result */ public function deleteDeliveryPrice($range_table) { $where = '`id_carrier` = '.(int) $this->id.' AND (`id_'.bqSQL($range_table).'` IS NOT NULL OR `id_'.bqSQL($range_table).'` = 0) '; if (Shop::getContext() == Shop::CONTEXT_ALL) { $where .= 'AND id_shop IS NULL AND id_shop_group IS NULL'; } elseif (Shop::getContext() == Shop::CONTEXT_GROUP) { $where .= 'AND id_shop IS NULL AND id_shop_group = '.(int) Shop::getContextShopGroupID(); } else { $where .= 'AND id_shop = '.(int) Shop::getContextShopID(); } return Db::getInstance()->delete('delivery', $where); } /** * Add new delivery prices. * * @param array $priceList Prices list in multiple arrays (changed to array since 1.5.0) * * @return bool Insertion result */ public function addDeliveryPrice($price_list, $delete = false) { if (!$price_list) { return false; } $keys = array_keys($price_list[0]); if (!in_array('id_shop', $keys)) { $keys[] = 'id_shop'; } if (!in_array('id_shop_group', $keys)) { $keys[] = 'id_shop_group'; } $sql = 'INSERT INTO `'._DB_PREFIX_.'delivery` ('.implode(', ', $keys).') VALUES '; foreach ($price_list as $values) { if (!isset($values['id_shop'])) { $values['id_shop'] = (Shop::getContext() == Shop::CONTEXT_SHOP) ? Shop::getContextShopID() : null; } if (!isset($values['id_shop_group'])) { $values['id_shop_group'] = (Shop::getContext() != Shop::CONTEXT_ALL) ? Shop::getContextShopGroupID() : null; } if ($delete) { Db::getInstance()->execute( 'DELETE FROM `'._DB_PREFIX_.'delivery` WHERE '.(is_null($values['id_shop']) ? 'ISNULL(`id_shop`) ' : 'id_shop = '.(int) $values['id_shop']).' AND '.(is_null($values['id_shop_group']) ? 'ISNULL(`id_shop`) ' : 'id_shop_group='.(int) $values['id_shop_group']).' AND id_carrier='.(int) $values['id_carrier']. ($values['id_range_price'] !== null ? ' AND id_range_price='.(int) $values['id_range_price'] : ' AND (ISNULL(`id_range_price`) OR `id_range_price` = 0)'). ($values['id_range_weight'] !== null ? ' AND id_range_weight='.(int) $values['id_range_weight'] : ' AND (ISNULL(`id_range_weight`) OR `id_range_weight` = 0)').' AND id_zone='.(int) $values['id_zone'] ); } $sql .= '('; foreach ($values as $v) { if (is_null($v)) { $sql .= 'NULL'; } elseif (is_int($v) || is_float($v)) { $sql .= $v; } else { $sql .= '\''.Db::getInstance()->escape($v, false, true).'\''; } $sql .= ', '; } $sql = rtrim($sql, ', ').'), '; } $sql = rtrim($sql, ', '); return Db::getInstance()->execute($sql); } /** * Copy old carrier informations when update carrier. * * @param int $oldId Old id carrier (copy from that id) */ public function copyCarrierData($old_id) { if (!Validate::isUnsignedId($old_id)) { throw new PrestaShopException('Incorrect identifier for carrier'); } if (!$this->id) { return false; } $old_logo = _PS_SHIP_IMG_DIR_.'/'.(int) $old_id.'.jpg'; if (file_exists($old_logo)) { copy($old_logo, _PS_SHIP_IMG_DIR_.'/'.(int) $this->id.'.jpg'); } $old_tmp_logo = _PS_TMP_IMG_DIR_.'/carrier_mini_'.(int) $old_id.'.jpg'; if (file_exists($old_tmp_logo)) { if (!isset($_FILES['logo'])) { copy($old_tmp_logo, _PS_TMP_IMG_DIR_.'/carrier_mini_'.$this->id.'.jpg'); } unlink($old_tmp_logo); } // Copy existing ranges price foreach (array('range_price', 'range_weight') as $range) { $res = Db::getInstance()->executeS(' SELECT `id_'.$range.'` as id_range, `delimiter1`, `delimiter2` FROM `'._DB_PREFIX_.$range.'` WHERE `id_carrier` = '.(int) $old_id); if (count($res)) { foreach ($res as $val) { Db::getInstance()->execute(' INSERT INTO `'._DB_PREFIX_.$range.'` (`id_carrier`, `delimiter1`, `delimiter2`) VALUES ('.(int) $this->id.','.(float) $val['delimiter1'].','.(float) $val['delimiter2'].')'); $range_id = (int) Db::getInstance()->Insert_ID(); $range_price_id = ($range == 'range_price') ? $range_id : 'NULL'; $range_weight_id = ($range == 'range_weight') ? $range_id : 'NULL'; Db::getInstance()->execute(' INSERT INTO `'._DB_PREFIX_.'delivery` (`id_carrier`, `id_shop`, `id_shop_group`, `id_range_price`, `id_range_weight`, `id_zone`, `price`) ( SELECT '.(int) $this->id.', `id_shop`, `id_shop_group`, '.(int) $range_price_id.', '.(int) $range_weight_id.', `id_zone`, `price` FROM `'._DB_PREFIX_.'delivery` WHERE `id_carrier` = '.(int) $old_id.' AND `id_'.$range.'` = '.(int) $val['id_range'].' ) '); } } } // Copy existing zones $res = Db::getInstance()->executeS(' SELECT * FROM `'._DB_PREFIX_.'carrier_zone` WHERE id_carrier = '.(int) $old_id); foreach ($res as $val) { Db::getInstance()->execute(' INSERT INTO `'._DB_PREFIX_.'carrier_zone` (`id_carrier`, `id_zone`) VALUES ('.(int) $this->id.','.(int) $val['id_zone'].') '); } //Copy default carrier if (Configuration::get('PS_CARRIER_DEFAULT') == $old_id) { Configuration::updateValue('PS_CARRIER_DEFAULT', (int) $this->id); } // Copy reference $id_reference = Db::getInstance()->getValue(' SELECT `id_reference` FROM `'._DB_PREFIX_.$this->def['table'].'` WHERE id_carrier = '.(int) $old_id); Db::getInstance()->execute(' UPDATE `'._DB_PREFIX_.$this->def['table'].'` SET `id_reference` = '.(int) $id_reference.' WHERE `id_carrier` = '.(int) $this->id); $this->id_reference = (int) $id_reference; // Copy tax rules group Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'carrier_tax_rules_group_shop` (`id_carrier`, `id_tax_rules_group`, `id_shop`) (SELECT '.(int) $this->id.', `id_tax_rules_group`, `id_shop` FROM `'._DB_PREFIX_.'carrier_tax_rules_group_shop` WHERE `id_carrier`='.(int) $old_id.')'); } /** * Get carrier using the reference id. */ public static function getCarrierByReference($id_reference, $id_lang = null) { // @todo class var $table must became static. here I have to use 'carrier' because this method is static $id_carrier = Db::getInstance()->getValue('SELECT `id_carrier` FROM `'._DB_PREFIX_.'carrier` WHERE id_reference = '.(int) $id_reference.' AND deleted = 0 ORDER BY id_carrier DESC'); if (!$id_carrier) { return false; } return new Carrier($id_carrier, $id_lang); } /** * Check if Carrier is used (at least one order placed). * * @return int Order count for this carrier */ public function isUsed() { $row = Db::getInstance()->getRow(' SELECT COUNT(`id_carrier`) AS total FROM `'._DB_PREFIX_.'orders` WHERE `id_carrier` = '.(int) $this->id); return (int) $row['total']; } /** * Get shipping method of the carrier (free, weight or price). * * @return int Shipping method enumerator */ public function getShippingMethod() { if ($this->is_free) { return Carrier::SHIPPING_METHOD_FREE; } $method = (int) $this->shipping_method; if ($this->shipping_method == Carrier::SHIPPING_METHOD_DEFAULT) { // backward compatibility if ((int) Configuration::get('PS_SHIPPING_METHOD')) { $method = Carrier::SHIPPING_METHOD_WEIGHT; } else { $method = Carrier::SHIPPING_METHOD_PRICE; } } return $method; } /** * Get range table of carrier. * * @return bool|string Range table, false if not found */ public function getRangeTable() { $shipping_method = $this->getShippingMethod(); if ($shipping_method == Carrier::SHIPPING_METHOD_WEIGHT) { return 'range_weight'; } elseif ($shipping_method == Carrier::SHIPPING_METHOD_PRICE) { return 'range_price'; } return false; } /** * Get Range object, price or weight, depending on the shipping method given. * * @param int|bool $shipping_method Shipping method enumerator * Use false in order to let this method find the correct one * * @return bool|RangePrice|RangeWeight */ public function getRangeObject($shipping_method = false) { if (!$shipping_method) { $shipping_method = $this->getShippingMethod(); } if ($shipping_method == Carrier::SHIPPING_METHOD_WEIGHT) { return new RangeWeight(); } elseif ($shipping_method == Carrier::SHIPPING_METHOD_PRICE) { return new RangePrice(); } return false; } /** * Get range suffix. * * @param Currency|null $currency Currency * * @return string Currency sign in suffix to use for the range */ public function getRangeSuffix($currency = null) { if (!$currency) { $currency = Context::getContext()->currency; } $suffix = Configuration::get('PS_WEIGHT_UNIT'); if ($this->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE) { $suffix = $currency->sign; } return $suffix; } /** * Get TaxRulesGroup ID for this Carrier. * * @param Context|null $context Context * * @return false|null|string TaxrulesGroup ID * false if not found */ public function getIdTaxRulesGroup(Context $context = null) { return Carrier::getIdTaxRulesGroupByIdCarrier((int) $this->id, $context); } /** * Get TaxRulesGroup ID for a given Carrier. * * @param int $id_carrier Carrier ID * @param Context|null $context Context * * @return false|null|string TaxRulesGroup ID * false if not found */ public static function getIdTaxRulesGroupByIdCarrier($id_carrier, Context $context = null) { if (!$context) { $context = Context::getContext(); } $key = 'carrier_id_tax_rules_group_'.(int) $id_carrier.'_'.(int) $context->shop->id; if (!Cache::isStored($key)) { $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue(' SELECT `id_tax_rules_group` FROM `'._DB_PREFIX_.'carrier_tax_rules_group_shop` WHERE `id_carrier` = '.(int) $id_carrier.' AND id_shop='.(int) Context::getContext()->shop->id); Cache::store($key, $result); return $result; } return Cache::retrieve($key); } /** * Set TaxRulesGroup. * * @param int $id_tax_rules_group Set the TaxRulesGroup with the given ID * as this Carrier's TaxRulesGroup * @param bool $all_shops True if this should be done for all shops * * @return bool Whether the TaxRulesGroup has been succesfully set * for this Carrier in this Shop or all given Shops */ public function setTaxRulesGroup($id_tax_rules_group, $all_shops = false) { if (!Validate::isUnsignedId($id_tax_rules_group)) { die(Tools::displayError()); } if (!$all_shops) { $shops = Shop::getContextListShopID(); } else { $shops = Shop::getShops(true, null, true); } $this->deleteTaxRulesGroup($shops); $values = array(); foreach ($shops as $id_shop) { $values[] = array( 'id_carrier' => (int) $this->id, 'id_tax_rules_group' => (int) $id_tax_rules_group, 'id_shop' => (int) $id_shop, ); } Cache::clean('carrier_id_tax_rules_group_'.(int) $this->id.'_'.(int) Context::getContext()->shop->id); return Db::getInstance()->insert('carrier_tax_rules_group_shop', $values); } /** * Delete TaxRulesGroup from this Carrier. * * @param array|null $shops Shops * * @return bool Whether the TaxRulesGroup has been successfully removed from this Carrier */ public function deleteTaxRulesGroup(array $shops = null) { if (!$shops) { $shops = Shop::getContextListShopID(); } $where = 'id_carrier = '.(int) $this->id; if ($shops) { $where .= ' AND id_shop IN('.implode(', ', array_map('intval', $shops)).')'; } return Db::getInstance()->delete('carrier_tax_rules_group_shop', $where); } /** * Returns the Tax rates associated to the Carrier. * * @since 1.5 * * @param Address $address Address * * @return float Total Tax rate for this Carrier */ public function getTaxesRate(Address $address) { $tax_calculator = $this->getTaxCalculator($address); return $tax_calculator->getTotalRate(); } /** * Returns the taxes calculator associated to the carrier. * * @since 1.5 * * @param Address $address Address * * @return TaxCalculator Tax calculator object */ public function getTaxCalculator(Address $address, $id_order = null, $use_average_tax_of_products = false) { if ($use_average_tax_of_products) { return \PrestaShop\PrestaShop\Adapter\ServiceLocator::get('AverageTaxOfProductsTaxCalculator')->setIdOrder($id_order); } else { $tax_manager = TaxManagerFactory::getManager($address, $this->getIdTaxRulesGroup()); return $tax_manager->getTaxCalculator(); } } /** * This tricky method generates a SQL clause to check if ranged data are overloaded by multishop. * * @since 1.5.0 * * @param string $range_table Range table * * @return string SQL quoer to get the delivery range table in this Shop(Group) */ public static function sqlDeliveryRangeShop($range_table, $alias = 'd') { if (Shop::getContext() == Shop::CONTEXT_ALL) { $where = 'AND d2.id_shop IS NULL AND d2.id_shop_group IS NULL'; } elseif (Shop::getContext() == Shop::CONTEXT_GROUP) { $where = 'AND ((d2.id_shop_group IS NULL OR d2.id_shop_group = '.Shop::getContextShopGroupID().') AND d2.id_shop IS NULL)'; } else { $where = 'AND (d2.id_shop = '.Shop::getContextShopID().' OR (d2.id_shop_group = '.Shop::getContextShopGroupID().' AND d2.id_shop IS NULL) OR (d2.id_shop_group IS NULL AND d2.id_shop IS NULL))'; } $sql = 'AND '.$alias.'.id_delivery = ( SELECT d2.id_delivery FROM '._DB_PREFIX_.'delivery d2 WHERE d2.id_carrier = `'.bqSQL($alias).'`.id_carrier AND d2.id_zone = `'.bqSQL($alias).'`.id_zone AND d2.`id_'.bqSQL($range_table).'` = `'.bqSQL($alias).'`.`id_'.bqSQL($range_table).'` '.$where.' ORDER BY d2.id_shop DESC, d2.id_shop_group DESC LIMIT 1 )'; return $sql; } /** * Moves a carrier. * * @since 1.5.0 * * @param bool $way Up (1) or Down (0) * @param int $position Current position of the Carrier * * @return bool Whether the update was successful */ public function updatePosition($way, $position) { if (!$res = Db::getInstance()->executeS( 'SELECT `id_carrier`, `position` FROM `'._DB_PREFIX_.'carrier` WHERE `deleted` = 0 ORDER BY `position` ASC' )) { return false; } foreach ($res as $carrier) { if ((int) $carrier['id_carrier'] == (int) $this->id) { $moved_carrier = $carrier; } } if (!isset($moved_carrier) || !isset($position)) { return false; } // < and > statements rather than BETWEEN operator // since BETWEEN is treated differently according to databases return Db::getInstance()->execute(' UPDATE `'._DB_PREFIX_.'carrier` SET `position`= `position` '.($way ? '- 1' : '+ 1').' WHERE `position` '.($way ? '> '.(int) $moved_carrier['position'].' AND `position` <= '.(int) $position : '< '.(int) $moved_carrier['position'].' AND `position` >= '.(int) $position.' AND `deleted` = 0')) && Db::getInstance()->execute(' UPDATE `'._DB_PREFIX_.'carrier` SET `position` = '.(int) $position.' WHERE `id_carrier` = '.(int) $moved_carrier['id_carrier']); } /** * Reorder Carrier positions * Called after deleting a Carrier. * * @since 1.5.0 * * @return bool $return */ public static function cleanPositions() { $return = true; $sql = ' SELECT `id_carrier` FROM `'._DB_PREFIX_.'carrier` WHERE `deleted` = 0 ORDER BY `position` ASC'; $result = Db::getInstance()->executeS($sql); $i = 0; foreach ($result as $value) { $return = Db::getInstance()->execute(' UPDATE `'._DB_PREFIX_.'carrier` SET `position` = '.(int) $i++.' WHERE `id_carrier` = '.(int) $value['id_carrier']); } return $return; } /** * Gets the highest carrier position. * * @since 1.5.0 * * @return int $position */ public static function getHigherPosition() { $sql = 'SELECT MAX(`position`) FROM `'._DB_PREFIX_.'carrier` WHERE `deleted` = 0'; $position = DB::getInstance()->getValue($sql); return (is_numeric($position)) ? $position : -1; } /** * For a given {product, warehouse}, gets the carrier available. * * @since 1.5.0 * * @param Product $product The id of the product, or an array with at least the package size and weight * @param int $id_warehouse Warehouse ID * @param int $id_address_delivery Delivery Address ID * @param int $id_shop Shop ID * @param Cart $cart Cart object * @param array &$error contain an error message if an error occurs * * @return array Available Carriers * * @throws PrestaShopDatabaseException */ public static function getAvailableCarrierList(Product $product, $id_warehouse, $id_address_delivery = null, $id_shop = null, $cart = null, &$error = array()) { static $ps_country_default = null; if ($ps_country_default === null) { $ps_country_default = Configuration::get('PS_COUNTRY_DEFAULT'); } if (is_null($id_shop)) { $id_shop = Context::getContext()->shop->id; } if (is_null($cart)) { $cart = Context::getContext()->cart; } if (is_null($error) || !is_array($error)) { $error = array(); } $id_address = (int) ((!is_null($id_address_delivery) && $id_address_delivery != 0) ? $id_address_delivery : $cart->id_address_delivery); if ($id_address) { $id_zone = Address::getZoneById($id_address); // Check the country of the address is activated if (!Address::isCountryActiveById($id_address)) { return array(); } } else { $country = new Country($ps_country_default); $id_zone = $country->id_zone; } // Does the product is linked with carriers? $cache_id = 'Carrier::getAvailableCarrierList_'.(int) $product->id.'-'.(int) $id_shop; if (!Cache::isStored($cache_id)) { $query = new DbQuery(); $query->select('id_carrier'); $query->from('product_carrier', 'pc'); $query->innerJoin( 'carrier', 'c', 'c.id_reference = pc.id_carrier_reference AND c.deleted = 0 AND c.active = 1' ); $query->where('pc.id_product = '.(int) $product->id); $query->where('pc.id_shop = '.(int) $id_shop); $carriers_for_product = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query); Cache::store($cache_id, $carriers_for_product); } else { $carriers_for_product = Cache::retrieve($cache_id); } $carrier_list = array(); if (!empty($carriers_for_product)) { //the product is linked with carriers foreach ($carriers_for_product as $carrier) { //check if the linked carriers are available in current zone if (Carrier::checkCarrierZone($carrier['id_carrier'], $id_zone)) { $carrier_list[$carrier['id_carrier']] = $carrier['id_carrier']; } } if (empty($carrier_list)) { return array(); }//no linked carrier are available for this zone } // The product is not directly linked with a carrier // Get all the carriers linked to a warehouse if ($id_warehouse) { $warehouse = new Warehouse($id_warehouse); $warehouse_carrier_list = $warehouse->getCarriers(); } $available_carrier_list = array(); $cache_id = 'Carrier::getAvailableCarrierList_getCarriersForOrder_'.(int) $id_zone.'-'.(int) $cart->id; if (!Cache::isStored($cache_id)) { $customer = new Customer($cart->id_customer); $carrier_error = array(); $carriers = Carrier::getCarriersForOrder($id_zone, $customer->getGroups(), $cart, $carrier_error); Cache::store($cache_id, array($carriers, $carrier_error)); } else { list($carriers, $carrier_error) = Cache::retrieve($cache_id); } $error = array_merge($error, $carrier_error); foreach ($carriers as $carrier) { $available_carrier_list[$carrier['id_carrier']] = $carrier['id_carrier']; } if ($carrier_list) { $carrier_list = array_intersect($available_carrier_list, $carrier_list); } else { $carrier_list = $available_carrier_list; } if (isset($warehouse_carrier_list)) { $carrier_list = array_intersect($carrier_list, $warehouse_carrier_list); } $cart_quantity = 0; $cart_weight = 0; foreach ($cart->getProducts(false, false) as $cart_product) { if ($cart_product['id_product'] == $product->id) { $cart_quantity += $cart_product['cart_quantity']; } if (isset($cart_product['weight_attribute']) && $cart_product['weight_attribute'] > 0) { $cart_weight += ($cart_product['weight_attribute'] * $cart_product['cart_quantity']); } else { $cart_weight += ($cart_product['weight'] * $cart_product['cart_quantity']); } } if ($product->width > 0 || $product->height > 0 || $product->depth > 0 || $product->weight > 0 || $cart_weight > 0) { foreach ($carrier_list as $key => $id_carrier) { $carrier = new Carrier($id_carrier); // Get the sizes of the carrier and the product and sort them to check if the carrier can take the product. $carrier_sizes = array((int) $carrier->max_width, (int) $carrier->max_height, (int) $carrier->max_depth); $product_sizes = array((int) $product->width, (int) $product->height, (int) $product->depth); rsort($carrier_sizes, SORT_NUMERIC); rsort($product_sizes, SORT_NUMERIC); if (($carrier_sizes[0] > 0 && $carrier_sizes[0] < $product_sizes[0]) || ($carrier_sizes[1] > 0 && $carrier_sizes[1] < $product_sizes[1]) || ($carrier_sizes[2] > 0 && $carrier_sizes[2] < $product_sizes[2])) { $error[$carrier->id] = Carrier::SHIPPING_SIZE_EXCEPTION; unset($carrier_list[$key]); } if ($carrier->max_weight > 0 && ($carrier->max_weight < $product->weight * $cart_quantity || $carrier->max_weight < $cart_weight)) { $error[$carrier->id] = Carrier::SHIPPING_WEIGHT_EXCEPTION; unset($carrier_list[$key]); } } } return $carrier_list; } /** * Assign one (ore more) group to all carriers. * * @since 1.5.0 * * @param int|array $id_group_list Group ID or array of Group IDs * @param array $exception List of Carrier IDs to ignore * * @return bool */ public static function assignGroupToAllCarriers($id_group_list, $exception = array()) { if (!is_array($id_group_list)) { $id_group_list = array($id_group_list); } $id_group_list = array_map('intval', $id_group_list); $exception = array_map('intval', $exception); Db::getInstance()->execute(' DELETE FROM `'._DB_PREFIX_.'carrier_group` WHERE `id_group` IN ('.implode(',', $id_group_list).')'); $carrier_list = Db::getInstance()->executeS(' SELECT id_carrier FROM `'._DB_PREFIX_.'carrier` WHERE deleted = 0 '.(is_array($exception) && count($exception) > 0 ? 'AND id_carrier NOT IN ('.implode(',', $exception).')' : '')); if ($carrier_list) { $data = array(); foreach ($carrier_list as $carrier) { foreach ($id_group_list as $id_group) { $data[] = array( 'id_carrier' => $carrier['id_carrier'], 'id_group' => $id_group, ); } } return Db::getInstance()->insert('carrier_group', $data, false, false, Db::INSERT); } return true; } /** * Set Carrier Groups. * * @param array $groups Carrier Groups * @param bool $delete Delete all previously Carrier Groups which * were linked to this Carrier * * @return bool Whether the Carrier Groups have been successfully set */ public function setGroups($groups, $delete = true) { if ($delete) { Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.'carrier_group WHERE id_carrier = '.(int) $this->id); } if (!is_array($groups) || !count($groups)) { return true; } $sql = 'INSERT INTO '._DB_PREFIX_.'carrier_group (id_carrier, id_group) VALUES '; foreach ($groups as $id_group) { $sql .= '('.(int) $this->id.', '.(int) $id_group.'),'; } return Db::getInstance()->execute(rtrim($sql, ',')); } /** * Return the carrier name from the shop name (e.g. if the carrier name is '0'). * * The returned carrier name is the shop name without '#' and ';' because this is not the same validation. * * @return string Carrier name */ public static function getCarrierNameFromShopName() { return str_replace( array('#', ';'), '', Configuration::get('PS_SHOP_NAME') ); } }
gpl-3.0
lyy289065406/expcodes
java/01-framework/dubbo-admin/incubator-dubbo-ops/dubbo-admin-frontend/node/node_modules/npm/node_modules/fs-vacuum/test/racy-entries-eexist.js
3757
var path = require('path') var test = require('tap').test var readdir = require('graceful-fs').readdir var readdirSync = require('graceful-fs').readdirSync var rmdir = require('graceful-fs').rmdir var statSync = require('graceful-fs').statSync var writeFile = require('graceful-fs').writeFile var mkdirp = require('mkdirp') var mkdtemp = require('tmp').dir var tmpFile = require('tmp').file var EEXIST = require('errno').code.EEXIST var ENOTEMPTY = require('errno').code.ENOTEMPTY var requireInject = require('require-inject') var vacuum = requireInject('../vacuum.js', { 'graceful-fs': { 'lstat': require('graceful-fs').lstat, 'readdir': function (dir, cb) { readdir(dir, function (err, files) { // Simulate racy removal by creating a file after vacuum // thinks the directory is empty if (dir === partialPath && files.length === 0) { tmpFile({dir: dir}, function (err, path, fd) { if (err) throw err cb(err, files) }) } else { cb(err, files) } }) }, 'rmdir': function (dir, cb) { rmdir(dir, function (err) { // Force EEXIST error from rmdir if the directory is non-empty var mockErr = EEXIST if (err) { if (err.code === ENOTEMPTY.code) { err.code = err.errno = mockErr.code err.message = mockErr.code + ': ' + mockErr.description + ', ' + err.syscall + ' \'' + dir + '\'' } } cb(err) }) }, 'unlink': require('graceful-fs').unlink } }) // CONSTANTS var TEMP_OPTIONS = { unsafeCleanup: true, mode: '0700' } var SHORT_PATH = path.join('i', 'am', 'a', 'path') var PARTIAL_PATH = path.join(SHORT_PATH, 'that', 'ends', 'at', 'a') var FULL_PATH = path.join(PARTIAL_PATH, 'file') var messages = [] function log () { messages.push(Array.prototype.slice.call(arguments).join(' ')) } var testBase, partialPath, fullPath test('xXx setup xXx', function (t) { mkdtemp(TEMP_OPTIONS, function (er, tmpdir) { t.ifError(er, 'temp directory exists') testBase = path.resolve(tmpdir, SHORT_PATH) partialPath = path.resolve(tmpdir, PARTIAL_PATH) fullPath = path.resolve(tmpdir, FULL_PATH) mkdirp(partialPath, function (er) { t.ifError(er, 'made test path') writeFile(fullPath, new Buffer('hi'), function (er) { t.ifError(er, 'made file') t.end() }) }) }) }) test('racy removal should quit gracefully', function (t) { vacuum(fullPath, {purge: false, base: testBase, log: log}, function (er) { t.ifError(er, 'cleaned up to base') t.equal(messages.length, 3, 'got 2 removal & 1 quit message') t.equal(messages[2], 'quitting because new (racy) entries in ' + partialPath) var stat var verifyPath = fullPath function verify () { stat = statSync(verifyPath) } // handle the file separately t.throws(verify, verifyPath + ' cannot be statted') t.notOk(stat && stat.isFile(), verifyPath + ' is totally gone') verifyPath = path.dirname(verifyPath) for (var i = 0; i < 4; i++) { t.doesNotThrow(function () { stat = statSync(verifyPath) }, verifyPath + ' can be statted') t.ok(stat && stat.isDirectory(), verifyPath + ' is still a directory') verifyPath = path.dirname(verifyPath) } t.doesNotThrow(function () { stat = statSync(testBase) }, testBase + ' can be statted') t.ok(stat && stat.isDirectory(), testBase + ' is still a directory') var files = readdirSync(testBase) t.equal(files.length, 1, 'base directory untouched') t.end() }) })
gpl-3.0
mapsquare/osm-contributor
src/main/java/io/jawg/osmcontributor/ui/dialogs/AddPoiBusLineDialogFragment.java
6684
/** * Copyright (C) 2019 Takima * <p> * This file is part of OSM Contributor. * <p> * OSM Contributor is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * <p> * OSM Contributor 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. * <p> * You should have received a copy of the GNU General Public License * along with OSM Contributor. If not, see <http://www.gnu.org/licenses/>. */ package io.jawg.osmcontributor.ui.dialogs; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.widget.AutoCompleteTextView; import io.jawg.osmcontributor.utils.edition.RelationDisplayDto; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnTextChanged; import io.jawg.osmcontributor.OsmTemplateApplication; import io.jawg.osmcontributor.R; import io.jawg.osmcontributor.model.entities.relation_display.RelationDisplay; import io.jawg.osmcontributor.model.events.BusLinesSuggestionForPoiLoadedEvent; import io.jawg.osmcontributor.ui.adapters.BusLineSuggestionAdapter; import io.jawg.osmcontributor.ui.adapters.PoiBusLineAddingAdapter; import io.jawg.osmcontributor.ui.adapters.parser.BusLineRelationDisplayParser; import io.jawg.osmcontributor.ui.events.type.PleaseLoadBusLinesSuggestionForPoiEvent; import io.jawg.osmcontributor.ui.managers.RelationManager; import io.jawg.osmcontributor.ui.utils.views.DividerItemDecoration; import io.jawg.osmcontributor.utils.edition.RelationDisplayUtils; public class AddPoiBusLineDialogFragment extends DialogFragment { @Inject EventBus eventBus; @Inject RelationManager relationManager; @Inject BusLineRelationDisplayParser busLineParser; @BindView(R.id.add_bus_line_poi_list_view) RecyclerView recyclerView; @BindView(R.id.bus_line_input_edit_text) AutoCompleteTextView searchBusLineTextView; @BindView(R.id.clear_suggestion_button) View clearButton; @OnTextChanged(R.id.bus_line_input_edit_text) protected void onSearchBusLineChanged(CharSequence constraint, int start, int before, int count) { String search = constraint.toString().trim(); if (!TextUtils.isEmpty(search)) { eventBus.post(new PleaseLoadBusLinesSuggestionForPoiEvent(search)); } } private static final String TAG_REF = "ref"; private List<RelationDisplay> currentBusLines; private List<RelationDisplay> busLinesNearby; private List<RelationDisplay> suggestionList; private AddBusLineListener addBusLineListener; private BusLineSuggestionAdapter suggestionAdapter; public interface AddBusLineListener { void onBusLineClick(RelationDisplay busLine); } public void setAddBusLineListener(AddBusLineListener addBusLineListener) { this.addBusLineListener = addBusLineListener; } public static AddPoiBusLineDialogFragment newInstance(List<RelationDisplay> currentBusLines, List<RelationDisplay> busLinesNearby) { AddPoiBusLineDialogFragment dialog = new AddPoiBusLineDialogFragment(); dialog.init(currentBusLines, busLinesNearby); return dialog; } private void init(List<RelationDisplay> currentBusLines, List<RelationDisplay> busLinesNearby) { this.currentBusLines = currentBusLines; this.busLinesNearby = busLinesNearby; this.suggestionList = new ArrayList<>(); } private void addBusLine(RelationDisplay busLine) { addBusLineListener.onBusLineClick(busLine); dismiss(); } @Override public void onAttach(Context context) { super.onAttach(context); EventBus.getDefault().register(this); } @Override public void onDetach() { super.onDetach(); EventBus.getDefault().unregister(this); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { View rootView = LayoutInflater.from(getActivity().getBaseContext()) .inflate(R.layout.dialog_add_bus_line_poi, null); ButterKnife.bind(this, rootView); ((OsmTemplateApplication) getActivity().getApplication()).getOsmTemplateComponent().inject(this); AlertDialog alertDialog = new AlertDialog.Builder(getActivity(), getTheme()) .setNegativeButton(R.string.cancel, (dialog, which) -> dismiss()) .create(); alertDialog.setView(rootView); alertDialog.setTitle(R.string.adding_poi_bus_line_title); clearButton.setOnClickListener(view -> searchBusLineTextView.setText("")); suggestionAdapter = new BusLineSuggestionAdapter(getActivity().getBaseContext(), busLineParser); searchBusLineTextView.setAdapter(suggestionAdapter); searchBusLineTextView.setOnItemClickListener((parent, view, position, id) -> addBusLine(suggestionAdapter.getItem(position))); PoiBusLineAddingAdapter adapter = new PoiBusLineAddingAdapter(getActivity().getBaseContext(), busLinesNearby, busLineParser); adapter.setAddBusLineListener((position, busLine) -> addBusLine(busLine)); recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity())); recyclerView.setAdapter(adapter); recyclerView.addItemDecoration(new DividerItemDecoration(recyclerView.getContext(), R.drawable.bus_line_divider)); return alertDialog; } @Subscribe(threadMode = ThreadMode.MAIN) public void onBusLinesSuggestionForPoiLoadedEvent(BusLinesSuggestionForPoiLoadedEvent event) { suggestionList.clear(); for (RelationDisplay relationDisplay : event.getRelationDisplays()) { if (!RelationDisplayUtils.isBusLineAlreadyStored(currentBusLines, relationDisplay, TAG_REF)) { suggestionList.add(relationDisplay); } } suggestionAdapter.setItems(suggestionList); } }
gpl-3.0
soulshake/hangupsbot
hangupsbot/commands/jokes.py
1650
import asyncio, random from hangupsbot.utils import strip_quotes, text_to_segments from hangupsbot.commands import command @asyncio.coroutine def easteregg_combo(client, conv_id, easteregg, eggcount=1, period=0.5): """Send easter egg combo (ponies, pitchforks, bikeshed, shydino)""" for i in range(eggcount): yield from client.sendeasteregg(conv_id, easteregg) if eggcount > 1: yield from asyncio.sleep(period + random.uniform(-0.1, 0.1)) @command.register(admin=True) def easteregg(bot, event, easteregg, eggcount=1, period=0.5, conv_name='', *args): """Annoy people with easter egg combo in current (or specified) conversation! Usage: /bot easteregg easter_egg_type [count] [period] [conv_name] Supported easter eggs: ponies, pitchforks, bikeshed, shydino""" conv_name = strip_quotes(conv_name) convs = [event.conv] if not conv_name or conv_name == '.' else bot.find_conversations(conv_name) for c in convs: asyncio.async( easteregg_combo(bot._client, c.id_, easteregg, int(eggcount), float(period)) ).add_done_callback(lambda future: future.result()) @command.register def spoof(bot, event, *args): """Spoof IngressBot on specified GPS coordinates Usage: /bot spoof latitude,longitude [hack|fire|deploy|mod] [level] [count]""" link = 'https://plus.google.com/u/0/{}/about'.format(event.user.id_.chat_id) text = _( '**!!! WARNING !!!**\n' 'Agent {} ({}) has been reported to Niantic for attempted spoofing!' ).format(event.user.full_name, link) yield from event.conv.send_message(text_to_segments(text))
gpl-3.0
Zheng-Yejian/xyplayer-package
xyplayer_unpacked/usr/lib/python3/dist-packages/mutagenx/oggspeex.py
4133
# -*- coding: utf-8 -*- # Copyright 2006 Joe Wreschnig # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. """Read and write Ogg Speex comments. This module handles Speex files wrapped in an Ogg bitstream. The first Speex stream found is used. Read more about Ogg Speex at http://www.speex.org/. This module is based on the specification at http://www.speex.org/manual2/node7.html and clarifications after personal communication with Jean-Marc, http://lists.xiph.org/pipermail/speex-dev/2006-July/004676.html. """ __all__ = ["OggSpeex", "Open", "delete"] from mutagenx import StreamInfo from mutagenx._vorbis import VCommentDict from mutagenx.ogg import OggPage, OggFileType, error as OggError from mutagenx._util import cdata class error(OggError): pass class OggSpeexHeaderError(error): pass class OggSpeexInfo(StreamInfo): """Ogg Speex stream information. Attributes: * bitrate - nominal bitrate in bits per second * channels - number of channels * length - file length in seconds, as a float The reference encoder does not set the bitrate; in this case, the bitrate will be 0. """ length = 0 def __init__(self, fileobj): page = OggPage(fileobj) while not page.packets[0].startswith(b"Speex "): page = OggPage(fileobj) if not page.first: raise OggSpeexHeaderError( "page has ID header, but doesn't start a stream") self.sample_rate = cdata.uint_le(page.packets[0][36:40]) self.channels = cdata.uint_le(page.packets[0][48:52]) self.bitrate = max(0, cdata.int_le(page.packets[0][52:56])) self.serial = page.serial def _post_tags(self, fileobj): page = OggPage.find_last(fileobj, self.serial) self.length = page.position / float(self.sample_rate) def pprint(self): return u"Ogg Speex, %.2f seconds" % self.length class OggSpeexVComment(VCommentDict): """Speex comments embedded in an Ogg bitstream.""" def __init__(self, fileobj, info): pages = [] complete = False while not complete: page = OggPage(fileobj) if page.serial == info.serial: pages.append(page) complete = page.complete or (len(page.packets) > 1) data = OggPage.to_packets(pages)[0] + b"\x01" super(OggSpeexVComment, self).__init__(data, framing=False) def _inject(self, fileobj): """Write tag data into the Speex comment packet/page.""" fileobj.seek(0) # Find the first header page, with the stream info. # Use it to get the serial number. page = OggPage(fileobj) while not page.packets[0].startswith(b"Speex "): page = OggPage(fileobj) # Look for the next page with that serial number, it'll start # the comment packet. serial = page.serial page = OggPage(fileobj) while page.serial != serial: page = OggPage(fileobj) # Then find all the pages with the comment packet. old_pages = [page] while not (old_pages[-1].complete or len(old_pages[-1].packets) > 1): page = OggPage(fileobj) if page.serial == old_pages[0].serial: old_pages.append(page) packets = OggPage.to_packets(old_pages, strict=False) # Set the new comment packet. packets[0] = self.write(framing=False) new_pages = OggPage.from_packets(packets, old_pages[0].sequence) OggPage.replace(fileobj, old_pages, new_pages) class OggSpeex(OggFileType): """An Ogg Speex file.""" _Info = OggSpeexInfo _Tags = OggSpeexVComment _Error = OggSpeexHeaderError _mimes = ["audio/x-speex"] @staticmethod def score(filename, fileobj, header): return (header.startswith(b"OggS") * (b"Speex " in header)) Open = OggSpeex def delete(filename): """Remove tags from a file.""" OggSpeex(filename).delete()
gpl-3.0
msigley/shopp
api/theme/cartitem.php
36118
<?php /** * cartitem.php * * ShoppCartItemThemeAPI provides shopp('cartitem') Theme API tags * * @api * @copyright Ingenesis Limited, 2012-2014 * @package Shopp\API\Theme\CartItem * @version 1.3 * @since 1.2 **/ defined( 'WPINC' ) || header( 'HTTP/1.1 403' ) & exit; // Prevent direct access add_filter('shopp_cartitem_input_data', 'wpautop'); /** * Provides support for the shopp('cartitem') tags * * @author Jonathan Davis, John Dillick * @since 1.2 * **/ class ShoppCartItemThemeAPI implements ShoppAPI { /** * @var array The registry of available `shopp('cart')` properties * @internal **/ static $register = array( '_cartitem', 'id' => 'id', 'product' => 'product', 'name' => 'name', 'type' => 'type', 'link' => 'url', 'url' => 'url', 'sku' => 'sku', 'description' => 'description', 'discount' => 'discount', 'unitprice' => 'unitprice', 'unittax' => 'unittax', 'discounts' => 'discounts', 'tax' => 'tax', 'total' => 'total', 'taxrate' => 'taxrate', 'quantity' => 'quantity', 'remove' => 'remove', 'onsale' => 'onsale', 'optionlabel' => 'option_label', 'options' => 'options', 'price' => 'price', 'prices' => 'prices', 'hasaddons' => 'has_addons', 'addons' => 'addons', 'addon' => 'addon', 'addonslist' => 'addons_list', 'hasinputs' => 'has_inputs', 'incategory' => 'in_category', 'inputs' => 'inputs', 'input' => 'input', 'inputslist' => 'inputs_list', 'coverimage' => 'coverimage', 'thumbnail' => 'coverimage', 'saleprice' => 'saleprice', 'saleprices' => 'saleprices', ); /** * Provides the API context name * * @internal * @return string The API context name **/ public static function _apicontext () { return 'cartitem'; } /** * _setobject - returns the global context object used in the shopp('cartitem) call * * @internal * @since 1.2 * * @return ShoppCartItem|bool The working ShoppCartItem context **/ public static function _setobject ( $Object, $context ) { if ( is_object($Object) && is_a($Object, 'Item') ) return $Object; if ( strtolower($context) != 'cartitem' ) return $Object; // not mine, do nothing else { $Cart = ShoppOrder()->Cart; $Item = false; if ( isset($Cart->_item_loop) ) { $Item = $Cart->current(); $Item->_id = $Cart->key(); return $Item; } elseif ( isset($Cart->_shipped_loop) ) { $Item = current($Cart->shipped); $Item->_id = key($Cart->shipped); return $Item; } elseif ( isset($Cart->_downloads_loop) ) { $Item = current($Cart->downloads); $Item->_id = key($Cart->downloads); return $Item; } return false; } } /** * Filter callback to add standard monetary option behaviors * * @internal * @since 1.2 * * @param string $result The output * @param array $options The options * - **money**: `on` (on, off) Format the amount in the current currency format * - **number**: `off` (on, off) Provide the unformatted number (floating point) * @param string $property The tag property name * @param ShoppCart $O The working object * @return ShoppCart The active ShoppCart context **/ public static function _cartitem ( $result, $options, $property, $O ) { // Passthru for non-monetary results $monetary = array('discount', 'unitprice', 'unittax', 'discounts', 'tax', 'total', 'price', 'prices', 'saleprice', 'saleprices'); if ( ! in_array($property, $monetary) || ! is_numeric($result) ) return $result; // @deprecated currency parameter if ( isset($options['currency']) ) $options['money'] = $options['currency']; $defaults = array( 'money' => 'on', 'number' => false, 'show' => '' ); $options = array_merge($defaults, $options); extract($options); if ( in_array($show, array('%', 'percent')) ) return $result; // Pass thru percentage rendering if ( Shopp::str_true($number) ) return $result; if ( Shopp::str_true($money) ) $result = money( roundprice($result) ); return $result; } /** * Provides the cart item ID (fingerprint) * * @api `shopp('cartitem.id')` * @since 1.0 * * @param string $result The output * @param array $options The options * @param ShoppCartItem $O The working object * @return string The item id (fingerprint) **/ public static function id ( $result, $options, $O ) { return $O->_id; } /** * Provides the product ID (or price record ID) * * @api * @since 1.0 * * @param string $result The output * @param array $options The options * - **priceline**: Requests the currently selected price record ID for the cart item * @param ShoppCartItem $O The working object * @return int The id for the product **/ public static function product ( $result, $options, $O ) { if ( isset($options['priceline']) && Shopp::str_true($options['priceline']) ) return $O->priceline; return $O->product; } /** * Provides the product name of the cart item * * @api `shopp('cartitem.name')` * @since 1.0 * * @param string $result The output * @param array $options The options * @param ShoppCartItem $O The working object * @return void **/ public static function name ( $result, $options, $O ) { return $O->name; } /** * The type of product for the cart item * * This is currently one of: shipped, download, virtual, donation, or recurring * * @api `shopp('cartitem.type')` * @since 1.0 * * @param string $result The output * @param array $options The options * @param ShoppCartItem $O The working object * @return string The product type for the cart item **/ public static function type ( $result, $options, $O ) { return $O->type; } /** * The URL of the product for the cart item * * @api `shopp('cartitem.url')` * @since 1.0 * * @param string $result The output * @param array $options The options * @param ShoppCartItem $O The working object * @return string The product URL **/ public static function url ( $result, $options, $O ) { return Shopp::url( '' == get_option('permalink_structure') ? array(ShoppProduct::$posttype => $O->slug ) : $O->slug, false ); } /** * Provides the product SKU (stock keeping unit) * * @api `shopp('cartitem.sku')` * @since 1.0 * * @param string $result The output * @param array $options The options * @param ShoppCartItem $O The working object * @return string The product SKU **/ public static function sku ( $result, $options, $O ) { return $O->sku; } /** * The product description of the cart item * * @api `shopp('cartitem.description')` * @since 1.0 * * @param string $result The output * @param array $options The options * @param ShoppCartItem $O The working object * @return string The product description **/ public static function description ( $result, $options, $O ) { return $O->description; } /** * Provides the per-unit discount amount currently applied to the cart item * * @api `shopp('cartitem.discount')` * @since 1.2 * * @param string $result The output * @param array $options The options * - **catalog**: Provide the catalog discount applied (catalog sale price discount amount, not the entire discount) * - **money**: `on` (on, off) Format the amount in the current currency format * - **number**: `off` (on, off) Provide the unformatted number (floating point) * - **show**: (%, percent) Provide the percent discount instead of the amount * @param ShoppCartItem $O The working object * @return void **/ public static function discount ( $result, $options, $O ) { $defaults = array( 'catalog' => false, 'show' => '' ); $options = array_merge($defaults, $options); extract($options, EXTR_SKIP); // Item unit discount $discount = $O->discount; if ( Shopp::str_true($catalog) ) $discount = $O->option->price - $O->option->promoprice; if ( in_array($show, array('%', 'percent')) ) return percentage( ( $discount / $O->option->price ) * 100, array('precision' => 0) ); return (float) $discount; } /** * Provides the total discounts applied to the cart item * * This is the unit discount * quantity * * @api `shopp('cartitem.discounts')` * @since 1.2 * * @param string $result The output * @param array $options The options * - **catalog**: Provide the catalog discount applied (catalog sale price discount amount, not the entire discount) * - **money**: `on` (on, off) Format the amount in the current currency format * - **number**: `off` (on, off) Provide the unformatted number (floating point) * - **show**: (%, percent) Provide the percent discount instead of the amount * @param ShoppCartItem $O The working object * @return void **/ public static function discounts ( $result, $options, $O ) { $defaults = array( 'catalog' => false, 'show' => '' ); $options = array_merge($defaults, $options); extract($options, EXTR_SKIP); // Unit discount * quantity $discounts = $O->discounts; if ( Shopp::str_true($catalog) ) $discounts = $O->quantity * self::discount('', array('catalog' => true, 'number' => true), $O); if ( in_array($show, array('%', 'percent')) ) return percentage( ( $discounts / self::prices('', array('number' => true), $O) ) * 100, array('precision' => 0) ); return (float) $discounts; } /** * The unit price of the cart item * * @api `shopp('cartitem.unitprice')` * @since 1.0 * * @param string $result The output * @param array $options The options * - **taxes**: `null` (on, off) On to include taxes in the unit price, off to exclude taxes * - **money**: `on` (on, off) Format the amount in the current currency format * - **number**: `off` (on, off) Provide the unformatted number (floating point) * @param ShoppCartItem $O The working object * @return void **/ public static function unitprice ( $result, $options, $O ) { $taxes = isset( $options['taxes'] ) ? Shopp::str_true( $options['taxes'] ) : null; $unitprice = (float) $O->unitprice; $unitprice = self::_taxes($unitprice, $O, $taxes); return (float) $unitprice; } /** * The unit tax amount applied to the cart item * * @api `shopp('cartitem.unit-tax')` * @since 1.2 * * @param string $result The output * @param array $options The options * - **money**: `on` (on, off) Format the amount in the current currency format * - **number**: `off` (on, off) Provide the unformatted number (floating point) * @param ShoppCartItem $O The working object * @return void **/ public static function unittax ( $result, $options, $O ) { return (float) $O->unittax; } /** * The total tax applied to the cart item * * @api `shopp('cartitem.tax')` * @since 1.0 * * @param string $result The output * @param array $options The options * - **money**: `on` (on, off) Format the amount in the current currency format * - **number**: `off` (on, off) Provide the unformatted number (floating point) * @param ShoppCartItem $O The working object * @return void **/ public static function tax ( $result, $options, $O ) { return (float) $O->tax; } /** * The total cost of the cart item * * @api `shopp('cartitem.total')` * @since 1.0 * * @param string $result The output * @param array $options The options * @param ShoppCartItem $O The working object * @return void **/ public static function total ( $result, $options, $O ) { $taxes = isset( $options['taxes'] ) ? Shopp::str_true( $options['taxes'] ) : null; $total = (float) $O->total; $total = self::_taxes($total, $O, $taxes, $O->quantity); return (float) $total; } /** * Provides the tax rate percentage * * @api `shopp('cartitem.taxrate')` * @since 1.0 * * @param string $result The output * @param array $options The options * @param ShoppCartItem $O The working object * @return string The tax rate percentage (10.1%) **/ public static function taxrate ( $result, $options, $O ) { if ( count($O->taxes) == 1 ) { $Tax = ShoppTax::appliedrate($O->taxes); return percentage( $Tax->rate * 100, array( 'precision' => 1 ) ); } $compounding = false; $rate = 0; foreach ( $O->taxes as $Tax ) { if ( is_null($Tax->amount) ) continue; $rate += $Tax->rate; if ( Shopp::str_true($Tax->compound) ) { $compounding = true; break; } } if ( $compounding ) $rate = $O->unittax / $O->unitprice; return percentage( $rate * 100, array( 'precision' => 1 ) ); } /** * Provides the quantity selector and current cart item quantity * * @api `shopp('cartitem.quantity')` * @since 1.0 * * @param string $result The output * @param array $options The options * - **input**: (menu, text, hidden) Sets the type of input element to render. Menu for a `<select>` menu, text for text box, hidden for a hidden input * - **options**: `1-15,20,25,30,35,40,45,50,60,70,80,90,100` Defines the default options when **input** is set to `menu`. Values are separated by commas. Ranges will automatically generate number options within the range. * - **autocomplete**: (on, off) Specifies whether an `<input>` element should have autocomplete enabled * - **accesskey**: Specifies a shortcut key to activate/focus an element. Linux/Windows: `[Alt]`+`accesskey`, Mac: `[Ctrl]``[Opt]`+`accesskey` * - **alt**: Specifies an alternate text for images (only for type="image") * - **checked**: Specifies that an `<input>` element should be pre-selected when the page loads (for type="checkbox" or type="radio") * - **class**: The class attribute specifies one or more class-names for an element * - **disabled**: Specifies that an `<input>` element should be disabled * - **format**: Specifies special field formatting class names for JS validation * - **minlength**: Sets a minimum length for the field enforced by JS validation * - **maxlength**: Specifies the maximum number of characters allowed in an `<input>` element * - **placeholder**: Specifies a short hint that describes the expected value of an `<input>` element * - **readonly**: Specifies that an input field is read-only * - **required**: Adds a class that specified an input field must be filled out before submitting the form, enforced by JS * - **size**: `5` Specifies the width, in characters, of an `<input>` element * - **src**: Specifies the URL of the image to use as a submit button (only for type="image") * - **tabindex**: Specifies the tabbing order of an element * - **cols**: Specifies the visible width of a `<textarea>` * - **rows**: Specifies the visible number of lines in a `<textarea>` * - **title**: Specifies extra information about an element * - **value**: Specifies the value of an `<input>` element * @param ShoppCartItem $O The working object * @return string The cart item quantity or quantity element markup **/ public static function quantity ( $result, $options, $O ) { $result = $O->quantity; if ( 'Donation' === $O->type && 'on' === $O->donation['var'] ) return $result; if ( 'Subscription' === $O->type || 'Membership' === $O->type ) return $result; if ( 'Download' === $O->type && ! shopp_setting_enabled('download_quantity') ) return $result; if ( isset($options['input']) && 'menu' === $options['input'] ) { if ( ! isset($options['value']) ) $options['value'] = $O->quantity; if ( ! isset($options['options']) ) $values = '1-15,20,25,30,35,40,45,50,60,70,80,90,100'; else $values = $options['options']; if ( strpos($values, ',') !== false ) $values = explode(',', $values); else $values = array($values); $qtys = array(); foreach ( $values as $value ) { if ( false !== strpos($value,'-') ) { $value = explode("-", $value); if ($value[0] >= $value[1]) $qtys[] = $value[0]; else for ($i = $value[0]; $i < $value[1]+1; $i++) $qtys[] = $i; } else $qtys[] = $value; } $result = '<select name="items['.$O->_id.'][quantity]">'; foreach ( $qtys as $qty ) $result .= '<option' . ( ($qty == $O->quantity) ? ' selected="selected"' : '' ) . ' value="' . $qty . '">' . $qty . '</option>'; $result .= '</select>'; } elseif ( isset($options['input']) && Shopp::valid_input($options['input']) ) { if ( ! isset($options['size']) ) $options['size'] = 5; if ( ! isset($options['value']) ) $options['value'] = $O->quantity; $result = '<input type="' . $options['input'] . '" name="items[' . $O->_id . '][quantity]" id="items-' . $O->_id . '-quantity" ' . inputattrs($options) . '/>'; } else $result = $O->quantity; return $result; } /** * Generates markup for an element to remove a cart item * * By default, the remove element is a plain text link. * * @api `shopp('cartitem.remove')` * @since 1.0 * * @param string $result The output * @param array $options The options * - **label**: `Remove` The text label shown * - **class**: The class attribute specifies one or more class-names for an element * - **input**: (button, checkbox) Display the remove element as an input instead of a link. * @param ShoppCartItem $O The working object * @return string The remove button markup **/ public static function remove ( $result, $options, $O ) { $label = __('Remove', 'Shopp'); if ( isset($options['label']) ) $label = $options['label']; if ( isset($options['class']) ) $class = ' class="'.$options['class'].'"'; else $class = ' class="remove"'; if ( isset($options['input']) ) { switch ($options['input']) { case "button": $result = '<button type="submit" name="remove[' . $O->_id . ']" value="' . $O->_id . '"' . $class . ' tabindex="">' . $label . '</button>'; break; case "checkbox": $result = '<input type="checkbox" name="remove[' . $O->_id . ']" value="' . $O->_id . '"' . $class . ' tabindex="" title="' . $label . '"/>'; break; } } else { $result = '<a href="' . href_add_query_arg(array('cart' => 'update', 'item' => $O->_id, 'quantity' => 0), Shopp::url(false, 'cart')) . '"' . $class . '>' . $label . '</a>'; } return $result; } /** * Displays the label of a cart item variant option * * @api `shopp('cartitem.option-label')` * @since 1.2 * * @param string $result The output * @param array $options The options * @param ShoppCartItem $O The working object * @return string The variant option label **/ public static function option_label ( $result, $options, $O ) { return $O->option->label; } /** * Displays the currently selected product variation for the item or a drop-down menu to change the selection * * @api `shopp('cartitem.options')` * @since 1.1 * * @param string $result The output * @param array $options The options * - **before**: ` ` Markup to add before the options * - **after**: ` ` Markup to add after the options * - **show**: (selected) Set to `selected` to provide the currently selected option label @see `shopp('cartitem.option-label')` * - **class**: The class attribute specifies one or more class-names for the menu element * @param ShoppCartItem $O The working object * @return string The options markup **/ public static function options ( $result, $options, $O ) { $class = ""; if ( ! isset($options['before']) ) $options['before'] = ''; if ( ! isset($options['after']) ) $options['after'] = ''; if ( isset($options['show']) && strtolower($options['show']) == "selected" ) return ( ! empty($O->option->label) ) ? $options['before'] . $O->option->label . $options['after'] : ''; if ( isset($options['class']) ) $class = ' class="' . $options['class'] . '" '; if ( count($O->variants) > 1 ) { $result .= $options['before']; $result .= '<input type="hidden" name="items[' . $O->_id . '][product]" value="' . $O->product . '"/>'; $result .= ' <select name="items[' . $O->_id . '][price]" id="items-' . $O->_id . '-price"' . $class . '>'; $result .= $O->options($O->priceline); $result .= '</select>'; $result .= $options['after']; } return $result; } /** * Checks if the item has addon options * * @api `shopp('cartitem.has-addons')` * @since 1.1 * * @param string $result The output * @param array $options The options * @param ShoppCartItem $O The working object * @return bool True if the cart item has addon options, false otherwise **/ public static function has_addons ( $result, $options, $O ) { reset($O->addons); return ( count($O->addons) > 0 ); } /** * Iterate over the available addon options for the item * * @api `shopp('cartitem.addons')` * @since 1.1 * * @param string $result The output * @param array $options The options * @param ShoppCartItem $O The working object * @return bool True if the next item exists, false otherwise **/ public static function addons ( $result, $options, $O ) { if ( ! isset($O->_addons_loop) ) { reset($O->addons); $O->_addons_loop = true; } else next($O->addons); if ( false !== current($O->addons) ) return true; unset($O->_addons_loop); reset($O->addons); return false; } /** * Displays one or more properties of the current cart item addon. * * * * @api `shopp('cartitem.addon')` * @since 1.1 * * @param string $result The output * @param array $options The options * - **id**: (on, off) Includes the addon option ID (the ShoppPrice record ID) * - **inventory**: (on, off) Include the inventory status of the addon option * - **label**: (on, off) Includes the cart item addon option label * - **menu**: (on, off) Includes the menu label the addon option is assigned to * - **price**: (on, off) Include the regular price of the addon option * - **sale**: (on, off) Include the sale status of the addon option * - **saleprice**: (on, off) Include the sale price of the addon option * - **separator**: The separator to use beteween requested fields * - **shipfee**: (on, off) Include the shipping fee of the addon option * - **sku**: (on, off) Include the SKU (Stock Keeping Unit) of the addon option * - **stock**: (on, off) Include the stock level of the addon option * - **type: (on, off) Includes the addon type (Shipped, Download, Donation, Subscription, Virtual) * - **unitprice**: (on, off) Include the actual unit price of the addon option * - **weight**: (on, off) Include the weight of the cart item addon option * @param ShoppCartItem $O The working object * @return void **/ public static function addon ( $result, $options, $O ) { if ( empty($O->addons) ) return false; $addon = current($O->addons); $defaults = array( 'separator' => ' ' ); $options = array_merge($defaults, $options); $fields = array('id', 'type', 'menu', 'label', 'sale', 'saleprice', 'price', 'inventory', 'stock', 'sku', 'weight', 'shipfee', 'unitprice'); $fieldset = array_intersect($fields, array_keys($options)); if ( empty($fieldset) ) $fieldset = array('label'); $_ = array(); foreach ( $fieldset as $field ) { switch ( $field ) { case 'menu': list($menus, $menumap) = self::_addon_menus(); $_[] = isset( $menumap[ $addon->options ]) ? $menus[ $menumap[ $addon->options ] ] : ''; break; case 'weight': $_[] = $addon->dimensions['weight']; case 'saleprice': case 'price': case 'shipfee': case 'unitprice': if ( $field === 'saleprice' ) $field = 'promoprice'; if ( isset($addon->$field) ) { $_[] = ( isset($options['currency']) && Shopp::str_true($options['currency']) ) ? money($addon->$field) : $addon->$field; } break; default: if ( isset($addon->$field) ) $_[] = $addon->$field; } } return join($options['separator'], $_); } /** * Displays all of the product addons for the cart item in an unordered list * * @api `shopp('cartitem.addons-list')` * @since 1.1 * * @param string $result The output * @param array $options The options * - **before**: ` ` Markup to add before the list * - **after**: ` ` Markup to add after the list * - **class**: The class attribute specifies one or more class-names for the list * - **exclude**: Used to specify addon labels to exclude from the list. Multiple addons can be excluded by separating them with a comma: `Addon Label 1,Addon Label 2...` * - **separator**: `: ` The separator to use between the menu name and the addon options * - **prices**: `on` (on, off) Shows or hides prices with the addon label * - **taxes**: `on` (on, off) Include taxes in the addon option price shown when `prices=on` * @param ShoppCartItem $O The working object * @return string The addon list markup **/ public static function addons_list ( $result, $options, $O ) { if ( empty($O->addons) ) return false; $defaults = array( 'before' => '', 'after' => '', 'class' => '', 'exclude' => '', 'separator' => ': ', 'prices' => true, 'taxes' => shopp_setting('tax_inclusive') ); $options = array_merge($defaults, $options); extract($options); $classes = ! empty($class) ? ' class="' . esc_attr($class) . '"' : ''; $excludes = explode(',', $exclude); $prices = Shopp::str_true($prices); $taxoption = Shopp::str_true($taxes); $inclusivetax = self::_inclusive_taxes($O); // Determine the price adjustment factor from the ratio of the tax price to the unit price, or use the tax rate $adjustment = isset($O->taxprice) ? $O->taxprice / $O->unitprice : $O->taxrate; if ( $adjustment < 0 ) $adjustment = 1 + $adjustment; // Get the menu labels list and addon options to menus map list($menus, $menumap) = self::_addon_menus(); $result .= $before . '<ul' . $classes . '>'; foreach ( $O->addons as $id => $addon ) { if ( in_array($addon->label, $excludes) ) continue; $menu = isset( $menumap[ $addon->options ]) ? $menus[ $menumap[ $addon->options ] ] . $separator : false; $price = ( Shopp::str_true($addon->sale) ? $addon->promoprice : $addon->price ); if ( 0 != $adjustment ) // Adjust price to net price $price = $price / $adjustment; if ( isset($taxoption) && ( $inclusivetax ^ $taxoption ) ) $price = $price + ( $price * $O->taxrate ); if ( $prices ) $pricing = " (" . ( $addon->price < 0 ? '-' : '+' ) . money($price) . ')'; $result .= '<li>' . $menu . $addon->label . $pricing . '</li>'; } $result .= '</ul>' . $after; return $result; } /** * Checks if the cart item has any custom product input data assigned to it * * @api `shopp('cartitem.has-inputs')` * @since 1.1 * * @param string $result The output * @param array $options The options * @param ShoppCartItem $O The working object * @return bool True if the cart item has custom input data, false otherwise **/ public static function has_inputs ( $result, $options, $O ) { reset($O->data); return ( count($O->data) > 0 ); } /** * Checks if the cart item is in a specified category * * @api `shopp('cartitem.in-category')` * @since 1.1 * * @param string $result The output * @param array $options The options * - **id**: Specify a category ID to check if the cart item is assigned to the category * - **name**: Specify a category name to check if the cart item is assigned to the category * @param ShoppCartItem $O The working object * @return bool True if the cart item is assigned to the category, false otherwise **/ public static function in_category ( $result, $options, $O ) { if ( empty($O->categories) ) return false; if ( isset($options['id']) ) $field = "id"; if ( isset($options['name']) ) $field = "name"; foreach ( $O->categories as $id => $name ) { switch ( strtolower($field) ) { case 'id': if ($options['id'] == $id) return true; case 'name': if ($options['name'] == $name) return true; } } return false; } /** * Iterates over the custom input data set on the cart item * * @api `shopp('cartitem.inputs')` * @since 1.1 * * @param string $result The output * @param array $options The options * @param ShoppCartItem $O The working object * @return bool True if the next input exists, false otherwise **/ public static function inputs ( $result, $options, $O ) { if ( ! isset($O->_data_loop) ) { reset($O->data); $O->_data_loop = true; } else next($O->data); if ( false !== current($O->data) ) return true; unset($O->_data_loop); reset($O->data); return false; } /** * Displays the current input data (or name) * * Used when looping through the cart item custom input data. * To show the name instead of the data use `shopp('cartitem.input', 'name')` * * @api `shopp('cartitem.input')` * @since 1.1 * * @param string $result The output * @param array $options The options * - **name**: Show the name of the input instead of the data * @param ShoppCartItem $O The working object * @return string The input name or data **/ public static function input ( $result, $options, $O ) { $data = current($O->data); $name = key($O->data); if ( isset($options['name']) ) return apply_filters('shopp_cartitem_input_name', $name); return apply_filters('shopp_cartitem_input_data', $data, $name); } /** * Displays all of the custom data inputs for the item in an unordered list * * @api `shopp('cartitem.inputs-list')` * @since 1.1 * * @param string $result The output * @param array $options The options * - **before**: ` ` Markup to add before the list * - **after**: ` ` Markup to add after the list * - **class**: The class attribute specifies one or more class-names for the list * - **exclude**: Used to specify the inputs to exclude from the list. Multiple inputs can be excluded by separating them with a comma: `Custom Input,Custom Input 2...` * - **separator**: `<br />` The separator to use between the input name and the input data * @param ShoppCartItem $O The working object * @return string The markup of the input list **/ public static function inputs_list ( $result, $options, $O ) { if ( empty($O->data) ) return false; $defaults = array( 'class' => '', 'exclude' => array(), 'before' => '', 'after' => '', 'separator' => '<br />' ); $options = array_merge($defaults, $options); extract($options); if ( ! empty($exclude) ) $exclude = explode(',', $exclude); $classes = ''; if ( ! empty($class) ) $classes = ' class="' . $class . '"'; $result .= $before . '<ul' . $classes . '>'; foreach ( $O->data as $name => $data ) { if (in_array($name,$exclude)) continue; if (is_array($data)) $data = join($separator, $data); $result .= '<li><strong>' . apply_filters('shopp_cartitem_input_name', $name) . '</strong>: ' . apply_filters('shopp_cartitem_input_data', $data, $name) . '</li>'; } $result .= '</ul>'.$after; return $result; } /** * Provides the markup to show the cover image for the cart item's product * * The **cover image** of a product is the image that is set as the first image * when using a customer image order, or which ever image is automatically sorted * to be first when using other image order settings in the Presentation settings screen. * * @api `shopp('cartitem.coverimage')` * @since 1.2 * * @param string $result The output * @param array $options The options * @param ShoppCartItem $O The working object * @return string The image markup **/ public static function coverimage ( $result, $options, $O ) { if ( false === $O->image ) return false; $O->images = array($O->image); $options['index'] = 0; return ShoppStorefrontThemeAPI::image( $result, $options, $O ); } /** * Detects if the cart item is on sale * * An on sale item either has the sale price enabled or a discount is applied * to it. * * @api `shopp('cartitem.onsale')` * @since 1.2 * * @param string $result The output * @param array $options The options * @param ShoppCartItem $O The working object * @return bool True if the cart item is on sale, false otherwise * **/ public static function onsale ( $result, $options, $O ) { return Shopp::str_true( $O->sale ); } /** * Provides the regular, non-discounted price of the cart item * * @api `shopp('cartitem.price')` * @since 1.0 * * @param string $result The output * @param array $options The options * @param ShoppCartItem $O The working object * @return string The price of the current cart item (or selected variant) **/ public static function price ( $result, $options, $O ) { return $O->option->price; } /** * Provides the regular, non-discounted line item total price (price * quantity) * * @api `shopp('cartitem.prices')` * @since 1.2 * * @param string $result The output * @param array $options The options * @param ShoppCartItem $O The working object * @return string The total cart line item price */ public static function prices ( $result, $options, $O ) { return ( $O->option->price * $O->quantity ); } /** * Returns the sale price of the cart item * * @api `shopp('cartitem.saleprice')` * @since 1.0 * * @param string $result The output * @param array $options The options * @param ShoppCartItem $O The working object * @return string The sale price of the cart item (or selected variant) **/ public static function saleprice ( $result, $options, $O ) { return $O->option->promoprice; } /** * Provides the total line item sale price * * @api `shopp('cartitem.saleprices')` * @since 1.2 * * @param string $result The output * @param array $options The options * @param ShoppCartItem $O The working object * @return string The line item total price with discounts **/ public static function saleprices ( $result, $options, $O ) { return ( $O->option->promoprice * $O->quantity ); } /** * Helper to determine when inclusive taxes apply * * @internal * * @param ShoppCartItem $O The cart item to evaluate * @return bool True if inclusive taxes apply, false otherwise **/ private static function _inclusive_taxes ( ShoppCartItem $O ) { return shopp_setting_enabled('tax_inclusive') && $O->includetax; } /** * Helper to apply or exclude taxes from a single amount based on inclusive tax settings and the tax option * * @internal * @since 1.3 * * @param float $amount The amount to add taxes to, or exclude taxes from * @param ShoppProduct $O The product to get properties from * @param boolean $taxoption The Theme API tax option given the the tag * @param int $quantity The quantity of items * @return float The amount with tax added or tax excluded **/ private static function _taxes ( $amount, ShoppCartItem $O, $taxoption = null, $quantity = 1) { if ( ! $O->istaxed ) return $amount; if ( 0 == $O->unittax ) return $amount; $inclusivetax = self::_inclusive_taxes($O); if ( isset($taxoption) && ( $inclusivetax ^ $taxoption ) ) { if ( $taxoption ) $amount += ( $O->unittax * $quantity ); else $amount = $amount -= ( $O->unittax * $quantity ); } return (float) $amount; } /** * Helper function that maps the current cart item's addons to the cart item's configured product menu options * * @internal * @since 1.3 * * @param int $id The product ID to retrieve addon menus from * @return array A combined list of the menu labels list and addons menu map **/ private static function _addon_menus () { return ShoppProductThemeAPI::_addon_menus(shopp('cartitem.get-product')); } }
gpl-3.0
woakes070048/crm-php
htdocs/societe/fiche.php
73105
<?php /* Copyright (C) 2001-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2003 Brian Fraval <brian@fraval.org> * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2005 Eric Seigne <eric.seigne@ryxeo.com> * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@capnetworks.com> * Copyright (C) 2008 Patrick Raguin <patrick.raguin@auguria.net> * Copyright (C) 2010-2011 Juanjo Menent <jmenent@2byte.es> * Copyright (C) 2010-2013 Herve Prot <herve.prot@symeos.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT . '/societe/lib/societe.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/images.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formadmin.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php'; if (!empty($conf->adherent->enabled)) require_once DOL_DOCUMENT_ROOT . '/adherent/class/adherent.class.php'; if (!empty($conf->agenda->enabled)) require_once DOL_DOCUMENT_ROOT . '/agenda/class/agenda.class.php'; $langs->load("companies"); $langs->load("commercial"); $langs->load("bills"); $langs->load("banks"); $langs->load("users"); if (!empty($conf->notification->enabled)) $langs->load("mails"); $mesg = ''; $error = 0; $errors = array(); $action = (GETPOST('action') ? GETPOST('action') : 'view'); $confirm = GETPOST('confirm'); $socid = GETPOST('id', 'alpha'); if ($user->societe_id) $socid = $user->societe_id; $object = new Societe($db); $contact = new Contact($db); // Get object canvas (By default, this is not defined, so standard usage of dolibarr) /* $object->getCanvas($socid); $canvas = $object->canvas ? $object->canvas : GETPOST("canvas"); $objcanvas = ''; if (!empty($canvas)) { require_once DOL_DOCUMENT_ROOT . '/core/class/canvas.class.php'; $objcanvas = new Canvas($db, $action); $objcanvas->getCanvas('thirdparty', 'card', $canvas); } */ // Security check $result = restrictedArea($user, 'societe', $socid, '&societe', '', 'fk_soc', 'rowid'); // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array $hookmanager->initHooks(array('thirdpartycard')); /* * Actions */ $parameters = array('id' => $socid); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $error = $hookmanager->error; $errors = array_merge($errors, (array) $hookmanager->errors); if (empty($reshook)) { if (GETPOST('getcustomercode')) { // We defined value code_client $_POST["code_client"] = "Acompleter"; } if (GETPOST('getsuppliercode')) { // We defined value code_fournisseur $_POST["code_fournisseur"] = "Acompleter"; } // Add new third party if ((!GETPOST('getcustomercode') && !GETPOST('getsuppliercode')) && ($action == 'add' || $action == 'update') && $user->rights->societe->creer) { require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php'; if ($action == 'update') { $ret = $object->fetch($socid); $oldcopy = dol_clone($object); } else { //$object->canvas = $canvas; $object->commercial_id->id = GETPOST('commercial_id'); } if (GETPOST("private") == 1) { $object->particulier = GETPOST("private"); $object->name = empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? GETPOST('prenom') . ' ' . GETPOST('nom') : GETPOST('nom') . ' ' . GETPOST('prenom'); $object->civilite_id = GETPOST('civilite_id'); // Add non official properties $object->name_bis = GETPOST('nom'); $object->firstname = GETPOST('prenom'); } else { $object->name = GETPOST('nom'); } $object->address = GETPOST('adresse'); $object->zip = GETPOST('zipcode'); $object->town = GETPOST('town'); $object->country_id = GETPOST('country_id'); $object->state_id = GETPOST('departement_id'); $object->phone = GETPOST('phone'); $object->fax = GETPOST('fax'); $object->email = GETPOST('email'); $object->url = GETPOST('url'); $object->idprof1 = GETPOST('idprof1'); $object->idprof2 = GETPOST('idprof2'); $object->idprof3 = GETPOST('idprof3'); $object->idprof4 = GETPOST('idprof4'); $object->prefix_comm = GETPOST('prefix_comm'); $object->code_client = GETPOST('code_client'); $object->code_fournisseur = GETPOST('code_fournisseur'); $object->capital = GETPOST('capital'); $object->barcode = GETPOST('barcode'); $object->tva_intra = GETPOST('tva_intra'); $object->tva_assuj = GETPOST('assujtva_value'); $object->Status = GETPOST('status'); // Local Taxes $object->localtax1_assuj = GETPOST('localtax1assuj_value'); $object->localtax2_assuj = GETPOST('localtax2assuj_value'); $object->forme_juridique_code = GETPOST('forme_juridique_code'); $object->effectif_id = GETPOST('effectif_id'); if (GETPOST("private") == 1) { $object->typent_id = "TE_PRIVATE"; } else { $object->typent_id = GETPOST('typent_id'); } $object->client = GETPOST('client'); $object->fournisseur = GETPOST('fournisseur'); $object->fournisseur_categorie = GETPOST('fournisseur_categorie'); $object->default_lang = GETPOST('default_lang'); // Get extra fields foreach ($_POST as $key => $value) { if (preg_match("/^options_/", $key)) { $object->array_options[$key] = GETPOST($key); } } if (GETPOST('deletephoto')) $object->logo = ''; else if (!empty($_FILES['photo']['name'])) $object->logo = dol_sanitizeFileName($_FILES['photo']['name']); // Check parameters if (empty($_POST["cancel"])) { if (!empty($object->email) && !isValidEMail($object->email)) { $langs->load("errors"); $error++; $errors[] = $langs->trans("ErrorBadEMail", $object->email); $action = ($action == 'add' ? 'create' : 'edit'); } if (!empty($object->url) && !isValidUrl($object->url)) { $langs->load("errors"); $error++; $errors[] = $langs->trans("ErrorBadUrl", $object->url); $action = ($action == 'add' ? 'create' : 'edit'); } if ($object->fournisseur && !$conf->fournisseur->enabled) { $langs->load("errors"); $error++; $errors[] = $langs->trans("ErrorSupplierModuleNotEnabled"); $action = ($action == 'add' ? 'create' : 'edit'); } // Check for duplicate prof id for ($i = 1; $i < 3; $i++) { $slabel = "idprof" . $i; $_POST[$slabel] = trim($_POST[$slabel]); $vallabel = $_POST[$slabel]; if ($vallabel && $object->id_prof_verifiable($i)) { if ($object->id_prof_exists($i, $vallabel, $object->id)) { $langs->load("errors"); $error++; $errors[] = $langs->transcountry('ProfId' . $i, $object->country_id) . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel); $action = ($action == 'add' ? 'create' : 'edit'); } } } } if (!$error) { if ($action == 'add') { if (empty($object->client)) $object->code_client = ''; if (empty($object->fournisseur)) $object->code_fournisseur = ''; $result = $object->create($user); if ($result >= 0) { if ($object->particulier) { $contact->civilite_id = $object->civilite_id; $contact->name = $object->name_bis; $contact->firstname = $object->firstname; $contact->address = $object->address; $contact->zip = $object->zip; $contact->town = $object->town; $contact->state_id = $object->state_id; $contact->country_id = $object->country_id; $contact->societe->id = $object->id; // fk_soc $contact->societe->name = $object->name; // fk_soc $contact->email = $object->email; $contact->phone_pro = $object->phone; $contact->fax = $object->fax; $result = $contact->create($user); if (!$result >= 0) { $error = $contact->error; $errors = $contact->errors; } } // Gestion du logo de la société $dir = $conf->societe->multidir_output[$conf->entity] . "/" . $object->id . "/logos/"; $file_OK = is_uploaded_file($_FILES['photo']['tmp_name']); if ($file_OK) { if (image_format_supported($_FILES['photo']['name'])) { dol_mkdir($dir); if (@is_dir($dir)) { $newfile = $dir . '/' . dol_sanitizeFileName($_FILES['photo']['name']); $result = dol_move_uploaded_file($_FILES['photo']['tmp_name'], $newfile, 1); if (!$result > 0) { $errors[] = "ErrorFailedToSaveFile"; } else { // Create small thumbs for company (Ratio is near 16/9) // Used on logon for example $imgThumbSmall = vignette($newfile, $maxwidthsmall, $maxheightsmall, '_small', $quality); // Create mini thumbs for company (Ratio is near 16/9) // Used on menu or for setup page for example $imgThumbMini = vignette($newfile, $maxwidthmini, $maxheightmini, '_mini', $quality); } } } } // Gestion du logo de la société } else { $error = $object->error; $errors = $object->errors; } if ($result >= 0) { $url = $_SERVER["PHP_SELF"] . "?id=" . $object->id; if (($object->client == 1 || $object->client == 3) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) $url = $_SERVER["PHP_SELF"] . "?id=" . $object->id; else if ($object->fournisseur == 1) $url = DOL_URL_ROOT . "/fourn/fiche.php?id=" . $object->id; header("Location: " . $url); exit; } else { $action = 'create'; } } if ($action == 'update') { if ($_POST["cancel"]) { header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $socid); exit; } $result = $object->update($socid, $user, 1, $oldcopy->codeclient_modifiable(), $oldcopy->codefournisseur_modifiable()); if ($result <= 0) { $error = $object->error; $errors = $object->errors; } // Gestion du logo de la société $dir = $conf->societe->multidir_output[$object->entity] . "/" . $object->id . "/logos"; $file_OK = is_uploaded_file($_FILES['photo']['tmp_name']); if ($file_OK) { if (GETPOST('deletephoto')) { $fileimg = $dir . '/' . $object->logo; $dirthumbs = $dir . '/thumbs'; dol_delete_file($fileimg); dol_delete_dir_recursive($dirthumbs); } if (image_format_supported($_FILES['photo']['name']) > 0) { dol_mkdir($dir); if (@is_dir($dir)) { $newfile = $dir . '/' . dol_sanitizeFileName($_FILES['photo']['name']); $result = dol_move_uploaded_file($_FILES['photo']['tmp_name'], $newfile, 1); if (!$result > 0) { $errors[] = "ErrorFailedToSaveFile"; } else { // Create small thumbs for company (Ratio is near 16/9) // Used on logon for example $imgThumbSmall = vignette($newfile, $maxwidthsmall, $maxheightsmall, '_small', $quality); // Create mini thumbs for company (Ratio is near 16/9) // Used on menu or for setup page for example $imgThumbMini = vignette($newfile, $maxwidthmini, $maxheightmini, '_mini', $quality); } } } else { $errors[] = "ErrorBadImageFormat"; } } // Gestion du logo de la société if (!$error && !count($errors)) { header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $socid); exit; } else { $object->id = $socid; $action = "edit"; } } } } // Delete third party if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->societe->supprimer) { $object->fetch($socid); $result = $object->delete($socid); if ($result > 0) { header("Location: " . DOL_URL_ROOT . "/societe/societe.php?delsoc=" . urlencode($object->name)); exit; } else { $langs->load("errors"); $error = $langs->trans($object->error); $errors = $object->errors; $action = ''; } } /* * Generate document */ if ($action == 'builddoc') { // En get ou en post if (is_numeric(GETPOST('model'))) { $error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Model")); } else { require_once DOL_DOCUMENT_ROOT . '/core/models/modules_societe.class.php'; $object->fetch($socid); // Define output language $outputlangs = $langs; $newlang = ''; if ($conf->global->MAIN_MULTILANGS && empty($newlang) && !empty($_REQUEST['lang_id'])) $newlang = $_REQUEST['lang_id']; if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $fac->client->default_lang; if (!empty($newlang)) { $outputlangs = new Translate(); $outputlangs->setDefaultLang($newlang); } $result = thirdparty_doc_create($db, $object, '', $_REQUEST['model'], $outputlangs); if ($result <= 0) { dol_print_error($db, $result); exit; } else { header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . (empty($conf->global->MAIN_JUMP_TAG) ? '' : '#builddoc')); exit; } } } // Remove file in doc form else if ($action == 'remove_file') { if ($object->fetch($socid)) { require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; $langs->load("other"); $upload_dir = $conf->societe->dir_output; $file = $upload_dir . '/' . GETPOST('file'); $ret = dol_delete_file($file, 0, 0, 0, $object); if ($ret) setEventMessage($langs->trans("FileWasRemoved", GETPOST('urlfile'))); else setEventMessage($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), 'errors'); } } } /* * View */ llxHeader('', $langs->trans("ThirdParty")); $form = new Form($db); $formfile = new FormFile($db); $formadmin = new FormAdmin($db); $formcompany = new FormCompany($db); $countrynotdefined = $langs->trans("ErrorSetACountryFirst") . ' (' . $langs->trans("SeeAbove") . ')'; if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { // ----------------------------------------- // When used with CANVAS // ----------------------------------------- if (empty($object->error) && $socid) { $object = new Societe($db); $object->fetch($socid); } $objcanvas->assign_values($action, $socid); // Set value for templates $objcanvas->display_canvas($action); // Show template } else { // ----------------------------------------- // When used in standard mode // ----------------------------------------- if ($action == 'create') { /* * Creation */ // Load object modCodeTiers $module = (!empty($conf->global->SOCIETE_CODECLIENT_ADDON) ? $conf->global->SOCIETE_CODECLIENT_ADDON : 'mod_codeclient_leopard'); if (substr($module, 0, 15) == 'mod_codeclient_' && substr($module, -3) == 'php') { $module = substr($module, 0, dol_strlen($module) - 4); } $dirsociete = array_merge(array('/societe/core/models/'), $conf->societe_modules); foreach ($dirsociete as $dirroot) { $res = dol_include_once($dirroot . $module . '.php'); if ($res) break; } $modCodeClient = new $module; $module = $conf->global->SOCIETE_CODEFOURNISSEUR_ADDON; if (!$module) $module = $conf->global->SOCIETE_CODECLIENT_ADDON; if (substr($module, 0, 15) == 'mod_codeclient_' && substr($module, -3) == 'php') { $module = substr($module, 0, dol_strlen($module) - 4); } $dirsociete = array_merge(array('/societe/core/models/'), $conf->societe_modules); foreach ($dirsociete as $dirroot) { $res = dol_include_once($dirroot . $module . '.php'); if ($res) break; } $modCodeFournisseur = new $module; //if ($_GET["type"]=='cp') { $object->client=3; } if (GETPOST("type") != 'f') { $object->client = 3; } if (GETPOST("type") == 'c') { $object->client = 1; } if (GETPOST("type") == 'p') { $object->client = 2; } if (!empty($conf->fournisseur->enabled) && (GETPOST("type") == 'f' || GETPOST("type") == '')) { $object->fournisseur = 1; } if (GETPOST("private") == 1) { $object->particulier = 1; } $object->name = GETPOST('nom'); $object->firstname = GETPOST('prenom'); $object->particulier = GETPOST('private', 'int'); $object->prefix_comm = GETPOST('prefix_comm'); $object->client = GETPOST('client') ? GETPOST('client') : $object->client; $object->code_client = GETPOST('code_client'); $object->fournisseur = GETPOST('fournisseur') ? GETPOST('fournisseur') : $object->fournisseur; $object->code_fournisseur = GETPOST('code_fournisseur'); $object->address = GETPOST('adresse'); $object->zip = GETPOST('zipcode'); $object->town = GETPOST('town'); $object->state_id = GETPOST('departement_id'); $object->phone = GETPOST('phone'); $object->fax = GETPOST('fax'); $object->email = GETPOST('email'); $object->url = GETPOST('url'); $object->capital = GETPOST('capital'); $object->barcode = GETPOST('barcode'); $object->idprof1 = GETPOST('idprof1'); $object->idprof2 = GETPOST('idprof2'); $object->idprof3 = GETPOST('idprof3'); $object->idprof4 = GETPOST('idprof4'); $object->typent_id = GETPOST('typent_id'); $object->effectif_id = GETPOST('effectif_id'); $object->civility_id = GETPOST('civilite_id'); $object->tva_assuj = GETPOST('assujtva_value'); $object->Status = GETPOST('status'); //Local Taxes $object->localtax1_assuj = GETPOST('localtax1assuj_value'); $object->localtax2_assuj = GETPOST('localtax2assuj_value'); $object->tva_intra = GETPOST('tva_intra'); if (!is_object($object->commercial_id)) $object->commercial_id = new stdClass(); $object->commercial_id->id = GETPOST('commercial_id'); $object->default_lang = GETPOST('default_lang'); $object->logo = (isset($_FILES['photo']) ? dol_sanitizeFileName($_FILES['photo']['name']) : ''); // Gestion du logo de la société $dir = $conf->societe->multidir_output[$conf->entity] . "/" . $object->id . "/logos"; $file_OK = (isset($_FILES['photo']) ? is_uploaded_file($_FILES['photo']['tmp_name']) : false); if ($file_OK) { if (image_format_supported($_FILES['photo']['name'])) { dol_mkdir($dir); if (@is_dir($dir)) { $newfile = $dir . '/' . dol_sanitizeFileName($_FILES['photo']['name']); $result = dol_move_uploaded_file($_FILES['photo']['tmp_name'], $newfile, 1); if (!$result > 0) { $errors[] = "ErrorFailedToSaveFile"; } else { // Create small thumbs for company (Ratio is near 16/9) // Used on logon for example $imgThumbSmall = vignette($newfile, $maxwidthsmall, $maxheightsmall, '_small', $quality); // Create mini thumbs for company (Ratio is near 16/9) // Used on menu or for setup page for example $imgThumbMini = vignette($newfile, $maxwidthmini, $maxheightmini, '_mini', $quality); } } } } // We set country_id country for the selected country $object->country_id = GETPOST('country_id') ? GETPOST('country_id') : $mysoc->country_id; $object->forme_juridique_code = GETPOST('forme_juridique_code'); /* Show create form */ print_fiche_titre($langs->trans("NewThirdParty")); print '<div class="with-padding">'; print '<div class="columns">'; $titre = $langs->trans("NewThirdParty"); //print start_box($titre, $object->fk_extrafields->ico); print column_start(); if (!empty($conf->use_javascript_ajax)) { print "\n" . '<script type="text/javascript">'; print '$(document).ready(function () { id_te_private=8; id_ef15=1; is_private=' . (GETPOST("private") ? GETPOST("private") : 0) . '; if (is_private) { $(".individualline").show(); } else { $(".individualline").hide(); } $("#radiocompany").click(function() { $(".individualline").hide(); $("#typent_id").val(0); $("#effectif_id").val(0); $("#TypeName").html(document.formsoc.ThirdPartyName.value); document.formsoc.private.value=0; }); $("#radioprivate").click(function() { $(".individualline").show(); $("#typent_id").val(id_te_private); $("#effectif_id").val(id_ef15); $("#TypeName").html(document.formsoc.LastName.value); document.formsoc.private.value=1; }); $("#selectcountry_id").change(function() { document.formsoc.action.value="create"; document.formsoc.submit(); }); });'; print '</script>' . "\n"; print "<br>\n"; print $langs->trans("ThirdPartyType") . ': &nbsp; '; print '<input type="radio" id="radiocompany" class="flat" name="private" value="0"' . (!GETPOST("private") ? ' checked="checked"' : ''); print '> ' . $langs->trans("Company/Fundation"); print ' &nbsp; &nbsp; '; print '<input type="radio" id="radioprivate" class="flat" name="private" value="1"' . (!GETPOST("private") ? '' : ' checked="checked"'); print '> ' . $langs->trans("Individual"); print ' (' . $langs->trans("ToCreateContactWithSameName") . ')'; print "<br>\n"; print "<br>\n"; } dol_htmloutput_errors($error, $errors); print '<form enctype="multipart/form-data" action="' . $_SERVER["PHP_SELF"] . '" method="post" name="formsoc">'; print '<input type="hidden" name="action" value="add">'; print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">'; print '<input type="hidden" name="private" value=' . $object->particulier . '>'; print '<input type="hidden" name="type" value=' . GETPOST("type") . '>'; print '<input type="hidden" name="LastName" value="' . $langs->trans('LastName') . '">'; print '<input type="hidden" name="ThirdPartyName" value="' . $langs->trans('ThirdPartyName') . '">'; if ($modCodeClient->code_auto || $modCodeFournisseur->code_auto) print '<input type="hidden" name="code_auto" value="1">'; print '<table class="border" width="100%">'; // Name, firstname if ($object->particulier || GETPOST("private")) { print '<tr><td><span id="TypeName" class="fieldrequired">' . $langs->trans('LastName') . '</span></td><td' . (empty($conf->global->SOCIETE_USEPREFIX) ? ' colspan="3"' : '') . '><input type="text" size="30" maxlength="60" name="nom" value="' . $object->name . '"></td>'; if (!empty($conf->global->SOCIETE_USEPREFIX)) { // Old not used prefix field print '<td>' . $langs->trans('Prefix') . '</td><td><input type="text" size="5" maxlength="5" name="prefix_comm" value="' . $object->prefix_comm . '"></td>'; } print '</tr>'; } else { print '<tr><td><span span id="TypeName" class="fieldrequired">' . $langs->trans('ThirdPartyName') . '</span></td><td' . (empty($conf->global->SOCIETE_USEPREFIX) ? ' colspan="3"' : '') . '><input type="text" size="30" maxlength="60" name="nom" value="' . $object->name . '"></td>'; if (!empty($conf->global->SOCIETE_USEPREFIX)) { // Old not used prefix field print '<td>' . $langs->trans('Prefix') . '</td><td><input type="text" size="5" maxlength="5" name="prefix_comm" value="' . $object->prefix_comm . '"></td>'; } print '</tr>'; } // If javascript on, we show option individual if ($conf->use_javascript_ajax) { print '<tr class="individualline"><td>' . $langs->trans('FirstName') . '</td><td><input type="text" size="30" name="prenom" value="' . $object->firstname . '"></td>'; print '<td colspan=2>&nbsp;</td></tr>'; print '<tr class="individualline"><td>' . $langs->trans("UserTitle") . '</td><td>'; print $object->select_fk_extrafields('civilite_id', 'civilite_id') . '</td>'; print '<td colspan=2>&nbsp;</td></tr>'; } // Prospect/Customer print '<tr><td width="25%"><span class="fieldrequired">' . $langs->trans('ProspectCustomer') . '</span></td><td width="25%"><select class="flat" name="client">'; $selected = isset($_POST['client']) ? GETPOST('client') : $object->client; if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) print '<option value="2"' . ($selected == 2 ? ' selected="selected"' : '') . '>' . $langs->trans('Prospect') . '</option>'; if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) print '<option value="3"' . ($selected == 3 ? ' selected="selected"' : '') . '>' . $langs->trans('ProspectCustomer') . '</option>'; print '<option value="1"' . ($selected == 1 ? ' selected="selected"' : '') . '>' . $langs->trans('Customer') . '</option>'; print '<option value="0"' . ($selected == 0 ? ' selected="selected"' : '') . '>' . $langs->trans('NorProspectNorCustomer') . '</option>'; print '</select></td>'; print '<td width="25%">' . $langs->trans('CustomerCode') . '</td><td width="25%">'; print '<table class="nobordernopadding"><tr><td>'; $tmpcode = $object->code_client; if ($modCodeClient->code_auto) $tmpcode = $modCodeClient->getNextValue($object, 0); print '<input type="text" name="code_client" size="16" value="' . $tmpcode . '" maxlength="15">'; print '</td><td>'; $s = $modCodeClient->getToolTip($langs, $object, 0); print $form->textwithpicto('', $s, 1); print '</td></tr></table>'; print '</td></tr>'; if (!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire)) { // Supplier print '<tr>'; print '<td><span class="fieldrequired">' . $langs->trans('Supplier') . '</span></td><td>'; print $form->selectyesno("fournisseur", (isset($_POST['fournisseur']) ? GETPOST('fournisseur') : $object->fournisseur), 1); print '</td>'; print '<td>' . $langs->trans('SupplierCode') . '</td><td>'; print '<table class="nobordernopadding"><tr><td>'; $tmpcode = $object->code_fournisseur; if ($modCodeFournisseur->code_auto) $tmpcode = $modCodeFournisseur->getNextValue($object, 1); print '<input type="text" name="code_fournisseur" size="16" value="' . $tmpcode . '" maxlength="15">'; print '</td><td>'; $s = $modCodeFournisseur->getToolTip($langs, $object, 1); print $form->textwithpicto('', $s, 1); print '</td></tr></table>'; print '</td></tr>'; // Category /* This must be set into category tab, like for customer category if ($object->fournisseur) { $load = $object->LoadSupplierCateg(); if ( $load == 0) { if (count($object->SupplierCategories) > 0) { print '<tr>'; print '<td>'.$langs->trans('SupplierCategory').'</td><td colspan="3">'; print $form->selectarray("fournisseur_categorie",$object->SupplierCategories,GETPOST('fournisseur_categorie'),1); print '</td></tr>'; } } } */ } // Status print '<tr><td>' . $langs->trans('Status') . '</td><td colspan="3">'; print $object->select_fk_extrafields('Status', "status"); print '</td></tr>'; // Barcode if (!empty($conf->barcode->enabled)) { print '<tr><td>' . $langs->trans('Gencod') . '</td><td colspan="3"><input type="text" name="barcode" value="' . $object->barcode . '">'; print '</td></tr>'; } // Address print '<tr><td valign="top">' . $langs->trans('Address') . '</td><td colspan="3"><textarea name="adresse" cols="40" rows="3" wrap="soft">'; print $object->address; print '</textarea></td></tr>'; // Zip / Town print '<tr><td>' . $langs->trans('Zip') . '</td><td>'; print $formcompany->select_ziptown($object->zip, 'zipcode', array('town', 'selectcountry_id', 'departement_id'), 6); print '</td><td>' . $langs->trans('Town') . '</td><td>'; print $formcompany->select_ziptown($object->town, 'town', array('zipcode', 'selectcountry_id', 'departement_id')); print '</td></tr>'; // Country print '<tr><td width="25%">' . $langs->trans('Country') . '</td><td colspan="3">'; print $object->select_fk_extrafields('country_id', 'country_id'); if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionnarySetup"), 1); print '</td></tr>'; // State if (empty($conf->global->SOCIETE_DISABLE_STATE)) { print '<tr><td>' . $langs->trans('State') . '</td><td colspan="3">'; if ($object->country_id) print $object->select_fk_extrafields('state_id', 'departement_id'); else print $countrynotdefined; print '</td></tr>'; } // Phone / Fax print '<tr><td>' . $langs->trans('Phone') . '</td><td><input type="text" name="phone" value="' . $object->phone . '"></td>'; print '<td>' . $langs->trans('Fax') . '</td><td><input type="text" name="fax" value="' . $object->fax . '"></td></tr>'; print '<tr><td>' . $langs->trans('EMail') . (!empty($conf->global->SOCIETE_MAIL_REQUIRED) ? '*' : '') . '</td><td><input type="text" name="email" size="32" value="' . $object->email . '"></td>'; print '<td>' . $langs->trans('Web') . '</td><td><input type="text" name="url" size="32" value="' . $object->url . '"></td></tr>'; // Prof ids $i = 1; $j = 0; while ($i <= 6) { $idprof = $langs->transcountry('ProfId' . $i, $object->country_id); if ($idprof != '-') { if (($j % 2) == 0) print '<tr>'; print '<td>' . $idprof . '</td><td>'; $key = 'idprof' . $i; print $formcompany->get_input_id_prof($i, 'idprof' . $i, $object->$key, $object->country_id); print '</td>'; if (($j % 2) == 1) print '</tr>'; $j++; } $i++; } if ($j % 2 == 1) print '<td colspan="2"></td></tr>'; // Assujeti TVA $form = new Form($db); print '<tr><td>' . $langs->trans('VATIsUsed') . '</td>'; print '<td>'; print $form->selectyesno('assujtva_value', 1, 1); // Assujeti par defaut en creation print '</td>'; print '<td nowrap="nowrap">' . $langs->trans('VATIntra') . '</td>'; print '<td nowrap="nowrap">'; $s = '<input type="text" class="flat" name="tva_intra" size="12" maxlength="20" value="' . $object->tva_intra . '">'; if (empty($conf->global->MAIN_DISABLEVATCHECK)) { $s.=' '; if (!empty($conf->use_javascript_ajax)) { print "\n"; print '<script language="JavaScript" type="text/javascript">'; print "function CheckVAT(a) {\n"; print "newpopup('" . DOL_URL_ROOT . "/societe/checkvat/checkVatPopup.php?vatNumber='+a,'" . dol_escape_js($langs->trans("VATIntraCheckableOnEUSite")) . "',500,300);\n"; print "}\n"; print '</script>'; print "\n"; $s.='<a href="#" onclick="javascript: CheckVAT(document.formsoc.tva_intra.value);">' . $langs->trans("VATIntraCheck") . '</a>'; $s = $form->textwithpicto($s, $langs->trans("VATIntraCheckDesc", $langs->trans("VATIntraCheck")), 1); } else { $s.='<a href="' . $langs->transcountry("VATIntraCheckURL", $object->country_id) . '" target="_blank">' . img_picto($langs->trans("VATIntraCheckableOnEUSite"), 'help') . '</a>'; } } print $s; print '</td>'; print '</tr>'; // Type - Size print '<tr><td>' . $langs->trans("ThirdPartyType") . '</td><td>' . "\n"; print $object->select_fk_extrafields("typent_id", "typent_id"); if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionnarySetup"), 1); print '</td>'; print '<td>' . $langs->trans("Staff") . '</td><td>'; print $object->select_fk_extrafields("effectif_id", "effectif_id"); if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionnarySetup"), 1); print '</td></tr>'; // Legal Form print '<tr><td>' . $langs->trans('JuridicalStatus') . '</td>'; print '<td colspan="3">'; if ($object->country_id) { print $object->select_fk_extrafields("forme_juridique_code", "forme_juridique_code"); } else { print $countrynotdefined; } print '</td></tr>'; // Capital print '<tr><td>' . $langs->trans('Capital') . '</td><td colspan="3"><input type="text" name="capital" size="10" value="' . $object->capital . '"> ' . $langs->trans("Currency" . $conf->currency) . '</td></tr>'; // Local Taxes // TODO add specific function by country if ($mysoc->country_id == 'ES') { if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") { print '<tr><td>' . $langs->trans("LocalTax1IsUsedES") . '</td><td>'; print $form->selectyesno('localtax1assuj_value', 0, 1); print '</td><td>' . $langs->trans("LocalTax2IsUsedES") . '</td><td>'; print $form->selectyesno('localtax2assuj_value', 0, 1); print '</td></tr>'; } elseif ($mysoc->localtax1_assuj == "1") { print '<tr><td>' . $langs->trans("LocalTax1IsUsedES") . '</td><td colspan="3">'; print $form->selectyesno('localtax1assuj_value', 0, 1); print '</td><tr>'; } elseif ($mysoc->localtax2_assuj == "1") { print '<tr><td>' . $langs->trans("LocalTax2IsUsedES") . '</td><td colspan="3">'; print $form->selectyesno('localtax2assuj_value', 0, 1); print '</td><tr>'; } } if (!empty($conf->global->MAIN_MULTILANGS)) { print '<tr><td>' . $langs->trans("DefaultLang") . '</td><td colspan="3">' . "\n"; print $formadmin->select_language(($object->default_lang ? $object->default_lang : $conf->global->MAIN_LANG_DEFAULT), 'default_lang', 0, 0, 1); print '</td>'; print '</tr>'; } // Assign a Name print '<tr>'; print '<td>' . $langs->trans("AllocateCommercial") . '</td>'; print '<td colspan="3">'; if ($user->rights->societe->client->voir) { $object->commercial_id->id = $user->id; print $object->select_fk_extrafields("commercial_id", "commercial_id"); } else { print $user->name; print '<input type="hidden" name="commercial_id" value=' . $user->id . '>'; } print '</td></tr>'; // Other attributes /* $parameters = array('colspan' => ' colspan="3"'); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook if (empty($reshook)) { foreach ($object->fk_extrafields->fields as $key => $aRow) { if ($aRow->optional && $aRow->enable) { $value = (isset($_POST["options_" . $key]) ? $_POST["options_" . $key] : (isset($object->array_options["options_" . $key]) ? $object->array_options["options_" . $key] : '')); print '<tr><td><strong class="blue">' . $aRow->label . '</strong></td><td colspan="3">'; print $object->fk_extrafields->showInputField($key, $value); print '</td></tr>' . "\n"; } } } */ // Ajout du logo print '<tr>'; print '<td>' . $langs->trans("Logo") . '</td>'; print '<td colspan="3">'; print '<input class="flat" type="file" name="photo" id="photoinput" />'; print '</td>'; print '</tr>'; print '</table>' . "\n"; print '<br><center>'; print '<input type="submit" class="button" value="' . $langs->trans('AddThirdParty') . '">'; print '</center>' . "\n"; print '</form>' . "\n"; print column_end(); print '</div></div>'; } elseif ($action == 'edit') { /* * Edition */ //print_fiche_titre($langs->trans("EditCompany")); if ($socid) { $object = new Societe($db); $res = $object->fetch($socid); if ($res < 0) { dol_print_error($db, $object->error); exit; } //$res = $object->fetch_optionals($object->id, $extralabels); //if ($res < 0) { dol_print_error($db); exit; } print_fiche_titre($object->name); print '<div class="with-padding">'; print '<div class="columns">'; $titre = $langs->trans("ThirdParty"); print column_start(); dol_fiche_head($head, 'card', $langs->trans("ThirdParty"), 0, 'company'); // Load object modCodeTiers $module = (!empty($conf->global->SOCIETE_CODECLIENT_ADDON) ? $conf->global->SOCIETE_CODECLIENT_ADDON : 'mod_codeclient_leopard'); if (substr($module, 0, 15) == 'mod_codeclient_' && substr($module, -3) == 'php') { $module = substr($module, 0, dol_strlen($module) - 4); } $dirsociete = array_merge(array('/societe/core/models/'), $conf->societe_modules); foreach ($dirsociete as $dirroot) { $res = dol_include_once($dirroot . $module . '.php'); if ($res) break; } $modCodeClient = new $module($db); // We verified if the tag prefix is used if ($modCodeClient->code_auto) { $prefixCustomerIsUsed = $modCodeClient->verif_prefixIsUsed(); } $module = $conf->global->SOCIETE_CODEFOURNISSEUR_ADDON; if (!$module) $module = $conf->global->SOCIETE_CODECLIENT_ADDON; if (substr($module, 0, 15) == 'mod_codeclient_' && substr($module, -3) == 'php') { $module = substr($module, 0, dol_strlen($module) - 4); } $dirsociete = array_merge(array('/societe/core/models/'), $conf->societe_modules); foreach ($dirsociete as $dirroot) { $res = dol_include_once($dirroot . $module . '.php'); if ($res) break; } $modCodeFournisseur = new $module($db); // On verifie si la balise prefix est utilisee if ($modCodeFournisseur->code_auto) { $prefixSupplierIsUsed = $modCodeFournisseur->verif_prefixIsUsed(); } if (GETPOST('nom')) { // We overwrite with values if posted $object->name = GETPOST('nom'); $object->prefix_comm = GETPOST('prefix_comm'); $object->client = GETPOST('client'); $object->code_client = GETPOST('code_client'); $object->fournisseur = GETPOST('fournisseur'); $object->code_fournisseur = GETPOST('code_fournisseur'); $object->address = GETPOST('adresse'); $object->zip = GETPOST('zipcode'); $object->town = GETPOST('town'); $object->country_id = GETPOST('country_id') ? GETPOST('country_id') : $mysoc->country_id; $object->state_id = GETPOST('departement_id'); $object->phone = GETPOST('phone'); $object->fax = GETPOST('fax'); $object->email = GETPOST('email'); $object->url = GETPOST('url'); $object->capital = GETPOST('capital'); $object->idprof1 = GETPOST('idprof1'); $object->idprof2 = GETPOST('idprof2'); $object->idprof3 = GETPOST('idprof3'); $object->idprof4 = GETPOST('idprof4'); $object->typent_id = GETPOST('typent_id'); $object->effectif_id = GETPOST('effectif_id'); $object->barcode = GETPOST('barcode'); $object->forme_juridique_code = GETPOST('forme_juridique_code'); $object->default_lang = GETPOST('default_lang'); $object->tva_assuj = GETPOST('assujtva_value'); $object->tva_intra = GETPOST('tva_intra'); $object->Status = GETPOST('status'); //Local Taxes $object->localtax1_assuj = GETPOST('localtax1assuj_value'); $object->localtax2_assuj = GETPOST('localtax2assuj_value'); } dol_htmloutput_errors($error, $errors); if ($conf->use_javascript_ajax) { print "\n" . '<script type="text/javascript" language="javascript">'; print '$(document).ready(function () { $("#selectcountry_id").change(function() { document.formsoc.action.value="edit"; document.formsoc.submit(); }); })'; print '</script>' . "\n"; } print '<form enctype="multipart/form-data" action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="post" name="formsoc">'; print '<input type="hidden" name="action" value="update">'; print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">'; print '<input type="hidden" name="socid" value="' . $object->id . '">'; if ($modCodeClient->code_auto || $modCodeFournisseur->code_auto) print '<input type="hidden" name="code_auto" value="1">'; print '<table class="border" width="100%">'; // Name print '<tr><td><span class="fieldrequired">' . $langs->trans('ThirdPartyName') . '</span></td><td colspan="3"><input type="text" size="40" maxlength="60" name="nom" value="' . $object->name . '"></td></tr>'; // Prefix if (!empty($conf->global->SOCIETE_USEPREFIX)) { // Old not used prefix field print '<tr><td>' . $langs->trans("Prefix") . '</td><td colspan="3">'; // It does not change the prefix mode using the auto numbering prefix if (($prefixCustomerIsUsed || $prefixSupplierIsUsed) && $object->prefix_comm) { print '<input type="hidden" name="prefix_comm" value="' . $object->prefix_comm . '">'; print $object->prefix_comm; } else { print '<input type="text" size="5" maxlength="5" name="prefix_comm" value="' . $object->prefix_comm . '">'; } print '</td>'; } // Prospect/Customer print '<tr><td width="25%"><span class="fieldrequired">' . $langs->trans('ProspectCustomer') . '</span></td><td width="25%"><select class="flat" name="client">'; if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) print '<option value="2"' . ($object->client == 2 ? ' selected="selected"' : '') . '>' . $langs->trans('Prospect') . '</option>'; if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) print '<option value="3"' . ($object->client == 3 ? ' selected="selected"' : '') . '>' . $langs->trans('ProspectCustomer') . '</option>'; print '<option value="1"' . ($object->client == 1 ? ' selected="selected"' : '') . '>' . $langs->trans('Customer') . '</option>'; print '<option value="0"' . ($object->client == 0 ? ' selected="selected"' : '') . '>' . $langs->trans('NorProspectNorCustomer') . '</option>'; print '</select></td>'; print '<td width="25%">' . $langs->trans('CustomerCode') . '</td><td width="25%">'; print '<table class="nobordernopadding"><tr><td>'; if ((!$object->code_client || $object->code_client == -1) && $modCodeClient->code_auto) { $tmpcode = $object->code_client; if (empty($tmpcode) && $modCodeClient->code_auto) $tmpcode = $modCodeClient->getNextValue($object, 0); print '<input type="text" name="code_client" size="16" value="' . $tmpcode . '" maxlength="15">'; } else if ($object->codeclient_modifiable()) { print '<input type="text" name="code_client" size="16" value="' . $object->code_client . '" maxlength="15">'; } else { print $object->code_client; print '<input type="hidden" name="code_client" value="' . $object->code_client . '">'; } print '</td><td>'; $s = $modCodeClient->getToolTip($langs, $object, 0); print $form->textwithpicto('', $s, 1); print '</td></tr></table>'; print '</td></tr>'; // Supplier if (!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire)) { print '<tr>'; print '<td><span class="fieldrequired">' . $langs->trans('Supplier') . '</span></td><td>'; print $form->selectyesno("fournisseur", $object->fournisseur, 1); print '</td>'; print '<td>' . $langs->trans('SupplierCode') . '</td><td>'; print '<table class="nobordernopadding"><tr><td>'; if ((!$object->code_fournisseur || $object->code_fournisseur == -1) && $modCodeFournisseur->code_auto) { $tmpcode = $object->code_fournisseur; if (empty($tmpcode) && $modCodeFournisseur->code_auto) $tmpcode = $modCodeFournisseur->getNextValue($object, 1); print '<input type="text" name="code_fournisseur" size="16" value="' . $tmpcode . '" maxlength="15">'; } else if ($object->codefournisseur_modifiable()) { print '<input type="text" name="code_fournisseur" size="16" value="' . $object->code_fournisseur . '" maxlength="15">'; } else { print $object->code_fournisseur; print '<input type="hidden" name="code_fournisseur" value="' . $object->code_fournisseur . '">'; } print '</td><td>'; $s = $modCodeFournisseur->getToolTip($langs, $object, 1); print $form->textwithpicto('', $s, 1); print '</td></tr></table>'; print '</td></tr>'; // Category if (!empty($conf->categorie->enabled) && $object->fournisseur) { $load = $object->LoadSupplierCateg(); if ($load == 0) { if (count($object->SupplierCategories) > 0) { print '<tr>'; print '<td>' . $langs->trans('SupplierCategory') . '</td><td colspan="3">'; print $form->selectarray("fournisseur_categorie", $object->SupplierCategories, '', 1); print '</td></tr>'; } } } } // Barcode if (!empty($conf->barcode->enabled)) { print '<tr><td valign="top">' . $langs->trans('Gencod') . '</td><td colspan="3"><input type="text" name="barcode" value="' . $object->barcode . '">'; print '</td></tr>'; } // Status print '<tr><td>' . $langs->trans("Status") . '</td><td colspan="3">'; print $object->select_fk_extrafields("Status", 'status'); print '</td></tr>'; // Address print '<tr><td valign="top">' . $langs->trans('Address') . '</td><td colspan="3"><textarea name="adresse" cols="40" rows="3" wrap="soft">'; print $object->address; print '</textarea></td></tr>'; // Zip / Town print '<tr><td>' . $langs->trans('Zip') . '</td><td>'; print $formcompany->select_ziptown($object->zip, 'zipcode', array('town', 'selectcountry_id', 'departement_id'), 6); print '</td><td>' . $langs->trans('Town') . '</td><td>'; print $formcompany->select_ziptown($object->town, 'town', array('zipcode', 'selectcountry_id', 'departement_id')); print '</td></tr>'; // Country print '<tr><td>' . $langs->trans('Country') . '</td><td colspan="3">'; print $object->select_fk_extrafields("country_id", 'country_id'); if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionnarySetup"), 1); print '</td></tr>'; // State if (empty($conf->global->SOCIETE_DISABLE_STATE)) { print '<tr><td>' . $langs->trans('State') . '</td><td colspan="3">'; print $object->select_fk_extrafields("state_id", "departement_id"); print '</td></tr>'; } // Phone / Fax print '<tr><td>' . $langs->trans('Phone') . '</td><td><input type="text" name="phone" value="' . $object->phone . '"></td>'; print '<td>' . $langs->trans('Fax') . '</td><td><input type="text" name="fax" value="' . $object->fax . '"></td></tr>'; // EMail / Web print '<tr><td>' . $langs->trans('EMail') . ($conf->global->SOCIETE_MAIL_REQUIRED ? '*' : '') . '</td><td><input type="text" name="email" size="32" value="' . $object->email . '"></td>'; print '<td>' . $langs->trans('Web') . '</td><td><input type="text" name="url" size="32" value="' . $object->url . '"></td></tr>'; // Prof ids $i = 1; $j = 0; while ($i <= 6) { $idprof = $langs->transcountry('ProfId' . $i, $object->country_id); if ($idprof != '-') { if (($j % 2) == 0) print '<tr>'; print '<td>' . $idprof . '</td><td>'; $key = 'idprof' . $i; print $formcompany->get_input_id_prof($i, 'idprof' . $i, $object->$key, $object->country_id); print '</td>'; if (($j % 2) == 1) print '</tr>'; $j++; } $i++; } if ($j % 2 == 1) print '<td colspan="2"></td></tr>'; // VAT payers print '<tr><td>' . $langs->trans('VATIsUsed') . '</td><td>'; print $form->selectyesno('assujtva_value', $object->tva_assuj, 1); print '</td>'; // VAT Code print '<td nowrap="nowrap">' . $langs->trans('VATIntra') . '</td>'; print '<td nowrap="nowrap">'; $s = '<input type="text" class="flat" name="tva_intra" size="12" maxlength="20" value="' . $object->tva_intra . '">'; if (empty($conf->global->MAIN_DISABLEVATCHECK)) { $s.=' &nbsp; '; if ($conf->use_javascript_ajax) { print "\n"; print '<script language="JavaScript" type="text/javascript">'; print "function CheckVAT(a) {\n"; print "newpopup('" . DOL_URL_ROOT . "/societe/checkvat/checkVatPopup.php?vatNumber='+a,'" . dol_escape_js($langs->trans("VATIntraCheckableOnEUSite")) . "',500,285);\n"; print "}\n"; print '</script>'; print "\n"; $s.='<a href="#" onclick="javascript: CheckVAT(document.formsoc.tva_intra.value);">' . $langs->trans("VATIntraCheck") . '</a>'; $s = $form->textwithpicto($s, $langs->trans("VATIntraCheckDesc", $langs->trans("VATIntraCheck")), 1); } else { $s.='<a href="' . $langs->transcountry("VATIntraCheckURL", $object->id_pays) . '" target="_blank">' . img_picto($langs->trans("VATIntraCheckableOnEUSite"), 'help') . '</a>'; } } print $s; print '</td>'; print '</tr>'; // Local Taxes // TODO add specific function by country if ($mysoc->country_id == 'ES') { if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") { print '<tr><td>' . $langs->trans("LocalTax1IsUsedES") . '</td><td>'; print $form->selectyesno('localtax1assuj_value', $object->localtax1_assuj, 1); print '</td><td>' . $langs->trans("LocalTax2IsUsedES") . '</td><td>'; print $form->selectyesno('localtax2assuj_value', $object->localtax2_assuj, 1); print '</td></tr>'; } elseif ($mysoc->localtax1_assuj == "1") { print '<tr><td>' . $langs->trans("LocalTax1IsUsedES") . '</td><td colspan="3">'; print $form->selectyesno('localtax1assuj_value', $object->localtax1_assuj, 1); print '</td></tr>'; } elseif ($mysoc->localtax2_assuj == "1") { print '<tr><td>' . $langs->trans("LocalTax2IsUsedES") . '</td><td colspan="3">'; print $form->selectyesno('localtax2assuj_value', $object->localtax2_assuj, 1); print '</td></tr>'; } } // Type - Size print '<tr><td>' . $langs->trans("ThirdPartyType") . '</td><td>'; print $object->select_fk_extrafields("typent_id", "typent_id"); if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionnarySetup"), 1); print '</td>'; print '<td>' . $langs->trans("Staff") . '</td><td>'; print $object->select_fk_extrafields("effectif_id", "effectif_id"); if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionnarySetup"), 1); print '</td></tr>'; // Juridical status print '<tr><td>' . $langs->trans('JuridicalStatus') . '</td><td colspan="3">'; print $object->select_fk_extrafields("forme_juridique_code", "forme_juridique_code"); print '</td></tr>'; // Capital print '<tr><td>' . $langs->trans("Capital") . '</td><td colspan="3"><input type="text" name="capital" size="10" value="' . $object->capital . '"> ' . $langs->trans("Currency" . $conf->currency) . '</td></tr>'; // Default language if (!empty($conf->global->MAIN_MULTILANGS)) { print '<tr><td>' . $langs->trans("DefaultLang") . '</td><td colspan="3">' . "\n"; print $formadmin->select_language($object->default_lang, 'default_lang', 0, 0, 1); print '</td>'; print '</tr>'; } // Other attributes /* $parameters = array('colspan' => ' colspan="3"'); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook if (empty($reshook)) { foreach ($object->fk_extrafields->fields as $key => $aRow) { if ($aRow->optional && $aRow->enable) { $value = (isset($_POST["options_" . $key]) ? $_POST["options_" . $key] : (isset($object->array_options["options_" . $key]) ? $object->array_options["options_" . $key] : '')); print '<tr><td><strong class="blue">' . $aRow->label . '</strong></td><td colspan="3">'; print $object->fk_extrafields->showInputField($key, $value); print '</td></tr>' . "\n"; } } } */ // Logo print '<tr>'; print '<td>' . $langs->trans("Logo") . '</td>'; print '<td colspan="3">'; if ($object->logo) print $form->showphoto('societe', $object, 50); $caneditfield = 1; if ($caneditfield) { if ($object->logo) print "<br>\n"; print '<table class="nobordernopadding">'; if ($object->logo) print '<tr><td><input type="checkbox" class="flat" name="deletephoto" id="photodelete"> ' . $langs->trans("Delete") . '<br><br></td></tr>'; //print '<tr><td>'.$langs->trans("PhotoFile").'</td></tr>'; print '<tr><td><input type="file" class="flat" name="photo" id="photoinput"></td></tr>'; print '</table>'; } print '</td>'; print '</tr>'; print '</table>'; print '<br>'; print '<center>'; print '<input type="submit" class="button" name="save" value="' . $langs->trans("Save") . '">'; print ' &nbsp; &nbsp; '; print '<input type="submit" class="button" name="cancel" value="' . $langs->trans("Cancel") . '">'; print '</center>'; print '</form>'; print column_end(); print '</div></div>'; } } else { /* * View */ $object = new Societe($db); $object->load($socid); //$res = $object->fetch_optionals($object->id, $extralabels); //if ($res < 0) { dol_print_error($db); exit; } print_fiche_titre($object->name); print '<div class="with-padding">'; print '<div class="columns">'; $titre = $langs->trans("ThirdParty"); print column_start("twelve"); dol_fiche_head($head, 'card', $langs->trans("ThirdParty"), 0, 'company'); // Confirm delete third party if ($action == 'delete' || $conf->use_javascript_ajax) { $form = new Form($db); $ret = $form->form_confirm($_SERVER["PHP_SELF"] . "?id=" . $object->id, $langs->trans("DeleteACompany"), $langs->trans("ConfirmDeleteCompany"), "confirm_delete", '', 0, "action-delete"); if ($ret == 'html') print '<br>'; } dol_htmloutput_errors($error, $errors); $showlogo = $object->logo; $showbarcode = (!empty($conf->barcode->enabled) && $user->rights->barcode->lire); print '<table class="border" width="100%">'; // Ref print '<tr><td width="20%">' . $langs->trans('Ref') . '</td>'; print '<td colspan="3">'; print $form->showrefnav($object, 'id', '', ($user->societe_id ? 0 : 1), 'rowid', 'nom'); print '</td>'; print '</tr>'; // Name print '<tr><td width="20%">' . $langs->trans('ThirdPartyName') . '</td>'; print '<td colspan="3">'; print $object->name; print '</td>'; print '</tr>'; // Logo+barcode $rowspan = 4; if (!empty($conf->global->SOCIETE_USEPREFIX)) $rowspan++; if (!empty($object->client)) $rowspan++; if (!empty($conf->fournisseur->enabled) && $object->fournisseur && !empty($user->rights->fournisseur->lire)) $rowspan++; if (!empty($conf->barcode->enabled)) $rowspan++; if (empty($conf->global->SOCIETE_DISABLE_STATE)) $rowspan++; $htmllogobar = ''; if ($showlogo || $showbarcode) { $htmllogobar.='<td rowspan="' . $rowspan . '" style="text-align: center;" width="25%">'; if ($showlogo) $htmllogobar.=$form->showphoto('societe', $object, 50); if ($showlogo && $showbarcode) $htmllogobar.='<br><br>'; if ($showbarcode) $htmllogobar.=$form->showbarcode($object, 50); $htmllogobar.='</td>'; } // Prefix if (!empty($conf->global->SOCIETE_USEPREFIX)) { // Old not used prefix field print '<tr><td>' . $langs->trans('Prefix') . '</td><td colspan="' . (2 + (($showlogo || $showbarcode) ? 0 : 1)) . '">' . $object->prefix_comm . '</td>'; print $htmllogobar; $htmllogobar = ''; print '</tr>'; } // Customer code print '<tr><td nowrap>'; print $langs->trans('CustomerCode') . '</td><td>'; print $object->code_client; if ($object->check_codeclient() <> 0) print ' <font class="error">(' . $langs->trans("WrongCustomerCode") . ')</font>'; print '</td>'; print '<td>'; print $form->editfieldkey("CustomerAccountancyCode", 'customeraccountancycode', $object->code_compta, $object, $user->rights->societe->creer); print '</td><td colspan="' . ((($showlogo || $showbarcode) ? 0 : 1)) . '">'; print $form->editfieldval("CustomerAccountancyCode", 'customeraccountancycode', $object->code_compta, $object, $user->rights->societe->creer); print '</td>'; print $htmllogobar; $htmllogobar = ''; print '</tr>'; // Supplier code if (!empty($conf->fournisseur->enabled) && $object->fournisseur && !empty($user->rights->fournisseur->lire)) { print '<tr><td>'; print $langs->trans('SupplierCode') . '</td><td>'; print $object->code_fournisseur; if ($object->check_codefournisseur() <> 0) print ' <font class="error">(' . $langs->trans("WrongSupplierCode") . ')</font>'; print '<td>'; print $form->editfieldkey("SupplierAccountancyCode", 'code_compta_fournisseur', $object->code_compta_fournisseur, $object, $user->rights->societe->creer); print '</td><td colspan="' . ((($showlogo || $showbarcode) ? 0 : 1)) . '">'; print $form->editfieldval("SupplierAccountancyCode", 'code_compta_fournisseur', $object->code_compta_fournisseur, $object, $user->rights->societe->creer); print '</td>'; print $htmllogobar; $htmllogobar = ''; print '</tr>'; } // Barcode if (!empty($conf->barcode->enabled)) { print '<tr><td>'; print $langs->trans('Gencod') . '</td><td colspan="' . (2 + (($showlogo || $showbarcode) ? 0 : 1)) . '">' . $object->barcode; print '</td>'; print $htmllogobar; $htmllogobar = ''; print '</tr>'; } // Status print '<tr><td>' . $form->editfieldkey("Status", 'Status', $object->Status, $object, $user->rights->societe->creer, "select") . '</td>'; print '<td>'; print $form->editfieldval("Status", 'Status', $object->Status, $object, $user->rights->societe->creer, "select"); print '</td>'; // Potential print '<td>' . $form->editfieldkey("ProspectLevelShort", 'prospectlevel', $object->prospectlevel, $object, $user->rights->societe->creer, "select") . '</td>'; print '<td colspan="' . ((($showlogo || $showbarcode) ? 0 : 1)) . '">'; print $form->editfieldval("ProspectLevelShort", 'prospectlevel', $object->prospectlevel, $object, $user->rights->societe->creer, "select"); print '</td>'; print $htmllogobar; $htmllogobar = ''; print '</tr>'; // Address print "<tr><td valign=\"top\">" . $langs->trans('Address') . '</td><td colspan="' . (2 + (($showlogo || $showbarcode) ? 0 : 1)) . '">'; print dol_print_address($object->address, 'gmap', 'thirdparty', $object->id, is_array($object->gps)); print "</td></tr>"; // Zip / Town print '<tr><td width="25%">' . $langs->trans('Zip') . ' / ' . $langs->trans("Town") . '</td><td colspan="' . (2 + (($showlogo || $showbarcode) ? 0 : 1)) . '">'; print $object->zip . ($object->zip && $object->town ? " / " : "") . $object->town; print "</td>"; print '</tr>'; // Country print '<tr><td>' . $langs->trans("Country") . '</td><td colspan="' . (2 + (($showlogo || $showbarcode) ? 0 : 1)) . '" nowrap="nowrap">'; $img = picto_from_langcode($object->country_id); if ($object->isInEEC()) print $form->textwithpicto(($img ? $img . ' ' : '') . $object->country_id, $langs->trans("CountryIsInEEC"), 1, 0); else print ($img ? $img . ' ' : '') . $object->print_fk_extrafields("country_id"); print '</td></tr>'; // State if (empty($conf->global->SOCIETE_DISABLE_STATE)) print '<tr><td>' . $langs->trans('State') . '</td><td colspan="' . (2 + (($showlogo || $showbarcode) ? 0 : 1)) . '">' . $object->print_fk_extrafields("state_id") . '</td>'; print '<tr><td>' . $langs->trans('Phone') . '</td><td style="min-width: 25%;">' . dol_print_phone($object->phone, $object->country_id, 0, $object->id, 'AC_TEL') . '</td>'; print '<td>' . $langs->trans('Fax') . '</td><td style="min-width: 25%;">' . dol_print_phone($object->fax, $object->country_id, 0, $object->id, 'AC_FAX') . '</td></tr>'; // Zone Geo print '<tr><td>' . $form->editfieldkey("zonegeo", 'zonegeo', $object->zonegeo, $object, $user->rights->societe->creer) . '</td>'; print '<td colspan="' . (2 + (($showlogo || $showbarcode) ? 0 : 1)) . '">'; print $form->editfieldval("zonegeo", 'zonegeo', $object->zonegeo, $object, $user->rights->societe->creer); print '</td>'; // EMail print '<tr><td>' . $langs->trans('EMail') . '</td><td width="25%">'; print dol_print_email($object->email, 0, $object->id, 'AC_EMAIL'); print '</td>'; // Web print '<td>' . $langs->trans('Web') . '</td><td>'; print dol_print_url($object->url); print '</td></tr>'; // Prof ids $i = 1; $j = 0; while ($i <= 6) { $idprof = $langs->transcountry('ProfId' . $i, $object->country_id); if ($idprof != '-') { if (($j % 2) == 0) print '<tr>'; print '<td>' . $idprof . '</td><td>'; $key = 'idprof' . $i; print $object->$key; if ($object->$key) { if ($object->id_prof_check($i, $object) > 0) print ' &nbsp; ' . $object->id_prof_url($i, $object); else print ' <font class="error">(' . $langs->trans("ErrorWrongValue") . ')</font>'; } print '</td>'; if (($j % 2) == 1) print '</tr>'; $j++; } $i++; } if ($j % 2 == 1) print '<td colspan="2"></td></tr>'; // VAT payers $form = new Form($db); print '<tr><td>'; print $langs->trans('VATIsUsed'); print '</td><td>'; print yn($object->tva_assuj); print '</td>'; // VAT Code print '<td nowrap="nowrap">' . $langs->trans('VATIntra') . '</td><td>'; if ($object->tva_intra) { $s = ''; $s.=$object->tva_intra; $s.='<input type="hidden" id="tva_intra" name="tva_intra" size="12" maxlength="20" value="' . $object->tva_intra . '">'; if (empty($conf->global->MAIN_DISABLEVATCHECK)) { $s.=' &nbsp; '; if ($conf->use_javascript_ajax) { print "\n"; print '<script language="JavaScript" type="text/javascript">'; print "function CheckVAT(a) {\n"; print "newpopup('" . DOL_URL_ROOT . "/societe/checkvat/checkVatPopup.php?vatNumber='+a,'" . dol_escape_js($langs->trans("VATIntraCheckableOnEUSite")) . "',500,285);\n"; print "}\n"; print '</script>'; print "\n"; $s.='<a href="#" onclick="javascript: CheckVAT( $(\'#tva_intra\').val() );">' . $langs->trans("VATIntraCheck") . '</a>'; $s = $form->textwithpicto($s, $langs->trans("VATIntraCheckDesc", $langs->trans("VATIntraCheck")), 1); } else { $s.='<a href="' . $langs->transcountry("VATIntraCheckURL", $object->id_pays) . '" target="_blank">' . img_picto($langs->trans("VATIntraCheckableOnEUSite"), 'help') . '</a>'; } } print $s; } else { print '&nbsp;'; } print '</td>'; print '</tr>'; // Local Taxes // TODO add specific function by country if ($mysoc->country_id == 'ES') { if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") { print '<tr><td>' . $langs->trans("LocalTax1IsUsedES") . '</td><td>'; print yn($object->localtax1_assuj); print '</td><td>' . $langs->trans("LocalTax2IsUsedES") . '</td><td>'; print yn($object->localtax2_assuj); print '</td></tr>'; } elseif ($mysoc->localtax1_assuj == "1") { print '<tr><td>' . $langs->trans("LocalTax1IsUsedES") . '</td><td colspan="3">'; print yn($object->localtax1_assuj); print '</td><tr>'; } elseif ($mysoc->localtax2_assuj == "1") { print '<tr><td>' . $langs->trans("LocalTax2IsUsedES") . '</td><td colspan="3">'; print yn($object->localtax2_assuj); print '</td><tr>'; } } // Type + Staff $arr = $formcompany->typent_array(1); $object->typent = $arr[$object->typent_code]; print '<tr><td>' . $langs->trans("ThirdPartyType") . '</td><td>' . $object->print_fk_extrafields("typent_id") . '</td><td>' . $langs->trans("Staff") . '</td><td>' . $object->print_fk_extrafields("effectif_id") . '</td></tr>'; // Legal print '<tr><td>' . $langs->trans('JuridicalStatus') . '</td><td colspan="3">' . $object->print_fk_extrafields("forme_juridique_code") . '</td></tr>'; // Capital print '<tr><td>' . $langs->trans('Capital') . '</td><td colspan="3">'; if ($object->capital) print $object->capital . ' ' . $langs->trans("Currency" . $conf->currency); else print '&nbsp;'; print '</td></tr>'; // Default language if (!empty($conf->global->MAIN_MULTILANGS)) { require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php'; print '<tr><td>' . $langs->trans("DefaultLang") . '</td><td colspan="3">'; //$s=picto_from_langcode($object->default_lang); //print ($s?$s.' ':''); $langs->load("languages"); $labellang = ($object->default_lang ? $langs->trans('Language_' . $object->default_lang) : ''); print $labellang; print '</td></tr>'; } // Price level if ($conf->product->enabled || $conf->service->enabled) { print '<tr><td>' . $form->editfieldkey("PriceLevel", 'price_level', $object->price_level, $object, $user->rights->societe->creer, "select") . '</td><td colspan="' . (2 + (($showlogo || $showbarcode) ? 0 : 1)) . '">'; print $form->editfieldval("PriceLevel", 'price_level', $object->price_level, $object, $user->rights->societe->creer, "select"); print "</td></tr>"; } // Tag print '<tr><td>' . $form->editfieldkey("Categories", 'Tag', $object->Tag, $object, $user->rights->societe->creer, "tag") . '</td><td colspan="' . (2 + (($showlogo || $showbarcode) ? 0 : 1)) . '">'; print $form->editfieldval("Categories", 'Tag', $object->Tag, $object, $user->rights->societe->creer, "tag"); print "</td></tr>"; // Other attributes $parameters = array('socid' => $socid, 'colspan' => ' colspan="3"'); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook if (empty($reshook)) { foreach ($object->fk_extrafields->fields as $key => $aRow) { if ($aRow->optional && $aRow->enable) { print '<tr><td><strong class="blue">' . $form->editfieldkey($aRow->label, $key, $object->$key, $object, $user->rights->societe->creer, $aRow->type) . '</strong></td><td colspan="3">'; print $form->editfieldval($aRow->label, $key, $object->$key, $object, $user->rights->societe->creer, $aRow->type); print '</td></tr>' . "\n"; } } } // Ban if (empty($conf->global->SOCIETE_DISABLE_BANKACCOUNT)) { print '<tr><td>'; print '<table width="100%" class="nobordernopadding"><tr><td>'; print $langs->trans('RIB'); print '<td><td align="right">'; if ($user->rights->societe->creer) print '<a href="' . DOL_URL_ROOT . '/societe/rib.php?id=' . $object->id . '">' . img_edit() . '</a>'; else print '&nbsp;'; print '</td></tr></table>'; print '</td>'; print '<td colspan="3">'; print $object->display_rib(); print '</td></tr>'; } // Conditions de reglement par defaut print '<tr><td>' . $form->editfieldkey("PaymentConditions", 'cond_reglement', $object->cond_reglement, $object, $user->rights->societe->creer, "select") . '</td><td colspan="' . (2 + (($showlogo || $showbarcode) ? 0 : 1)) . '">'; print $form->editfieldval("PaymentConditions", 'cond_reglement', $object->cond_reglement, $object, $user->rights->societe->creer, "select"); print "</td></tr>"; // Mode de reglement par defaut print '<tr><td>' . $form->editfieldkey("PaymentMode", 'mode_reglement', $object->mode_reglement, $object, $user->rights->societe->creer, "select") . '</td><td colspan="' . (2 + (($showlogo || $showbarcode) ? 0 : 1)) . '">'; print $form->editfieldval("PaymentMode", 'mode_reglement', $object->mode_reglement, $object, $user->rights->societe->creer, "select"); print "</td></tr>"; // Relative discounts (Discounts-Drawbacks-Rebates) print '<tr><td>' . $form->editfieldkey("CustomerRelativeDiscountShort", 'remise_client', $object->remise_client, $object, $user->rights->societe->creer, "numeric") . '</td><td colspan="' . (2 + (($showlogo || $showbarcode) ? 0 : 1)) . '">'; print $form->editfieldval("CustomerRelativeDiscountShort", 'remise_client', $object->remise_client, $object, $user->rights->societe->creer, "numeric"); print "</td></tr>"; // Absolute discounts (Discounts-Drawbacks-Rebates) /* print '<tr><td nowrap>'; print '<table width="100%" class="nobordernopadding">'; print '<tr><td nowrap>'; print $langs->trans("CustomerAbsoluteDiscountShort"); print '<td><td align="right">'; if ($user->rights->societe->creer && !$user->societe_id > 0) { print '<a href="' . DOL_URL_ROOT . '/comm/remx.php?id=' . $object->id . '&backtopage=' . urlencode($_SERVER["PHP_SELF"] . '?socid=' . $object->id) . '">' . img_edit($langs->trans("Modify")) . '</a>'; } print '</td></tr></table>'; print '</td>'; print '<td colspan="3">'; $amount_discount = $object->getAvailableDiscounts(); if ($amount_discount < 0) dol_print_error($db, $object->error); if ($amount_discount > 0) print '<a href="' . DOL_URL_ROOT . '/comm/remx.php?id=' . $object->id . '&backtopage=' . urlencode($_SERVER["PHP_SELF"] . '?socid=' . $object->id) . '">' . price($amount_discount) . '</a>&nbsp;' . $langs->trans("Currency" . $conf->currency); else print $langs->trans("DiscountNone"); print '</td>'; print '</tr>'; */ // Sales representative print '<tr><td>' . $form->editfieldkey("SalesRepresentatives", 'commercial_id', $object->commercial_id->name, $object, $user->rights->societe->creer, "select") . '</td><td colspan="' . (2 + (($showlogo || $showbarcode) ? 0 : 1)) . '">'; print $form->editfieldval("SalesRepresentatives", 'commercial_id', $object->commercial_id->name, $object, $user->rights->societe->creer, "select"); print "</td></tr>"; // Module Adherent if (!empty($conf->adherent->enabled)) { $langs->load("members"); print '<tr><td width="25%" valign="top">' . $langs->trans("LinkedToSpeedealingMember") . '</td>'; print '<td colspan="3">'; $adh = new Adherent($db); $result = $adh->fetch('', '', $object->id); if ($result > 0) { $adh->ref = $adh->getFullName($langs); print $adh->getNomUrl(1); } else { print $langs->trans("UserNotLinkedToMember"); } print '</td>'; print "</tr>\n"; } print '</table>'; /* * Actions */ print '<div class="tabsAction">' . "\n"; print '<div class="button-height">'; print '<span class="button-group">'; if ($user->rights->societe->creer) { print '<a class="button icon-pencil" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&amp;action=edit">' . $langs->trans("Modify") . '</a>' . "\n"; } if ($user->rights->societe->supprimer) { if ($conf->use_javascript_ajax) { print '<span id="action-delete" class="button icon-trash red-gradient">' . $langs->trans('Delete') . '</span>' . "\n"; } else { print '<a class="button icon-trash red-gradient" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&amp;action=delete">' . $langs->trans('Delete') . '</a>' . "\n"; } } print "</span>"; print "</div>"; print '</div>'; print '</div>'; print column_end(); print column_start("six"); // Print Notes print $object->show_notes(); print column_end(); if ($conf->propal->enabled) { require_once(DOL_DOCUMENT_ROOT . '/propal/class/propal.class.php'); $propal = new Propal($db); print column_start("six"); $propal->show($object->id); print column_end(); } if ($conf->commande->enabled) { require_once(DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php'); $commande = new Commande($db); print column_start("six"); $commande->show($object->id); print column_end(); } if ($conf->facture->enabled) { require_once(DOL_DOCUMENT_ROOT . '/facture/class/facture.class.php'); $facture = new Facture($db); print column_start("six"); $facture->show($object->id); print column_end(); } if ($conf->ecm->enabled) { // Generated documents $filedir = $conf->societe->multidir_output[$object->entity] . '/' . $object->id; $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; $genallowed = $user->rights->societe->creer; $delallowed = $user->rights->societe->supprimer; $var = true; print column_start("six"); $somethingshown = $formfile->show_documents('company', $object->id, $filedir, $urlsource, $genallowed, $delallowed, '', 0, 0, 0, 28, 0, '', 0, '', $object->default_lang); print column_end(); } // Subsidiaries list //$result = show_subsidiaries($conf, $langs, $db, $object); // Contacts list print column_start("six"); $contact->show(25, $object->id); print column_end(); //$result = show_contacts($conf, $langs, $db, $object, $_SERVER["PHP_SELF"] . '?id=' . $object->id); // Show actions // TODO use hookmanager for show box of anothers modules for avoid multiple declarations // Other attributes $parameters = array(); $reshook = $hookmanager->executeHooks('show', $parameters, $object, $action); // Note that $action and $object may have been modified by hook if ($conf->agenda->enabled) { $cal = new Agenda($db); print column_start("six"); $cal->show($object->id, 25); print column_end(); } // Addresses list // TODO replace with show method //$result = show_addresses($conf, $langs, $db, $object, $_SERVER["PHP_SELF"] . '?id=' . $object->id); // Projects list // TODO replace with show method //$result = show_projects($conf, $langs, $db, $object, $_SERVER["PHP_SELF"] . '?id=' . $object->id); print '</div></div>'; } } // End of page llxFooter(); ?>
gpl-3.0
rreddy70/openemr
interface/forms/newpatient/common.php
14116
<?php // 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. require_once("$srcdir/options.inc.php"); $months = array("01","02","03","04","05","06","07","08","09","10","11","12"); $days = array("01","02","03","04","05","06","07","08","09","10","11","12","13","14", "15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31"); $thisyear = date("Y"); $years = array($thisyear-1, $thisyear, $thisyear+1, $thisyear+2); if ($viewmode) { $id = $_REQUEST['id']; $result = sqlQuery("SELECT * FROM form_encounter WHERE id = '$id'"); $encounter = $result['encounter']; if ($result['sensitivity'] && !acl_check('sensitivities', $result['sensitivity'])) { echo "<body>\n<html>\n"; echo "<p>" . xl('You are not authorized to see this encounter.') . "</p>\n"; echo "</body>\n</html>\n"; exit(); } } // Sort comparison for sensitivities by their order attribute. function sensitivity_compare($a, $b) { return ($a[2] < $b[2]) ? -1 : 1; } // get issues $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " . "pid = $pid AND enddate IS NULL " . "ORDER BY type, begdate"); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <?php html_header_show();?> <title><?php xl('Patient Encounter','e'); ?></title> <link rel="stylesheet" href="<?php echo $css_header;?>" type="text/css"> <link rel="stylesheet" type="text/css" href="<?php echo $GLOBALS['webroot'] ?>/library/js/fancybox-1.3.4/jquery.fancybox-1.3.4.css" media="screen" /> <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/js/jquery-1.4.3.min.js"></script> <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/js/common.js"></script> <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/js/fancybox-1.3.4/jquery.fancybox-1.3.4.pack.js"></script> <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/dialog.js"></script> <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/overlib_mini.js"></script> <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/textformat.js"></script> <!-- pop up calendar --> <style type="text/css">@import url(<?php echo $GLOBALS['webroot'] ?>/library/dynarch_calendar.css);</style> <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/dynarch_calendar.js"></script> <?php include_once("{$GLOBALS['srcdir']}/dynarch_calendar_en.inc.php"); ?> <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/dynarch_calendar_setup.js"></script> <?php include_once("{$GLOBALS['srcdir']}/ajax/facility_ajax_jav.inc.php"); ?> <script language="JavaScript"> var mypcc = '<?php echo $GLOBALS['phone_country_code'] ?>'; // Process click on issue title. function newissue() { dlgopen('../../patient_file/summary/add_edit_issue.php', '_blank', 800, 600); return false; } // callback from add_edit_issue.php: function refreshIssue(issue, title) { var s = document.forms[0]['issues[]']; s.options[s.options.length] = new Option(title, issue, true, true); } function saveClicked() { var f = document.forms[0]; <?php if (!$GLOBALS['athletic_team']) { ?> var category = document.forms[0].pc_catid.value; if ( category == '_blank' ) { alert("<?php echo xl('You must select a visit category'); ?>"); return; } <?php } ?> <?php if (false /* $GLOBALS['ippf_specific'] */) { // ippf decided not to do this ?> if (f['issues[]'].selectedIndex < 0) { if (!confirm('There is no issue selected. If this visit relates to ' + 'contraception or abortion, click Cancel now and then select or ' + 'create the appropriate issue. Otherwise you can click OK.')) { return; } } <?php } ?> top.restoreSession(); f.submit(); } $(document).ready(function(){ enable_big_modals(); }); function bill_loc(){ var pid=<?php echo $pid;?>; var dte=document.getElementById('form_date').value; var facility=document.forms[0].facility_id.value; ajax_bill_loc(pid,dte,facility); } </script> </head> <?php if ($viewmode) { ?> <body class="body_top"> <?php } else { ?> <body class="body_top" onload="javascript:document.new_encounter.reason.focus();"> <?php } ?> <!-- Required for the popup date selectors --> <div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"></div> <form method='post' action="<?php echo $rootdir ?>/forms/newpatient/save.php" name='new_encounter' <?php if (!$GLOBALS['concurrent_layout']) echo "target='Main'"; ?>> <div style = 'float:left'> <?php if ($viewmode) { ?> <input type=hidden name='mode' value='update'> <input type=hidden name='id' value='<?php echo $_GET["id"] ?>'> <span class=title><?php xl('Patient Encounter Form','e'); ?></span> <?php } else { ?> <input type='hidden' name='mode' value='new'> <span class='title'><?php xl('New Encounter Form','e'); ?></span> <?php } ?> </div> <div> <div style = 'float:left; margin-left:8px;margin-top:-3px'> <a href="javascript:saveClicked();" class="css_button link_submit"><span><?php xl('Save','e'); ?></span></a> <?php if ($viewmode || !isset($_GET["autoloaded"]) || $_GET["autoloaded"] != "1") { ?> </div> <div style = 'float:left; margin-top:-3px'> <?php if ($GLOBALS['concurrent_layout']) { ?> <a href="<?php echo "$rootdir/patient_file/encounter/encounter_top.php"; ?>" class="css_button link_submit" onClick="top.restoreSession()"><span><?php xl('Cancel','e'); ?></span></a> <?php } else { ?> <a href="<?php echo "$rootdir/patient_file/encounter/patient_encounter.php"; ?>" class="css_button link_submit" target='Main' onClick="top.restoreSession()"> <span><?php xl('Cancel','e'); ?>]</span></a> <?php } // end not concurrent layout ?> <?php } // end not autoloading ?> </div> </div> <br> <br> <table width='96%'> <tr> <td width='33%' nowrap class='bold'><?php xl('Consultation Brief Description','e'); ?>:</td> <td width='34%' rowspan='2' align='center' valign='center' class='text'> <table> <tr<?php if ($GLOBALS['athletic_team']) echo " style='visibility:hidden;'"; ?>> <td class='bold' nowrap><?php xl('Visit Category:','e'); ?></td> <td class='text'> <select name='pc_catid' id='pc_catid'> <option value='_blank'>-- Select One --</option> <?php $cres = sqlStatement("SELECT pc_catid, pc_catname " . "FROM openemr_postcalendar_categories ORDER BY pc_catname"); while ($crow = sqlFetchArray($cres)) { $catid = $crow['pc_catid']; if ($catid < 9 && $catid != 5) continue; echo " <option value='$catid'"; if ($viewmode && $crow['pc_catid'] == $result['pc_catid']) echo " selected"; echo ">" . xl_appt_category($crow['pc_catname']) . "</option>\n"; } ?> </select> </td> </tr> <tr> <td class='bold' nowrap><?php xl('Facility:','e'); ?></td> <td class='text'> <select name='facility_id' onChange="bill_loc()"> <?php if ($viewmode) { $def_facility = $result['facility_id']; } else { $dres = sqlStatement("select facility_id from users where username = '" . $_SESSION['authUser'] . "'"); $drow = sqlFetchArray($dres); $def_facility = $drow['facility_id']; } $fres = sqlStatement("select * from facility where service_location != 0 order by name"); if ($fres) { $fresult = array(); for ($iter = 0; $frow = sqlFetchArray($fres); $iter++) $fresult[$iter] = $frow; foreach($fresult as $iter) { ?> <option value="<?php echo $iter['id']; ?>" <?php if ($def_facility == $iter['id']) echo "selected";?>><?php echo $iter['name']; ?></option> <?php } } ?> </select> </td> </tr> <tr> <td class='bold' nowrap><?php echo htmlspecialchars( xl('Billing Facility'), ENT_NOQUOTES); ?>:</td> <td class='text'> <div id="ajaxdiv"> <?php billing_facility('billing_facility',$result['billing_facility']); ?> </div> </td> </tr> <tr> <?php $sensitivities = acl_get_sensitivities(); if ($sensitivities && count($sensitivities)) { usort($sensitivities, "sensitivity_compare"); ?> <td class='bold' nowrap><?php xl('Sensitivity:','e'); ?></td> <td class='text'> <select name='form_sensitivity'> <?php foreach ($sensitivities as $value) { // Omit sensitivities to which this user does not have access. if (acl_check('sensitivities', $value[1])) { echo " <option value='" . $value[1] . "'"; if ($viewmode && $result['sensitivity'] == $value[1]) echo " selected"; echo ">" . xl($value[3]) . "</option>\n"; } } echo " <option value=''"; if ($viewmode && !$result['sensitivity']) echo " selected"; echo ">" . xl('None'). "</option>\n"; ?> </select> </td> <?php } else { ?> <td colspan='2'><!-- sensitivities not used --></td> <?php } ?> </tr> <tr<?php if (!$GLOBALS['gbl_visit_referral_source']) echo " style='visibility:hidden;'"; ?>> <td class='bold' nowrap><?php xl('Referral Source','e'); ?>:</td> <td class='text'> <?php echo generate_select_list('form_referral_source', 'refsource', $viewmode ? $result['referral_source'] : '', ''); ?> </td> </tr> <tr> <td class='bold' nowrap><?php xl('Date of Service:','e'); ?></td> <td class='text' nowrap> <input type='text' size='10' name='form_date' id='form_date' <?php echo $disabled ?> value='<?php echo $viewmode ? substr($result['date'], 0, 10) : date('Y-m-d'); ?>' title='<?php xl('yyyy-mm-dd Date of service','e'); ?>' onkeyup='datekeyup(this,mypcc)' onblur='dateblur(this,mypcc)' /> <img src='../../pic/show_calendar.gif' align='absbottom' width='24' height='22' id='img_form_date' border='0' alt='[?]' style='cursor:pointer;cursor:hand' title='<?php xl('Click here to choose a date','e'); ?>'> </td> </tr> <tr<?php if ($GLOBALS['ippf_specific'] || $GLOBALS['athletic_team']) echo " style='visibility:hidden;'"; ?>> <td class='bold' nowrap><?php xl('Onset/hosp. date:','e'); ?></td> <td class='text' nowrap><!-- default is blank so that while generating claim the date is blank. --> <input type='text' size='10' name='form_onset_date' id='form_onset_date' value='<?php echo $viewmode && $result['onset_date']!='0000-00-00 00:00:00' ? substr($result['onset_date'], 0, 10) : ''; ?>' title='<?php xl('yyyy-mm-dd Date of onset or hospitalization','e'); ?>' onkeyup='datekeyup(this,mypcc)' onblur='dateblur(this,mypcc)' /> <img src='../../pic/show_calendar.gif' align='absbottom' width='24' height='22' id='img_form_onset_date' border='0' alt='[?]' style='cursor:pointer;cursor:hand' title='<?php xl('Click here to choose a date','e'); ?>'> </td> </tr> <tr> <td class='text' colspan='2' style='padding-top:1em'> <?php if ($GLOBALS['athletic_team']) { ?> <p><i>Click [Add Issue] to add a new issue if:<br /> New injury likely to miss &gt; 1 day<br /> New significant illness/medical<br /> New allergy - only if nil exist</i></p> <?php } ?> </td> </tr> </table> </td> <td class='bold' width='33%' nowrap> <div style='float:left'> <?php xl('Issues (Injuries/Medical/Allergy)','e'); ?> </div> <div style='float:left;margin-left:8px;margin-top:-3px'> <?php if ($GLOBALS['athletic_team']) { // they want the old-style popup window ?> <a href="#" class="css_button_small link_submit" onclick="return newissue()"><span><?php echo htmlspecialchars(xl('Add')); ?></span></a> <?php } else { ?> <a href="../../patient_file/summary/add_edit_issue.php" class="css_button_small link_submit iframe" onclick="top.restoreSession()"><span><?php echo htmlspecialchars(xl('Add')); ?></span></a> <?php } ?> </div> </td> </tr> <tr> <td class='text' valign='top'> <textarea name='reason' cols='40' rows='12' wrap='virtual' style='width:96%' ><?php echo $viewmode ? htmlspecialchars($result['reason']) : $GLOBALS['default_chief_complaint']; ?></textarea> </td> <td class='text' valign='top'> <select multiple name='issues[]' size='8' style='width:100%' title='<?php xl('Hold down [Ctrl] for multiple selections or to unselect','e'); ?>'> <?php while ($irow = sqlFetchArray($ires)) { $list_id = $irow['id']; $tcode = $irow['type']; if ($ISSUE_TYPES[$tcode]) $tcode = $ISSUE_TYPES[$tcode][2]; echo " <option value='$list_id'"; if ($viewmode) { $perow = sqlQuery("SELECT count(*) AS count FROM issue_encounter WHERE " . "pid = '$pid' AND encounter = '$encounter' AND list_id = '$list_id'"); if ($perow['count']) echo " selected"; } else { // For new encounters the invoker may pass an issue ID. if (!empty($_REQUEST['issue']) && $_REQUEST['issue'] == $list_id) echo " selected"; } echo ">$tcode: " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40)) . "</option>\n"; } ?> </select> <p><i><?php xl('To link this encounter/consult to an existing issue, click the ' . 'desired issue above to highlight it and then click [Save]. ' . 'Hold down [Ctrl] button to select multiple issues.','e'); ?></i></p> </td> </tr> </table> </form> </body> <script language="javascript"> /* required for popup calendar */ Calendar.setup({inputField:"form_date", ifFormat:"%Y-%m-%d", button:"img_form_date"}); Calendar.setup({inputField:"form_onset_date", ifFormat:"%Y-%m-%d", button:"img_form_onset_date"}); <?php if (!$viewmode) { $erow = sqlQuery("SELECT count(*) AS count " . "FROM form_encounter AS fe, forms AS f WHERE " . "fe.pid = '$pid' AND fe.date = '" . date('Y-m-d 00:00:00') . "' AND " . "f.formdir = 'newpatient' AND f.form_id = fe.id AND f.deleted = 0"); if ($erow['count'] > 0) { echo "alert('" . xl('Warning: A visit was already created for this patient today!') . "');\n"; } } ?> </script> </html>
gpl-3.0
Hello23-Ygopro/ygopro-kaijudo
expansions/script/c25003062.lua
362
--Spy Mission local ka=require "expansions.utility_ktcg" local scard,sid=ka.GetID() function scard.initial_effect(c) ka.EnableSpellAttribute(c) --shield blast ka.EnableShieldBlast(c) --draw ka.AddSpellCastAbility(c,0,nil,ka.DrawOperation(PLAYER_PLAYER,2)) ka.AddShieldBlastCastAbility(c,0,nil,ka.DrawOperation(PLAYER_PLAYER,2)) end scard.kaijudo_card=true
gpl-3.0
wooknight/phpcallgraph
lib/ezcomponents/Reflection/tests/parameter_static_test.php
3087
<?php /** * @copyright Copyright (C) 2005-2009 eZ Systems AS. All rights reserved. * @license http://ez.no/licenses/new_bsd New BSD License * @version //autogen// * @filesource * @package Reflection * @subpackage Tests */ class ezcReflectionParameterStaticTest extends ezcReflectionParameterTest { public function setUpFixtures() { $session = new pdepend\reflection\ReflectionSession(); $array = array( 'TestMethods' => dirname( __FILE__ ) . '/test_classes/methods.php', ); $resolver = new pdepend\reflection\resolvers\AutoloadArrayResolver( $array ); //$resolver = new pdepend\reflection\resolvers\AutoloadArrayResolver( include( '../src/reflection_autoload.php' ) ); $session->addClassFactory( new pdepend\reflection\factories\StaticReflectionClassFactory( new pdepend\reflection\ReflectionClassProxyContext( $session ), $resolver ) ); $session->addClassFactory( new pdepend\reflection\factories\InternalReflectionClassFactory() ); // function with undocumented parameter $t that has default value 'foo' // Functions are not yet supported in staticReflection, thus using ezcReflection again foreach ( $this->expected['mmm'] as $key => $param ) { $this->actual['mmm'][$key] = new ezcReflectionParameter( null, $param ); } // function with three parameters that have type annotations but no type hints $paramTypes = array( 'string', 'ezcReflection', 'ReflectionClass' ); foreach ( $this->expected['m1'] as $key => $param ) { $this->actualParamsOfM1[] = new ezcReflectionParameter( null, $param, $paramTypes[$key] ); } // method with one undocumented parameter $classTestMethods = $session->getClass( 'TestMethods' ); $m3 = $classTestMethods->getMethod( 'm3' ); foreach ( $m3->getParameters() as $param ) { $this->actualParamsOf_TestMethods_m3[] = new ezcReflectionParameter( null, $param ); } // method with parameter that has type hint $ezcReflection = $session->getClass( 'ezcReflection' ); $setReflectionTypeFactory = $ezcReflection->getMethod( 'setReflectionTypeFactory' ); foreach ( $setReflectionTypeFactory->getParameters() as $param ) { $this->actualParamsOf_ezcReflection_setReflectionTypeFactory[] = new ezcReflectionParameter( null, $param, 'ezcReflectionTypeFactory' ); } // function with parameter that has type hint only // Functions are not yet supported in staticReflection, thus using ezcReflection again $this->actualParamsOf_functionWithTypeHint[] = new ezcReflectionParameter( 'ReflectionClass', $this->expected['functionWithTypeHint'][0] ); } public function testExport( $functionName = null, $paramKey = null ) { // no need to test this again } public static function suite() { return new PHPUnit_Framework_TestSuite( __CLASS__ ); } }
gpl-3.0
halfwit/qutebrowser
tests/unit/misc/test_readline.py
10042
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2016 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # qutebrowser 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 qutebrowser. If not, see <http://www.gnu.org/licenses/>. """Tests for qutebrowser.misc.readline.""" import re import inspect from PyQt5.QtWidgets import QLineEdit, QApplication import pytest from qutebrowser.misc import readline # Some functions aren't 100% readline compatible: # https://github.com/The-Compiler/qutebrowser/issues/678 # Those are marked with fixme and have another value marked with '# wrong' # which marks the current behavior. fixme = pytest.mark.xfail(reason='readline compatibility - see #678') class LineEdit(QLineEdit): """QLineEdit with some methods to make testing easier.""" def _get_index(self, haystack, needle): """Get the index of a char (needle) in a string (haystack). Return: The position where needle was found, or None if it wasn't found. """ try: return haystack.index(needle) except ValueError: return None def set_aug_text(self, text): """Set a text with </> markers for selected text and | as cursor.""" real_text = re.sub('[<>|]', '', text) self.setText(real_text) cursor_pos = self._get_index(text, '|') sel_start_pos = self._get_index(text, '<') sel_end_pos = self._get_index(text, '>') if sel_start_pos is not None and sel_end_pos is None: raise ValueError("< given without >!") if sel_start_pos is None and sel_end_pos is not None: raise ValueError("> given without <!") if cursor_pos is not None: if sel_start_pos is not None or sel_end_pos is not None: raise ValueError("Can't mix | and </>!") self.setCursorPosition(cursor_pos) elif sel_start_pos is not None: if sel_start_pos > sel_end_pos: raise ValueError("< given after >!") sel_len = sel_end_pos - sel_start_pos - 1 self.setSelection(sel_start_pos, sel_len) def aug_text(self): """Get a text with </> markers for selected text and | as cursor.""" text = self.text() chars = list(text) cur_pos = self.cursorPosition() assert cur_pos >= 0 chars.insert(cur_pos, '|') if self.hasSelectedText(): selected_text = self.selectedText() sel_start = self.selectionStart() sel_end = sel_start + len(selected_text) assert sel_start > 0 assert sel_end > 0 assert sel_end > sel_start assert cur_pos == sel_end assert text[sel_start:sel_end] == selected_text chars.insert(sel_start, '<') chars.insert(sel_end + 1, '>') return ''.join(chars) @pytest.fixture def lineedit(qtbot, monkeypatch): """Fixture providing a LineEdit.""" le = LineEdit() qtbot.add_widget(le) monkeypatch.setattr(QApplication.instance(), 'focusWidget', lambda: le) return le @pytest.fixture def bridge(): """Fixture providing a ReadlineBridge.""" return readline.ReadlineBridge() def test_none(bridge, qtbot): """Call each rl_* method with a None focusWidget.""" assert QApplication.instance().focusWidget() is None for name, method in inspect.getmembers(bridge, inspect.ismethod): if name.startswith('rl_'): method() @pytest.mark.parametrize('text, expected', [('f<oo>bar', 'fo|obar'), ('|foobar', '|foobar')]) def test_rl_backward_char(text, expected, lineedit, bridge): """Test rl_backward_char.""" lineedit.set_aug_text(text) bridge.rl_backward_char() assert lineedit.aug_text() == expected @pytest.mark.parametrize('text, expected', [('f<oo>bar', 'foob|ar'), ('foobar|', 'foobar|')]) def test_rl_forward_char(text, expected, lineedit, bridge): """Test rl_forward_char.""" lineedit.set_aug_text(text) bridge.rl_forward_char() assert lineedit.aug_text() == expected @pytest.mark.parametrize('text, expected', [('one <tw>o', 'one |two'), ('<one >two', '|one two'), ('|one two', '|one two')]) def test_rl_backward_word(text, expected, lineedit, bridge): """Test rl_backward_word.""" lineedit.set_aug_text(text) bridge.rl_backward_word() assert lineedit.aug_text() == expected @pytest.mark.parametrize('text, expected', [ fixme(('<o>ne two', 'one| two')), ('<o>ne two', 'one |two'), # wrong fixme(('<one> two', 'one two|')), ('<one> two', 'one |two'), # wrong ('one t<wo>', 'one two|') ]) def test_rl_forward_word(text, expected, lineedit, bridge): """Test rl_forward_word.""" lineedit.set_aug_text(text) bridge.rl_forward_word() assert lineedit.aug_text() == expected def test_rl_beginning_of_line(lineedit, bridge): """Test rl_beginning_of_line.""" lineedit.set_aug_text('f<oo>bar') bridge.rl_beginning_of_line() assert lineedit.aug_text() == '|foobar' def test_rl_end_of_line(lineedit, bridge): """Test rl_end_of_line.""" lineedit.set_aug_text('f<oo>bar') bridge.rl_end_of_line() assert lineedit.aug_text() == 'foobar|' @pytest.mark.parametrize('text, expected', [('foo|bar', 'foo|ar'), ('foobar|', 'foobar|'), ('|foobar', '|oobar'), ('f<oo>bar', 'f|bar')]) def test_rl_delete_char(text, expected, lineedit, bridge): """Test rl_delete_char.""" lineedit.set_aug_text(text) bridge.rl_delete_char() assert lineedit.aug_text() == expected @pytest.mark.parametrize('text, expected', [('foo|bar', 'fo|bar'), ('foobar|', 'fooba|'), ('|foobar', '|foobar'), ('f<oo>bar', 'f|bar')]) def test_rl_backward_delete_char(text, expected, lineedit, bridge): """Test rl_backward_delete_char.""" lineedit.set_aug_text(text) bridge.rl_backward_delete_char() assert lineedit.aug_text() == expected @pytest.mark.parametrize('text, deleted, rest', [ ('delete this| test', 'delete this', '| test'), fixme(('delete <this> test', 'delete this', '| test')), ('delete <this> test', 'delete ', '|this test'), # wrong fixme(('f<oo>bar', 'foo', '|bar')), ('f<oo>bar', 'f', '|oobar'), # wrong ]) def test_rl_unix_line_discard(lineedit, bridge, text, deleted, rest): """Delete from the cursor to the beginning of the line and yank back.""" lineedit.set_aug_text(text) bridge.rl_unix_line_discard() assert bridge._deleted[lineedit] == deleted assert lineedit.aug_text() == rest lineedit.clear() bridge.rl_yank() assert lineedit.aug_text() == deleted + '|' @pytest.mark.parametrize('text, deleted, rest', [ ('test |delete this', 'delete this', 'test |'), fixme(('<test >delete this', 'test delete this', 'test |')), ('<test >delete this', 'test delete this', '|'), # wrong ]) def test_rl_kill_line(lineedit, bridge, text, deleted, rest): """Delete from the cursor to the end of line and yank back.""" lineedit.set_aug_text(text) bridge.rl_kill_line() assert bridge._deleted[lineedit] == deleted assert lineedit.aug_text() == rest lineedit.clear() bridge.rl_yank() assert lineedit.aug_text() == deleted + '|' @pytest.mark.parametrize('text, deleted, rest', [ ('test delete|foobar', 'delete', 'test |foobar'), ('test delete |foobar', 'delete ', 'test |foobar'), ('open -t github.com/foo/bar |', 'github.com/foo/bar ', 'open -t |'), ('open -t |github.com/foo/bar', '-t ', 'open |github.com/foo/bar'), fixme(('test del<ete>foobar', 'delete', 'test |foobar')), ('test del<ete >foobar', 'del', 'test |ete foobar'), # wrong ]) def test_rl_unix_word_rubout(lineedit, bridge, text, deleted, rest): """Delete to word beginning and see if it comes back with yank.""" lineedit.set_aug_text(text) bridge.rl_unix_word_rubout() assert bridge._deleted[lineedit] == deleted assert lineedit.aug_text() == rest lineedit.clear() bridge.rl_yank() assert lineedit.aug_text() == deleted + '|' @pytest.mark.parametrize('text, deleted, rest', [ fixme(('test foobar| delete', ' delete', 'test foobar|')), ('test foobar| delete', ' ', 'test foobar|delete'), # wrong fixme(('test foo|delete bar', 'delete', 'test foo| bar')), ('test foo|delete bar', 'delete ', 'test foo|bar'), # wrong fixme(('test foo<bar> delete', ' delete', 'test foobar|')), ('test foo<bar>delete', 'bardelete', 'test foo|'), # wrong ]) def test_rl_kill_word(lineedit, bridge, text, deleted, rest): """Delete to word end and see if it comes back with yank.""" lineedit.set_aug_text(text) bridge.rl_kill_word() assert bridge._deleted[lineedit] == deleted assert lineedit.aug_text() == rest lineedit.clear() bridge.rl_yank() assert lineedit.aug_text() == deleted + '|' def test_rl_yank_no_text(lineedit, bridge): """Test yank without having deleted anything.""" lineedit.clear() bridge.rl_yank() assert lineedit.aug_text() == '|'
gpl-3.0
edagarli/Nicole
src/main/java/org/edagarli/framework/util/ArrayUtil.java
503
package org.edagarli.framework.util; import org.apache.commons.lang3.ArrayUtils; /** * User: lurou * Email: lurou@2dfire.com * Date: 16/1/22 * Time: 17:54 * Desc: */ public class ArrayUtil { /** * 判断数组是否非空 */ public static boolean isNotEmpty(Object[] array) { return !ArrayUtils.isEmpty(array); } /** * 判断数组是否为空 */ public static boolean isEmpty(Object[] array) { return ArrayUtils.isEmpty(array); } }
gpl-3.0
DIRACGrid/DIRAC
src/DIRAC/DataManagementSystem/Agent/RequestOperations/RemoveReplica.py
9352
######################################################################## # File: RemoveReplica.py # Author: Krzysztof.Ciba@NOSPAMgmail.com # Date: 2013/03/25 07:45:06 ######################################################################## """ :mod: RemoveReplica =================== .. module: RemoveReplica :synopsis: removeReplica operation handler .. moduleauthor:: Krzysztof.Ciba@NOSPAMgmail.com RemoveReplica operation handler """ from __future__ import absolute_import from __future__ import division from __future__ import print_function __RCSID__ = "$Id $" # # # @file RemoveReplica.py # @author Krzysztof.Ciba@NOSPAMgmail.com # @date 2013/03/25 07:45:17 # @brief Definition of RemoveReplica class. # # imports import os # # from DIRAC from DIRAC import S_OK from DIRAC.FrameworkSystem.Client.MonitoringClient import gMonitor from DIRAC.DataManagementSystem.Agent.RequestOperations.DMSRequestOperationsBase import DMSRequestOperationsBase from DIRAC.MonitoringSystem.Client.MonitoringReporter import MonitoringReporter ######################################################################## class RemoveReplica(DMSRequestOperationsBase): """ .. class:: RemoveReplica """ def __init__(self, operation=None, csPath=None): """c'tor :param self: self reference :param Operation operation: operation to execute :param str csPath: CS path for this handler """ # # base class ctor DMSRequestOperationsBase.__init__(self, operation, csPath) def __call__(self): """remove replicas""" # The flag 'rmsMonitoring' is set by the RequestTask and is False by default. # Here we use 'createRMSRecord' to create the ES record which is defined inside OperationHandlerBase. if self.rmsMonitoring: self.rmsMonitoringReporter = MonitoringReporter(monitoringType="RMSMonitoring") else: # # gMonitor stuff gMonitor.registerActivity( "RemoveReplicaAtt", "Replica removals attempted", "RequestExecutingAgent", "Files/min", gMonitor.OP_SUM ) gMonitor.registerActivity( "RemoveReplicaOK", "Successful replica removals", "RequestExecutingAgent", "Files/min", gMonitor.OP_SUM ) gMonitor.registerActivity( "RemoveReplicaFail", "Failed replica removals", "RequestExecutingAgent", "Files/min", gMonitor.OP_SUM ) # # prepare list of targetSEs targetSEs = self.operation.targetSEList # # check targetSEs for removal bannedTargets = self.checkSEsRSS(targetSEs, access="RemoveAccess") if not bannedTargets["OK"]: if self.rmsMonitoring: for status in ["Attempted", "Failed"]: self.rmsMonitoringReporter.addRecord(self.createRMSRecord(status, len(self.operation))) self.rmsMonitoringReporter.commit() else: gMonitor.addMark("RemoveReplicaAtt") gMonitor.addMark("RemoveReplicaFail") return bannedTargets if bannedTargets["Value"]: return S_OK("%s targets are banned for removal" % ",".join(bannedTargets["Value"])) # # get waiting files waitingFiles = self.getWaitingFilesList() # # and prepare dict toRemoveDict = dict((opFile.LFN, opFile) for opFile in waitingFiles) self.log.info("Todo: %s replicas to delete from %s SEs" % (len(toRemoveDict), len(targetSEs))) if self.rmsMonitoring: self.rmsMonitoringReporter.addRecord(self.createRMSRecord("Attempted", len(toRemoveDict))) else: gMonitor.addMark("RemoveReplicaAtt", len(toRemoveDict) * len(targetSEs)) # # keep status for each targetSE removalStatus = dict.fromkeys(toRemoveDict, None) for lfn in removalStatus: removalStatus[lfn] = dict.fromkeys(targetSEs, None) # # loop over targetSEs for targetSE in targetSEs: self.log.info("Removing replicas at %s" % targetSE) # # 1st step - bulk removal bulkRemoval = self._bulkRemoval(toRemoveDict, targetSE) if not bulkRemoval["OK"]: self.log.error("Bulk replica removal failed", bulkRemoval["Message"]) if self.rmsMonitoring: self.rmsMonitoringReporter.commit() return bulkRemoval # # report removal status for successful files if self.rmsMonitoring: self.rmsMonitoringReporter.addRecord( self.createRMSRecord( "Successful", len(([opFile for opFile in toRemoveDict.values() if not opFile.Error])) ) ) else: gMonitor.addMark( "RemoveReplicaOK", len([opFile for opFile in toRemoveDict.values() if not opFile.Error]) ) # # 2nd step - process the rest again toRetry = dict((lfn, opFile) for lfn, opFile in toRemoveDict.items() if opFile.Error) for lfn, opFile in toRetry.items(): self._removeWithOwnerProxy(opFile, targetSE) if opFile.Error: if self.rmsMonitoring: self.rmsMonitoringReporter.addRecord(self.createRMSRecord("Failed", 1)) else: gMonitor.addMark("RemoveReplicaFail", 1) removalStatus[lfn][targetSE] = opFile.Error else: if self.rmsMonitoring: self.rmsMonitoringReporter.addRecord(self.createRMSRecord("Successful", 1)) else: gMonitor.addMark("RemoveReplicaOK", 1) # # update file status for waiting files failed = 0 for opFile in self.operation: if opFile.Status == "Waiting": errors = list(set(error for error in removalStatus[opFile.LFN].values() if error)) if errors: opFile.Error = "\n".join(errors) # This seems to be the only unrecoverable error if "Write access not permitted for this credential" in opFile.Error: failed += 1 opFile.Status = "Failed" else: opFile.Status = "Done" if failed: self.operation.Error = "failed to remove %s replicas" % failed if self.rmsMonitoring: self.rmsMonitoringReporter.commit() return S_OK() def _bulkRemoval(self, toRemoveDict, targetSE): """remove replicas :toRemoveDict: at :targetSE: :param dict toRemoveDict: { lfn: opFile, ... } :param str targetSE: target SE name """ # Clear the error for opFile in toRemoveDict.values(): opFile.Error = "" removeReplicas = self.dm.removeReplica(targetSE, list(toRemoveDict)) if not removeReplicas["OK"]: for opFile in toRemoveDict.values(): opFile.Error = removeReplicas["Message"] return removeReplicas removeReplicas = removeReplicas["Value"] # # filter out failed for lfn, opFile in toRemoveDict.items(): if lfn in removeReplicas["Failed"]: errorReason = str(removeReplicas["Failed"][lfn]) # If the reason is that the file does not exist, # we consider the removal successful # TODO: use cmpError once the FC returns the proper error msg corresponding to ENOENT if "No such file" not in errorReason: opFile.Error = errorReason self.log.error("Failed removing lfn", "%s:%s" % (lfn, opFile.Error)) return S_OK() def _removeWithOwnerProxy(self, opFile, targetSE): """remove opFile replica from targetSE using owner proxy :param File opFile: File instance :param str targetSE: target SE name """ if "Write access not permitted for this credential" in opFile.Error: proxyFile = None if "DataManager" in self.shifter: # # you're a data manager - save current proxy and get a new one for LFN and retry saveProxy = os.environ["X509_USER_PROXY"] try: fileProxy = self.getProxyForLFN(opFile.LFN) if not fileProxy["OK"]: opFile.Error = fileProxy["Message"] else: proxyFile = fileProxy["Value"] removeReplica = self.dm.removeReplica(targetSE, opFile.LFN) if not removeReplica["OK"]: opFile.Error = removeReplica["Message"] else: # Set or reset the error if all OK opFile.Error = removeReplica["Value"]["Failed"].get(opFile.LFN, "") finally: if proxyFile: os.unlink(proxyFile) # # put back request owner proxy to env os.environ["X509_USER_PROXY"] = saveProxy
gpl-3.0
nortikin/sverchok
nodes/solid/transform_solid.py
1832
from sverchok.dependencies import FreeCAD from sverchok.utils.dummy_nodes import add_dummy if FreeCAD is None: add_dummy('SvTransformSolidNode', 'Transform Solid', 'FreeCAD') else: import bpy from bpy.props import FloatProperty from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode, match_long_repeat as mlr from sverchok.utils.solid import transform_solid from FreeCAD import Base class SvTransformSolidNode(bpy.types.Node, SverchCustomTreeNode): """ Triggers: Apply Matrix to Solid Tooltip: Transform Solid with Matrix """ bl_idname = 'SvTransformSolidNode' bl_label = 'Transform Solid' bl_icon = 'MESH_CUBE' sv_icon = 'SV_TRANSFORM_SOLID' solid_catergory = "Operators" precision: FloatProperty( name="Precision", default=0.1, precision=4, update=updateNode) def sv_init(self, context): self.inputs.new('SvSolidSocket', "Solid") self.inputs.new('SvMatrixSocket', "Matrix") self.outputs.new('SvSolidSocket', "Solid") def process(self): if not any(socket.is_linked for socket in self.outputs): return solids_in = self.inputs[0].sv_get() matrixes = self.inputs[1].sv_get() solids = [] for solid, matrix in zip(*mlr([solids_in, matrixes])): solid_o = transform_solid(matrix, solid) solids.append(solid_o) self.outputs['Solid'].sv_set(solids) def register(): if FreeCAD is not None: bpy.utils.register_class(SvTransformSolidNode) def unregister(): if FreeCAD is not None: bpy.utils.unregister_class(SvTransformSolidNode)
gpl-3.0
Entropy512/libsigrokdecode
decoders/ir_nec/pd.py
9333
## ## This file is part of the libsigrokdecode project. ## ## Copyright (C) 2014 Gump Yang <gump.yang@gmail.com> ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 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 sigrokdecode as srd from .lists import * class SamplerateError(Exception): pass class Decoder(srd.Decoder): api_version = 3 id = 'ir_nec' name = 'IR NEC' longname = 'IR NEC' desc = 'NEC infrared remote control protocol.' license = 'gplv2+' inputs = ['logic'] outputs = [] tags = ['IR'] channels = ( {'id': 'ir', 'name': 'IR', 'desc': 'Data line'}, ) options = ( {'id': 'polarity', 'desc': 'Polarity', 'default': 'active-low', 'values': ('active-low', 'active-high')}, {'id': 'cd_freq', 'desc': 'Carrier Frequency', 'default': 0}, ) annotations = ( ('bit', 'Bit'), ('agc-pulse', 'AGC pulse'), ('longpause', 'Long pause'), ('shortpause', 'Short pause'), ('stop-bit', 'Stop bit'), ('leader-code', 'Leader code'), ('addr', 'Address'), ('addr-inv', 'Address#'), ('cmd', 'Command'), ('cmd-inv', 'Command#'), ('repeat-code', 'Repeat code'), ('remote', 'Remote'), ('warnings', 'Warnings'), ) annotation_rows = ( ('bits', 'Bits', (0, 1, 2, 3, 4)), ('fields', 'Fields', (5, 6, 7, 8, 9, 10)), ('remote', 'Remote', (11,)), ('warnings', 'Warnings', (12,)), ) def putx(self, data): self.put(self.ss_start, self.samplenum, self.out_ann, data) def putb(self, data): self.put(self.ss_bit, self.samplenum, self.out_ann, data) def putd(self, data): name = self.state.title() d = {'ADDRESS': 6, 'ADDRESS#': 7, 'COMMAND': 8, 'COMMAND#': 9} s = {'ADDRESS': ['ADDR', 'A'], 'ADDRESS#': ['ADDR#', 'A#'], 'COMMAND': ['CMD', 'C'], 'COMMAND#': ['CMD#', 'C#']} self.putx([d[self.state], ['%s: 0x%02X' % (name, data), '%s: 0x%02X' % (s[self.state][0], data), '%s: 0x%02X' % (s[self.state][1], data), s[self.state][1]]]) def putstop(self, ss): self.put(ss, ss + self.stop, self.out_ann, [4, ['Stop bit', 'Stop', 'St', 'S']]) def putpause(self, p): self.put(self.ss_start, self.ss_other_edge, self.out_ann, [1, ['AGC pulse', 'AGC', 'A']]) idx = 2 if p == 'Long' else 3 self.put(self.ss_other_edge, self.samplenum, self.out_ann, [idx, [p + ' pause', '%s-pause' % p[0], '%sP' % p[0], 'P']]) def putremote(self): dev = address.get(self.addr, 'Unknown device') buttons = command.get(self.addr, None) if buttons is None: btn = ['Unknown', 'Unk'] else: btn = buttons.get(self.cmd, ['Unknown', 'Unk']) self.put(self.ss_remote, self.ss_bit + self.stop, self.out_ann, [11, ['%s: %s' % (dev, btn[0]), '%s: %s' % (dev, btn[1]), '%s' % btn[1]]]) def __init__(self): self.reset() def reset(self): self.state = 'IDLE' self.ss_bit = self.ss_start = self.ss_other_edge = self.ss_remote = 0 self.data = self.count = self.active = None self.addr = self.cmd = None def start(self): self.out_ann = self.register(srd.OUTPUT_ANN) self.active = 0 if self.options['polarity'] == 'active-low' else 1 def metadata(self, key, value): if key == srd.SRD_CONF_SAMPLERATE: self.samplerate = value self.tolerance = 0.05 # +/-5% self.lc = int(self.samplerate * 0.0135) - 1 # 13.5ms self.rc = int(self.samplerate * 0.01125) - 1 # 11.25ms self.dazero = int(self.samplerate * 0.001125) - 1 # 1.125ms self.daone = int(self.samplerate * 0.00225) - 1 # 2.25ms self.stop = int(self.samplerate * 0.000652) - 1 # 0.652ms def compare_with_tolerance(self, measured, base): return (measured >= base * (1 - self.tolerance) and measured <= base * (1 + self.tolerance)) def handle_bit(self, tick): ret = None if self.compare_with_tolerance(tick, self.dazero): ret = 0 elif self.compare_with_tolerance(tick, self.daone): ret = 1 if ret in (0, 1): self.putb([0, ['%d' % ret]]) self.data |= (ret << self.count) # LSB-first self.count = self.count + 1 self.ss_bit = self.samplenum def data_ok(self): ret, name = (self.data >> 8) & (self.data & 0xff), self.state.title() if self.count == 8: if self.state == 'ADDRESS': self.addr = self.data if self.state == 'COMMAND': self.cmd = self.data self.putd(self.data) self.ss_start = self.samplenum return True if ret == 0: self.putd(self.data >> 8) else: self.putx([12, ['%s error: 0x%04X' % (name, self.data)]]) self.data = self.count = 0 self.ss_bit = self.ss_start = self.samplenum return ret == 0 def decode(self): if not self.samplerate: raise SamplerateError('Cannot decode without samplerate.') cd_count = None if self.options['cd_freq']: cd_count = int(self.samplerate / self.options['cd_freq']) + 1 prev_ir = None while True: # Detect changes in the presence of an active input signal. # The decoder can either be fed an already filtered RX signal # or optionally can detect the presence of a carrier. Periods # of inactivity (signal changes slower than the carrier freq, # if specified) pass on the most recently sampled level. This # approach works for filtered and unfiltered input alike, and # only slightly extends the active phase of input signals with # carriers included by one period of the carrier frequency. # IR based communication protocols can cope with this slight # inaccuracy just fine by design. Enabling carrier detection # on already filtered signals will keep the length of their # active period, but will shift their signal changes by one # carrier period before they get passed to decoding logic. if cd_count: (cur_ir,) = self.wait([{0: 'e'}, {'skip': cd_count}]) if self.matched[0]: cur_ir = self.active if cur_ir == prev_ir: continue prev_ir = cur_ir self.ir = cur_ir else: (self.ir,) = self.wait({0: 'e'}) if self.ir != self.active: # Save the non-active edge, then wait for the next edge. self.ss_other_edge = self.samplenum continue b = self.samplenum - self.ss_bit # State machine. if self.state == 'IDLE': if self.compare_with_tolerance(b, self.lc): self.putpause('Long') self.putx([5, ['Leader code', 'Leader', 'LC', 'L']]) self.ss_remote = self.ss_start self.data = self.count = 0 self.state = 'ADDRESS' elif self.compare_with_tolerance(b, self.rc): self.putpause('Short') self.putstop(self.samplenum) self.samplenum += self.stop self.putx([10, ['Repeat code', 'Repeat', 'RC', 'R']]) self.data = self.count = 0 self.ss_bit = self.ss_start = self.samplenum elif self.state == 'ADDRESS': self.handle_bit(b) if self.count == 8: self.state = 'ADDRESS#' if self.data_ok() else 'IDLE' elif self.state == 'ADDRESS#': self.handle_bit(b) if self.count == 16: self.state = 'COMMAND' if self.data_ok() else 'IDLE' elif self.state == 'COMMAND': self.handle_bit(b) if self.count == 8: self.state = 'COMMAND#' if self.data_ok() else 'IDLE' elif self.state == 'COMMAND#': self.handle_bit(b) if self.count == 16: self.state = 'STOP' if self.data_ok() else 'IDLE' elif self.state == 'STOP': self.putstop(self.ss_bit) self.putremote() self.ss_bit = self.ss_start = self.samplenum self.state = 'IDLE'
gpl-3.0
mayioit/MacroMedicalSystem
ImageServer/Web/Application/Controls/CheckJavascript.ascx.designer.cs
852
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.4005 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Macro.ImageServer.Web.Application.Controls { public partial class CheckJavascript { /// <summary> /// hfClientJSEnabled control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.HiddenField hfClientJSEnabled; } }
gpl-3.0
swordiemen/Mushy
src/handling/channel/handler/MovementParse.java
5463
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 ~ 2010 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package handling.channel.handler; import java.awt.Point; import java.util.ArrayList; import java.util.List; import client.MapleCharacter; import server.maps.AnimatedMapleMapObject; import server.movement.*; import tools.data.LittleEndianAccessor; public class MovementParse { // 1 = player, 2 = mob, 3 = pet, 4 = summon, 5 = dragon (missing: android, familiar, haku) public static List<LifeMovementFragment> parseMovement(final LittleEndianAccessor lea, final int kind) { return parseMovement(lea, kind, null); } public static List<LifeMovementFragment> parseMovement(final LittleEndianAccessor lea, final int kind, MapleCharacter chr) { final List<LifeMovementFragment> res = new ArrayList<>(); final byte numCommands = lea.readByte(); for (byte i = 0; i < numCommands; i++) { byte command = lea.readByte(); switch (command) { case 0: case 8: case 15: case 17: case 19: case 67: case 68: case 69: { res.add(new Movement1(lea, command)); break; } case 56: case 66: case 85: { res.add(new Movement2(lea, command)); break; } case 1: case 2: case 18: case 21: case 22: case 24: case 62: case 63: case 64: case 65: { res.add(new Movement3(lea, command)); break; } case 29: case 30: case 31: case 32: case 33: case 34: case 35: case 36: case 37: case 38: case 39: case 40: case 41: case 42: case 43: case 44: case 45: case 46: case 47: case 48: case 49: case 50: case 51: case 57: case 58: case 59: case 60: case 70: case 71: case 72: case 74: case 79: case 81: case 83: { res.add(new Movement4(lea, command)); break; } case 3: case 4: case 5: case 6: case 7: case 9: case 10: case 11: case 13: case 26: case 27: case 52: case 53: case 54: case 61: case 76: case 77: case 78: case 80: case 82: { res.add(new Movement5(lea, command)); break; } case 14: case 16: { res.add(new Movement6(lea, command)); break; } case 23: { res.add(new Movement7(lea, command)); break; } case 12: { res.add(new Movement8(lea, command)); break; } default: // System.out.printf("The command (%s) is unhandled. %n", command); break; } } if (numCommands != res.size()) { return null; } return res; } public static void updatePosition(final List<LifeMovementFragment> movement, final AnimatedMapleMapObject target, final int yoffset) { if (movement == null) { return; } for (final LifeMovementFragment move : movement) { if (move instanceof LifeMovement) { final Point position = ((LifeMovement) move).getPosition(); position.y += yoffset; target.setPosition(position); target.setStance(((LifeMovement) move).getMoveAction()); } } } }
gpl-3.0
irregulator/ganetimgr
context/session_remaining.py
1629
# -*- coding: utf-8 -*- vim:fileencoding=utf-8: # Copyright (C) 2010-2014 GRNET S.A. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from django.conf import settings import datetime def seconds(request): remaining = False if ( request.user.is_authenticated() and request.user.get_profile().force_logout_date and ( 'LAST_LOGIN_DATE' not in request.session or request.session['LAST_LOGIN_DATE'] < request.user.get_profile().force_logout_date ) ): remaining = 2 if not request.user.is_anonymous(): if 'LAST_LOGIN_DATE' in request.session: last_login = request.session['LAST_LOGIN_DATE'] now = datetime.datetime.now() if now > last_login: elapsed = (now-last_login).seconds remaining = settings.SESSION_COOKIE_AGE - elapsed if remaining < 0: remaining = 2 else: remaining = 2 return {"session_remaining": remaining}
gpl-3.0
turdusmerula/PgDbo
doc/html/search/files_5.js
576
var searchData= [ ['field_2eh',['Field.h',['../_field_8h.html',1,'']]], ['fieldinfo_2ecpp',['FieldInfo.cpp',['../_field_info_8cpp.html',1,'']]], ['fieldinfo_2eh',['FieldInfo.h',['../_field_info_8h.html',1,'']]], ['fieldref_2ecxx',['FieldRef.cxx',['../_field_ref_8cxx.html',1,'']]], ['fieldref_2ehpp',['FieldRef.hpp',['../_field_ref_8hpp.html',1,'']]], ['foreignkeyconstraint_2ecpp',['ForeignKeyConstraint.cpp',['../_foreign_key_constraint_8cpp.html',1,'']]], ['foreignkeyconstraint_2eh',['ForeignKeyConstraint.h',['../_foreign_key_constraint_8h.html',1,'']]] ];
gpl-3.0
gedads/Neodynamis
scripts/zones/Sacrarium/npcs/qm7.lua
1770
----------------------------------- -- Area: Sacrarium -- NPC: qm7 (???) -- Notes: Used to spawn Old Prof. Mariselle -- !pos 22.669 -3.111 -127.318 28 ----------------------------------- package.loaded["scripts/zones/Sacrarium/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Sacrarium/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local OldProfessor = 16891970; if (GetServerVariable("Old_Prof_Spawn_Location") == 7) then if (player:getCurrentMission(COP) == THE_SECRETS_OF_WORSHIP and player:getVar("PromathiaStatus") == 3 and player:hasKeyItem(RELIQUIARIUM_KEY)==false and GetMobAction(OldProfessor) == 0) then player:messageSpecial(EVIL_PRESENCE); SpawnMob(OldProfessor):updateClaim(player); GetMobByID(OldProfessor):setPos(npc:getXPos()+1, npc:getYPos(), npc:getZPos()+1); -- Set Prof. spawn x and z pos. +1 from NPC else player:messageSpecial(DRAWER_SHUT); end elseif (player:getCurrentMission(COP) == THE_SECRETS_OF_WORSHIP and player:getVar("PromathiaStatus") == 4 and player:hasKeyItem(RELIQUIARIUM_KEY)==false) then player:addKeyItem(RELIQUIARIUM_KEY); player:messageSpecial(KEYITEM_OBTAINED,RELIQUIARIUM_KEY); else player:messageSpecial(DRAWER_OPEN); player:messageSpecial(DRAWER_EMPTY); end end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) end;
gpl-3.0
micaherne/moodle
mod/assignment/lang/en/assignment.php
14250
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Strings for component 'assignment', language 'en', branch 'MOODLE_20_STABLE' * * @package assignment * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ $string['allowdeleting'] = 'Allow deleting'; $string['allowdeleting_help'] = 'If enabled, students may delete uploaded files at any time before submitting for grading.'; $string['allowmaxfiles'] = 'Maximum number of uploaded files'; $string['allowmaxfiles_help'] = 'The maximum number of files which may be uploaded. As this figure is not displayed anywhere, it is suggested that it is mentioned in the assignment description.'; $string['allownotes'] = 'Allow notes'; $string['allownotes_help'] = 'If enabled, students may enter notes into a text area, as in an online text assignment.'; $string['allowresubmit'] = 'Allow resubmitting'; $string['allowresubmit_help'] = 'If enabled, students will be allowed to resubmit assignments after they have been graded (for them to be re-graded).'; $string['alreadygraded'] = 'Your assignment has already been graded and resubmission is not allowed.'; $string['assignmentdetails'] = 'Assignment details'; $string['assignment:exportownsubmission'] = 'Export own submission'; $string['assignment:exportsubmission'] = 'Export submission'; $string['assignment:grade'] = 'Grade assignment'; $string['assignmentmail'] = '{$a->teacher} has posted some feedback on your assignment submission for \'{$a->assignment}\' You can see it appended to your assignment submission: {$a->url}'; $string['assignmentmailhtml'] = '{$a->teacher} has posted some feedback on your assignment submission for \'<i>{$a->assignment}</i>\'<br /><br /> You can see it appended to your <a href="{$a->url}">assignment submission</a>.'; $string['assignmentmailsmall'] = '{$a->teacher} has posted some feedback on your assignment submission for \'{$a->assignment}\' You can see it appended to your submission'; $string['assignmentname'] = 'Assignment name'; $string['assignment:submit'] = 'Submit assignment'; $string['assignmentsubmission'] = 'Assignment submissions'; $string['assignmenttype'] = 'Assignment type'; $string['assignment:view'] = 'View assignment'; $string['availabledate'] = 'Available from'; $string['cannotdeletefiles'] = 'An error occurred and files could not be deleted'; $string['cannotviewassignment'] = 'You can not view this assignment'; $string['comment'] = 'Comment'; $string['commentinline'] = 'Comment inline'; $string['commentinline_help'] = 'If enabled, the submission text will be copied into the feedback comment field during grading, making it easier to comment inline (using a different colour, perhaps) or to edit the original text.'; $string['configitemstocount'] = 'Nature of items to be counted for student submissions in online assignments.'; $string['configmaxbytes'] = 'Default maximum assignment size for all assignments on the site (subject to course limits and other local settings)'; $string['configshowrecentsubmissions'] = 'Everyone can see notifications of submissions in recent activity reports.'; $string['confirmdeletefile'] = 'Are you absolutely sure you want to delete this file?<br /><strong>{$a}</strong>'; $string['coursemisconf'] = 'Course is misconfigured'; $string['currentgrade'] = 'Current grade in gradebook'; $string['deleteallsubmissions'] = 'Delete all submissions'; $string['deletefilefailed'] = 'Deleting of file failed.'; $string['description'] = 'Description'; $string['downloadall'] = 'Download all assignments as a zip'; $string['draft'] = 'Draft'; $string['due'] = 'Assignment due'; $string['duedate'] = 'Due date'; $string['duedateno'] = 'No due date'; $string['early'] = '{$a} early'; $string['editmysubmission'] = 'Edit my submission'; $string['editthesefiles'] = 'Edit these files'; $string['editthisfile'] = 'Update this file'; $string['addsubmission'] = 'Add submission'; $string['emailstudents'] = 'Email alerts to students'; $string['emailteachermail'] = '{$a->username} has updated their assignment submission for \'{$a->assignment}\' at {$a->timeupdated} It is available here: {$a->url}'; $string['emailteachermailhtml'] = '{$a->username} has updated their assignment submission for <i>\'{$a->assignment}\' at {$a->timeupdated}</i><br /><br /> It is <a href="{$a->url}">available on the web site</a>.'; $string['emailteachers'] = 'Email alerts to teachers'; $string['emailteachers_help'] = 'If enabled, teachers receive email notification whenever students add or update an assignment submission. Only teachers who are able to grade the particular assignment are notified. So, for example, if the course uses separate groups, teachers restricted to particular groups won\'t receive notification about students in other groups.'; $string['emptysubmission'] = 'You have not submitted anything yet'; $string['enablenotification'] = 'Send notifications'; $string['enablenotification_help'] = 'If enabled, students will be notified when their assignment submissions are graded.'; $string['errornosubmissions'] = 'There are no submissions to download'; $string['existingfiledeleted'] = 'Existing file has been deleted: {$a}'; $string['failedupdatefeedback'] = 'Failed to update submission feedback for user {$a}'; $string['feedback'] = 'Feedback'; $string['feedbackfromteacher'] = 'Feedback from the {$a}'; $string['feedbackupdated'] = 'Submissions feedback updated for {$a} people'; $string['finalize'] = 'Prevent submission updates'; $string['finalizeerror'] = 'An error occurred and that submission could not be finalised'; $string['graded'] = 'Graded'; $string['guestnosubmit'] = 'Sorry, guests are not allowed to submit an assignment. You have to log in/ register before you can submit your answer.'; $string['guestnoupload'] = 'Sorry, guests are not allowed to upload'; $string['helpoffline'] = '<p>This is useful when the assignment is performed outside of Moodle. It could be something elsewhere on the web or face-to-face.</p><p>Students can see a description of the assignment, but can\'t upload files or anything. Grading works normally, and students will get notifications of their grades.</p>'; $string['helponline'] = '<p>This assignment type asks users to edit a text, using the normal editing tools. Teachers can grade them online, and even add inline comments or changes.</p> <p>(If you are familiar with older versions of Moodle, this Assignment type does the same thing as the old Journal module used to do.)</p>'; $string['helpupload'] = '<p>This type of assignment allows each participant to upload one or more files in any format. These might be a Word processor documents, images, a zipped web site, or anything you ask them to submit.</p> <p>This type also allows you to upload multiple response files. Response files can be also uploaded before submission which can be used to give each participant different file to work with.</p> <p>Participants may also enter notes describing the submitted files, progress status or any other text information.</p> <p>Submission of this type of assignment must be manually finalised by the participant. You can review the current status at any time, unfinished assignments are marked as Draft. You can revert any ungraded assignment back to draft status.</p>'; $string['helpuploadsingle'] = '<p>This type of assignment allows each participant to upload a single file, of any type.</p> <p>This might be a Word processor document, an image, a zipped web site, or anything you ask them to submit.</p>'; $string['hideintro'] = 'Hide description before available date'; $string['hideintro_help'] = 'If enabled, the assignment description is hidden before the "Available from" date. Only the assignment name is displayed.'; $string['invalidassignment'] = 'incorrect assignment'; $string['invalidid'] = 'assignment ID was incorrect'; $string['invalidtype'] = 'Incorrect assignment type'; $string['invaliduserid'] = 'Invalid user ID'; $string['itemstocount'] = 'Count'; $string['lastgrade'] = 'Last grade'; $string['late'] = '{$a} late'; $string['maximumgrade'] = 'Maximum grade'; $string['maximumsize'] = 'Maximum size'; $string['maxpublishstate'] = 'Maximum visibility for blog entry before due date'; $string['messageprovider:assignment_updates'] = 'Assignment notifications'; $string['modulename'] = 'Assignment'; $string['modulename_help'] = 'Assignments enable the teacher to specify a task either on or offline which can then be graded.'; $string['modulenameplural'] = 'Assignments'; $string['newsubmissions'] = 'Assignments submitted'; $string['noassignments'] = 'There are no assignments yet'; $string['noattempts'] = 'No attempts have been made on this assignment'; $string['noblogs'] = 'You have no blog entries to submit!'; $string['nofiles'] = 'No files were submitted'; $string['nofilesyet'] = 'No files submitted yet'; $string['nomoresubmissions'] = 'No further submissions are allowed.'; $string['notavailableyet'] = 'Sorry, this assignment is not yet available.<br />Assignment instructions will be displayed here on the date given below.'; $string['notes'] = 'Notes'; $string['notesempty'] = 'No entry'; $string['notesupdateerror'] = 'Error when updating notes'; $string['notgradedyet'] = 'Not graded yet'; $string['norequiregrading'] = 'There are no assignments that require grading'; $string['nosubmisson'] = 'No assignments have been submit'; $string['notsubmittedyet'] = 'Not submitted yet'; $string['onceassignmentsent'] = 'Once the assignment is sent for marking, you will no longer be able to delete or attach file(s). Do you want to continue?'; $string['operation'] = 'Operation'; $string['optionalsettings'] = 'Optional settings'; $string['overwritewarning'] = 'Warning: uploading again will REPLACE your current submission'; $string['page-mod-assignment-x'] = 'Any assignment module page'; $string['page-mod-assignment-view'] = 'Assignment module main page'; $string['page-mod-assignment-submissions'] = 'Assignment module submission page'; $string['pagesize'] = 'Submissions shown per page'; $string['popupinnewwindow'] = 'Open in a popup window'; $string['pluginadministration'] = 'Assignment administration'; $string['pluginname'] = 'Assignment'; $string['preventlate'] = 'Prevent late submissions'; $string['quickgrade'] = 'Allow quick grading'; $string['quickgrade_help'] = 'If enabled, multiple assignments can be graded on one page. Add grades and comments then click the "Save all my feedback" button to save all changes for that page.'; $string['requiregrading'] = 'Require grading'; $string['responsefiles'] = 'Response files'; $string['reviewed'] = 'Reviewed'; $string['saveallfeedback'] = 'Save all my feedback'; $string['selectblog'] = 'Select which blog entry you wish to submit'; $string['sendformarking'] = 'Send for marking'; $string['showrecentsubmissions'] = 'Show recent submissions'; $string['submission'] = 'Submission'; $string['submissiondraft'] = 'Submission draft'; $string['submissionfeedback'] = 'Submission feedback'; $string['submissions'] = 'Submissions'; $string['submissionsaved'] = 'Your changes have been saved'; $string['submissionsnotgraded'] = '{$a} submissions not graded'; $string['submitassignment'] = 'Submit your assignment using this form'; $string['submitedformarking'] = 'Assignment was already submitted for marking and can not be updated'; $string['submitformarking'] = 'Final submission for assignment marking'; $string['submitted'] = 'Submitted'; $string['submittedfiles'] = 'Submitted files'; $string['subplugintype_assignment'] = 'Assignment type'; $string['subplugintype_assignment_plural'] = 'Assignment types'; $string['trackdrafts'] = 'Enable "Send for marking" button'; $string['trackdrafts_help'] = 'The "Send for marking" button allows students to indicate to the teacher that they have finished working on an assignment. The teacher may choose to revert the assignment to draft status (if it requires further work, for example).'; $string['typeblog'] = 'Blog post'; $string['typeoffline'] = 'Offline activity'; $string['typeonline'] = 'Online text'; $string['typeupload'] = 'Advanced uploading of files'; $string['typeuploadsingle'] = 'Upload a single file'; $string['unfinalize'] = 'Revert to draft'; $string['unfinalize_help'] = 'Reverting to draft enables the student to make further updates to their assignment'; $string['unfinalizeerror'] = 'An error occurred and that submission could not be reverted to draft'; $string['uploadafile'] = 'Upload a file'; $string['uploadfiles'] = 'Upload files'; $string['uploadbadname'] = 'This filename contained strange characters and couldn\'t be uploaded'; $string['uploadedfiles'] = 'uploaded files'; $string['uploaderror'] = 'An error happened while saving the file on the server'; $string['uploadfailnoupdate'] = 'File was uploaded OK but could not update your submission!'; $string['uploadfiletoobig'] = 'Sorry, but that file is too big (limit is {$a} bytes)'; $string['uploadnofilefound'] = 'No file was found - are you sure you selected one to upload?'; $string['uploadnotregistered'] = '\'{$a}\' was uploaded OK but submission did not register!'; $string['uploadsuccess'] = 'Uploaded \'{$a}\' successfully'; $string['usermisconf'] = 'User is misconfigured'; $string['usernosubmit'] = 'Sorry, you are not allowed to submit an assignment.'; $string['viewfeedback'] = 'View assignment grades and feedback'; $string['viewmysubmission'] = 'View my submission'; $string['viewsubmissions'] = 'View {$a} submitted assignments'; $string['yoursubmission'] = 'Your submission';
gpl-3.0
ecastro/moodle23ulpgc
mod/tracker/classes/trackercategorytype/dropdown/dropdown.class.php
1343
<?php /** * @package tracker * @author Clifford Tham * @review Valery Fremaux / 1.8 * @date 02/12/2007 * * A class implementing a dropdown element */ include_once $CFG->dirroot.'/mod/tracker/classes/trackercategorytype/trackerelement.class.php'; class dropdownelement extends trackerelement{ var $options; function dropdownelement(&$tracker, $id=null){ $this->tracker = $tracker; if (isset($id)){ $this->id = $id; $this->setoptionsfromdb(); } else { $this->options = array(); } } function view($editable, $issueid = 0){ $this->getvalue($issueid); // loads $this->value with current value for this issue if ($editable){ if (!empty($this->options)){ foreach($this->options as $option){ $optionsmenu[$option->id] = format_string($option->description); } choose_from_menu($optionsmenu, "element$this->name", $this->value, 'choose'); } else { echo "\t\t" . get_string('nooptions', 'tracker'); } } else { if (isset($this->options)){ $optionstrs = array(); foreach ($this->options as $option){ if ($this->value != null){ if ($this->value == $option->id){ $optionstrs[] = format_string($option->description); } } } echo implode(', ', $optionstrs); } } } } ?>
gpl-3.0
ned14/crust
src/getifaddrs.rs
18857
// Copyright 2015 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By contributing code to the SAFE Network Software, or to this project generally, you agree to be // bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the // Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. // // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. // // Please review the Licences for the specific language governing permissions and limitations // relating to use of the SAFE Network Software. use std::net::{IpAddr, Ipv4Addr}; /// Details about an interface on this host #[derive(Debug, PartialEq, Eq, Hash, Clone)] pub struct IfAddr { /// The name of the interface pub name: String, /// The IP address of the interface pub addr: IpAddr, /// The netmask of the interface pub netmask: IpAddr, /// How to send a broadcast on the interface pub broadcast: IpAddr, } impl IfAddr { /// Create a new IfAddr pub fn new() -> IfAddr { IfAddr { name: String::new(), addr: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), netmask: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), broadcast: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)) } } } #[cfg(not(windows))] mod getifaddrs_posix { use super::IfAddr; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::{mem, str}; use std::ffi::CStr; use libc::consts::os::bsd44::{AF_INET, AF_INET6}; use libc::funcs::bsd43::getifaddrs as posix_getifaddrs; use libc::funcs::bsd43::freeifaddrs as posix_freeifaddrs; use libc::types::os::common::bsd44::ifaddrs as posix_ifaddrs; use libc::types::os::common::bsd44::sockaddr as posix_sockaddr; use libc::types::os::common::bsd44::sockaddr_in as posix_sockaddr_in; use libc::types::os::common::bsd44::sockaddr_in6 as posix_sockaddr_in6; #[allow(unsafe_code)] fn sockaddr_to_ipaddr(sockaddr : *const posix_sockaddr) -> Option<IpAddr> { if sockaddr.is_null() { return None } if unsafe{*sockaddr}.sa_family as u32 == AF_INET as u32 { let ref sa = unsafe{*(sockaddr as *const posix_sockaddr_in)}; Some(IpAddr::V4(Ipv4Addr::new( ((sa.sin_addr.s_addr>>0) & 255) as u8, ((sa.sin_addr.s_addr>>8) & 255) as u8, ((sa.sin_addr.s_addr>>16) & 255) as u8, ((sa.sin_addr.s_addr>>24) & 255) as u8, ))) } else if unsafe{*sockaddr}.sa_family as u32 == AF_INET6 as u32 { let ref sa = unsafe{*(sockaddr as *const posix_sockaddr_in6)}; // Ignore all fe80:: addresses as these are link locals if sa.sin6_addr.s6_addr[0]==0x80fe { return None } Some(IpAddr::V6(Ipv6Addr::new( ((sa.sin6_addr.s6_addr[0] & 255)<<8) | ((sa.sin6_addr.s6_addr[0]>>8) & 255), ((sa.sin6_addr.s6_addr[1] & 255)<<8) | ((sa.sin6_addr.s6_addr[1]>>8) & 255), ((sa.sin6_addr.s6_addr[2] & 255)<<8) | ((sa.sin6_addr.s6_addr[2]>>8) & 255), ((sa.sin6_addr.s6_addr[3] & 255)<<8) | ((sa.sin6_addr.s6_addr[3]>>8) & 255), ((sa.sin6_addr.s6_addr[4] & 255)<<8) | ((sa.sin6_addr.s6_addr[4]>>8) & 255), ((sa.sin6_addr.s6_addr[5] & 255)<<8) | ((sa.sin6_addr.s6_addr[5]>>8) & 255), ((sa.sin6_addr.s6_addr[6] & 255)<<8) | ((sa.sin6_addr.s6_addr[6]>>8) & 255), ((sa.sin6_addr.s6_addr[7] & 255)<<8) | ((sa.sin6_addr.s6_addr[7]>>8) & 255), ))) } else { None } } #[cfg(any(target_os = "linux", target_os = "android", target_os = "nacl"))] fn do_broadcast(ifaddr : &posix_ifaddrs) -> IpAddr { sockaddr_to_ipaddr(ifaddr.ifa_ifu) .unwrap_or(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))) } #[cfg(any(target_os = "freebsd", target_os = "macos", target_os = "ios"))] fn do_broadcast(ifaddr : &posix_ifaddrs) -> IpAddr { sockaddr_to_ipaddr(ifaddr.ifa_dstaddr) .unwrap_or(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))) } /// Return a vector of IP details for all the valid interfaces on this host #[allow(unsafe_code)] pub fn getifaddrs() -> Vec<IfAddr> { let mut ret = Vec::<IfAddr>::new(); let mut ifaddrs : *mut posix_ifaddrs; unsafe { ifaddrs = mem::uninitialized(); if -1 == posix_getifaddrs(&mut ifaddrs) { panic!("failed to retrieve interface details from getifaddrs()"); } } let mut _ifaddr = ifaddrs; let mut first = true; while !_ifaddr.is_null() { if first { first=false; } else { _ifaddr = unsafe { (*_ifaddr).ifa_next }; } if _ifaddr.is_null() { break; } let ref ifaddr = unsafe { *_ifaddr }; // println!("ifaddr1={}, next={}", _ifaddr as u64, ifaddr.ifa_next as u64); if ifaddr.ifa_addr.is_null() { continue; } let mut item = IfAddr::new(); let name = unsafe { CStr::from_ptr(ifaddr.ifa_name) }.to_bytes(); item.name = item.name + str::from_utf8(name).unwrap(); match sockaddr_to_ipaddr(ifaddr.ifa_addr) { Some(a) => item.addr = a, None => continue, }; if let Some(a) = sockaddr_to_ipaddr(ifaddr.ifa_netmask) { item.netmask = a }; if (ifaddr.ifa_flags & 2 /*IFF_BROADCAST*/) != 0 { item.broadcast = do_broadcast(ifaddr); } ret.push(item); } unsafe { posix_freeifaddrs(ifaddrs); } ret } } #[cfg(not(windows))] pub fn getifaddrs() -> Vec<IfAddr> { getifaddrs_posix::getifaddrs() } #[cfg(windows)] mod getifaddrs_windows { use super::IfAddr; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::{str, ptr}; use std::ffi::CStr; use libc::types::common::c95::c_void; use libc::types::os::arch::c95::{c_char, c_ulong, size_t, c_int }; use libc::types::os::arch::extra::*; // libc source code says this is all the Windows integral types use libc::consts::os::extra::*; // win32 status code, constants etc use libc::consts::os::bsd44::*; // the winsock constants use libc::types::os::common::bsd44::*; // the winsock types use libc; #[repr(C)] #[allow(bad_style)] struct SOCKET_ADDRESS { pub lpSockaddr : *const sockaddr, pub iSockaddrLength : c_int, } #[repr(C)] #[allow(bad_style)] struct IP_ADAPTER_UNICAST_ADDRESS { pub Length : c_ulong, pub Flags : DWORD, pub Next : *const IP_ADAPTER_UNICAST_ADDRESS, pub Address : SOCKET_ADDRESS, // Loads more follows, but I'm not bothering to map these for now } #[repr(C)] #[allow(bad_style)] struct IP_ADAPTER_PREFIX { pub Length : c_ulong, pub Flags : DWORD, pub Next : *const IP_ADAPTER_PREFIX, pub Address : SOCKET_ADDRESS, pub PrefixLength : c_ulong, } #[repr(C)] #[allow(bad_style)] struct IP_ADAPTER_ADDRESSES { pub Length : c_ulong, pub IfIndex : DWORD, pub Next : *const IP_ADAPTER_ADDRESSES, pub AdapterName : *const c_char, pub FirstUnicastAddress : *const IP_ADAPTER_UNICAST_ADDRESS, FirstAnycastAddress : *const c_void, FirstMulticastAddress : *const c_void, FirstDnsServerAddress : *const c_void, DnsSuffix : *const c_void, Description : *const c_void, FriendlyName : *const c_void, PhysicalAddress : [c_char; 8], PhysicalAddressLength : DWORD, Flags : DWORD, Mtu : DWORD, IfType : DWORD, OperStatus : c_int, Ipv6IfIndex : DWORD, ZoneIndices : [DWORD; 16], pub FirstPrefix : *const IP_ADAPTER_PREFIX, // Loads more follows, but I'm not bothering to map these for now } #[link(name="Iphlpapi")] extern "system" { pub fn GetAdaptersAddresses(family : c_ulong, flags : c_ulong, reserved : *const c_void, addresses : *const IP_ADAPTER_ADDRESSES, size : *mut c_ulong) -> c_ulong; } #[allow(unsafe_code)] fn sockaddr_to_ipaddr(sockaddr : *const sockaddr) -> Option<IpAddr> { if sockaddr.is_null() { return None } if unsafe{*sockaddr}.sa_family as u32 == AF_INET as u32 { let ref sa = unsafe{*(sockaddr as *const sockaddr_in)}; // Ignore all 169.254.x.x addresses as these are not active interfaces if sa.sin_addr.s_addr & 65535 == 0xfea9 { return None } Some(IpAddr::V4(Ipv4Addr::new( ((sa.sin_addr.s_addr>>0) & 255) as u8, ((sa.sin_addr.s_addr>>8) & 255) as u8, ((sa.sin_addr.s_addr>>16) & 255) as u8, ((sa.sin_addr.s_addr>>24) & 255) as u8, ))) } else if unsafe{*sockaddr}.sa_family as u32 == AF_INET6 as u32 { let ref sa = unsafe{*(sockaddr as *const sockaddr_in6)}; // Ignore all fe80:: addresses as these are link locals if sa.sin6_addr.s6_addr[0]==0x80fe { return None } Some(IpAddr::V6(Ipv6Addr::new( ((sa.sin6_addr.s6_addr[0] & 255)<<8) | ((sa.sin6_addr.s6_addr[0]>>8) & 255), ((sa.sin6_addr.s6_addr[1] & 255)<<8) | ((sa.sin6_addr.s6_addr[1]>>8) & 255), ((sa.sin6_addr.s6_addr[2] & 255)<<8) | ((sa.sin6_addr.s6_addr[2]>>8) & 255), ((sa.sin6_addr.s6_addr[3] & 255)<<8) | ((sa.sin6_addr.s6_addr[3]>>8) & 255), ((sa.sin6_addr.s6_addr[4] & 255)<<8) | ((sa.sin6_addr.s6_addr[4]>>8) & 255), ((sa.sin6_addr.s6_addr[5] & 255)<<8) | ((sa.sin6_addr.s6_addr[5]>>8) & 255), ((sa.sin6_addr.s6_addr[6] & 255)<<8) | ((sa.sin6_addr.s6_addr[6]>>8) & 255), ((sa.sin6_addr.s6_addr[7] & 255)<<8) | ((sa.sin6_addr.s6_addr[7]>>8) & 255), ))) } else { None } } /// Return a vector of IP details for all the valid interfaces on this host #[allow(unsafe_code)] pub fn getifaddrs() -> Vec<IfAddr> { let mut ret = Vec::<IfAddr>::new(); let mut ifaddrs : *const IP_ADAPTER_ADDRESSES; let mut buffersize : c_ulong = 15000; loop { unsafe { ifaddrs = libc::malloc(buffersize as size_t) as *mut IP_ADAPTER_ADDRESSES; if ifaddrs.is_null() { panic!("Failed to allocate buffer in getifaddrs()"); } let retcode = GetAdaptersAddresses(0, 0x3e /* GAA_FLAG_SKIP_ANYCAST|GAA_FLAG_SKIP_MULTICAST|GAA_FLAG_SKIP_DNS_SERVER|GAA_FLAG_INCLUDE_PREFIX|GAA_FLAG_SKIP_FRIENDLY_NAME */, ptr::null(), ifaddrs, &mut buffersize) as c_int; match retcode { ERROR_SUCCESS => break, 111 /*ERROR_BUFFER_OVERFLOW*/ => { libc::free(ifaddrs as *mut c_void); buffersize = buffersize * 2; continue }, _ => panic!("GetAdaptersAddresses() failed with error code {}", retcode) } } } let mut _ifaddr = ifaddrs; let mut first = true; while !_ifaddr.is_null() { if first { first=false; } else { _ifaddr = unsafe { (*_ifaddr).Next }; } if _ifaddr.is_null() { break; } let ref ifaddr = unsafe { &*_ifaddr }; // println!("ifaddr1={}, next={}", _ifaddr as u64, ifaddr.ifa_next as u64); let mut addr = ifaddr.FirstUnicastAddress; if addr.is_null() { continue; } let mut firstaddr = true; while !addr.is_null() { if firstaddr { firstaddr=false; } else { addr = unsafe { (*addr).Next }; } if addr.is_null() { break; } let mut item = IfAddr::new(); let name = unsafe { CStr::from_ptr(ifaddr.AdapterName) }.to_bytes(); item.name = item.name + str::from_utf8(name).unwrap(); let ipaddr = sockaddr_to_ipaddr(unsafe { (*addr).Address.lpSockaddr }); if !ipaddr.is_some() { continue; } item.addr = ipaddr.unwrap(); // Search prefixes for a prefix matching addr let mut prefix = ifaddr.FirstPrefix; if !prefix.is_null() { let mut firstprefix = true; 'prefixloop: while !prefix.is_null() { if firstprefix { firstprefix=false; } else { prefix = unsafe { (*prefix).Next }; } if prefix.is_null() { break; } let ipprefix = sockaddr_to_ipaddr(unsafe { (*prefix).Address.lpSockaddr }); if !ipprefix.is_some() { continue; } match ipprefix.unwrap() { IpAddr::V4(ref a) => { if let IpAddr::V4(b) = item.addr { let mut netmask : [u8; 4] = [0; 4]; for n in 0..unsafe{ (*prefix).PrefixLength as usize + 7 }/8 { let x_byte = b.octets()[n]; let y_byte = a.octets()[n]; for m in 0..8 { if (n * 8) + m > unsafe{ (*prefix).PrefixLength as usize } { break; } let bit = 1 << m; if (x_byte & bit) == (y_byte & bit) { netmask[n] = netmask[n] | bit; } else { continue 'prefixloop; } } } item.netmask = IpAddr::V4(Ipv4Addr::new( netmask[0], netmask[1], netmask[2], netmask[3], )); let mut broadcast : [u8; 4] = b.octets(); for n in 0..4 { broadcast[n] = broadcast[n] | !netmask[n]; } item.broadcast = IpAddr::V4(Ipv4Addr::new( broadcast[0], broadcast[1], broadcast[2], broadcast[3], )); break 'prefixloop; } }, IpAddr::V6(ref a) => { if let IpAddr::V6(b) = item.addr { // Iterate the bits in the prefix, if they all match this prefix is the // right one, else try the next prefix let mut netmask : [u16; 8] = [0; 8]; for n in 0..unsafe{ (*prefix).PrefixLength as usize + 15 }/16 { let x_word = b.segments()[n]; let y_word = a.segments()[n]; for m in 0..16 { if (n * 16) + m > unsafe{ (*prefix).PrefixLength as usize } { break; } let bit = 1 << m; if (x_word & bit) == (y_word & bit) { netmask[n] = netmask[n] | bit; } else { continue 'prefixloop; } } } item.netmask = IpAddr::V6(Ipv6Addr::new( netmask[0], netmask[1], netmask[2], netmask[3], netmask[4], netmask[5], netmask[6], netmask[7], )); break 'prefixloop; } }, }; } } ret.push(item); } } unsafe { libc::free(ifaddrs as *mut c_void); } ret } } #[cfg(windows)] pub fn getifaddrs() -> Vec<IfAddr> { getifaddrs_windows::getifaddrs() } #[cfg(test)] mod test { use super::getifaddrs; use std::net::IpAddr; #[test] fn test_getifaddrs() { let mut has_loopback4 = false; let mut has_loopback6 = false; for ifaddr in getifaddrs() { println!(" Interface {} has IP {} netmask {} broadcast {}", ifaddr.name, ifaddr.addr, ifaddr.netmask, ifaddr.broadcast); match ifaddr.addr { IpAddr::V4(v4) => if v4.is_loopback() { has_loopback4=true; }, IpAddr::V6(v6) => if v6.is_loopback() { has_loopback6=true; }, } } // Quick sanity test, can't think of anything better assert_eq!(has_loopback4 || has_loopback6, true); } }
gpl-3.0
Pfeil/polyvr
extras/python/rosclient.py
1991
#!/usr/bin/python """ This script starts a web server that accepts any data string via post: import VR, httplib, urllib params = urllib.urlencode({'data' : 'myData'}) headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} conn = httplib.HTTPConnection("localhost:8000") conn.request("POST", "", params, headers) The data is then published on an ros network """ import os, sys def initNonBash(): p1 = '/opt/ros/jade/lib/python2.7/dist-packages' sys.path.insert(0, p1) sys.argv = [] os.environ['PYTHONPATH'] = p1 os.environ['ROS_ROOT'] = '/opt/ros/jade/share/ros' os.environ['ROS_DISTRO'] = 'jade' os.environ['ROSLISP_PACKAGE_DIRECTORIES']='' os.environ['CMAKE_PREFIX_PATH'] = '/opt/ros/jade' os.environ['PKG_CONFIG_PATH'] = '/opt/ros/jade/lib/pkgconfig:/opt/ros/jade/lib/x86_64-linux-gnu/pkgconfig' os.environ['CPATH'] = '/opt/ros/jade/include' os.environ['LD_LIBRARY_PATH']='/opt/ros/jade/lib:/opt/ros/jade/lib/x86_64-linux-gnu:/usr/lib32' os.environ['ROS_ETC_DIR']='/opt/ros/jade/etc/ros' os.environ['ROS_PACKAGE_PATH']='/opt/ros/jade/share:/opt/ros/jade/stacks' os.environ['ROS_MASTER_URI']='http://localhost:11311' #initNonBash() import rospy, std_msgs from sensor_msgs.msg import JointState def rosCallback(data): print data return # last step, init ros node rospy.init_node('polyvr') #rospy.Subscriber('/svh/joint_states', JointState, rosCallback) pub = rospy.Publisher('/svh/polyvr_data', std_msgs.msg.String, queue_size = 10) pub.publish(std_msgs.msg.String("foo")) # webserver from BaseHTTPServer import * import urllib class HttpHandler(BaseHTTPRequestHandler): def do_POST(self): content_len = int(self.headers.getheader('content-length', 0)) post_body = urllib.unquote_plus( self.rfile.read(content_len) ) print post_body pub.publish(std_msgs.msg.String(post_body)) server = HTTPServer( ('127.0.0.1', 8000), HttpHandler) server.serve_forever()
gpl-3.0
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/v8/src/libplatform/default-platform.cc
6963
// Copyright 2013 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/libplatform/default-platform.h" #include <algorithm> #include <queue> #include "include/libplatform/libplatform.h" #include "src/base/logging.h" #include "src/base/platform/platform.h" #include "src/base/platform/time.h" #include "src/base/sys-info.h" #include "src/libplatform/worker-thread.h" namespace v8 { namespace platform { v8::Platform* CreateDefaultPlatform(int thread_pool_size) { DefaultPlatform* platform = new DefaultPlatform(); platform->SetThreadPoolSize(thread_pool_size); platform->EnsureInitialized(); return platform; } bool PumpMessageLoop(v8::Platform* platform, v8::Isolate* isolate) { return reinterpret_cast<DefaultPlatform*>(platform)->PumpMessageLoop(isolate); } void SetTracingController( v8::Platform* platform, v8::platform::tracing::TracingController* tracing_controller) { return reinterpret_cast<DefaultPlatform*>(platform)->SetTracingController( tracing_controller); } const int DefaultPlatform::kMaxThreadPoolSize = 8; DefaultPlatform::DefaultPlatform() : initialized_(false), thread_pool_size_(0) {} DefaultPlatform::~DefaultPlatform() { if (tracing_controller_) { tracing_controller_->StopTracing(); tracing_controller_.reset(); } base::LockGuard<base::Mutex> guard(&lock_); queue_.Terminate(); if (initialized_) { for (auto i = thread_pool_.begin(); i != thread_pool_.end(); ++i) { delete *i; } } for (auto i = main_thread_queue_.begin(); i != main_thread_queue_.end(); ++i) { while (!i->second.empty()) { delete i->second.front(); i->second.pop(); } } for (auto i = main_thread_delayed_queue_.begin(); i != main_thread_delayed_queue_.end(); ++i) { while (!i->second.empty()) { delete i->second.top().second; i->second.pop(); } } } void DefaultPlatform::SetThreadPoolSize(int thread_pool_size) { base::LockGuard<base::Mutex> guard(&lock_); DCHECK(thread_pool_size >= 0); if (thread_pool_size < 1) { thread_pool_size = base::SysInfo::NumberOfProcessors() - 1; } thread_pool_size_ = std::max(std::min(thread_pool_size, kMaxThreadPoolSize), 1); } void DefaultPlatform::EnsureInitialized() { base::LockGuard<base::Mutex> guard(&lock_); if (initialized_) return; initialized_ = true; for (int i = 0; i < thread_pool_size_; ++i) thread_pool_.push_back(new WorkerThread(&queue_)); } Task* DefaultPlatform::PopTaskInMainThreadQueue(v8::Isolate* isolate) { auto it = main_thread_queue_.find(isolate); if (it == main_thread_queue_.end() || it->second.empty()) { return NULL; } Task* task = it->second.front(); it->second.pop(); return task; } Task* DefaultPlatform::PopTaskInMainThreadDelayedQueue(v8::Isolate* isolate) { auto it = main_thread_delayed_queue_.find(isolate); if (it == main_thread_delayed_queue_.end() || it->second.empty()) { return NULL; } double now = MonotonicallyIncreasingTime(); std::pair<double, Task*> deadline_and_task = it->second.top(); if (deadline_and_task.first > now) { return NULL; } it->second.pop(); return deadline_and_task.second; } bool DefaultPlatform::PumpMessageLoop(v8::Isolate* isolate) { Task* task = NULL; { base::LockGuard<base::Mutex> guard(&lock_); // Move delayed tasks that hit their deadline to the main queue. task = PopTaskInMainThreadDelayedQueue(isolate); while (task != NULL) { main_thread_queue_[isolate].push(task); task = PopTaskInMainThreadDelayedQueue(isolate); } task = PopTaskInMainThreadQueue(isolate); if (task == NULL) { return false; } } task->Run(); delete task; return true; } void DefaultPlatform::CallOnBackgroundThread(Task *task, ExpectedRuntime expected_runtime) { EnsureInitialized(); queue_.Append(task); } void DefaultPlatform::CallOnForegroundThread(v8::Isolate* isolate, Task* task) { base::LockGuard<base::Mutex> guard(&lock_); main_thread_queue_[isolate].push(task); } void DefaultPlatform::CallDelayedOnForegroundThread(Isolate* isolate, Task* task, double delay_in_seconds) { base::LockGuard<base::Mutex> guard(&lock_); double deadline = MonotonicallyIncreasingTime() + delay_in_seconds; main_thread_delayed_queue_[isolate].push(std::make_pair(deadline, task)); } void DefaultPlatform::CallIdleOnForegroundThread(Isolate* isolate, IdleTask* task) { UNREACHABLE(); } bool DefaultPlatform::IdleTasksEnabled(Isolate* isolate) { return false; } double DefaultPlatform::MonotonicallyIncreasingTime() { return base::TimeTicks::HighResolutionNow().ToInternalValue() / static_cast<double>(base::Time::kMicrosecondsPerSecond); } uint64_t DefaultPlatform::AddTraceEvent( char phase, const uint8_t* category_enabled_flag, const char* name, const char* scope, uint64_t id, uint64_t bind_id, int num_args, const char** arg_names, const uint8_t* arg_types, const uint64_t* arg_values, std::unique_ptr<v8::ConvertableToTraceFormat>* arg_convertables, unsigned int flags) { if (tracing_controller_) { return tracing_controller_->AddTraceEvent( phase, category_enabled_flag, name, scope, id, bind_id, num_args, arg_names, arg_types, arg_values, arg_convertables, flags); } return 0; } void DefaultPlatform::UpdateTraceEventDuration( const uint8_t* category_enabled_flag, const char* name, uint64_t handle) { if (tracing_controller_) { tracing_controller_->UpdateTraceEventDuration(category_enabled_flag, name, handle); } } const uint8_t* DefaultPlatform::GetCategoryGroupEnabled(const char* name) { if (tracing_controller_) { return tracing_controller_->GetCategoryGroupEnabled(name); } static uint8_t no = 0; return &no; } const char* DefaultPlatform::GetCategoryGroupName( const uint8_t* category_enabled_flag) { static const char dummy[] = "dummy"; return dummy; } void DefaultPlatform::SetTracingController( tracing::TracingController* tracing_controller) { tracing_controller_.reset(tracing_controller); } size_t DefaultPlatform::NumberOfAvailableBackgroundThreads() { return static_cast<size_t>(thread_pool_size_); } void DefaultPlatform::AddTraceStateObserver(TraceStateObserver* observer) { if (!tracing_controller_) return; tracing_controller_->AddTraceStateObserver(observer); } void DefaultPlatform::RemoveTraceStateObserver(TraceStateObserver* observer) { if (!tracing_controller_) return; tracing_controller_->RemoveTraceStateObserver(observer); } } // namespace platform } // namespace v8
gpl-3.0
jewzaam/lightblue-rest
metadata/src/test/java/com/redhat/lightblue/rest/metadata/ITCaseMetadataResourceTest.java
11364
/* * Copyright 2013 Red Hat, Inc. and/or its affiliates. * * This file is part of lightblue. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.redhat.lightblue.rest.metadata; import static com.redhat.lightblue.util.test.FileUtil.readFile; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import javax.inject.Inject; import javax.ws.rs.core.SecurityContext; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.json.JSONException; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.skyscreamer.jsonassert.JSONAssert; import com.mongodb.BasicDBObject; import com.redhat.lightblue.config.MetadataConfiguration; import com.redhat.lightblue.mongo.metadata.MongoMetadata; import com.redhat.lightblue.mongo.test.EmbeddedMongo; import com.redhat.lightblue.rest.RestConfiguration; import com.redhat.lightblue.rest.test.RestConfigurationRule; /** * @author lcestari */ @RunWith(Arquillian.class) public class ITCaseMetadataResourceTest { @Rule public final RestConfigurationRule resetRuleConfiguration = new RestConfigurationRule(); private static EmbeddedMongo mongo = EmbeddedMongo.getInstance(); @Before public void setup() { mongo.getDB().createCollection(MongoMetadata.DEFAULT_METADATA_COLLECTION, null); BasicDBObject index = new BasicDBObject("name", 1); index.put("version.value", 1); mongo.getDB().getCollection(MongoMetadata.DEFAULT_METADATA_COLLECTION).createIndex(index, "name", true); } @After public void teardown() { mongo.reset(); } @Deployment public static WebArchive createDeployment() { File[] libs = Maven.resolver().loadPomFromFile("pom.xml").importRuntimeDependencies().resolve().withTransitivity().asFile(); WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addAsResource(new File("src/test/resources/lightblue-metadata.json"), MetadataConfiguration.FILENAME) .addAsResource(new File("src/test/resources/datasources.json"), "datasources.json") .addAsResource(EmptyAsset.INSTANCE, "resources/test.properties"); for (File file : libs) { archive.addAsLibrary(file); } archive.addPackages(true, "com.redhat.lightblue"); return archive; } private String esc(String s) { return s.replace("'", "\""); } @Inject private AbstractMetadataResource cutMetadataResource; @Test public void testFirstIntegrationTest() throws IOException, URISyntaxException, JSONException { Assert.assertNotNull("MetadataResource was not injected by the container", cutMetadataResource); SecurityContext sc = new TestSecurityContext(); System.out.println("factory:" + RestConfiguration.getFactory()); String expectedCreated = readFile("expectedCreated.json"); String resultCreated = cutMetadataResource.createMetadata(sc, "country", "1.0.0", readFile("resultCreated.json")); JSONAssert.assertEquals(expectedCreated, resultCreated, false); String expectedDepGraph = readFile("expectedDepGraph.json").replace("Notsupportedyet", " Not supported yet"); String resultDepGraph = cutMetadataResource.getDepGraph(sc); JSONAssert.assertEquals(expectedDepGraph, resultDepGraph, false); String expectedDepGraph1 = readFile("expectedDepGraph1.json").replace("Notsupportedyet", " Not supported yet"); String resultDepGraph1 = cutMetadataResource.getDepGraph(sc, "country"); JSONAssert.assertEquals(expectedDepGraph1, resultDepGraph1, false); String expectedDepGraph2 = readFile("expectedDepGraph2.json").replace("Notsupportedyet", " Not supported yet"); String resultDepGraph2 = cutMetadataResource.getDepGraph(sc, "country", "1.0.0"); JSONAssert.assertEquals(expectedDepGraph2, resultDepGraph2, false); String expectedEntityNames = "{\"entities\":[\"country\"]}"; String resultEntityNames = cutMetadataResource.getEntityNames(sc); JSONAssert.assertEquals(expectedEntityNames, resultEntityNames, false); // no default version String expectedEntityRoles = esc("{'status':'ERROR','modifiedCount':0,'matchCount':0,'dataErrors':[{'data':{'name':'country'},'errors':[{'objectType':'error','context':'GetEntityRolesCommand','errorCode':'ERR_NO_METADATA','msg':'Could not get metadata for given input. Error message: version'}]}]}"); String expectedEntityRoles1 = esc("{'status':'ERROR','modifiedCount':0,'matchCount':0,'dataErrors':[{'data':{'name':'country'},'errors':[{'objectType':'error','context':'GetEntityRolesCommand/country','errorCode':'ERR_NO_METADATA','msg':'Could not get metadata for given input. Error message: version'}]}]}"); String resultEntityRoles = cutMetadataResource.getEntityRoles(sc); String resultEntityRoles1 = cutMetadataResource.getEntityRoles(sc, "country"); JSONAssert.assertEquals(expectedEntityRoles, resultEntityRoles, false); JSONAssert.assertEquals(expectedEntityRoles1, resultEntityRoles1, false); String expectedEntityRoles2 = readFile("expectedEntityRoles2.json"); String resultEntityRoles2 = cutMetadataResource.getEntityRoles(sc, "country", "1.0.0"); JSONAssert.assertEquals(expectedEntityRoles2, resultEntityRoles2, false); String expectedEntityVersions = esc("[{'version':'1.0.0','changelog':'blahblah'}]"); String resultEntityVersions = cutMetadataResource.getEntityVersions(sc, "country"); JSONAssert.assertEquals(expectedEntityVersions, resultEntityVersions, false); String expectedGetMetadata = esc("{'entityInfo':{'name':'country','indexes':[{'name':null,'unique':true,'fields':[{'field':'name','dir':'$asc'}]},{'name': null,'unique': true,'fields': [{'field': '_id','dir': '$asc'}]}],'datastore':{'backend':'mongo','datasource':'mongo','collection':'country'}},'schema':{'name':'country','version':{'value':'1.0.0','changelog':'blahblah'},'status':{'value':'active'},'access':{'insert':['anyone'],'update':['anyone'],'find':['anyone'],'delete':['anyone']},'fields':{'iso3code':{'type':'string'},'name':{'type':'string'},'iso2code':{'type':'string'},'objectType':{'type':'string','access':{'find':['anyone'],'update':['noone']},'constraints':{'required':true,'minLength':1}}}}}"); String resultGetMetadata = cutMetadataResource.getMetadata(sc, "country", "1.0.0"); JSONAssert.assertEquals(expectedGetMetadata, resultGetMetadata, false); String expectedCreateSchema = readFile("expectedCreateSchema.json"); String resultCreateSchema = cutMetadataResource.createSchema(sc, "country", "1.1.0", readFile("expectedCreateSchemaInput.json")); JSONAssert.assertEquals(expectedCreateSchema, resultCreateSchema, false); String expectedUpdateEntityInfo = readFile("expectedUpdateEntityInfo.json"); String resultUpdateEntityInfo = cutMetadataResource.updateEntityInfo(sc, "country", readFile("expectedUpdateEntityInfoInput.json")); JSONAssert.assertEquals(expectedUpdateEntityInfo, resultUpdateEntityInfo, false); String x = cutMetadataResource.setDefaultVersion(sc, "country", "1.0.0"); String expected = esc("{'entityInfo':{'name':'country','defaultVersion':'1.0.0','indexes':[{'name':null,'unique':true,'fields':[{'field':'name','dir':'$asc'}]},{'name': null,'unique': true,'fields': [{'field': '_id','dir': '$asc'}]}],'datastore':{'backend':'mongo','datasource':'mongo','collection':'country'}},'schema':{'name':'country','version':{'value':'1.0.0','changelog':'blahblah'},'status':{'value':'active'},'access':{'insert':['anyone'],'update':['anyone'],'find':['anyone'],'delete':['anyone']},'fields':{'iso3code':{'type':'string'},'name':{'type':'string'},'iso2code':{'type':'string'},'objectType':{'type':'string','access':{'find':['anyone'],'update':['noone']},'constraints':{'required':true,'minLength':1}}}}}"); JSONAssert.assertEquals(expected, x, false); x = cutMetadataResource.clearDefaultVersion(sc, "country"); //System.out.println(x); expected = esc("{'name':'country','indexes':[{'name':null,'unique':true,'fields':[{'field':'name','dir':'$asc'}]},{'name': null,'unique': true,'fields': [{'field': '_id','dir': '$asc'}]}],'datastore':{'backend':'mongo','datasource':'mongo','collection':'country'}}"); JSONAssert.assertEquals(expected, x, false); String expectedUpdateSchemaStatus = esc("{'entityInfo':{'name':'country','indexes':[{'name':null,'unique':true,'fields':[{'field':'name','dir':'$asc'}]},{'name': null,'unique': true,'fields': [{'field': '_id','dir': '$asc'}]}],'datastore':{'backend':'mongo','datasource':'mongo','collection':'country'}},'schema':{'name':'country','version':{'value':'1.0.0','changelog':'blahblah'},'status':{'value':'deprecated'},'access':{'insert':['anyone'],'update':['anyone'],'find':['anyone'],'delete':['anyone']},'fields':{'iso3code':{'type':'string'},'name':{'type':'string'},'iso2code':{'type':'string'},'objectType':{'type':'string','access':{'find':['anyone'],'update':['noone']},'constraints':{'required':true,'minLength':1}}}}}"); String resultUpdateSchemaStatus = cutMetadataResource.updateSchemaStatus(sc, "country", "1.0.0", "deprecated", "No comment"); JSONAssert.assertEquals(expectedUpdateSchemaStatus, resultUpdateSchemaStatus, false); } @Test public void createMetadataAlsoUpdates() throws Exception { Assert.assertNotNull("MetadataResource was not injected by the container", cutMetadataResource); SecurityContext sc = new TestSecurityContext(); System.out.println("factory:" + RestConfiguration.getFactory()); String expectedCreated = readFile("expectedCreated.json"); String resultCreated = cutMetadataResource.createMetadata(sc, "country", "1.0.0", readFile("resultCreated.json")); JSONAssert.assertEquals(expectedCreated, resultCreated, false); String expectedUpdateEntityInfo = readFile("expectedCreateSchema.json"); String resultUpdateEntityInfo = cutMetadataResource.createMetadata(sc, "country", "1.1.0", expectedUpdateEntityInfo); JSONAssert.assertEquals(expectedUpdateEntityInfo, resultUpdateEntityInfo, false); } }
gpl-3.0
subhashsaran/rails-dashboard
db/migrate/20140310191148_create_relationships.rb
372
class CreateRelationships < ActiveRecord::Migration def change create_table :relationships do |t| t.integer :follower_id t.integer :followed_id t.timestamps end add_index :relationships, :follower_id add_index :relationships, :followed_id add_index :relationships, [:follower_id, :followed_id], :unique => true end end
gpl-3.0
TheTechnobear/MEC
mec-vst/JuceLibraryCode/modules/juce_events/messages/juce_ApplicationBase.cpp
9864
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2017 - ROLI Ltd. JUCE is an open source library subject to commercial or open-source licensing. The code included in this file is provided under the terms of the ISC license http://www.isc.org/downloads/software-support-policy/isc-license. Permission To use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted provided that the above copyright notice and this permission notice appear in all copies. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ JUCEApplicationBase::CreateInstanceFunction JUCEApplicationBase::createInstance = 0; JUCEApplicationBase* JUCEApplicationBase::appInstance = nullptr; #if JUCE_IOS void* JUCEApplicationBase::iOSCustomDelegate = nullptr; #endif JUCEApplicationBase::JUCEApplicationBase() : appReturnValue (0), stillInitialising (true) { jassert (isStandaloneApp() && appInstance == nullptr); appInstance = this; } JUCEApplicationBase::~JUCEApplicationBase() { jassert (appInstance == this); appInstance = nullptr; } void JUCEApplicationBase::setApplicationReturnValue (const int newReturnValue) noexcept { appReturnValue = newReturnValue; } // This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown.. void JUCEApplicationBase::appWillTerminateByForce() { JUCE_AUTORELEASEPOOL { { const ScopedPointer<JUCEApplicationBase> app (appInstance); if (app != nullptr) app->shutdownApp(); } DeletedAtShutdown::deleteAll(); MessageManager::deleteInstance(); } } void JUCEApplicationBase::quit() { MessageManager::getInstance()->stopDispatchLoop(); } void JUCEApplicationBase::sendUnhandledException (const std::exception* const e, const char* const sourceFile, const int lineNumber) { if (JUCEApplicationBase* const app = JUCEApplicationBase::getInstance()) { // If you hit this assertion then the __FILE__ macro is providing a // relative path instead of an absolute path. On Windows this will be // a path relative to the build directory rather than the currently // running application. To fix this you must compile with the /FC flag. jassert (File::isAbsolutePath (sourceFile)); app->unhandledException (e, sourceFile, lineNumber); } } //============================================================================== #if ! (JUCE_IOS || JUCE_ANDROID) #define JUCE_HANDLE_MULTIPLE_INSTANCES 1 #endif #if JUCE_HANDLE_MULTIPLE_INSTANCES struct JUCEApplicationBase::MultipleInstanceHandler : public ActionListener { public: MultipleInstanceHandler (const String& appName) : appLock ("juceAppLock_" + appName) { } bool sendCommandLineToPreexistingInstance() { if (appLock.enter (0)) return false; JUCEApplicationBase* const app = JUCEApplicationBase::getInstance(); jassert (app != nullptr); MessageManager::broadcastMessage (app->getApplicationName() + "/" + app->getCommandLineParameters()); return true; } void actionListenerCallback (const String& message) override { if (JUCEApplicationBase* const app = JUCEApplicationBase::getInstance()) { const String appName (app->getApplicationName()); if (message.startsWith (appName + "/")) app->anotherInstanceStarted (message.substring (appName.length() + 1)); } } private: InterProcessLock appLock; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultipleInstanceHandler) }; bool JUCEApplicationBase::sendCommandLineToPreexistingInstance() { jassert (multipleInstanceHandler == nullptr); // this must only be called once! multipleInstanceHandler = new MultipleInstanceHandler (getApplicationName()); return multipleInstanceHandler->sendCommandLineToPreexistingInstance(); } #else struct JUCEApplicationBase::MultipleInstanceHandler {}; #endif //============================================================================== #if JUCE_ANDROID StringArray JUCEApplicationBase::getCommandLineParameterArray() { return {}; } String JUCEApplicationBase::getCommandLineParameters() { return {}; } #else #if JUCE_WINDOWS && ! defined (_CONSOLE) String JUCE_CALLTYPE JUCEApplicationBase::getCommandLineParameters() { return CharacterFunctions::findEndOfToken (CharPointer_UTF16 (GetCommandLineW()), CharPointer_UTF16 (L" "), CharPointer_UTF16 (L"\"")).findEndOfWhitespace(); } StringArray JUCE_CALLTYPE JUCEApplicationBase::getCommandLineParameterArray() { StringArray s; int argc = 0; if (LPWSTR* const argv = CommandLineToArgvW (GetCommandLineW(), &argc)) { s = StringArray (argv + 1, argc - 1); LocalFree (argv); } return s; } #else #if JUCE_IOS extern int juce_iOSMain (int argc, const char* argv[], void* classPtr); #endif #if JUCE_MAC extern void initialiseNSApplication(); #endif #if JUCE_LINUX && JUCE_MODULE_AVAILABLE_juce_gui_extra && (! defined(JUCE_WEB_BROWSER) || JUCE_WEB_BROWSER) extern int juce_gtkWebkitMain (int argc, const char* argv[]); #endif #if JUCE_WINDOWS const char* const* juce_argv = nullptr; int juce_argc = 0; #else extern const char* const* juce_argv; // declared in juce_core extern int juce_argc; #endif String JUCEApplicationBase::getCommandLineParameters() { String argString; for (int i = 1; i < juce_argc; ++i) { String arg (juce_argv[i]); if (arg.containsChar (' ') && ! arg.isQuotedString()) arg = arg.quoted ('"'); argString << arg << ' '; } return argString.trim(); } StringArray JUCEApplicationBase::getCommandLineParameterArray() { return StringArray (juce_argv + 1, juce_argc - 1); } int JUCEApplicationBase::main (int argc, const char* argv[]) { JUCE_AUTORELEASEPOOL { juce_argc = argc; juce_argv = argv; #if JUCE_MAC initialiseNSApplication(); #endif #if JUCE_LINUX && JUCE_MODULE_AVAILABLE_juce_gui_extra && (! defined(JUCE_WEB_BROWSER) || JUCE_WEB_BROWSER) if (argc >= 2 && String (argv[1]) == "--juce-gtkwebkitfork-child") return juce_gtkWebkitMain (argc, argv); #endif #if JUCE_IOS return juce_iOSMain (argc, argv, iOSCustomDelegate); #else return JUCEApplicationBase::main(); #endif } } #endif //============================================================================== int JUCEApplicationBase::main() { ScopedJuceInitialiser_GUI libraryInitialiser; jassert (createInstance != nullptr); const ScopedPointer<JUCEApplicationBase> app (createInstance()); jassert (app != nullptr); if (! app->initialiseApp()) return app->shutdownApp(); JUCE_TRY { // loop until a quit message is received.. MessageManager::getInstance()->runDispatchLoop(); } JUCE_CATCH_EXCEPTION return app->shutdownApp(); } #endif //============================================================================== bool JUCEApplicationBase::initialiseApp() { #if JUCE_HANDLE_MULTIPLE_INSTANCES if ((! moreThanOneInstanceAllowed()) && sendCommandLineToPreexistingInstance()) { DBG ("Another instance is running - quitting..."); return false; } #endif #if JUCE_WINDOWS && JUCE_STANDALONE_APPLICATION && (! defined (_CONSOLE)) && (! JUCE_MINGW) if (AttachConsole (ATTACH_PARENT_PROCESS) != 0) { // if we've launched a GUI app from cmd.exe or PowerShell, we need this to enable printf etc. // However, only reassign stdout, stderr, stdin if they have not been already opened by // a redirect or similar. FILE* ignore; if (_fileno(stdout) < 0) freopen_s (&ignore, "CONOUT$", "w", stdout); if (_fileno(stderr) < 0) freopen_s (&ignore, "CONOUT$", "w", stderr); if (_fileno(stdin) < 0) freopen_s (&ignore, "CONIN$", "r", stdin); } #endif // let the app do its setting-up.. initialise (getCommandLineParameters()); stillInitialising = false; if (MessageManager::getInstance()->hasStopMessageBeenSent()) return false; #if JUCE_HANDLE_MULTIPLE_INSTANCES if (multipleInstanceHandler != nullptr) MessageManager::getInstance()->registerBroadcastListener (multipleInstanceHandler); #endif return true; } int JUCEApplicationBase::shutdownApp() { jassert (JUCEApplicationBase::getInstance() == this); #if JUCE_HANDLE_MULTIPLE_INSTANCES if (multipleInstanceHandler != nullptr) MessageManager::getInstance()->deregisterBroadcastListener (multipleInstanceHandler); #endif JUCE_TRY { // give the app a chance to clean up.. shutdown(); } JUCE_CATCH_EXCEPTION multipleInstanceHandler = nullptr; return getApplicationReturnValue(); }
gpl-3.0
nerdiabet/webSPELL
languages/sl/demos.php
3504
<?php /* ########################################################################## # # # Version 4 / / / # # -----------__---/__---__------__----__---/---/- # # | /| / /___) / ) (_ ` / ) /___) / / # # _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ # # Free Content / Management System # # / # # # # # # Copyright 2005-2015 by webspell.org # # # # visit webSPELL.org, webspell.info to get webSPELL for free # # - Script runs under the GNU GENERAL PUBLIC LICENSE # # - It's NOT allowed to remove this copyright-tag # # -- http://www.fsf.org/licensing/licenses/gpl.html # # # # Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), # # Far Development by Development Team - webspell.org # # # # visit webspell.org # # # ########################################################################## */ $language_array = array( /* do not edit above this line */ 'all_demos' => 'Vsi demo-ti', 'allready_rated' => 'Že ocenjeno', 'clan1' => 'Klan 1', 'clan1_country' => 'Zemlja klana 1', 'clan1_homepage' => 'Domača stran klana 1', 'clan1_name' => 'Ime klana 1', 'clan1_tag' => 'Tag klana 1', 'clan2' => 'Klan 2', 'clan2_country' => 'Zemlja klana 2', 'clan2_homepage' => 'Domača stran klana 2', 'clan2_name' => 'Ime klana 2', 'clan2_tag' => 'Tag klana 2', 'date' => 'Datum', 'delete' => 'izbriši', 'demo_details' => 'Demo detalji', 'demo_upload' => 'Naloži demo', 'demos' => 'demo-ti', 'disable_comments' => 'Onemogoči komentarje', 'download' => 'Prenesi', 'download_now' => 'Prenesi zdaj', 'downloaded' => 'Prenesli', 'downloads' => 'Prenosi', 'edit' => 'uredi', 'edit_demo' => 'uredi demo', 'extern_link' => 'Externi link', 'file_exists' => 'Dokument že obstaja!', 'game' => 'Igra', 'league' => 'Liga', 'league_homepage' => 'Domača stran lige', 'maps' => 'Mape', 'match' => 'Bitke', 'new_demo' => 'Novi demo', 'no_access' => 'Ni dostopa!', 'no_demos' => 'ni demo-tov', 'perfect' => 'Odličen', 'players' => 'Igralci', 'poor' => 'Slab', 'rate' => 'Oceni', 'rate_with' => 'Oceni od 0 do 10 točk', 'rating' => 'Ocena', 'save_demo' => 'Shrani demo', 'sort' => 'Razvrsti', 'to_download' => 'Morate biti registrirani in prijavljeni prenesti to demo!', 'to_rate' => 'Morate biti registrirani in prijavljeni oceniti ta demo!', 'update_demo' => 'Posodobi izmjene', 'user_comments' => 'Omogoči komentarje uporabnikom', 'visitor_comments' => 'Omogoči komentarje obiskovalcem' );
gpl-3.0
mochaoss/inspace
inspace/tests/core/test_models.py
2028
import pytest from django.db.utils import IntegrityError from mixer.backend.django import mixer from core.models import Planet, Resource, ResourceLink pytestmark = pytest.mark.django_db def test_planet_uniqueness(): mixer.blend(Planet, name='test name') with pytest.raises(IntegrityError): mixer.blend(Planet, name='test name') def test_planet_str(): planet = mixer.blend(Planet, name='test name') assert 'test name' == str(planet) def test_resource_uniqueness(): mixer.blend(Resource, title='test title') with pytest.raises(IntegrityError): mixer.blend(Resource, title='test title') # ResourceLink should update the slug field if not provided def test_resource_link_save_method_mixin(): resource_link = mixer.blend( ResourceLink, url='https://www.planetexpress.com/', title='Planet Express', planet__name='Earth' ) assert resource_link.slug == 'planet-express' def test_resource_save_method_mixin(): resource = mixer.blend( ResourceLink, title='Planet Express', planet__name='Earth' ) assert resource.slug == 'planet-express' def test_resource_str(): resource = mixer.blend(Resource, title='test title') assert 'test title' == str(resource) def test_resource_is_link(): assert not mixer.blend(Resource).is_link() def test_resource_link_uniqueness_title(): mixer.blend(ResourceLink, title='test title', url='') with pytest.raises(IntegrityError): mixer.blend(ResourceLink, title='test title') def test_resource_link_uniqueness_url(): mixer.blend(ResourceLink, url='www.testurl.com') with pytest.raises(IntegrityError): mixer.blend(ResourceLink, url='www.testurl.com') def test_resource_link_str(): resource_link = mixer.blend(ResourceLink, url='www.testurl.com', title="test title") assert 'test title <www.testurl.com>' == str(resource_link) def test_resource_link_is_link(): assert mixer.blend(ResourceLink, url='').is_link()
gpl-3.0
TheValarProject/AwakenDreamsClient
mcp/src/minecraft/net/minecraft/util/math/MathHelper.java
17366
package net.minecraft.util.math; import java.util.Random; import java.util.UUID; public class MathHelper { public static final float SQRT_2 = sqrt_float(2.0F); /** * A table of sin values computed from 0 (inclusive) to 2*pi (exclusive), with steps of 2*PI / 65536. */ private static final float[] SIN_TABLE = new float[65536]; private static final Random RANDOM = new Random(); /** * Though it looks like an array, this is really more like a mapping. Key (index of this array) is the upper 5 bits * of the result of multiplying a 32-bit unsigned integer by the B(2, 5) De Bruijn sequence 0x077CB531. Value * (value stored in the array) is the unique index (from the right) of the leftmost one-bit in a 32-bit unsigned * integer that can cause the upper 5 bits to get that value. Used for highly optimized "find the log-base-2 of * this number" calculations. */ private static final int[] MULTIPLY_DE_BRUIJN_BIT_POSITION; private static final double FRAC_BIAS; private static final double[] ASINE_TAB; private static final double[] COS_TAB; /** * sin looked up in a table */ public static float sin(float value) { return SIN_TABLE[(int)(value * 10430.378F) & 65535]; } /** * cos looked up in the sin table with the appropriate offset */ public static float cos(float value) { return SIN_TABLE[(int)(value * 10430.378F + 16384.0F) & 65535]; } public static float sqrt_float(float value) { return (float)Math.sqrt((double)value); } public static float sqrt_double(double value) { return (float)Math.sqrt(value); } /** * Returns the greatest integer less than or equal to the float argument */ public static int floor_float(float value) { int i = (int)value; return value < (float)i ? i - 1 : i; } /** * returns par0 cast as an int, and no greater than Integer.MAX_VALUE-1024 */ public static int truncateDoubleToInt(double value) { return (int)(value + 1024.0D) - 1024; } /** * Returns the greatest integer less than or equal to the double argument */ public static int floor_double(double value) { int i = (int)value; return value < (double)i ? i - 1 : i; } /** * Long version of floor_double */ public static long floor_double_long(double value) { long i = (long)value; return value < (double)i ? i - 1L : i; } public static int absFloor(double value) { return (int)(value >= 0.0D ? value : -value + 1.0D); } public static float abs(float value) { return value >= 0.0F ? value : -value; } /** * Returns the unsigned value of an int. */ public static int abs_int(int value) { return value >= 0 ? value : -value; } public static int ceiling_float_int(float value) { int i = (int)value; return value > (float)i ? i + 1 : i; } public static int ceiling_double_int(double value) { int i = (int)value; return value > (double)i ? i + 1 : i; } /** * Returns the value of the first parameter, clamped to be within the lower and upper limits given by the second and * third parameters. */ public static int clamp_int(int num, int min, int max) { return num < min ? min : (num > max ? max : num); } /** * Returns the value of the first parameter, clamped to be within the lower and upper limits given by the second and * third parameters */ public static float clamp_float(float num, float min, float max) { return num < min ? min : (num > max ? max : num); } public static double clamp_double(double num, double min, double max) { return num < min ? min : (num > max ? max : num); } public static double denormalizeClamp(double lowerBnd, double upperBnd, double slide) { return slide < 0.0D ? lowerBnd : (slide > 1.0D ? upperBnd : lowerBnd + (upperBnd - lowerBnd) * slide); } /** * Maximum of the absolute value of two numbers. */ public static double abs_max(double p_76132_0_, double p_76132_2_) { if (p_76132_0_ < 0.0D) { p_76132_0_ = -p_76132_0_; } if (p_76132_2_ < 0.0D) { p_76132_2_ = -p_76132_2_; } return p_76132_0_ > p_76132_2_ ? p_76132_0_ : p_76132_2_; } /** * Buckets an integer with specifed bucket sizes. */ public static int bucketInt(int p_76137_0_, int p_76137_1_) { return p_76137_0_ < 0 ? -((-p_76137_0_ - 1) / p_76137_1_) - 1 : p_76137_0_ / p_76137_1_; } public static int getRandomIntegerInRange(Random random, int minimum, int maximum) { return minimum >= maximum ? minimum : random.nextInt(maximum - minimum + 1) + minimum; } public static float randomFloatClamp(Random random, float minimum, float maximum) { return minimum >= maximum ? minimum : random.nextFloat() * (maximum - minimum) + minimum; } public static double getRandomDoubleInRange(Random random, double minimum, double maximum) { return minimum >= maximum ? minimum : random.nextDouble() * (maximum - minimum) + minimum; } public static double average(long[] values) { long i = 0L; for (long j : values) { i += j; } return (double)i / (double)values.length; } public static boolean epsilonEquals(float p_180185_0_, float p_180185_1_) { return abs(p_180185_1_ - p_180185_0_) < 1.0E-5F; } public static int normalizeAngle(int p_180184_0_, int p_180184_1_) { return (p_180184_0_ % p_180184_1_ + p_180184_1_) % p_180184_1_; } public static float positiveModulo(float numerator, float denominator) { return (numerator % denominator + denominator) % denominator; } /** * the angle is reduced to an angle between -180 and +180 by mod, and a 360 check */ public static float wrapDegrees(float value) { value = value % 360.0F; if (value >= 180.0F) { value -= 360.0F; } if (value < -180.0F) { value += 360.0F; } return value; } /** * the angle is reduced to an angle between -180 and +180 by mod, and a 360 check */ public static double wrapDegrees(double value) { value = value % 360.0D; if (value >= 180.0D) { value -= 360.0D; } if (value < -180.0D) { value += 360.0D; } return value; } /** * Adjust the angle so that his value is in range [-180;180[ */ public static int clampAngle(int angle) { angle = angle % 360; if (angle >= 180) { angle -= 360; } if (angle < -180) { angle += 360; } return angle; } /** * parses the string as integer or returns the second parameter if it fails */ public static int parseIntWithDefault(String value, int defaultValue) { try { return Integer.parseInt(value); } catch (Throwable var3) { return defaultValue; } } /** * parses the string as integer or returns the second parameter if it fails. this value is capped to par2 */ public static int parseIntWithDefaultAndMax(String value, int defaultValue, int max) { return Math.max(max, parseIntWithDefault(value, defaultValue)); } /** * parses the string as double or returns the second parameter if it fails. */ public static double parseDoubleWithDefault(String value, double defaultValue) { try { return Double.parseDouble(value); } catch (Throwable var4) { return defaultValue; } } public static double parseDoubleWithDefaultAndMax(String value, double defaultValue, double max) { return Math.max(max, parseDoubleWithDefault(value, defaultValue)); } /** * Returns the input value rounded up to the next highest power of two. */ public static int roundUpToPowerOfTwo(int value) { int i = value - 1; i = i | i >> 1; i = i | i >> 2; i = i | i >> 4; i = i | i >> 8; i = i | i >> 16; return i + 1; } /** * Is the given value a power of two? (1, 2, 4, 8, 16, ...) */ private static boolean isPowerOfTwo(int value) { return value != 0 && (value & value - 1) == 0; } /** * Uses a B(2, 5) De Bruijn sequence and a lookup table to efficiently calculate the log-base-two of the given * value. Optimized for cases where the input value is a power-of-two. If the input value is not a power-of-two, * then subtract 1 from the return value. */ public static int calculateLogBaseTwoDeBruijn(int value) { value = isPowerOfTwo(value) ? value : roundUpToPowerOfTwo(value); return MULTIPLY_DE_BRUIJN_BIT_POSITION[(int)((long)value * 125613361L >> 27) & 31]; } /** * Efficiently calculates the floor of the base-2 log of an integer value. This is effectively the index of the * highest bit that is set. For example, if the number in binary is 0...100101, this will return 5. */ public static int calculateLogBaseTwo(int value) { return calculateLogBaseTwoDeBruijn(value) - (isPowerOfTwo(value) ? 0 : 1); } /** * Rounds the first parameter up to the next interval of the second parameter. * * For instance, {@code roundUp(1, 4)} returns 4; {@code roundUp(0, 4)} returns 0; and {@code roundUp(4, 4)} returns * 4. */ public static int roundUp(int number, int interval) { if (interval == 0) { return 0; } else if (number == 0) { return interval; } else { if (number < 0) { interval *= -1; } int i = number % interval; return i == 0 ? number : number + interval - i; } } /** * Makes an integer color from the given red, green, and blue float values */ public static int rgb(float rIn, float gIn, float bIn) { return rgb(floor_float(rIn * 255.0F), floor_float(gIn * 255.0F), floor_float(bIn * 255.0F)); } /** * Makes a single int color with the given red, green, and blue values. */ public static int rgb(int rIn, int gIn, int bIn) { int lvt_3_1_ = (rIn << 8) + gIn; lvt_3_1_ = (lvt_3_1_ << 8) + bIn; return lvt_3_1_; } public static int multiplyColor(int p_180188_0_, int p_180188_1_) { int i = (p_180188_0_ & 16711680) >> 16; int j = (p_180188_1_ & 16711680) >> 16; int k = (p_180188_0_ & 65280) >> 8; int l = (p_180188_1_ & 65280) >> 8; int i1 = (p_180188_0_ & 255) >> 0; int j1 = (p_180188_1_ & 255) >> 0; int k1 = (int)((float)i * (float)j / 255.0F); int l1 = (int)((float)k * (float)l / 255.0F); int i2 = (int)((float)i1 * (float)j1 / 255.0F); return p_180188_0_ & -16777216 | k1 << 16 | l1 << 8 | i2; } /** * Gets the decimal portion of the given double. For instance, {@code frac(5.5)} returns {@code .5}. */ public static double frac(double number) { return number - Math.floor(number); } public static long getPositionRandom(Vec3i pos) { return getCoordinateRandom(pos.getX(), pos.getY(), pos.getZ()); } public static long getCoordinateRandom(int x, int y, int z) { long i = (long)(x * 3129871) ^ (long)z * 116129781L ^ (long)y; i = i * i * 42317861L + i * 11L; return i; } public static UUID getRandomUuid(Random rand) { long i = rand.nextLong() & -61441L | 16384L; long j = rand.nextLong() & 4611686018427387903L | Long.MIN_VALUE; return new UUID(i, j); } /** * Generates a random UUID using the shared random */ public static UUID getRandomUUID() { return getRandomUuid(RANDOM); } public static double pct(double p_181160_0_, double p_181160_2_, double p_181160_4_) { return (p_181160_0_ - p_181160_2_) / (p_181160_4_ - p_181160_2_); } public static double atan2(double p_181159_0_, double p_181159_2_) { double d0 = p_181159_2_ * p_181159_2_ + p_181159_0_ * p_181159_0_; if (Double.isNaN(d0)) { return Double.NaN; } else { boolean flag = p_181159_0_ < 0.0D; if (flag) { p_181159_0_ = -p_181159_0_; } boolean flag1 = p_181159_2_ < 0.0D; if (flag1) { p_181159_2_ = -p_181159_2_; } boolean flag2 = p_181159_0_ > p_181159_2_; if (flag2) { double d1 = p_181159_2_; p_181159_2_ = p_181159_0_; p_181159_0_ = d1; } double d9 = fastInvSqrt(d0); p_181159_2_ = p_181159_2_ * d9; p_181159_0_ = p_181159_0_ * d9; double d2 = FRAC_BIAS + p_181159_0_; int i = (int)Double.doubleToRawLongBits(d2); double d3 = ASINE_TAB[i]; double d4 = COS_TAB[i]; double d5 = d2 - FRAC_BIAS; double d6 = p_181159_0_ * d4 - p_181159_2_ * d5; double d7 = (6.0D + d6 * d6) * d6 * 0.16666666666666666D; double d8 = d3 + d7; if (flag2) { d8 = (Math.PI / 2D) - d8; } if (flag1) { d8 = Math.PI - d8; } if (flag) { d8 = -d8; } return d8; } } public static double fastInvSqrt(double p_181161_0_) { double d0 = 0.5D * p_181161_0_; long i = Double.doubleToRawLongBits(p_181161_0_); i = 6910469410427058090L - (i >> 1); p_181161_0_ = Double.longBitsToDouble(i); p_181161_0_ = p_181161_0_ * (1.5D - d0 * p_181161_0_ * p_181161_0_); return p_181161_0_; } public static int hsvToRGB(float p_181758_0_, float p_181758_1_, float p_181758_2_) { int i = (int)(p_181758_0_ * 6.0F) % 6; float f = p_181758_0_ * 6.0F - (float)i; float f1 = p_181758_2_ * (1.0F - p_181758_1_); float f2 = p_181758_2_ * (1.0F - f * p_181758_1_); float f3 = p_181758_2_ * (1.0F - (1.0F - f) * p_181758_1_); float f4; float f5; float f6; switch (i) { case 0: f4 = p_181758_2_; f5 = f3; f6 = f1; break; case 1: f4 = f2; f5 = p_181758_2_; f6 = f1; break; case 2: f4 = f1; f5 = p_181758_2_; f6 = f3; break; case 3: f4 = f1; f5 = f2; f6 = p_181758_2_; break; case 4: f4 = f3; f5 = f1; f6 = p_181758_2_; break; case 5: f4 = p_181758_2_; f5 = f1; f6 = f2; break; default: throw new RuntimeException("Something went wrong when converting from HSV to RGB. Input was " + p_181758_0_ + ", " + p_181758_1_ + ", " + p_181758_2_); } int j = clamp_int((int)(f4 * 255.0F), 0, 255); int k = clamp_int((int)(f5 * 255.0F), 0, 255); int l = clamp_int((int)(f6 * 255.0F), 0, 255); return j << 16 | k << 8 | l; } public static int getHash(int p_188208_0_) { p_188208_0_ = p_188208_0_ ^ p_188208_0_ >>> 16; p_188208_0_ = p_188208_0_ * -2048144789; p_188208_0_ = p_188208_0_ ^ p_188208_0_ >>> 13; p_188208_0_ = p_188208_0_ * -1028477387; p_188208_0_ = p_188208_0_ ^ p_188208_0_ >>> 16; return p_188208_0_; } static { for (int i = 0; i < 65536; ++i) { SIN_TABLE[i] = (float)Math.sin((double)i * Math.PI * 2.0D / 65536.0D); } MULTIPLY_DE_BRUIJN_BIT_POSITION = new int[] {0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9}; FRAC_BIAS = Double.longBitsToDouble(4805340802404319232L); ASINE_TAB = new double[257]; COS_TAB = new double[257]; for (int j = 0; j < 257; ++j) { double d0 = (double)j / 256.0D; double d1 = Math.asin(d0); COS_TAB[j] = Math.cos(d1); ASINE_TAB[j] = d1; } } }
gpl-3.0
FireBladeNooT/Medusa_1_6
lib/chardet/charsetprober.py
5110
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Universal charset detector code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 2001 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # Shy Shalom - original C code # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### import logging import re from .enums import ProbingState class CharSetProber(object): SHORTCUT_THRESHOLD = 0.95 def __init__(self, lang_filter=None): self._state = None self.lang_filter = lang_filter self.logger = logging.getLogger(__name__) def reset(self): self._state = ProbingState.detecting @property def charset_name(self): return None def feed(self, buf): pass @property def state(self): return self._state def get_confidence(self): return 0.0 @staticmethod def filter_high_byte_only(buf): buf = re.sub(b'([\x00-\x7F])+', b' ', buf) return buf @staticmethod def filter_international_words(buf): """ We define three types of bytes: alphabet: english alphabets [a-zA-Z] international: international characters [\x80-\xFF] marker: everything else [^a-zA-Z\x80-\xFF] The input buffer can be thought to contain a series of words delimited by markers. This function works to filter all words that contain at least one international character. All contiguous sequences of markers are replaced by a single space ascii character. This filter applies to all scripts which do not use English characters. """ filtered = bytearray() # This regex expression filters out only words that have at-least one # international character. The word may include one marker character at # the end. words = re.findall(b'[a-zA-Z]*[\x80-\xFF]+[a-zA-Z]*[^a-zA-Z\x80-\xFF]?', buf) for word in words: filtered.extend(word[:-1]) # If the last character in the word is a marker, replace it with a # space as markers shouldn't affect our analysis (they are used # similarly across all languages and may thus have similar # frequencies). last_char = word[-1:] if not last_char.isalpha() and last_char < b'\x80': last_char = b' ' filtered.extend(last_char) return filtered @staticmethod def filter_with_english_letters(buf): """ Returns a copy of ``buf`` that retains only the sequences of English alphabet and high byte characters that are not between <> characters. Also retains English alphabet and high byte characters immediately before occurrences of >. This filter can be applied to all scripts which contain both English characters and extended ASCII characters, but is currently only used by ``Latin1Prober``. """ filtered = bytearray() in_tag = False prev = 0 for curr in range(len(buf)): # Slice here to get bytes instead of an int with Python 3 buf_char = buf[curr:curr + 1] # Check if we're coming out of or entering an HTML tag if buf_char == b'>': in_tag = False elif buf_char == b'<': in_tag = True # If current character is not extended-ASCII and not alphabetic... if buf_char < b'\x80' and not buf_char.isalpha(): # ...and we're not in a tag if curr > prev and not in_tag: # Keep everything after last non-extended-ASCII, # non-alphabetic character filtered.extend(buf[prev:curr]) # Output a space to delimit stretch we kept filtered.extend(b' ') prev = curr + 1 # If we're not in a tag... if not in_tag: # Keep everything after last non-extended-ASCII, non-alphabetic # character filtered.extend(buf[prev:]) return filtered
gpl-3.0
UnitooTeam/harbour-boxing-timer
documentation/html/search/all_0.js
256
var searchData= [ ['activechanged',['activeChanged',['../class_boxing_timer.html#a4f2001335cd6249a350d87708b785de5',1,'BoxingTimer']]], ['applystatus',['applyStatus',['../class_boxing_timer.html#add8675aed0b0f7f2a90482456c63c8f3',1,'BoxingTimer']]] ];
gpl-3.0
ndlib/annex-ims
app/helpers/trays_helper.rb
23
module TraysHelper end
gpl-3.0
rudhir-upretee/Sumo_With_Netsim
src/netimport/vissim/tempstructs/NIVissimVehTypeClass.cpp
2789
/****************************************************************************/ /// @file NIVissimVehTypeClass.cpp /// @author Daniel Krajzewicz /// @date Sept 2002 /// @version $Id: NIVissimVehTypeClass.cpp 12050 2012-03-12 06:53:15Z behrisch $ /// // ------------------- /****************************************************************************/ // SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/ // Copyright (C) 2001-2012 DLR (http://www.dlr.de/) and contributors /****************************************************************************/ // // This file is part of SUMO. // SUMO is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // /****************************************************************************/ // =========================================================================== // included modules // =========================================================================== #ifdef _MSC_VER #include <windows_config.h> #else #include <config.h> #endif #include <string> #include <utils/common/RGBColor.h> #include <utils/common/VectorHelper.h> #include "NIVissimVehTypeClass.h" #ifdef CHECK_MEMORY_LEAKS #include <foreign/nvwa/debug_new.h> #endif // CHECK_MEMORY_LEAKS NIVissimVehTypeClass::DictType NIVissimVehTypeClass::myDict; NIVissimVehTypeClass::NIVissimVehTypeClass(int id, const std::string& name, const RGBColor& color, std::vector<int>& types) : myID(id), myName(name), myColor(color), myTypes(types) {} NIVissimVehTypeClass::~NIVissimVehTypeClass() {} bool NIVissimVehTypeClass::dictionary(int id, const std::string& name, const RGBColor& color, std::vector<int>& types) { NIVissimVehTypeClass* o = new NIVissimVehTypeClass(id, name, color, types); if (!dictionary(id, o)) { delete o; return false; } return true; } bool NIVissimVehTypeClass::dictionary(int name, NIVissimVehTypeClass* o) { DictType::iterator i = myDict.find(name); if (i == myDict.end()) { myDict[name] = o; return true; } return false; } NIVissimVehTypeClass* NIVissimVehTypeClass::dictionary(int name) { DictType::iterator i = myDict.find(name); if (i == myDict.end()) { return 0; } return (*i).second; } void NIVissimVehTypeClass::clearDict() { for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { delete(*i).second; } myDict.clear(); } /****************************************************************************/
gpl-3.0
wmcnicho/Gotham-City
src/simcity/restaurants/restaurant4/Restaurant4Gui/Restaurant4CustomerGui.java
5479
package simcity.restaurants.restaurant4.Restaurant4Gui; import java.util.*; import java.util.List; import java.awt.*; import simcity.Market.MarketCustomerRole; import simcity.restaurants.restaurant4.Restaurant4CustomerRole; import simcity.restaurants.restaurant4.interfaces.Restaurant4Customer; import Gui.RoleGui; import Gui.Screen; public class Restaurant4CustomerGui extends RoleGui{ private Restaurant4Customer agent = null; private boolean isPresent = false; //private ListPanel listPanel; private boolean isHungry = false; // RestaurantGui gui; static final int defaultPos = -40; static final int defaultPosX = 120; static final int defaultPosY = 30; static final int rectSize = 20; private enum Command {noCommand, GoToSeat, GoToCashier, LeaveRestaurant, GoToRestaurant}; private Command command=Command.noCommand; public List <Restaurant4Customer> waitingLine = new ArrayList<Restaurant4Customer>(); private Status status; private enum Status{seated, notSeated }; private int xTable; private int yTable; public boolean ordered; public boolean gotOrder; public boolean doneEating; public Restaurant4CustomerGui(Restaurant4CustomerRole c){ //HostAgent m) { agent = c; xPos = defaultPos; yPos = defaultPos; status = Status.notSeated; /*xDestination = defaultPosX; yDestination = defaultPosY;*/ //maitreD = m; //this.gui = gui; } public Restaurant4CustomerGui(Restaurant4CustomerRole role, Screen s){ super(role, s); agent = role; xPos = defaultPos; yPos = defaultPos; status = Status.notSeated; } public void setTable(int x, int y){ xTable = x; yTable = y; } public void updatePosition() { // if(agent.getPause() == false){ super.updatePosition(); if (xPos == 220 && yPos == 50 && command==Command.GoToCashier){ command=Command.noCommand; agent.arrivedToCashier(); } if (yPos == 30 && xPos == 120 && command == Command.GoToRestaurant){ command = Command.noCommand; agent.AtRestaurant(); } if (xPos == defaultPos && yPos == defaultPos && command == Command.LeaveRestaurant){ agent.msgOutOfRestaurant4(); } if (xPos == xDestination && yPos == yDestination) { if (command==Command.GoToSeat) { //waitingLine.remove(agent); agent.msgAnimationFinishedGoToSeat(); } else if (command==Command.LeaveRestaurant) { agent.msgAnimationFinishedLeaveRestaurant(); System.out.println("about to call gui.setCustomerEnabled(agent);"); isHungry = false; //gui.setCustomerEnabled(agent); } command=Command.noCommand; } } public void draw(Graphics g) { super.draw(g); /*g.setColor(Color.GREEN); g.fillRect(xPos, yPos, rectSize, rectSize);*/ if (ordered ==true && gotOrder==false){ drawOrder(g); } if (ordered == false && gotOrder ==true && doneEating == false){ drawOrdered(g); } } public void drawOrder(Graphics g){ g.setColor(Color.BLACK); if (agent.getChoice()=="Steak"){ g.drawString("st?", xTable, yTable); } else if (agent.getChoice()=="Pizza"){ g.drawString("p?", xTable, yTable); } else if (agent.getChoice()=="Chicken"){ g.drawString("ch?", xTable, yTable); } else if (agent.getChoice()=="Salad"){ g.drawString("s?", xTable, yTable); } } public void drawOrdered(Graphics g){ g.setColor(Color.BLACK); if (agent.getChoice()=="Steak"){ g.drawString("st", xTable, yTable); } else if (agent.getChoice()=="Pizza"){ g.drawString("p", xTable, yTable); } else if (agent.getChoice()=="Chicken"){ g.drawString("ch", xTable, yTable); } else if (agent.getChoice()=="Salad"){ g.drawString("s", xTable, yTable); } } public boolean isPresent() { return isPresent; } public void setHungry() { isHungry = true; agent.gotHungry(); setPresent(true); } public boolean isHungry() { return isHungry; } public void setPresent(boolean p) { isPresent = p; } public void DoGoToSeat() {//later you will map seatnumber to table coordinates. xDestination = xTable; yDestination = yTable; command = Command.GoToSeat; status = Status.seated; int x = 120; for (int i=0; i<waitingLine.size(); i++){ if (waitingLine.get(i).getGui().status!=Status.seated){ waitingLine.get(i).getGui().xDestination = x; x = x-40; } } } public void DoGoToRestaurant(){ //for waiting area /*for (int i=0; i<listPanel.getCustomers().size(); i++){ if (listPanel.getCustomers().get(i).customerGui.status != Status.seated) waitingLine.add(listPanel.getCustomers().get(i)); }*/ waitingLine = agent.getHost().getWaitingCustomers(); /* System.out.println(waitingLine.size()); for (int i=0; i<waitingLine.size(); i++){ if (waitingLine.get(i) == agent){ if (i == 0){ System.out.println("my place " + i); xDestination = 120; } else if(i==1){ System.out.println("my place " + i); xDestination = 80; } else if (i==2){ System.out.println("my place " + i); xDestination = 40; } else if (i==3){ System.out.println("my place " + i); xDestination = 0; } }*/ xDestination = 120; yDestination = 30; command = Command.GoToRestaurant; } public void doGoToCashier(){ xDestination = 220; yDestination = 50; command = Command.GoToCashier; } public void DoExitRestaurant() { isHungry= false; xDestination = defaultPos; yDestination = defaultPos; command = Command.LeaveRestaurant; } }
gpl-3.0
mobilipia/Deskera-CRM
crm-app2/crm-webapp/src/main/webapp/scripts/common/KWLNotification.js
2296
/* * Copyright (C) 2012 Krawler Information Systems Pvt Ltd * All rights reserved. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ var fnInt; function createMaintainanceCall(){ var time=300000; fnInt = setInterval(getSysMaintainanceData, time); } function abortMaintainanceCall() { clearInterval(fnInt); } function getSysMaintainanceData(){ Wtf.Ajax.requestEx({ url : "deskeracommon/Notification/getMaintainanceDetails.do" }, this, function(result, req){ if(result.data!=undefined&&result.success==true ){ var announcementpan = Wtf.getCmp('announcementpan'); announcementpan.setVisible(true); notificationMessage(result.data[0].message); announcementpan.doLayout(); Wtf.getCmp('viewport').doLayout(); } else{ hideTopPanel(); // abortMaintainanceCall()//to be removed } }); } function notificationMessage(msg) { var announcementpan = Wtf.getCmp('announcementpan'); if(announcementpan !=null) { announcementpan.setVisible(true); document.getElementById("announcementpandiv").innerHTML =msg; announcementpan.doLayout(); Wtf.getCmp('viewport').doLayout(); } } function hideTopPanel() { var announcementpan = Wtf.getCmp('announcementpan'); if(announcementpan !=null) { document.getElementById("announcementpandiv").innerHTML =""; announcementpan.setVisible(false); announcementpan.doLayout(); Wtf.getCmp('viewport').doLayout(); abortMaintainanceCall(); } }
gpl-3.0
epfl-lara/leon
src/test/resources/regression/genc/valid/RegressionTest1.scala
1255
/* Copyright 2009-2016 EPFL, Lausanne */ import leon.annotation._ import leon.lang._ import leon.io.{ FileInputStream => FIS } /* * This test was reduced from a bigger one. A bug caused GenC to crash * when converting `processImage` from Scala to its IR because there was * a mismatch between the function argument name and the one used in its * body: bh$2 vs bh$1. This mismatch in identifier was generated by * RemoveVCPhase, for some obscure reasons. */ object RegressionTest1 { case class BitmapHeader(width: Int, height: Int) { require(0 <= width && 0 <= height) } def maybeReadBitmapHeader(fis: FIS)(implicit state: leon.io.State): BitmapHeader = { require(fis.isOpen) BitmapHeader(16, 16) } def process(fis: FIS)(implicit state: leon.io.State): Boolean = { require(fis.isOpen) def processImage(bh: BitmapHeader): Boolean = { if (bh.width > 0) true else false } val bitmapHeader = maybeReadBitmapHeader(fis) processImage(bitmapHeader) } def _main(): Int = { implicit val state = leon.io.newState val input = FIS.open("input.bmp") if (input.isOpen) { process(input) () } 0 } @extern def main(args: Array[String]): Unit = _main() }
gpl-3.0
nstarke/hootenanny
tgs/src/test/cpp/tgs/PluginFactory.cpp
1860
/* * This file is part of Hootenanny. * * Hootenanny is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * -------------------------------------------------------------------- * * The following copyright notices are generated automatically. If you * have a new notice to add, please use the format: * " * @copyright Copyright ..." * This will properly maintain the copyright information. DigitalGlobe * copyrights will be updated automatically. * * @copyright Copyright (C) 2013 DigitalGlobe (http://www.digitalglobe.com/) */ #include "PluginFactory.h" // STL includes #include <iostream> #include <map> #include <string> // CPP Unit Includes #include <cppunit/plugin/TestPlugIn.h> #include <cppunit/extensions/HelperMacros.h> #ifndef SA_VERSION #define SA_VERSION "3.2.0" #endif #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" CPPUNIT_PLUGIN_IMPLEMENT(); #pragma GCC diagnostic pop boost::any createObjectNoParams(const std::string& className) { if (className == "Tgs::TestSuite" || className == "TestSuite") { return CppUnit::TestFactoryRegistry::getRegistry(PluginFactory::testName()).makeTest(); } return boost::any(); } const char* getVersion() { return SA_VERSION; }
gpl-3.0