repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
reginbald/TicTacToe
src/selenium/java/is/deltazedacreed/tictactoe/TestTitle.java
1881
/* * Copyright (c) 2014 Delta Zeda Creed. */ package is.deltazedacreed.tictactoe; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import org.junit.*; import org.openqa.selenium.*; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.Select; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; /** * Class for testing webapp title. */ public class TestTitle { private WebDriver driver; private String baseUrl; private boolean acceptNextAlert = true; private StringBuffer verificationErrors = new StringBuffer(); @Before public void setUp() throws Exception { driver = new FirefoxDriver(); baseUrl = "https://www.google.is/"; driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } @Test public void testTitle() throws Exception { driver.get("http://tictactoe420.herokuapp.com/"); assertEquals("Tic Tac Toe", driver.getTitle()); } @After public void tearDown() throws Exception { driver.quit(); String verificationErrorString = verificationErrors.toString(); if (!"".equals(verificationErrorString)) { fail(verificationErrorString); } } private boolean isElementPresent(By by) { try { driver.findElement(by); return true; } catch (NoSuchElementException e) { return false; } } private boolean isAlertPresent() { try { driver.switchTo().alert(); return true; } catch (NoAlertPresentException e) { return false; } } private String closeAlertAndGetItsText() { try { Alert alert = driver.switchTo().alert(); String alertText = alert.getText(); if (acceptNextAlert) { alert.accept(); } else { alert.dismiss(); } return alertText; } finally { acceptNextAlert = true; } } }
gpl-2.0
zhangbojr/ICB
DAL/ICaiBan.ModelDB/Tab_User_Bind_Merc_App.cs
3268
using System; using System.Data; using System.Collections.Generic; using System.Text; using ICaiBan.Framework.ORM; namespace ICaiBan.ModelDB { [Serializable, TableInfo("Tab_User_Bind_Merc_App")] public class Tab_User_Bind_Merc_App : Entity<Tab_User_Bind_Merc_App> { decimal _Ubma_Flow_Id; /// <summary> /// 绑定申请流水ID /// </summary> [FieldInfo(SqlDbType=SqlDbType.Decimal, IsPrimeKey=true, Description="绑定申请流水ID", AllowNull=false, IsIdentity=true)] public decimal Ubma_Flow_Id { get { return _Ubma_Flow_Id; } set { _Ubma_Flow_Id=value; } } decimal _User_Id; /// <summary> /// 会员ID /// </summary> [FieldInfo(SqlDbType=SqlDbType.Decimal, Description="会员ID", AllowNull=false)] public decimal User_Id { get { return _User_Id; } set { _User_Id=value; } } decimal _Merchant_Id; /// <summary> /// 商户ID /// </summary> [FieldInfo(SqlDbType=SqlDbType.Decimal, Description="商户ID", AllowNull=false)] public decimal Merchant_Id { get { return _Merchant_Id; } set { _Merchant_Id=value; } } decimal _Payment_Status=0; /// <summary> /// 支付状态(0:待支付;1:已支付;2:支付失败;3:已取消) /// </summary> [FieldInfo(SqlDbType=SqlDbType.Decimal, Description="支付状态(0:待支付;1:已支付;2:支付失败;3:已取消)", AllowNull=false)] public decimal Payment_Status { get { return _Payment_Status; } set { _Payment_Status=value; } } decimal _Spread_User_Type; /// <summary> /// 推广用户类型(0:会员;1:商户;2:平台) /// </summary> [FieldInfo(SqlDbType=SqlDbType.Decimal, Description="推广用户类型(0:会员;1:商户;2:平台)", AllowNull=false)] public decimal Spread_User_Type { get { return _Spread_User_Type; } set { _Spread_User_Type=value; } } decimal _Spread_User_Id; /// <summary> /// 推广用户ID /// </summary> [FieldInfo(SqlDbType=SqlDbType.Decimal, Description="推广用户ID", AllowNull=false)] public decimal Spread_User_Id { get { return _Spread_User_Id; } set { _Spread_User_Id=value; } } DateTime _Create_Time=DateTime.Now; /// <summary> /// 创建时间 /// </summary> [FieldInfo(SqlDbType=SqlDbType.DateTime, Description="创建时间", AllowNull=false)] public DateTime Create_Time { get { return _Create_Time; } set { _Create_Time=value; } } DateTime _Modify_Time=DateTime.Now; /// <summary> /// 修改时间 /// </summary> [FieldInfo(SqlDbType=SqlDbType.DateTime, Description="修改时间", AllowNull=false)] public DateTime Modify_Time { get { return _Modify_Time; } set { _Modify_Time=value; } } } }
gpl-2.0
thepointchurch/thepoint
thepoint/settings.py
1040
from pathlib import Path from upperroom.settings import * # NOQA: F403 pylint: disable=wildcard-import,unused-wildcard-import BASE_DIR = Path(__file__).resolve(strict=True).parent TEMPLATES[0]["DIRS"] = [BASE_DIR / "templates"] # NOQA: F405 pylint: disable=undefined-variable STATICFILES_DIRS = (BASE_DIR / "static",) ROOT_URLCONF = "thepoint.urls" LANGUAGE_CODE = "en-au" TIME_ZONE = "Australia/Brisbane" WEBMASTER_EMAIL = "webmaster@thepoint.org.au" DIRECTORY_EMAIL = "directory@thepoint.org.au" ROSTER_EMAIL = "roster@thepoint.org.au" DEFAULT_FROM_EMAIL = WEBMASTER_EMAIL CSP_FRAME_SRC = ("'self'", "https://www.youtube-nocookie.com/embed/") LOCALE_PATHS = (BASE_DIR / "locale",) SITE_METADATA_IMAGE = "style/image.jpg" PASSWORD_HASHERS = ( "thepoint.hashers.LiteArgon2PasswordHasher", "django.contrib.auth.hashers.PBKDF2PasswordHasher", "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher", "django.contrib.auth.hashers.BCryptSHA256PasswordHasher", "django.contrib.auth.hashers.BCryptPasswordHasher", )
gpl-2.0
lysender/twentyten-dc
footer.php
2280
<?php /** * The template for displaying the footer. * * Contains the closing of the id=main div and all content * after. Calls sidebar-footer.php for bottom widgets. * * @package WordPress * @subpackage Twenty_Ten * @since Twenty Ten 1.0 */ ?> </div><!-- #main --> <div id="footer" role="contentinfo"> <div id="colophon"> <?php /* A sidebar in the footer? Yep. You can can customize * your footer with four columns of widgets. */ get_sidebar( 'footer' ); ?> <div id="site-info"> <a href="<?php echo home_url( '/' ) ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"> <?php bloginfo( 'name' ); ?> </a> </div><!-- #site-info --> <div id="site-generator"> <?php do_action( 'twentyten_credits' ); ?> <a href="<?php echo esc_url( __('http://wordpress.org/', 'twentyten') ); ?>" title="<?php esc_attr_e('Semantic Personal Publishing Platform', 'twentyten'); ?>" rel="generator"> <?php printf( __('Proudly powered by %s.', 'twentyten'), 'WordPress' ); ?> </a> </div><!-- #site-generator --> </div><!-- #colophon --> </div><!-- #footer --> </div><!-- #wrapper --> <?php /* Always have wp_footer() just before the closing </body> * tag of your theme, or you will break many plugins, which * generally use this hook to reference JavaScript files. */ wp_footer(); ?> <!-- google analytics --> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-17635698-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <!-- Start Quantcast tag --> <script type="text/javascript"> _qoptions={ qacct:"p-514yFKdjDiF72" }; </script> <script type="text/javascript" src="http://edge.quantserve.com/quant.js"></script> <noscript> <img src="http://pixel.quantserve.com/pixel/p-514yFKdjDiF72.gif" style="display: none; border: none;" height="1" width="1" alt="Quantcast"/> </noscript> <!-- End Quantcast tag --> </body> </html>
gpl-2.0
cfloersch/JSONMarshaller
src/main/java/org/xpertss/json/desc/DoubleDescriptor.java
2597
package org.xpertss.json.desc; import xpertss.json.JSONNumber; import xpertss.json.JSONValue; import xpertss.json.MarshallingException; import java.lang.reflect.Array; import java.math.BigDecimal; import static java.lang.String.format; import static xpertss.json.JSON.NULL; import static xpertss.json.JSON.number; /** * Descriptor for the {@link Double} type. */ public class DoubleDescriptor extends NumberDescriptor<Double> { public final static DoubleDescriptor DOUBLE_DESC = new DoubleDescriptor(Double.class); public final static DoubleDescriptor DOUBLE_LITERAL_DESC = new DoubleDescriptor(Double.TYPE) { @Override public JSONValue marshall(FieldDescriptor fieldDescriptor, Object parentEntity, String view) { return number(fieldDescriptor.getFieldValueDouble(parentEntity)); } @Override public void unmarshall(FieldDescriptor fieldDescriptor, Object entity, JSONValue marshalled, String view) { if(NULL.equals(marshalled)) { throw new MarshallingException("did not expect null for double field"); } else if(marshalled instanceof JSONNumber) { JSONNumber number = (JSONNumber) marshalled; fieldDescriptor.setFieldValueDouble(entity, number.getNumber().doubleValue()); } else { throw new MarshallingException(format("expected JSONNumber but found %s", type(marshalled))); } } @Override public JSONNumber marshallArray(Object array, int index, String view) { return number(Array.getDouble(array, index)); } @Override public void unmarshallArray(Object array, JSONValue marshalled, int index, String view) { if(NULL.equals(marshalled)) { throw new MarshallingException("did not expect null for double field"); } else if(marshalled instanceof JSONNumber) { JSONNumber number = (JSONNumber) marshalled; Array.setDouble(array, index, number.getNumber().doubleValue()); } else { throw new MarshallingException(format("expected JSONNumber but found %s", type(marshalled))); } } @Override public String toString() { return getClass().getSuperclass().getSimpleName(); } }; private DoubleDescriptor(Class<Double> klass) { super(klass); } @Override BigDecimal encode(Double entity) { return BigDecimal.valueOf(entity.doubleValue()); } @Override Double decode(BigDecimal number) { return number.doubleValue(); } }
gpl-2.0
ridoo/SensorWebClient
sensorwebclient-sos-rest/src/main/java/org/n52/series/api/proxy/v1/io/FileUtility.java
1372
/** * Copyright (C) 2012-2016 52°North Initiative for Geospatial Open Source * Software GmbH * * 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 publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * 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. */ package org.n52.series.api.proxy.v1.io; public class FileUtility { }
gpl-2.0
gggeek/ezpublish-kernel
eZ/Publish/Core/Repository/Mapper/ProxyAwareDomainMapper.php
1077
<?php /** * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. */ declare(strict_types=1); namespace eZ\Publish\Core\Repository\Mapper; use eZ\Publish\Core\Repository\ProxyFactory\ProxyDomainMapperInterface; /** * @internal For internal use by Domain Mappers * * Common abstraction for domain mappers providing properties loaded via proxy. */ abstract class ProxyAwareDomainMapper { /** @var \eZ\Publish\Core\Repository\ProxyFactory\ProxyDomainMapperInterface */ protected $proxyFactory; public function __construct(?ProxyDomainMapperInterface $proxyFactory = null) { $this->proxyFactory = $proxyFactory; } /** * Setter for Proxy Factory to work around cyclic dependency issue on Repository. * * Note: to be resolved by Repository decoupling. */ final public function setProxyFactory(ProxyDomainMapperInterface $proxyFactory): void { $this->proxyFactory = $proxyFactory; } }
gpl-2.0
vongdeptaydep/vongdeotaydep
wp-content/themes/ri-everest/included/templates/header/header-default.php
3200
<?php if(is_single()||is_page()){ if (get_post_meta(get_the_ID(), 'rit_header_options', true) == 'use-default' || get_post_meta(get_the_ID(), 'rit_header_options', true) == '') { get_theme_mod('rit_enable_sticky_header') ? $enable_sticky = true : $enable_sticky = false; //get_theme_mod('rit_enable_main_widget') ? $enable_main_wd = true : $enable_main_wd = false; } else { get_post_meta(get_the_ID(), 'rit_enable_sticky_header', true) ? $enable_sticky = true : $enable_sticky = false; //get_post_meta(get_the_ID(), 'rit_enable_main_widget', true) ? $enable_main_wd = true : $enable_main_wd = false; } } else{ get_theme_mod('rit_enable_sticky_header') ? $enable_sticky = true : $enable_sticky = false; //get_theme_mod('rit_enable_main_widget') ? $enable_main_wd = true : $enable_main_wd = false; } ?> <header id="header-page" class="header-default"> <?php if(is_active_sidebar('top-left-header')||is_active_sidebar('top-header')):?> <div id="top-header"> <div class="container"> <div class="row"> <div class="col-xs-12 col-sm-6 top-header-left"> <?php dynamic_sidebar('top-left-header') ?> </div> <div class="col-xs-12 col-sm-6 top-header-right"> <?php dynamic_sidebar('top-header') ?> </div> </div> </div> </div> <?php endif;?> <div id="rit-main-header"> <div class="container"> <div class="row"> <div id="rit-logo" class="col-xs-12 col-sm-4"> <?php get_template_part('included/templates/logo'); ?> </div> <div id="top-search" class=" <?php echo esc_attr(class_exists('WooCommerce')?'col-xs-10 col-sm-5 col-md-6':'col-xs-12 col-sm-8')?> "> <?php get_template_part('included/templates/search');?> </div> <?php if (class_exists('WooCommerce')) {?> <div class="col-xs-2 col-sm-3 col-md-2 right-main-header"> <?php get_template_part('included/templates/topheadcart');?> </div> <?php } ?> </div> </div> </div> <div id="rit-bottom-header"> <div class="container"> <div class="row"> <nav id="primary-nav" class="col-sm-12 col-xs-3 primary-nav-block"> <div class="mobile-nav"><span></span></div> <?php wp_nav_menu(array('theme_location' => 'primary', 'container' => false, 'menu_class' => 'nav-menu', 'menu_id' => 'primary-menu')); ?> </nav> <div class="col-xs-9 col-sm-3 right-bottom-header"> <?php dynamic_sidebar('main-header') ?> </div> </div> </div> </div> <?php if($enable_sticky){?> <script> (function ($) { "use strict"; $(document).ready(function () { $("#rit-bottom-header").sticky(); }) })(jQuery) </script> <?php }?> </header>
gpl-2.0
tisoft/xtcmodified
admin/includes/modules/export/idealo.php
36319
<?php /* * export module for php version 4.x */ /* ----------------------------------------------------------------------------------------- XT-Commerce - community made shopping http://www.xt-commerce.com Copyright (c) 2005 XT-Commerce (c) idealo 2009, provided as is, no warranty ----------------------------------------------------------------------------------------- based on: (c) 2000-2001 The Exchange Project (earlier name of osCommerce) (c) 2002-2003 osCommerce(cod.php,v 1.28 2003/02/14); www.oscommerce.com (c) 2003 nextcommerce (invoice.php,v 1.6 2003/08/24); www.nextcommerce.org Extended by - Jens-Uwe Rumstich (Idealo Internet GmbH, http://www.idealo.de) - Andreas Geisler (Idealo Internet GmbH, http://www.idealo.de) Released under the GNU General Public License ---------------------------------------------------------------------------------------*/ defined( '_VALID_XTC' ) or die( 'Direct Access to this location is not allowed.' ); // module display config define('MODULE_IDEALO_TEXT_DESCRIPTION', 'Export - Idealo (Semikolon getrennt)'); define('MODULE_IDEALO_TEXT_TITLE', 'Idealo - CSV'); define('MODULE_IDEALO_FILE_TITLE' , '<hr noshade>Dateiname'); define('MODULE_IDEALO_FILE_DESC' , 'Geben Sie einen Dateinamen ein, falls die Exportadatei am Server gespeichert werden soll.<br>(Verzeichnis export/)'); define('FIELDSEPARATOR', '<b>Spaltentrenner</b>'); define('FIELDSEPARATOR_HINT', 'Beispiel:<br>;&nbsp;&nbsp;&nbsp;(Semikolon)<br>,&nbsp;&nbsp;&nbsp;(Komma)<br>\t&nbsp;&nbsp;(Tab)<br>...<br>Wird das Feld leer gelassen, wird Tab als Trenner genutzt.'); define('QUOTING','<b>Quoting</b>'); define('QUOTING_HINT','Beispiel:<br>"&nbsp;&nbsp;&nbsp;(Anf&uuml;hrungszeichen)<br>\'&nbsp;&nbsp;&nbsp;(Hochkomma)<br>#&nbsp;&nbsp;(Raute)<br>... <br>Wird das Feld leer gelassen, wird nicht gequotet.'); define('SHIPPINGCOMMENT', '<b>Versandkommentar</b>'); define('SHIPPINGCOMMENT_HINT', 'Max. 100 Zeichen'); define('FREESHIPPINGCOMMENT', '<b>Kommentar zur Versankosten-Grenze</b>'); define('FREESHIPPINGCOMMENT_HINT', 'Wird bei allen Angeboten angezeigt, die unter der Versandkostenfreiheits-Grenze liegen.<br>Max. 100 Zeichen'); define('LANGUAGE', '<b>Export f&uuml;r</b>'); define('LANGUAGE_HINT', 'Beispiel:<br>DE (Deutschland)<br>AT (&Ouml;sterreich)<br>...<br>Es sollten(!) die Sprachen genutzt werden, die auch bei den Versandkosten etc. korrekt hinterlegt sind.<br>Wird das Feld leer gelassen, wird \'DE\' benutzt.'); define('MODULE_IDEALO_STATUS_DESC','Modulstatus'); define('MODULE_IDEALO_STATUS_TITLE','Status'); define('MODULE_IDEALO_CURRENCY_TITLE','W&auml;hrung'); define('MODULE_IDEALO_CURRENCY_DESC','Welche W&auml;hrung soll exportiert werden?'); define('EXPORT_YES','Nur Herunterladen'); define('EXPORT_NO','Am Server Speichern'); define('CURRENCY','<hr noshade><b>W&auml;hrung:</b>'); define('CURRENCY_DESC','W&auml;hrung in der Exportdatei'); define('EXPORT','Bitte den Sicherungsprozess AUF KEINEN FALL unterbrechen. Dieser kann einige Minuten in Anspruch nehmen.'); define('EXPORT_TYPE','<hr noshade><b>Speicherart:</b>'); define('EXPORT_STATUS_TYPE','<hr noshade><b>Kundengruppe:</b>'); define('EXPORT_STATUS','Bitte w&auml;hlen Sie die Kundengruppe, die Basis f&uuml;r den Exportierten Preis bildet. (Falls Sie keine Kundengruppenpreise haben, w&auml;hlen Sie <i>Gast</i>):</b>'); define('CAMPAIGNS','<hr noshade><b>Kampagnen:</b>'); define('CAMPAIGNS_DESC','Mit Kampagne zur Nachverfolgung verbinden.'); define('DATE_FORMAT_EXPORT', '%d.%m.%Y'); // this is used for strftime() define('DISPLAY_PRICE_WITH_TAX','true'); define('COMMENTLENGTH', 100); // check admin file config // is a specific separator set? if( isset($_POST['separator_input']) && $_POST['separator_input'] != '' ) { $separator = $_POST['separator_input']; } else { // if nothing is entered by the admin: $separator gets \t as default $separator = "\t"; } // is a specific quoting character set? if( isset($_POST['quoting_input']) && $_POST['quoting_input'] != '' ) { $quoting = stripcslashes($_POST['quoting_input']); } else { // if nothing is entered by the admin: $quoting is disabled $quoting = ""; } // is a specific language set? if( isset($_POST['language_input']) && $_POST['language_input'] != '' ) { $country_sc = stripslashes($_POST['language_input']); } else { // if nothing is entered by the admin: $quoting is disabled $country_sc = "DE"; } // check if freeshippinglimit_input is already in db $shipping_input_query = xtc_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_IDEALO_SHIPPINGCOMMENT' LIMIT 1"); $shipping_comment_db = xtc_db_fetch_array($shipping_input_query); // false if 'MODULE_IDEALO_SHIPPINGCOMMENT' doesn't exist // is shipping comment set? // do not exceed COMMENTLENGTH if( isset( $_POST['shippingcomment_input']) && ( strlen($_POST['shippingcomment_input']) <= COMMENTLENGTH ) ) { // does a dataset exist? if( $shipping_comment_db !== false ) { // update value if $_POST['freeshippinglimit_input'] != $freeshipping_comment_db if( $_POST['shippingcomment_input'] != $shipping_comment_db['configuration_value'] ) { xtc_db_query("update " . TABLE_CONFIGURATION . " set configuration_value = '" . $_POST['shippingcomment_input'] . "' where configuration_key = 'MODULE_IDEALO_SHIPPINGCOMMENT'"); } } else { // insert data xtc_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('MODULE_IDEALO_SHIPPINGCOMMENT', '" . $_POST['shippingcomment_input'] . "', 6, 1, '', now()) "); } $shipping_comment_input = stripslashes($_POST['shippingcomment_input']); } else { $shipping_comment_input = ""; } // check if freeshippinglimit_input is already in db $freeshipping_input_query = xtc_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_IDEALO_FREESHIPPINGCOMMENT' LIMIT 1"); $freeshipping_comment_db = xtc_db_fetch_array($freeshipping_input_query); // false if 'MODULE_IDEALO_FREESHIPPINGCOMMENT' doesn't exist // is free shipping comment set? // do not exceed COMMENTLENGTH if( isset( $_POST['freeshippingcomment_input']) && ( strlen($_POST['freeshippingcomment_input']) <= COMMENTLENGTH ) ) { // does a dataset exist? if( $freeshipping_comment_db !== false ) { // update value if $_POST['freeshippingcomment_input'] != $freeshipping_comment_db if( $_POST['freeshippingcomment_input'] != $freeshipping_comment_db['configuration_value'] ) { xtc_db_query("update " . TABLE_CONFIGURATION . " set configuration_value = '" . $_POST['freeshippingcomment_input'] . "' where configuration_key = 'MODULE_IDEALO_FREESHIPPINGCOMMENT'"); } } else { // insert data xtc_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('MODULE_IDEALO_FREESHIPPINGCOMMENT', '" . $_POST['freeshippingcomment_input'] . "', 6, 1, '', now()) "); } $freeshipping_comment_input = stripslashes($_POST['freeshippingcomment_input']); } else { $freeshipping_comment_input = ""; } // file config define('SEPARATOR', $separator); // character that separates the data define('QUOTECHAR', $quoting); // character to quote the data define('COUNTRY_SC', $country_sc); // country the shipping costs are for define('DISPLAYINACTIVEMODULES', true); // display modules that are not active but in the payment array // advantage: structure of the file hardly changes define('SHIPPINGCOMMENT_INPUT', $shipping_comment_input); define('FREESHIPPINGCOMMENT_INPUT', $freeshipping_comment_input); define('SHOWFREESHIPPINGLIMITCOMMENT', true); // set 'true' to show comment for free shipping limit require_once(DIR_FS_CATALOG.DIR_WS_CLASSES . 'xtcPrice.php'); class idealo { var $code , $title, $description, $enabled; // all payment (and its status) that should be displayed in the csv // if a payment is 'false', the column in the csv stays empty // the key needs to be the same as it is used in the db for the entry in `configuration_key` in the table `configuration` var $payment = array('MONEYORDER' => array('active' => false, 'title' => 'Vorkasse'), 'COD' => array('active' => false, 'title' => 'Nachnahme'), 'INVOICE' => array('active' => false, 'title' => 'Rechnung'), 'CC' => array('active' => false, 'title' => 'Kreditkarte'), 'BANKTRANSFER' => array('active' => false, 'title' => 'Lastschrift'), 'PAYPAL' => array('active' => false, 'title' => 'PayPal'), 'MONEYBOOKERS' => array('active' => false, 'title' => 'Moneybookers'), 'UOS_GIROPAY' => array('active' => false, 'title' => 'Giropay') ); // types of shipping cost and 2-3 properties // this is neccessary to get the correct values for "cash on delivery" var $paymentTable = false; // table sc var $paymentTableMode = 'weight'; // default mode for table sc var $paymentItem = false; // sc per item var $paymentFlat = false; // flat rate sc var $freeShipping = false; // no sc var $freeShippingValue; // calculates when shipping is free // table shipping var $paymentTableValues = array(); // default shipping cost (does NOT count when modul "table shipping cost" is active) var $standardShippingCost = 0.00; function idealo() { $this->code = 'idealo'; $this->title = MODULE_IDEALO_TEXT_TITLE; $this->description = MODULE_IDEALO_TEXT_DESCRIPTION; $this->sort_order = MODULE_IDEALO_SORT_ORDER; $this->enabled = ((MODULE_IDEALO_STATUS == 'True') ? true : false); $this->CAT=array(); $this->PARENT=array(); $this->productsPrice = 0; // check which payment method (cod, cash etc. ...) is active $this->checkActivePayment(); // check which payment option (default, per item, table) is active $this->checkStandardShippingCostsOption(); } /** * Checks which payment method (pm) is active * If a pm is not active, it wont appear in the csv * * A pm is only active when the entry 'MODULE_PAYMENT_{paymentmethod}_STATUS' in the table `configuration` exists * and the `configuration_value` is 'true' */ function checkActivePayment() { // run through every payment method foreach($this->payment as $singlePayment => $status) { // is the pm active? $checkPayment = xtc_db_query("SELECT COUNT(*) AS `found` FROM `configuration` WHERE `configuration_key` LIKE 'MODULE_PAYMENT_{$singlePayment}_STATUS' AND `configuration_value` LIKE 'True';"); $result = xtc_db_fetch_array($checkPayment); // if the result is > 0, the pm is active if($result['found'] > 0) { $this->payment[$singlePayment]['active'] = true; } } } /** * Method returns the shipping cost for a specific payment method * * @param string $payment * @param double|null $price * @param double|null $offerWeight * * @return double|'' shipping costs else an empty string */ function getShippingCosts($payment, $price = null, $offerWeight = null) { $shippingCost = ''; // is the is payment active? if( $this->payment[$payment]['active'] === true ) { // is free delivery active and price equal or higher than the limit? if(($this->freeShipping) === true && ($price >= $this->freeShippingValue)) { $shippingCost = 0.00; } // is at least one shipping option active? elseif(($this->paymentTable === true) || ($this->paymentItem === true) || ($this->paymentFlat === true) ) { // first of all we get the standard shipping costs (default sc, per item or table) // are the table shipping costs active? Check which table payment option is active if($this->paymentTable === true) { // run through the table values and check which weight / price matches the offer switch($this->paymentTableMode) { case 'weight': $offerCompareValue = $offerWeight; break; case 'price': $offerCompareValue = $price; break; } if(is_array($this->paymentTableValues) && $offerCompareValue != null) { foreach($this->paymentTableValues as $tableModeValue => $tablePrice) { // stop the loop if sth. matched if($offerCompareValue <= $tableModeValue) { $shippingCost = $tablePrice; break; } } // If no weight / price was matched accordingly, the last entry in the array is taken if($shippingCost == '') { end($this->paymentTableValues); // Zeiger an letzte Stelle bewegen $shippingCost = current($this->paymentTableValues); // Wert ausgeben auf den der Zeiger aktuell zeigt reset($this->paymentTableValues); // Setze Zeiger wieder in Ausgangsposition } } else { // if the table sc values are not correct or the weight / price is null => nothing shall appear in the csv $shippingCost = ''; } } else { $shippingCost = $this->standardShippingCost; } } // cod needs additional calculation // the additional cod_fee (if active) depends on the shipping option that is active as the fee can differ if($payment == 'COD') { // check if extra fee for Cash on Delivery is active // 1. get the db data $getCodExtraFeeStatus = xtc_db_query("SELECT `configuration_value` AS `cod_fee_status` FROM `configuration` WHERE `configuration_key` LIKE 'MODULE_ORDER_TOTAL_COD_FEE_STATUS';"); $result = array(); $result = xtc_db_fetch_array($getCodExtraFeeStatus); // 2. is the fee status active? if(isset($result['cod_fee_status']) && $result['cod_fee_status'] == 'true') { $modul = ''; // which shipping option is active? if(($this->freeShipping) === true && ($price >= $this->freeShippingValue)) { $modul = 'MODULE_ORDER_TOTAL_FREEAMOUNT_FREE'; } elseif($this->paymentTable === true) { $modul = 'MODULE_ORDER_TOTAL_COD_FEE_TABLE'; } elseif($this->paymentItem === true) { $modul = 'MODULE_ORDER_TOTAL_COD_FEE_ITEM'; } elseif($this->paymentFlat === true) { $modul = 'MODULE_ORDER_TOTAL_COD_FEE_FLAT'; } $getCodCost = xtc_db_query("SELECT `configuration_value` AS `cod_cost` FROM `configuration` WHERE `configuration_key` LIKE '{$modul}';"); unset($result); $result = array(); $result = xtc_db_fetch_array($getCodCost); // Are there any costs? if(isset($result['cod_cost']) && $result['cod_cost'] != '') { // get the value for the country preg_match_all('/' . COUNTRY_SC . ':([^,]+)?/', $result['cod_cost'], $match); // $match[1][0] contains the result in the form of (e.g.) 7.00 or 7 // to make sure that mistakes like 7.00:9.99 (correct would be 7,00:9.99) are also handled, we check for the colon if(preg_match('/:/', $match[1][0])) { $tmpArr = explode(':', $match[1][0]); $codCost = $tmpArr[0]; } else { $codCost = $match[1][0]; } // de we ge a useful value? if(isset($codCost) && $codCost != NULL && is_numeric($codCost)) { $shippingCost += $codCost; } } } } // calculate taxes if (DISPLAY_PRICE_WITH_TAX == 'true') { $tax = xtc_get_tax_rate_export(MODULE_SHIPPING_FLAT_TAX_CLASS, STORE_COUNTRY, MODULE_SHIPPING_FLAT_ZONE); $shippingCost = xtc_add_tax($shippingCost, $tax); } // format and round numbers $shippingCost = number_format($shippingCost, 2, '.', ''); } return $shippingCost; } /** * Method checks which standard shipping option is active. * - is the freeShipping active, $this->freeShipping = true * - is table sc option active, $this->paymentTable = true * - is table sc option NOT active, but sc per item, $this->paymentItem = true * - are neither table sc NOR sc per item, BUT the default sc active, $this->paymentFlat = true * * This is important for cash on delivery as there are different fee options possible. */ function checkStandardShippingCostsOption() { // free shipping? if($this->checkShippingCostOption('FREEAMOUNT') > 0 ) { $this->freeShipping = true; // catch the limit for free shipping $getFreeamountValue = xtc_db_query("SELECT `configuration_value` AS `freeShippingValue` FROM `configuration` WHERE `configuration_key` LIKE 'MODULE_SHIPPING_FREEAMOUNT_AMOUNT';"); $result = xtc_db_fetch_array($getFreeamountValue); // if the value of the free shipping value is not set, its 0.00 ( = always free) if(isset($result['freeShippingValue']) && is_numeric($result['freeShippingValue'])) { $this->freeShippingValue = $result['freeShippingValue']; } else { $this->freeShippingValue = 0.00; } } if($this->checkShippingCostOption('TABLE') > 0) { // table shipping cost $this->paymentTable = true; // set the values for table sc to get the correct sc for every offer $this->setPaymentTableValues(); } elseif($this->checkShippingCostOption('ITEM') > 0) { // sc per item $this->paymentItem = true; // set the standard shipping costs $this->setStandardShippingCosts(); } elseif($this->checkShippingCostOption('FLAT') > 0) { // flat sc $this->paymentFlat = true; // set the standard shipping costs $this->setStandardShippingCosts(); } } /** * Method sets the standard shipping costs (NOT the one for "table sc") * The standard sc can consist of the "flat sc" OR the "sc per item" * as the offer listing in the csv refers to ONE offer */ function setStandardShippingCosts() { $shippingModul = ''; if($this->paymentItem === true) { $shippingModul = 'MODULE_SHIPPING_ITEM_COST'; } else { $shippingModul = 'MODULE_SHIPPING_FLAT_COST'; } $getStandardShippingCosts = xtc_db_query("SELECT `configuration_value` AS `standard_sc` FROM `configuration` WHERE `configuration_key` LIKE '{$shippingModul}';"); $result = xtc_db_fetch_array($getStandardShippingCosts); // if $result['standard_sc'] is not set, $this->standardShippingCost stays empty (to be on the safe side) if(isset($result['standard_sc'])) { $this->standardShippingCost = $result['standard_sc']; } else { $this->standardShippingCost = ''; } } /** * Method checks if a specific shipping costs option is activated * * @param string $option * * @return integer 0 when nothing is found, otherwise a number bigger than 0 */ function checkShippingCostOption($option) { // transform to uppercase $option = strtoupper($option); $checkOption = xtc_db_query(" SELECT COUNT(*) AS found FROM configuration WHERE configuration_key LIKE 'MODULE_SHIPPING_{$option}_STATUS' AND configuration_value LIKE 'True'; "); $result = xtc_db_fetch_array($checkOption); if (isset($result['found']) && $result['found'] > 0) { // module is active, check allowed countries $countryOption = xtc_db_query(" SELECT COUNT(*) AS found FROM configuration WHERE configuration_key LIKE 'MODULE_SHIPPING_{$option}_ALLOWED' AND (configuration_value LIKE '%".COUNTRY_SC."%' OR configuration_value=''); "); $countryOk = xtc_db_fetch_array($countryOption); // if $countryOk['found'] is not set, 0 (country is not activated) will be returned return (isset($countryOk['found'])) ? $countryOk['found'] : 0; } else { return 0; } } /** * Method sets the "table shipping costs" values */ function setPaymentTableValues() { $explodedValues = array(); // take the data from the db $getValues = xtc_db_query("SELECT `configuration_value` AS `table_values` FROM `configuration` WHERE `configuration_key` LIKE 'MODULE_SHIPPING_TABLE_COST';"); $result = xtc_db_fetch_array($getValues); // the result shouldnt be empty // otherwise $this->paymentTableValues stays empty // example string: 25:8.50,50:5.50,10000:0.00 if( isset($result['table_values']) && $result['table_values'] != '') { // split die Value at the comma $explodedValues = explode(',', $result['table_values']); // run through the values and split again at the colon // the key is the weight / price and the value is the sc foreach($explodedValues as $values) { $tmpAr = array(); $tmpAr = explode(":", $values); // are there only numbers? if( is_numeric($tmpAr[0]) && is_numeric($tmpAr[1]) ) { $this->paymentTableValues[$tmpAr[0]] = $tmpAr[1]; } unset($tmpAr); } } // check what param is used for "table sc": weight or price $getPaymentTableMode = xtc_db_query("SELECT `configuration_value` AS `table_mode` FROM `configuration` WHERE `configuration_key` LIKE 'MODULE_SHIPPING_TABLE_MODE';"); $result = xtc_db_fetch_array($getPaymentTableMode); if(isset($result['table_mode']) && $result['table_mode'] != '') { $this->paymentTableMode = $result['table_mode']; } } /** * Methode creates the content of the csv * * @param string $file */ function process($file) { $schema = ''; @xtc_set_time_limit(0); $xtPrice = new xtcPrice($_POST['currencies'],$_POST['status']); $schema .= QUOTECHAR . 'artikelId' . QUOTECHAR . SEPARATOR . QUOTECHAR . 'hersteller' . QUOTECHAR . SEPARATOR . QUOTECHAR . 'bezeichnung' . QUOTECHAR . SEPARATOR . QUOTECHAR . 'kategorie' . QUOTECHAR . SEPARATOR . QUOTECHAR . 'beschreibung_kurz' . QUOTECHAR . SEPARATOR . QUOTECHAR . 'beschreibung_lang' . QUOTECHAR . SEPARATOR . QUOTECHAR . 'bild' . QUOTECHAR . SEPARATOR . QUOTECHAR . 'deeplink' . QUOTECHAR . SEPARATOR . QUOTECHAR . 'preis' . QUOTECHAR . SEPARATOR . QUOTECHAR . 'ean' . QUOTECHAR . SEPARATOR . QUOTECHAR . 'lieferzeit' . QUOTECHAR . SEPARATOR; // run through the payment method titles to display them in the header foreach($this->payment as $payment => $options) { // display only the payment methods that are active (if this is desired) if($options['active'] === true || DISPLAYINACTIVEMODULES === true) { $schema .= QUOTECHAR . $options['title'] . QUOTECHAR . SEPARATOR; } } // shipping comment $schema .= QUOTECHAR . 'Versandkommentar' . QUOTECHAR . SEPARATOR; // free shipping comment (if active) if( ($this->freeShipping === true) && (SHOWFREESHIPPINGLIMITCOMMENT === true) ) { $schema .= QUOTECHAR . 'Kommentar Versandkosten-Grenze' . QUOTECHAR . SEPARATOR; } $schema .= "\n"; $export_query =xtc_db_query("SELECT p.products_id, pd.products_name, pd.products_description,pd.products_short_description, p.products_model,p.products_ean, p.products_image, p.products_price, p.products_status, p.products_date_available, p.products_shippingtime, p.products_discount_allowed, pd.products_meta_keywords, p.products_tax_class_id, p.products_date_added, p.products_weight, m.manufacturers_name FROM " . TABLE_PRODUCTS . " p LEFT JOIN " . TABLE_MANUFACTURERS . " m ON p.manufacturers_id = m.manufacturers_id LEFT JOIN " . TABLE_PRODUCTS_DESCRIPTION . " pd ON p.products_id = pd.products_id AND pd.language_id = '".$_SESSION['languages_id']."' LEFT JOIN " . TABLE_SPECIALS . " s ON p.products_id = s.products_id WHERE p.products_status = 1 ORDER BY p.products_date_added DESC, pd.products_name"); while ($products = xtc_db_fetch_array($export_query)) { $products_price = $xtPrice->xtcGetPrice($products['products_id'], $format=false, 1, $products['products_tax_class_id'], ''); $this->productsPrice = $products_price; // get product categorie $categorie_query=xtc_db_query("SELECT categories_id FROM ".TABLE_PRODUCTS_TO_CATEGORIES." WHERE products_id='".$products['products_id']."'"); while ($categorie_data=xtc_db_fetch_array($categorie_query)) { $categories=$categorie_data['categories_id']; } // remove trash // characters that should be replaced $spaceToReplace = array("<br>", "<br />", "\n", "\r", "\t", "\v", chr(13)); // replace by space $commaToReplace = array("'"); // replace by comma $quoteToReplace = array("&quot,", "&qout,"); // replace by quote ( " ) // replace characters and cut to the appropriate length $products_description = strip_tags($products['products_description']); $products_description = str_replace($spaceToReplace," ",$products_description); $products_description = str_replace($commaToReplace,", ",$products_description); $products_description = str_replace($quoteToReplace," \"",$products_description); $products_description = substr($products_description, 0, 65536); $products_short_description = strip_tags($products['products_short_description']); $products_short_description = str_replace($spaceToReplace," ",$products_short_description); $products_short_description = str_replace($commaToReplace,", ",$products_short_description); $products_short_description = str_replace($quoteToReplace," \"",$products_short_description); $products_short_description = substr($products_short_description, 0, 255); $cat = $this->buildCAT($categories); if ($products['products_image'] != ''){ $image = HTTP_CATALOG_SERVER . DIR_WS_CATALOG_ORIGINAL_IMAGES .$products['products_image']; }else{ $image = ''; } //create content $schema .= QUOTECHAR . $products['products_id'] . QUOTECHAR . SEPARATOR . QUOTECHAR . $products['manufacturers_name']. QUOTECHAR . SEPARATOR . QUOTECHAR . $products['products_name'] . QUOTECHAR . SEPARATOR . QUOTECHAR . substr($cat,0,strlen($cat)-2) . QUOTECHAR. SEPARATOR . QUOTECHAR . $products_short_description . QUOTECHAR . SEPARATOR . QUOTECHAR . $products_description . QUOTECHAR . SEPARATOR . QUOTECHAR . $image . QUOTECHAR . SEPARATOR . QUOTECHAR . HTTP_CATALOG_SERVER . DIR_WS_CATALOG . 'product_info.php?'.$_POST['campaign'].xtc_product_link($products['products_id'], $products['products_name']) . QUOTECHAR . SEPARATOR . QUOTECHAR . number_format($products_price,2,'.','') . QUOTECHAR . SEPARATOR . QUOTECHAR . $products['products_ean'] . QUOTECHAR . SEPARATOR . QUOTECHAR . xtc_get_shipping_status_name($products['products_shippingtime']) . QUOTECHAR . SEPARATOR; // free shipping costs AND free sc comment available? $showScFreeComment = false; // run through the payment methods to display the fee foreach($this->payment as $singlePayment => $options) { // display only the payment fee that is active (if this is desired) if($options['active'] === true || DISPLAYINACTIVEMODULES === true) { $sc = $this->getShippingCosts($singlePayment, $products_price, $products['products_weight']); $schema .= QUOTECHAR . $sc . QUOTECHAR . SEPARATOR; // if there's one payment with sc > 0.00, display the sc free comment // exception: cash on delivery if( $singlePayment != 'COD' && $sc > 0.00 ) { $showScFreeComment = true; } } } $schema .= QUOTECHAR . SHIPPINGCOMMENT_INPUT . QUOTECHAR . SEPARATOR; // Only if free shipping costs are available AND SHOWFREESHIPPINGLIMITCOMMENT is set to true if( ($this->freeShipping === true) && SHOWFREESHIPPINGLIMITCOMMENT === true ) { // is shipping of the offer for free? if( $showScFreeComment === true ) { $schema .= QUOTECHAR . FREESHIPPINGCOMMENT_INPUT . QUOTECHAR . SEPARATOR; } else { $schema .= QUOTECHAR . '' . QUOTECHAR . SEPARATOR; } } $schema .= "\n"; } // create File $fp = fopen(DIR_FS_DOCUMENT_ROOT.'export/' . $file, "w+"); fputs($fp, $schema); fclose($fp); if( isset($_POST['export']) && $_POST['export'] == 'yes' ) { // send File to Browser $extension = substr($file, -3); $fp = fopen(DIR_FS_DOCUMENT_ROOT.'export/' . $file,"rb"); $buffer = fread($fp, filesize(DIR_FS_DOCUMENT_ROOT.'export/' . $file)); fclose($fp); header('Content-type: application/x-octet-stream'); header('Content-disposition: attachment; filename=' . $file); echo $buffer; exit; } } /** * Methods creates the Categorie for a categorieId * * @param int $catID * @return string Category */ function buildCAT($catID) { if (isset($this->CAT[$catID])) { return $this->CAT[$catID]; } else { $cat=array(); $tmpID=$catID; while ($this->getParent($catID)!=0 || $catID!=0) { $cat_select=xtc_db_query("SELECT categories_name FROM ".TABLE_CATEGORIES_DESCRIPTION." WHERE categories_id='".$catID."' and language_id='".$_SESSION['languages_id']."'"); $cat_data=xtc_db_fetch_array($cat_select); $catID=$this->getParent($catID); $cat[]=$cat_data['categories_name']; } $catStr=''; for ($i=count($cat);$i>0;$i--) { $catStr.=$cat[$i-1].' > '; } $this->CAT[$tmpID]=$catStr; return $this->CAT[$tmpID]; } } /** * Method returns the parentId of a categoryId * * @param int $catID * @return int parent id of the category */ function getParent($catID) { if (isset($this->PARENT[$catID])) { return $this->PARENT[$catID]; } else { $parent_query=xtc_db_query("SELECT parent_id FROM ".TABLE_CATEGORIES." WHERE categories_id='".$catID."'"); $parent_data=xtc_db_fetch_array($parent_query); $this->PARENT[$catID]=$parent_data['parent_id']; return $parent_data['parent_id']; } } /** * Method prepares the text that is displayed at the detailed options on module_export.php */ function display() { $customers_statuses_array = xtc_get_customers_statuses(); // build Currency Select $curr=''; $currencies=xtc_db_query("SELECT code FROM ".TABLE_CURRENCIES); while ($currencies_data=xtc_db_fetch_array($currencies)) { $curr.=xtc_draw_radio_field('currencies', $currencies_data['code'],true).$currencies_data['code'].'<br>'; } $campaign_array = array(array('id' => '', 'text' => TEXT_NONE)); $campaign_query = xtc_db_query("select campaigns_name, campaigns_refID from ".TABLE_CAMPAIGNS." order by campaigns_id"); while ($campaign = xtc_db_fetch_array($campaign_query)) { $campaign_array[] = array ('id' => 'refID='.$campaign['campaigns_refID'].'&', 'text' => $campaign['campaigns_name'],); } // get free shipping comment from db if( $this->freeShipping === true && SHOWFREESHIPPINGLIMITCOMMENT === true ) { $freeshipping_input_query = xtc_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_IDEALO_FREESHIPPINGCOMMENT' LIMIT 1"); $freeshipping_comment_db = xtc_db_fetch_array($freeshipping_input_query); $freeValue_Input_Text = ( $this->freeShippingValue != '' ) ? $freeshipping_comment_db['configuration_value'] : ''; $freeshippingHTML = FREESHIPPINGCOMMENT . '<br>' . FREESHIPPINGCOMMENT_HINT . '<br>' . xtc_draw_input_field('freeshippingcomment_input', "{$freeValue_Input_Text}") . '<br><br>'; } else { $freeshippingHTML = ''; } // get shipping comment from db $shipping_input_query = xtc_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_IDEALO_SHIPPINGCOMMENT' LIMIT 1"); $shipping_comment_db = xtc_db_fetch_array($shipping_input_query); $shipping_comment_text = ( $shipping_comment_db !== false ) ? $shipping_comment_db['configuration_value'] : ''; return array('text' => '<br>' . FIELDSEPARATOR . '<br>' . FIELDSEPARATOR_HINT . '<br>' . xtc_draw_small_input_field('separator_input', ';') . '<br><br>' . QUOTING . '<br>' . QUOTING_HINT . '<br>' . xtc_draw_small_input_field('quoting_input', '"') . '<br><br>' . SHIPPINGCOMMENT . '<br>' . SHIPPINGCOMMENT_HINT . '<br>' . xtc_draw_input_field('shippingcomment_input', $shipping_comment_text) . '<br><br>'. $freeshippingHTML . LANGUAGE . '<br>' . LANGUAGE_HINT . '<br>' . xtc_draw_small_input_field('language_input', 'DE') . '<br>' . EXPORT_STATUS_TYPE.'<br>'. EXPORT_STATUS.'<br>'. xtc_draw_pull_down_menu('status',$customers_statuses_array, '1').'<br>'. CURRENCY.'<br>'. CURRENCY_DESC.'<br>'. $curr. CAMPAIGNS.'<br>'. CAMPAIGNS_DESC.'<br>'. xtc_draw_pull_down_menu('campaign',$campaign_array).'<br>'. EXPORT_TYPE.'<br>'. EXPORT.'<br>'. xtc_draw_radio_field('export', 'no',false).EXPORT_NO.'<br>'. xtc_draw_radio_field('export', 'yes',true).EXPORT_YES.'<br>'. '<br>' . xtc_button(BUTTON_EXPORT) . xtc_button_link(BUTTON_CANCEL, xtc_href_link(FILENAME_MODULE_EXPORT, 'set=' . $_GET['set'] . '&module=idealo'))); } function check() { if (!isset($this->_check)) { $check_query = xtc_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_IDEALO_STATUS'"); $this->_check = xtc_db_num_rows($check_query); } return $this->_check; } /** * Method installs a module in module_export.php */ function install() { xtc_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('MODULE_IDEALO_FILE', 'idealo.csv', '6', '1', '', now())"); xtc_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('MODULE_IDEALO_STATUS', 'True', '6', '1', 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())"); } /** * Method removes a module */ function remove() { xtc_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')"); } function keys() { return array('MODULE_IDEALO_STATUS','MODULE_IDEALO_FILE'); } } ?>
gpl-2.0
justdude/OrdersManager
OrdersManager/CacheManager/CacheManager.cs
2092
using System; using System.Collections.Generic; using System.Linq; using System.Text; using OrdersManager.ModelView; using System.Collections.ObjectModel; namespace OrdersManager.Cache { public class CacheManager { public CacheManager() { } private ObservableCollection<ProjectViewModel> projects; private ObservableCollection<TaskViewModel> tasks; private ObservableCollection<CostumerViewModel> costumers; private ObservableCollection<FreelancerViewModel> freelancers; public ObservableCollection<ProjectViewModel> Projects { get { /*if (projects == null) projects = new ObservableCollection<ProjectViewModel>();*/ return projects; } set { projects = value; } } public ObservableCollection<CostumerViewModel> Costumers { get { /*if (projects == null) projects = new ObservableCollection<ProjectViewModel>();*/ return costumers; } set { costumers = value; } } public ObservableCollection<FreelancerViewModel> Freelancers { get { return freelancers; } set { freelancers = value; } } public ObservableCollection<TaskViewModel> Tasks { get { return tasks; } set { tasks = value; } } private static CacheManager cacheManager; public static CacheManager Instance { get { if (cacheManager==null) { cacheManager = new CacheManager(); } return cacheManager; } } } }
gpl-2.0
Dave-Choi/pomello
app/components/timer-donut.js
128
import ProgressDonut from './progress-donut'; export default ProgressDonut.extend({ classNameBindings: ["isTiming:pulse"] });
gpl-2.0
snake77se/proyectoszeppelin
administrator/components/com_crowdfundingfinance/models/payouts.php
7241
<?php /** * @package CrowdfundingFinance * @subpackage Components * @author Todor Iliev * @copyright Copyright (C) 2015 Todor Iliev <todor@itprism.com>. All rights reserved. * @license GNU General Public License version 3 or later; see LICENSE.txt */ // no direct access defined('_JEXEC') or die; class CrowdfundingFinanceModelPayouts extends JModelList { /** * Constructor. * * @param array $config An optional associative array of configuration settings. * * @see JController * @since 1.6 */ public function __construct($config = array()) { if (empty($config['filter_fields'])) { $config['filter_fields'] = array( 'id', 'a.id', 'title', 'a.title', 'category', 'b.title', 'published', 'a.published', ); } parent::__construct($config); } protected function populateState($ordering = null, $direction = null) { // Load the component parameters. $params = JComponentHelper::getParams($this->option); $this->setState('params', $params); // Load filter search. $value = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search'); $this->setState('filter.search', $value); // Load filter state. $value = $this->getUserStateFromRequest($this->context . '.filter.state', 'filter_state', '', 'string'); $this->setState('filter.state', $value); // Load filter approved state. $value = $this->getUserStateFromRequest($this->context . '.filter.approved', 'filter_approved', '', 'string'); $this->setState('filter.approved', $value); // Load filter featured state. $value = $this->getUserStateFromRequest($this->context . '.filter.featured', 'filter_featured', '', 'string'); $this->setState('filter.featured', $value); // Load filter category. $value = $this->getUserStateFromRequest($this->context . '.filter.category_id', 'filter_category_id', 0, 'int'); $this->setState('filter.category_id', $value); // Load filter type. $value = $this->getUserStateFromRequest($this->context . '.filter.type_id', 'filter_type_id', 0, 'int'); $this->setState('filter.type_id', $value); // List state information. parent::populateState('a.created', 'asc'); } /** * Method to get a store id based on model configuration state. * * This is necessary because the model is used by the component and * different modules that might need different sets of data or different * ordering requirements. * * @param string $id A prefix for the store id. * * @return string A store id. * @since 1.6 */ protected function getStoreId($id = '') { // Compile the store id. $id .= ':' . $this->getState('filter.search'); $id .= ':' . $this->getState('filter.state'); $id .= ':' . $this->getState('filter.approved'); $id .= ':' . $this->getState('filter.featured'); $id .= ':' . $this->getState('filter.category_id'); $id .= ':' . $this->getState('filter.type_id'); return parent::getStoreId($id); } /** * Build an SQL query to load the list data. * * @return JDatabaseQuery * @since 1.6 */ protected function getListQuery() { $db = $this->getDbo(); /** @var $db JDatabaseDriver */ // Create a new query object. $query = $db->getQuery(true); // Select the required fields from the table. $query->select( $this->getState( 'list.select', 'a.id, a.title, a.goal, a.funded, a.funding_start, a.funding_end, a.user_id, ' . 'a.funding_days, a.ordering, a.created, a.catid, ROUND( (a.funded/a.goal) * 100, 1 ) AS funded_percents, ' . 'a.featured, a.published, a.approved, ' . 'b.title AS category, ' . 'c.title AS type, ' . 'd.name AS username, ' . 'e.paypal_email, e.paypal_first_name, e.paypal_last_name, e.iban, e.bank_account ' ) ); $query->from($db->quoteName('#__crowdf_projects', 'a')); $query->leftJoin($db->quoteName('#__categories', 'b') . ' ON a.catid = b.id'); $query->leftJoin($db->quoteName('#__crowdf_types', 'c') . ' ON a.type_id = c.id'); $query->leftJoin($db->quoteName('#__users', 'd') . ' ON a.user_id = d.id'); $query->leftJoin($db->quoteName('#__cffinance_payouts', 'e') . ' ON a.id = e.id'); // Filter by category $categoryId = $this->getState('filter.category_id'); if (!empty($categoryId)) { $query->where('b.id = ' . (int)$categoryId); } // Filter by state $state = $this->getState('filter.state'); if (is_numeric($state)) { $query->where('a.published = ' . (int)$state); } elseif ($state === '') { $query->where('(a.published IN (0, 1))'); } // Filter by approved state $state = $this->getState('filter.approved'); if (is_numeric($state)) { $query->where('a.approved = ' . (int)$state); } elseif ($state === '') { $query->where('(a.approved IN (0, 1))'); } // Filter by approved state $state = $this->getState('filter.featured'); if (is_numeric($state)) { $query->where('a.featured = ' . (int)$state); } elseif ($state === '') { $query->where('(a.featured IN (0, 1))'); } // Filter by type $typeId = $this->getState('filter.type_id'); if (!empty($typeId)) { $query->where('a.type_id = ' . (int)$typeId); } // Filter by search in title $search = $this->getState('filter.search'); if (!empty($search)) { if (stripos($search, 'id:') === 0) { $query->where('a.id = ' . (int)substr($search, 3)); } elseif (stripos($search, 'uid:') === 0) { $query->where('a.user_id = ' . (int)substr($search, 4)); } else { $escaped = $db->escape($search, true); $quoted = $db->quote("%" . $escaped . "%", false); $query->where('a.title LIKE ' . $quoted); } } // Add the list ordering clause. $orderString = $this->getOrderString(); $query->order($db->escape($orderString)); return $query; } protected function getOrderString() { $orderCol = $this->getState('list.ordering', 'a.created'); $orderDirn = $this->getState('list.direction', 'asc'); if ($orderCol == 'a.ordering') { $orderCol = 'a.catid ' . $orderDirn . ', a.ordering'; } return $orderCol . ' ' . $orderDirn; } }
gpl-2.0
trepidacious/boxes-graph
src/main/scala/org/rebeam/boxes/graph/GraphAxis.scala
2688
package org.rebeam.boxes.graph import org.rebeam.boxes.core._ import org.rebeam.boxes.swing.SwingView import org.rebeam.boxes.swing.icons.IconFactory import BoxScriptImports._ import BoxTypes._ import BoxUtils._ import java.awt.Color import java.awt.geom.Rectangle2D import java.text.DecimalFormat import GraphMouseEventType._ import Axis._ object GraphAxis { val fontSize = 10 val titleFontSize = 12 val fontColor = SwingView.textColor val axisColor = SwingView.dividingColor val axisHighlightColor = SwingView.alternateBackgroundColor.brighter val gridMajorColor = new Color(0f, 0f, 0f, 0.08f) val gridMinorColor = new Color(0f, 0f, 0f, 0.03f) val defaultFormat = new DecimalFormat("0.###") def apply(axis: Axis, pixelsPerMajor: Int = 100, format: DecimalFormat = GraphAxis.defaultFormat) = new GraphAxis(axis, pixelsPerMajor, format) } class GraphAxis(val axis: Axis, val pixelsPerMajor: Int = 100, val format: DecimalFormat = GraphAxis.defaultFormat, val gridlines: Boolean = true, val minorGridLines: Boolean = false, highlights: Boolean = false) extends UnboundedGraphDisplayLayer { def paint = just ( (canvas:GraphCanvas) => { val dataArea = canvas.spaces.dataArea val ticks = Ticks(dataArea.axisBounds(axis), canvas.spaces.pixelArea.axisSize(axis), pixelsPerMajor) ticks.foreach(t => { val (p, major) = t val start = canvas.spaces.toPixel(dataArea.axisPosition(axis, p)) canvas.color = GraphAxis.axisColor axis match { case X => canvas.line(start, start + Vec2(0, if (major) 8 else 4)) case Y => canvas.line(start, start + Vec2(if (major) -8 else -4, 0)) } if (highlights) { canvas.color = GraphAxis.axisHighlightColor axis match { case X => canvas.line(start + Vec2(1, 0), start + Vec2(1, if (major) 8 else 4)) case Y => canvas.line(start + Vec2(0, 1), start + Vec2(if (major) -8 else -4, 1)) } } if (major) { canvas.color = GraphAxis.fontColor canvas.fontSize = GraphAxis.fontSize axis match { case X => canvas.string(format.format(p), start + Vec2(0, 10), Vec2(0.5, 1)) case Y => canvas.string(format.format(p), start + Vec2(-10, 0), Vec2(1, 0.5)) } if (gridlines) { canvas.color = GraphAxis.gridMajorColor canvas.line(start, start + canvas.spaces.pixelArea.axisPerpVec2(axis)) } } else if (minorGridLines) { canvas.color = GraphAxis.gridMinorColor canvas.line(start, start + canvas.spaces.pixelArea.axisPerpVec2(axis)) } }) } ) }
gpl-2.0
utilo-web-app-development/REZERVI
rezerviGeneric/belegungsplan/suche/index.php
4971
<?php $root="../.."; /** date: 3.4.06 author: christian osterrieder utilo.net */ if (!isset($nachricht)){ session_start(); // Send modified header for session-problem of ie: // @see http://de.php.net/session header('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"'); } //datenbank öffnen: include_once($root."/conf/rdbmsConfig.inc.php"); //conf file öffnen: include_once($root."/conf/conf.inc.php"); include_once($root."/include/uebersetzer.inc.php"); include_once($root."/include/sessionFunctions.inc.php"); include_once($root."/include/cssFunctions.inc.php"); include_once($root."/include/vermieterFunctions.inc.php"); include_once($root."/include/mietobjektFunctions.inc.php"); //wurde die suche direkt aufgerufen? if (isset($_GET["vermieter_id"])){ $vermieter_id = $_GET["vermieter_id"]; } else if (isset($_POST["vermieter_id"])){ $vermieter_id = $_POST["vermieter_id"]; } else{ $vermieter_id = 1; } //ist die suchfunktion überhaupt aktiv? $sucheAktiv = getVermieterEigenschaftenWert(SUCHFUNKTION_AKTIV,$vermieter_id); if ($sucheAktiv == "true"){ $sucheAktiv = true; } else{ $nachricht = ""; include_once($root."/start.php"); exit; } //sprache? $temp = getSessionWert(SPRACHE); if (isset($_GET["sprache"])){ $sprache = $_GET["sprache"]; } else if (isset($_POST["sprache"])){ $sprache = $_POST["sprache"]; } else if (!empty($temp)){ $sprache = getSessionWert(SPRACHE); } else{ $sprache = getVermieterEigenschaftenWert(STANDARDSPRACHE,$vermieter_id); } $temp = getSessionWert(SPRACHE); if (empty($temp) && !empty($sprache)){ setSessionWert(SPRACHE,$sprache); } //header einfuegen: ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Rezervi Generic Booking System - Rezervi Generic Buchungssystem - utilo.net</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <?php include_once($root."/templates/stylesheets.php"); ?> </style> </head> <?php include_once($root."/templates/bodyStart.inc.php"); ?> <table border="0"> <tr> <td><p class="<?php echo STANDARD_SCHRIFT ?>"> <?php echo getUebersetzung("Sie können den Belegungsplan" . "betrachten,<br/>indem Sie eine Auswahl treffen " . "und auf [Belegungsplan anzeigen] klicken...") ?> </p> </td> </tr> </table> <form action="<?php echo $root ?>/start.php" method="post" name="form1" target="_self"> <table border="0" class="<?php echo TABLE_STANDARD ?>"> <tr> <td class="<?php echo STANDARD_SCHRIFT_BOLD ?>"> <?php echo getUebersetzung("Belegungsplan für:") ?> </td> </tr> <tr> <td><?php //es sollte die liste auf keinen fall groesser als 10 werden: $selectSize = getAnzahlVorhandeneMietobjekte($vermieter_id); if ($selectSize > 10) { $selectSize = 10; } ?> <select name="mietobjekt_id" size="<?php echo $selectSize ?>" class="<?php echo STANDARD_SCHRIFT ?>"> <?php $res = getMietobjekte($vermieter_id); $zaehler = 0; while ($d = mysqli_fetch_array($res)){ $mietobjekt_ez = getMietobjekt_EZ($vermieter_id); $bezeichnung = getUebersetzungVermieter($mietobjekt_ez,$sprache,$vermieter_id); $bezeichnung .= " ".$d["BEZEICHNUNG"]; ?> <option value="<?php echo $d["MIETOBJEKT_ID"] ?>" <?php if ($zaehler++ == 0) { echo("selected=\"selected\""); } ?>><?php echo $bezeichnung ?> </option> <?php } //ende while mietobjekte ?> </select> </td> </tr> <tr> <td><input type="submit" name="Submit" class="<?php echo BUTTON ?>" onMouseOver="this.className='<?php echo BUTTON_HOVER ?>';" onMouseOut="this.className='<?php echo BUTTON ?>';" value="<?php echo(getUebersetzung("Belegungsplan anzeigen")); ?>"> </td> </tr> </table> </form> <table border="0"> <tr> <td><span class="<?php echo STANDARD_SCHRIFT ?>"> <?php echo getUebersetzung("...oder eine automatische Suche durchführen, " . "<br/>indem sie unterstehende Daten angeben und [Suche starten] klicken.") ?> </span></td> </tr> </table> <form action="./sucheDurchfuehren.php" method="post" name="suchen" target="_self" id="suchen"> <table border="0" class="<?php echo TABLE_STANDARD ?>"> <tr> <td><p class="<?php echo STANDARD_SCHRIFT_BOLD ?>"> <?php include_once($root."/templates/datumVonDatumBis.inc.php"); ?> </p> </td> </tr> <tr> <td class="<?php echo STANDARD_SCHRIFT_BOLD ?>"><input name="sucheStarten" type="submit" class="<?php echo BUTTON ?>" onMouseOver="this.className='<?php echo BUTTON_HOVER ?>';" onMouseOut="this.className='<?php echo BUTTON ?>';" id="sucheStarten" value="<?php echo(getUebersetzung("Suche starten...")); ?>"> </td> </tr> </table> </form> <?php include_once($root."/templates/footer.inc.php"); ?>
gpl-2.0
Hixon10/tiny-workflow
Domain/Contracts/IRoleService.cs
1282
using System.Collections.Generic; namespace Domain.Contracts { /// <summary> /// Сервис для работы с Ролями системы /// </summary> public interface IRoleService { /// <summary> /// Изменить приоритеты ролей /// </summary> /// <param name="priorities">Словарь вида роль-приоритет</param> void ChangeRolesPriority(Dictionary<ApplicationRole.RoleTypes, ApplicationRole.Priorities> priorities); /// <summary> /// Получить все роли системы /// </summary> /// <returns>Роли</returns> List<ApplicationRole> GetRoles(); /// <summary> /// Получить Роли пользователя /// </summary> /// <param name="user">Пользователь</param> /// <returns>Роли</returns> List<ApplicationRole.RoleTypes> GetRolesByUser(ApplicationUser user); /// <summary> /// Получить Роль по типу /// </summary> /// <param name="type">Тип Роли</param> /// <returns>Роль</returns> ApplicationRole GetRoleByType(ApplicationRole.RoleTypes type); } }
gpl-2.0
skhale/chelton-dashboard
modules/api/ApiModule.php
203
<?php namespace app\modules\api; class ApiModule extends \yii\base\Module { public function init() { parent::init(); \Yii::configure($this, require __DIR__ . '/config.php'); } }
gpl-2.0
blueliquiddesigns/gravity-forms-pdf-extended
src/Helper/Fields/Field_Option.php
3905
<?php namespace GFPDF\Helper\Fields; use GFPDF\Helper\Helper_Abstract_Field_Products; use GFFormsModel; use GFCommon; /** * @package Gravity PDF * @copyright Copyright (c) 2020, Blue Liquid Designs * @license http://opensource.org/licenses/gpl-2.0.php GNU Public License */ /* Exit if accessed directly */ if ( ! defined( 'ABSPATH' ) ) { exit; } /** * @since 4.3 */ class Field_Option extends Helper_Abstract_Field_Products { /** * Return the HTML form data * * @return array * * @since 4.3 */ public function form_data() { $field = $this->field; /** * Gravity Forms doesn't currently store the option field ID with the standard product information. * However, it does allow multiple fields to be an option for a single product. * This becomes problematic when you have multiple option fields that contains the same name and are * trying to determine which field it was selected from. * * To get around this limitation we'll process the entry option fields and make this data available. */ /* Get the current option value for this field */ $option_value = GFFormsModel::get_lead_field_value( $this->entry, $field ); /* Ensure this variable is an array */ $option_value = ( ! is_array( $option_value ) ) ? [ $option_value ] : $option_value; /* Reset the array keys and remove any empty values */ $option_value = array_values( $option_value ); $option_value = array_filter( $option_value ); /* Get the field name ( */ $name = array_map( function( $value ) use ( $field ) { $option_info = GFCommon::get_option_info( $value, $field, false ); return esc_html( $option_info['name'] ); }, $option_value ); /* Get the field value (the price) */ $price = array_map( function( $value ) use ( $field ) { $option_info = GFCommon::get_option_info( $value, $field, false ); return esc_html( $option_info['price'] ); }, $option_value ); /** * Valid option fields can only be radio, checkbox and select boxes * To ensure backwards compatibility we'll remove the array if not a checkbox value */ if ( $field->inputType !== 'checkbox' ) { $name = array_shift( $name ); $price = array_shift( $price ); } return $this->set_form_data( $name, $price ); } /** * Display the HTML version of this field * * @param string $value * @param bool $label * * @return string * * @since 4.3 */ public function html( $value = '', $label = true ) { $value = $this->value(); $html = ''; if ( isset( $value['options'] ) ) { $html .= $this->get_option_html( $value['options'] ); } return parent::html( $html ); } /** * Get a HTML list of the product's selected options * * @param array $options A list of the selected products * @param string $html Pass in an existing HTML, or default to blank * * @return string The finalised HTML * * @since 4.3 */ public function get_option_html( $options, $html = '' ) { if ( is_array( $options ) ) { $html .= '<ul class="product_options">'; foreach ( $options as $option ) { $html .= '<li>' . esc_html( $option['option_name'] . ' - ' . $option['price_formatted'] ) . '</li>'; } $html .= '</ul>'; } return $html; } /** * Get the standard GF value of this field * * @return array * * @since 4.3 */ public function value() { if ( $this->has_cache() ) { return $this->cache(); } $data = $this->products->value(); if ( isset( $data['products'][ $this->field->productField ]['options'] ) ) { $this->cache( [ 'options' => array_filter( $data['products'][ $this->field->productField ]['options'], function( $option ) { return ! isset( $option['id'] ) || $option['id'] === $this->field->id; } ), ] ); } else { $this->cache( [] ); } return $this->cache(); } }
gpl-2.0
weleoka/discdex
dd_utils/dd_prompt.py
3407
""" Utility module for Discdex. Functions return information data to stdout and take user input for processing. """ from dd_utils import mnt_autodetect def device_name(indexing_file): """ Display all device names currently existing in indexing file. Prompt for a new device name and then check if user input is unique, if not unique prompt y/n for continue. parameters: indexing_file: string. The current indexing file. return: device_name: string. The name of the device to index. """ current_device = ""; device_list = [] for line in open(indexing_file): # open under default flag -r if current_device != line[0]: device_list.append(line[0]) current_device = line[0] while True: print("\nCurrently indexed device names are:\n%s" % (device_list)) device_name = input('Enter a name for the new device (ex. disc_01): ') if device_name in device_list: y_n = input("' %s ' as a device name already exists. Do you want to continue anyway? y/n: " % (device_name)) if y_n in ['y', 'n']: if y_n == 'y': break elif y_n == 'n': continue elif device_name != "": return device_name def device_path(): """ Display select list of all file systems currently mounted. Prompt for path to device or one of the select options. parameters: none. return: path_to_device: string. The path to the device to index. """ mnt_points = mnt_autodetect.get_mount_points() i = 0 print ("\n") for mnt_point in mnt_points: i += 1 print("[%i] %s %s" % (i, mnt_point[0].decode().split('/')[2], mnt_point[1].decode())) path_to_device = input('Enter path (ex. /media/simoni/superCD ) or choose from above options: ') try: dev = int(path_to_device) except ValueError as e: print ("The argument does not contain numbers\n%s" % (e)) dev = False if dev and dev <= len(mnt_points): path_to_device = mnt_points[dev - 1] path_to_device = path_to_device[1].decode() return path_to_device def sorting_option(): """ Promt for the sorting method. [1] Alphabetical order. [2] Alphabetical order grouped by device name. Promt for a description to be written to the new list. parameters: return: path_to_device: string. The path to the device to index. list_file: string. The file which will contain the sorted list. description: string. A description for the sorted list. """ print("\nChoose a sorting mode for the new list.\n") print("[1] Alphabetical order.") print("[2] Alphabetical order grouped by device name.") print("[9] Main menu.") while True: sorting_option = input('Enter option: ') if sorting_option in ['1', '2']: while True: list_file = input('\nGive the new list file a file name: ') # Use specified or query for new. description = input('\nGive the new list a description (or leave blank): \n') if list_file != '': break return sorting_option, list_file, description elif sorting_option == "9": return None, None, None
gpl-2.0
Jacklli/ActionDB
rocksdb-3.9/java/org/rocksdb/RocksDB.java
53733
// Copyright (c) 2014, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. package org.rocksdb; import java.util.*; import java.io.IOException; import org.rocksdb.util.Environment; /** * A RocksDB is a persistent ordered map from keys to values. It is safe for * concurrent access from multiple threads without any external synchronization. * All methods of this class could potentially throw RocksDBException, which * indicates sth wrong at the RocksDB library side and the call failed. */ public class RocksDB extends RocksObject { public static final String DEFAULT_COLUMN_FAMILY = "default"; public static final int NOT_FOUND = -1; static { RocksDB.loadLibrary(); } /** * Loads the necessary library files. * Calling this method twice will have no effect. * By default the method extracts the shared library for loading at * java.io.tmpdir, however, you can override this temporary location by * setting the environment variable ROCKSDB_SHAREDLIB_DIR. */ public static synchronized void loadLibrary() { String tmpDir = System.getenv("ROCKSDB_SHAREDLIB_DIR"); // loading possibly necessary libraries. for (CompressionType compressionType : CompressionType.values()) { try { if (compressionType.getLibraryName() != null) { System.loadLibrary(compressionType.getLibraryName()); } } catch (UnsatisfiedLinkError e) { // since it may be optional, we ignore its loading failure here. } } try { NativeLibraryLoader.getInstance().loadLibraryFromJar(tmpDir); } catch (IOException e) { throw new RuntimeException("Unable to load the RocksDB shared library" + e); } } /** * Tries to load the necessary library files from the given list of * directories. * * @param paths a list of strings where each describes a directory * of a library. */ public static synchronized void loadLibrary(List<String> paths) { for (CompressionType compressionType : CompressionType.values()) { if (compressionType.equals(CompressionType.NO_COMPRESSION)) { continue; } for (String path : paths) { try { System.load(path + "/" + Environment.getSharedLibraryName( compressionType.getLibraryName())); break; } catch (UnsatisfiedLinkError e) { // since they are optional, we ignore loading fails. } } } boolean success = false; UnsatisfiedLinkError err = null; for (String path : paths) { try { System.load(path + "/" + Environment.getJniLibraryName("rocksdbjni")); success = true; break; } catch (UnsatisfiedLinkError e) { err = e; } } if (!success) { throw err; } } /** * The factory constructor of RocksDB that opens a RocksDB instance given * the path to the database using the default options w/ createIfMissing * set to true. * * @param path the path to the rocksdb. * @return a {@link RocksDB} instance on success, null if the specified * {@link RocksDB} can not be opened. * * @throws RocksDBException thrown if error happens in underlying * native library. * @see Options#setCreateIfMissing(boolean) */ public static RocksDB open(String path) throws RocksDBException { // This allows to use the rocksjni default Options instead of // the c++ one. Options options = new Options(); options.setCreateIfMissing(true); return open(options, path); } /** * The factory constructor of RocksDB that opens a RocksDB instance given * the path to the database using the specified options and db path and a list * of column family names. * <p> * If opened in read write mode every existing column family name must be passed * within the list to this method.</p> * <p> * If opened in read-only mode only a subset of existing column families must * be passed to this method.</p> * <p> * Options instance *should* not be disposed before all DBs using this options * instance have been closed. If user doesn't call options dispose explicitly, * then this options instance will be GC'd automatically</p> * <p> * ColumnFamily handles are disposed when the RocksDB instance is disposed. * </p> * * @param path the path to the rocksdb. * @param columnFamilyDescriptors list of column family descriptors * @param columnFamilyHandles will be filled with ColumnFamilyHandle instances * on open. * @return a {@link RocksDB} instance on success, null if the specified * {@link RocksDB} can not be opened. * * @throws RocksDBException thrown if error happens in underlying * native library. * @see DBOptions#setCreateIfMissing(boolean) */ public static RocksDB open(String path, List<ColumnFamilyDescriptor> columnFamilyDescriptors, List<ColumnFamilyHandle> columnFamilyHandles) throws RocksDBException { // This allows to use the rocksjni default Options instead of // the c++ one. DBOptions options = new DBOptions(); return open(options, path, columnFamilyDescriptors, columnFamilyHandles); } /** * The factory constructor of RocksDB that opens a RocksDB instance given * the path to the database using the specified options and db path. * * <p> * Options instance *should* not be disposed before all DBs using this options * instance have been closed. If user doesn't call options dispose explicitly, * then this options instance will be GC'd automatically.</p> * <p> * Options instance can be re-used to open multiple DBs if DB statistics is * not used. If DB statistics are required, then its recommended to open DB * with new Options instance as underlying native statistics instance does not * use any locks to prevent concurrent updates.</p> * * @param options {@link org.rocksdb.Options} instance. * @param path the path to the rocksdb. * @return a {@link RocksDB} instance on success, null if the specified * {@link RocksDB} can not be opened. * * @throws RocksDBException thrown if error happens in underlying * native library. * * @see Options#setCreateIfMissing(boolean) */ public static RocksDB open(Options options, String path) throws RocksDBException { // when non-default Options is used, keeping an Options reference // in RocksDB can prevent Java to GC during the life-time of // the currently-created RocksDB. RocksDB db = new RocksDB(); db.open(options.nativeHandle_, path); db.storeOptionsInstance(options); return db; } /** * The factory constructor of RocksDB that opens a RocksDB instance given * the path to the database using the specified options and db path and a list * of column family names. * <p> * If opened in read write mode every existing column family name must be passed * within the list to this method.</p> * <p> * If opened in read-only mode only a subset of existing column families must * be passed to this method.</p> * <p> * Options instance *should* not be disposed before all DBs using this options * instance have been closed. If user doesn't call options dispose explicitly, * then this options instance will be GC'd automatically.</p> * <p> * Options instance can be re-used to open multiple DBs if DB statistics is * not used. If DB statistics are required, then its recommended to open DB * with new Options instance as underlying native statistics instance does not * use any locks to prevent concurrent updates.</p> * <p> * ColumnFamily handles are disposed when the RocksDB instance is disposed.</p> * * @param options {@link org.rocksdb.DBOptions} instance. * @param path the path to the rocksdb. * @param columnFamilyDescriptors list of column family descriptors * @param columnFamilyHandles will be filled with ColumnFamilyHandle instances * on open. * @return a {@link RocksDB} instance on success, null if the specified * {@link RocksDB} can not be opened. * * @throws RocksDBException thrown if error happens in underlying * native library. * * @see DBOptions#setCreateIfMissing(boolean) */ public static RocksDB open(DBOptions options, String path, List<ColumnFamilyDescriptor> columnFamilyDescriptors, List<ColumnFamilyHandle> columnFamilyHandles) throws RocksDBException { RocksDB db = new RocksDB(); List<Long> cfReferences = db.open(options.nativeHandle_, path, columnFamilyDescriptors, columnFamilyDescriptors.size()); for (int i = 0; i < columnFamilyDescriptors.size(); i++) { columnFamilyHandles.add(new ColumnFamilyHandle(db, cfReferences.get(i))); } db.storeOptionsInstance(options); return db; } /** * The factory constructor of RocksDB that opens a RocksDB instance in * Read-Only mode given the path to the database using the default * options. * * @param path the path to the RocksDB. * @return a {@link RocksDB} instance on success, null if the specified * {@link RocksDB} can not be opened. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public static RocksDB openReadOnly(String path) throws RocksDBException { // This allows to use the rocksjni default Options instead of // the c++ one. Options options = new Options(); return openReadOnly(options, path); } /** * The factory constructor of RocksDB that opens a RocksDB instance in * Read-Only mode given the path to the database using the default * options. * * @param path the path to the RocksDB. * @param columnFamilyDescriptors list of column family descriptors * @param columnFamilyHandles will be filled with ColumnFamilyHandle instances * on open. * @return a {@link RocksDB} instance on success, null if the specified * {@link RocksDB} can not be opened. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public static RocksDB openReadOnly(String path, List<ColumnFamilyDescriptor> columnFamilyDescriptors, List<ColumnFamilyHandle> columnFamilyHandles) throws RocksDBException { // This allows to use the rocksjni default Options instead of // the c++ one. DBOptions options = new DBOptions(); return openReadOnly(options, path, columnFamilyDescriptors, columnFamilyHandles); } /** * The factory constructor of RocksDB that opens a RocksDB instance in * Read-Only mode given the path to the database using the specified * options and db path. * * Options instance *should* not be disposed before all DBs using this options * instance have been closed. If user doesn't call options dispose explicitly, * then this options instance will be GC'd automatically. * * @param options {@link Options} instance. * @param path the path to the RocksDB. * @return a {@link RocksDB} instance on success, null if the specified * {@link RocksDB} can not be opened. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public static RocksDB openReadOnly(Options options, String path) throws RocksDBException { // when non-default Options is used, keeping an Options reference // in RocksDB can prevent Java to GC during the life-time of // the currently-created RocksDB. RocksDB db = new RocksDB(); db.openROnly(options.nativeHandle_, path); db.storeOptionsInstance(options); return db; } /** * The factory constructor of RocksDB that opens a RocksDB instance in * Read-Only mode given the path to the database using the specified * options and db path. * * <p>This open method allows to open RocksDB using a subset of available * column families</p> * <p>Options instance *should* not be disposed before all DBs using this * options instance have been closed. If user doesn't call options dispose * explicitly,then this options instance will be GC'd automatically.</p> * * @param options {@link DBOptions} instance. * @param path the path to the RocksDB. * @param columnFamilyDescriptors list of column family descriptors * @param columnFamilyHandles will be filled with ColumnFamilyHandle instances * on open. * @return a {@link RocksDB} instance on success, null if the specified * {@link RocksDB} can not be opened. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public static RocksDB openReadOnly(DBOptions options, String path, List<ColumnFamilyDescriptor> columnFamilyDescriptors, List<ColumnFamilyHandle> columnFamilyHandles) throws RocksDBException { // when non-default Options is used, keeping an Options reference // in RocksDB can prevent Java to GC during the life-time of // the currently-created RocksDB. RocksDB db = new RocksDB(); List<Long> cfReferences = db.openROnly(options.nativeHandle_, path, columnFamilyDescriptors, columnFamilyDescriptors.size()); for (int i=0; i<columnFamilyDescriptors.size(); i++) { columnFamilyHandles.add(new ColumnFamilyHandle(db, cfReferences.get(i))); } db.storeOptionsInstance(options); return db; } /** * Static method to determine all available column families for a * rocksdb database identified by path * * @param options Options for opening the database * @param path Absolute path to rocksdb database * @return List&lt;byte[]&gt; List containing the column family names * * @throws RocksDBException thrown if error happens in underlying * native library. */ public static List<byte[]> listColumnFamilies(Options options, String path) throws RocksDBException { return RocksDB.listColumnFamilies(options.nativeHandle_, path); } private void storeOptionsInstance(DBOptionsInterface options) { options_ = options; } @Override protected void disposeInternal() { synchronized (this) { assert (isInitialized()); disposeInternal(nativeHandle_); } } /** * Close the RocksDB instance. * This function is equivalent to dispose(). */ public void close() { dispose(); } /** * Set the database entry for "key" to "value". * * @param key the specified key to be inserted. * @param value the value associated with the specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void put(byte[] key, byte[] value) throws RocksDBException { put(nativeHandle_, key, key.length, value, value.length); } /** * Set the database entry for "key" to "value" in the specified * column family. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param key the specified key to be inserted. * @param value the value associated with the specified key. * * throws IllegalArgumentException if column family is not present * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void put(ColumnFamilyHandle columnFamilyHandle, byte[] key, byte[] value) throws RocksDBException { put(nativeHandle_, key, key.length, value, value.length, columnFamilyHandle.nativeHandle_); } /** * Set the database entry for "key" to "value". * * @param writeOpts {@link org.rocksdb.WriteOptions} instance. * @param key the specified key to be inserted. * @param value the value associated with the specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void put(WriteOptions writeOpts, byte[] key, byte[] value) throws RocksDBException { put(nativeHandle_, writeOpts.nativeHandle_, key, key.length, value, value.length); } /** * Set the database entry for "key" to "value" for the specified * column family. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param writeOpts {@link org.rocksdb.WriteOptions} instance. * @param key the specified key to be inserted. * @param value the value associated with the specified key. * * throws IllegalArgumentException if column family is not present * * @throws RocksDBException thrown if error happens in underlying * native library. * @see IllegalArgumentException */ public void put(ColumnFamilyHandle columnFamilyHandle, WriteOptions writeOpts, byte[] key, byte[] value) throws RocksDBException { put(nativeHandle_, writeOpts.nativeHandle_, key, key.length, value, value.length, columnFamilyHandle.nativeHandle_); } /** * If the key definitely does not exist in the database, then this method * returns false, else true. * * This check is potentially lighter-weight than invoking DB::Get(). One way * to make this lighter weight is to avoid doing any IOs. * * @param key byte array of a key to search for * @param value StringBuffer instance which is a out parameter if a value is * found in block-cache. * @return boolean value indicating if key does not exist or might exist. */ public boolean keyMayExist(byte[] key, StringBuffer value){ return keyMayExist(key, key.length, value); } /** * If the key definitely does not exist in the database, then this method * returns false, else true. * * This check is potentially lighter-weight than invoking DB::Get(). One way * to make this lighter weight is to avoid doing any IOs. * * @param columnFamilyHandle {@link ColumnFamilyHandle} instance * @param key byte array of a key to search for * @param value StringBuffer instance which is a out parameter if a value is * found in block-cache. * @return boolean value indicating if key does not exist or might exist. */ public boolean keyMayExist(ColumnFamilyHandle columnFamilyHandle, byte[] key, StringBuffer value){ return keyMayExist(key, key.length, columnFamilyHandle.nativeHandle_, value); } /** * If the key definitely does not exist in the database, then this method * returns false, else true. * * This check is potentially lighter-weight than invoking DB::Get(). One way * to make this lighter weight is to avoid doing any IOs. * * @param readOptions {@link ReadOptions} instance * @param key byte array of a key to search for * @param value StringBuffer instance which is a out parameter if a value is * found in block-cache. * @return boolean value indicating if key does not exist or might exist. */ public boolean keyMayExist(ReadOptions readOptions, byte[] key, StringBuffer value){ return keyMayExist(readOptions.nativeHandle_, key, key.length, value); } /** * If the key definitely does not exist in the database, then this method * returns false, else true. * * This check is potentially lighter-weight than invoking DB::Get(). One way * to make this lighter weight is to avoid doing any IOs. * * @param readOptions {@link ReadOptions} instance * @param columnFamilyHandle {@link ColumnFamilyHandle} instance * @param key byte array of a key to search for * @param value StringBuffer instance which is a out parameter if a value is * found in block-cache. * @return boolean value indicating if key does not exist or might exist. */ public boolean keyMayExist(ReadOptions readOptions, ColumnFamilyHandle columnFamilyHandle, byte[] key, StringBuffer value){ return keyMayExist(readOptions.nativeHandle_, key, key.length, columnFamilyHandle.nativeHandle_, value); } /** * Apply the specified updates to the database. * * @param writeOpts WriteOptions instance * @param updates WriteBatch instance * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void write(WriteOptions writeOpts, WriteBatch updates) throws RocksDBException { write(writeOpts.nativeHandle_, updates.nativeHandle_); } /** * Add merge operand for key/value pair. * * @param key the specified key to be merged. * @param value the value to be merged with the current value for * the specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void merge(byte[] key, byte[] value) throws RocksDBException { merge(nativeHandle_, key, key.length, value, value.length); } /** * Add merge operand for key/value pair in a ColumnFamily. * * @param columnFamilyHandle {@link ColumnFamilyHandle} instance * @param key the specified key to be merged. * @param value the value to be merged with the current value for * the specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void merge(ColumnFamilyHandle columnFamilyHandle, byte[] key, byte[] value) throws RocksDBException { merge(nativeHandle_, key, key.length, value, value.length, columnFamilyHandle.nativeHandle_); } /** * Add merge operand for key/value pair. * * @param writeOpts {@link WriteOptions} for this write. * @param key the specified key to be merged. * @param value the value to be merged with the current value for * the specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void merge(WriteOptions writeOpts, byte[] key, byte[] value) throws RocksDBException { merge(nativeHandle_, writeOpts.nativeHandle_, key, key.length, value, value.length); } /** * Add merge operand for key/value pair. * * @param columnFamilyHandle {@link ColumnFamilyHandle} instance * @param writeOpts {@link WriteOptions} for this write. * @param key the specified key to be merged. * @param value the value to be merged with the current value for * the specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void merge(ColumnFamilyHandle columnFamilyHandle, WriteOptions writeOpts, byte[] key, byte[] value) throws RocksDBException { merge(nativeHandle_, writeOpts.nativeHandle_, key, key.length, value, value.length, columnFamilyHandle.nativeHandle_); } /** * Get the value associated with the specified key within column family* * @param key the key to retrieve the value. * @param value the out-value to receive the retrieved value. * @return The size of the actual value that matches the specified * {@code key} in byte. If the return value is greater than the * length of {@code value}, then it indicates that the size of the * input buffer {@code value} is insufficient and partial result will * be returned. RocksDB.NOT_FOUND will be returned if the value not * found. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public int get(byte[] key, byte[] value) throws RocksDBException { return get(nativeHandle_, key, key.length, value, value.length); } /** * Get the value associated with the specified key within column family. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param key the key to retrieve the value. * @param value the out-value to receive the retrieved value. * @return The size of the actual value that matches the specified * {@code key} in byte. If the return value is greater than the * length of {@code value}, then it indicates that the size of the * input buffer {@code value} is insufficient and partial result will * be returned. RocksDB.NOT_FOUND will be returned if the value not * found. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public int get(ColumnFamilyHandle columnFamilyHandle, byte[] key, byte[] value) throws RocksDBException, IllegalArgumentException { return get(nativeHandle_, key, key.length, value, value.length, columnFamilyHandle.nativeHandle_); } /** * Get the value associated with the specified key. * * @param opt {@link org.rocksdb.ReadOptions} instance. * @param key the key to retrieve the value. * @param value the out-value to receive the retrieved value. * @return The size of the actual value that matches the specified * {@code key} in byte. If the return value is greater than the * length of {@code value}, then it indicates that the size of the * input buffer {@code value} is insufficient and partial result will * be returned. RocksDB.NOT_FOUND will be returned if the value not * found. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public int get(ReadOptions opt, byte[] key, byte[] value) throws RocksDBException { return get(nativeHandle_, opt.nativeHandle_, key, key.length, value, value.length); } /** * Get the value associated with the specified key within column family. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param opt {@link org.rocksdb.ReadOptions} instance. * @param key the key to retrieve the value. * @param value the out-value to receive the retrieved value. * @return The size of the actual value that matches the specified * {@code key} in byte. If the return value is greater than the * length of {@code value}, then it indicates that the size of the * input buffer {@code value} is insufficient and partial result will * be returned. RocksDB.NOT_FOUND will be returned if the value not * found. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public int get(ColumnFamilyHandle columnFamilyHandle, ReadOptions opt, byte[] key, byte[] value) throws RocksDBException { return get(nativeHandle_, opt.nativeHandle_, key, key.length, value, value.length, columnFamilyHandle.nativeHandle_); } /** * The simplified version of get which returns a new byte array storing * the value associated with the specified input key if any. null will be * returned if the specified key is not found. * * @param key the key retrieve the value. * @return a byte array storing the value associated with the input key if * any. null if it does not find the specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public byte[] get(byte[] key) throws RocksDBException { return get(nativeHandle_, key, key.length); } /** * The simplified version of get which returns a new byte array storing * the value associated with the specified input key if any. null will be * returned if the specified key is not found. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param key the key retrieve the value. * @return a byte array storing the value associated with the input key if * any. null if it does not find the specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public byte[] get(ColumnFamilyHandle columnFamilyHandle, byte[] key) throws RocksDBException { return get(nativeHandle_, key, key.length, columnFamilyHandle.nativeHandle_); } /** * The simplified version of get which returns a new byte array storing * the value associated with the specified input key if any. null will be * returned if the specified key is not found. * * @param key the key retrieve the value. * @param opt Read options. * @return a byte array storing the value associated with the input key if * any. null if it does not find the specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public byte[] get(ReadOptions opt, byte[] key) throws RocksDBException { return get(nativeHandle_, opt.nativeHandle_, key, key.length); } /** * The simplified version of get which returns a new byte array storing * the value associated with the specified input key if any. null will be * returned if the specified key is not found. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param key the key retrieve the value. * @param opt Read options. * @return a byte array storing the value associated with the input key if * any. null if it does not find the specified key. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public byte[] get(ColumnFamilyHandle columnFamilyHandle, ReadOptions opt, byte[] key) throws RocksDBException { return get(nativeHandle_, opt.nativeHandle_, key, key.length, columnFamilyHandle.nativeHandle_); } /** * Returns a map of keys for which values were found in DB. * * @param keys List of keys for which values need to be retrieved. * @return Map where key of map is the key passed by user and value for map * entry is the corresponding value in DB. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public Map<byte[], byte[]> multiGet(List<byte[]> keys) throws RocksDBException { assert(keys.size() != 0); List<byte[]> values = multiGet( nativeHandle_, keys, keys.size()); Map<byte[], byte[]> keyValueMap = new HashMap<>(); for(int i = 0; i < values.size(); i++) { if(values.get(i) == null) { continue; } keyValueMap.put(keys.get(i), values.get(i)); } return keyValueMap; } /** * Returns a map of keys for which values were found in DB. * <p> * Note: Every key needs to have a related column family name in * {@code columnFamilyHandleList}. * </p> * * @param columnFamilyHandleList {@link java.util.List} containing * {@link org.rocksdb.ColumnFamilyHandle} instances. * @param keys List of keys for which values need to be retrieved. * @return Map where key of map is the key passed by user and value for map * entry is the corresponding value in DB. * * @throws RocksDBException thrown if error happens in underlying * native library. * @throws IllegalArgumentException thrown if the size of passed keys is not * equal to the amount of passed column family handles. */ public Map<byte[], byte[]> multiGet(List<ColumnFamilyHandle> columnFamilyHandleList, List<byte[]> keys) throws RocksDBException, IllegalArgumentException { assert(keys.size() != 0); // Check if key size equals cfList size. If not a exception must be // thrown. If not a Segmentation fault happens. if (keys.size()!=columnFamilyHandleList.size()) { throw new IllegalArgumentException( "For each key there must be a ColumnFamilyHandle."); } List<byte[]> values = multiGet(nativeHandle_, keys, keys.size(), columnFamilyHandleList); Map<byte[], byte[]> keyValueMap = new HashMap<>(); for(int i = 0; i < values.size(); i++) { if (values.get(i) == null) { continue; } keyValueMap.put(keys.get(i), values.get(i)); } return keyValueMap; } /** * Returns a map of keys for which values were found in DB. * * @param opt Read options. * @param keys of keys for which values need to be retrieved. * @return Map where key of map is the key passed by user and value for map * entry is the corresponding value in DB. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public Map<byte[], byte[]> multiGet(ReadOptions opt, List<byte[]> keys) throws RocksDBException { assert(keys.size() != 0); List<byte[]> values = multiGet( nativeHandle_, opt.nativeHandle_, keys, keys.size()); Map<byte[], byte[]> keyValueMap = new HashMap<>(); for(int i = 0; i < values.size(); i++) { if(values.get(i) == null) { continue; } keyValueMap.put(keys.get(i), values.get(i)); } return keyValueMap; } /** * Returns a map of keys for which values were found in DB. * <p> * Note: Every key needs to have a related column family name in * {@code columnFamilyHandleList}. * </p> * * @param opt Read options. * @param columnFamilyHandleList {@link java.util.List} containing * {@link org.rocksdb.ColumnFamilyHandle} instances. * @param keys of keys for which values need to be retrieved. * @return Map where key of map is the key passed by user and value for map * entry is the corresponding value in DB. * * @throws RocksDBException thrown if error happens in underlying * native library. * @throws IllegalArgumentException thrown if the size of passed keys is not * equal to the amount of passed column family handles. */ public Map<byte[], byte[]> multiGet(ReadOptions opt, List<ColumnFamilyHandle> columnFamilyHandleList, List<byte[]> keys) throws RocksDBException { assert(keys.size() != 0); // Check if key size equals cfList size. If not a exception must be // thrown. If not a Segmentation fault happens. if (keys.size()!=columnFamilyHandleList.size()){ throw new IllegalArgumentException( "For each key there must be a ColumnFamilyHandle."); } List<byte[]> values = multiGet(nativeHandle_, opt.nativeHandle_, keys, keys.size(), columnFamilyHandleList); Map<byte[], byte[]> keyValueMap = new HashMap<>(); for(int i = 0; i < values.size(); i++) { if(values.get(i) == null) { continue; } keyValueMap.put(keys.get(i), values.get(i)); } return keyValueMap; } /** * Remove the database entry (if any) for "key". Returns OK on * success, and a non-OK status on error. It is not an error if "key" * did not exist in the database. * * @param key Key to delete within database * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void remove(byte[] key) throws RocksDBException { remove(nativeHandle_, key, key.length); } /** * Remove the database entry (if any) for "key". Returns OK on * success, and a non-OK status on error. It is not an error if "key" * did not exist in the database. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param key Key to delete within database * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void remove(ColumnFamilyHandle columnFamilyHandle, byte[] key) throws RocksDBException { remove(nativeHandle_, key, key.length, columnFamilyHandle.nativeHandle_); } /** * Remove the database entry (if any) for "key". Returns OK on * success, and a non-OK status on error. It is not an error if "key" * did not exist in the database. * * @param writeOpt WriteOptions to be used with delete operation * @param key Key to delete within database * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void remove(WriteOptions writeOpt, byte[] key) throws RocksDBException { remove(nativeHandle_, writeOpt.nativeHandle_, key, key.length); } /** * Remove the database entry (if any) for "key". Returns OK on * success, and a non-OK status on error. It is not an error if "key" * did not exist in the database. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param writeOpt WriteOptions to be used with delete operation * @param key Key to delete within database * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void remove(ColumnFamilyHandle columnFamilyHandle, WriteOptions writeOpt, byte[] key) throws RocksDBException { remove(nativeHandle_, writeOpt.nativeHandle_, key, key.length, columnFamilyHandle.nativeHandle_); } /** * DB implements can export properties about their state * via this method on a per column family level. * * <p>If {@code property} is a valid property understood by this DB * implementation, fills {@code value} with its current value and * returns true. Otherwise returns false.</p> * * <p>Valid property names include: * <ul> * <li>"rocksdb.num-files-at-level&lt;N&gt;" - return the number of files at level &lt;N&gt;, * where &lt;N&gt; is an ASCII representation of a level number (e.g. "0").</li> * <li>"rocksdb.stats" - returns a multi-line string that describes statistics * about the internal operation of the DB.</li> * <li>"rocksdb.sstables" - returns a multi-line string that describes all * of the sstables that make up the db contents.</li> * </ul> * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param property to be fetched. See above for examples * @return property value * * @throws RocksDBException thrown if error happens in underlying * native library. */ public String getProperty(ColumnFamilyHandle columnFamilyHandle, String property) throws RocksDBException { return getProperty0(nativeHandle_, columnFamilyHandle.nativeHandle_, property, property.length()); } /** * DB implementations can export properties about their state * via this method. If "property" is a valid property understood by this * DB implementation, fills "*value" with its current value and returns * true. Otherwise returns false. * * <p>Valid property names include: * <ul> * <li>"rocksdb.num-files-at-level&lt;N&gt;" - return the number of files at level &lt;N&gt;, * where &lt;N&gt; is an ASCII representation of a level number (e.g. "0").</li> * <li>"rocksdb.stats" - returns a multi-line string that describes statistics * about the internal operation of the DB.</li> * <li>"rocksdb.sstables" - returns a multi-line string that describes all * of the sstables that make up the db contents.</li> *</ul> * * @param property to be fetched. See above for examples * @return property value * * @throws RocksDBException thrown if error happens in underlying * native library. */ public String getProperty(String property) throws RocksDBException { return getProperty0(nativeHandle_, property, property.length()); } /** * <p> Similar to GetProperty(), but only works for a subset of properties whose * return value is a numerical value. Return the value as long.</p> * * <p><strong>Note</strong>: As the returned property is of type * {@code uint64_t} on C++ side the returning value can be negative * because Java supports in Java 7 only signed long values.</p> * * <p><strong>Java 7</strong>: To mitigate the problem of the non * existent unsigned long tpye, values should be encapsulated using * {@link java.math.BigInteger} to reflect the correct value. The correct * behavior is guaranteed if {@code 2^64} is added to negative values.</p> * * <p><strong>Java 8</strong>: In Java 8 the value should be treated as * unsigned long using provided methods of type {@link Long}.</p> * * @param property to be fetched. * * @return numerical property value. * * @throws RocksDBException if an error happens in the underlying native code. */ public long getLongProperty(String property) throws RocksDBException { return getLongProperty(nativeHandle_, property, property.length()); } /** * <p> Similar to GetProperty(), but only works for a subset of properties whose * return value is a numerical value. Return the value as long.</p> * * <p><strong>Note</strong>: As the returned property is of type * {@code uint64_t} on C++ side the returning value can be negative * because Java supports in Java 7 only signed long values.</p> * * <p><strong>Java 7</strong>: To mitigate the problem of the non * existent unsigned long tpye, values should be encapsulated using * {@link java.math.BigInteger} to reflect the correct value. The correct * behavior is guaranteed if {@code 2^64} is added to negative values.</p> * * <p><strong>Java 8</strong>: In Java 8 the value should be treated as * unsigned long using provided methods of type {@link Long}.</p> * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @param property to be fetched. * * @return numerical property value * * @throws RocksDBException if an error happens in the underlying native code. */ public long getLongProperty(ColumnFamilyHandle columnFamilyHandle, String property) throws RocksDBException { return getLongProperty(nativeHandle_, columnFamilyHandle.nativeHandle_, property, property.length()); } /** * Return a heap-allocated iterator over the contents of the database. * The result of newIterator() is initially invalid (caller must * call one of the Seek methods on the iterator before using it). * * Caller should close the iterator when it is no longer needed. * The returned iterator should be closed before this db is closed. * * @return instance of iterator object. */ public RocksIterator newIterator() { return new RocksIterator(this, iterator0(nativeHandle_)); } /** * <p>Return a handle to the current DB state. Iterators created with * this handle will all observe a stable snapshot of the current DB * state. The caller must call ReleaseSnapshot(result) when the * snapshot is no longer needed.</p> * * <p>nullptr will be returned if the DB fails to take a snapshot or does * not support snapshot.</p> * * @return Snapshot {@link Snapshot} instance */ public Snapshot getSnapshot() { long snapshotHandle = getSnapshot(nativeHandle_); if (snapshotHandle != 0) { return new Snapshot(snapshotHandle); } return null; } /** * Release a previously acquired snapshot. The caller must not * use "snapshot" after this call. * * @param snapshot {@link Snapshot} instance */ public void releaseSnapshot(final Snapshot snapshot) { if (snapshot != null) { releaseSnapshot(nativeHandle_, snapshot.nativeHandle_); } } /** * Return a heap-allocated iterator over the contents of the database. * The result of newIterator() is initially invalid (caller must * call one of the Seek methods on the iterator before using it). * * Caller should close the iterator when it is no longer needed. * The returned iterator should be closed before this db is closed. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * @return instance of iterator object. */ public RocksIterator newIterator(ColumnFamilyHandle columnFamilyHandle) { return new RocksIterator(this, iterator0(nativeHandle_, columnFamilyHandle.nativeHandle_)); } /** * Returns iterators from a consistent database state across multiple * column families. Iterators are heap allocated and need to be deleted * before the db is deleted * * @param columnFamilyHandleList {@link java.util.List} containing * {@link org.rocksdb.ColumnFamilyHandle} instances. * @return {@link java.util.List} containing {@link org.rocksdb.RocksIterator} * instances * * @throws RocksDBException thrown if error happens in underlying * native library. */ public List<RocksIterator> newIterators( List<ColumnFamilyHandle> columnFamilyHandleList) throws RocksDBException { List<RocksIterator> iterators = new ArrayList<>(columnFamilyHandleList.size()); long[] iteratorRefs = iterators(nativeHandle_, columnFamilyHandleList); for (int i=0; i<columnFamilyHandleList.size(); i++){ iterators.add(new RocksIterator(this, iteratorRefs[i])); } return iterators; } /** * Creates a new column family with the name columnFamilyName and * allocates a ColumnFamilyHandle within an internal structure. * The ColumnFamilyHandle is automatically disposed with DB disposal. * * @param columnFamilyDescriptor column family to be created. * @return {@link org.rocksdb.ColumnFamilyHandle} instance. * * @throws RocksDBException thrown if error happens in underlying * native library. */ public ColumnFamilyHandle createColumnFamily( ColumnFamilyDescriptor columnFamilyDescriptor) throws RocksDBException { return new ColumnFamilyHandle(this, createColumnFamily(nativeHandle_, columnFamilyDescriptor)); } /** * Drops the column family identified by columnFamilyName. Internal * handles to this column family will be disposed. If the column family * is not known removal will fail. * * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} * instance * * @throws RocksDBException thrown if error happens in underlying * native library. */ public void dropColumnFamily(ColumnFamilyHandle columnFamilyHandle) throws RocksDBException, IllegalArgumentException { // throws RocksDBException if something goes wrong dropColumnFamily(nativeHandle_, columnFamilyHandle.nativeHandle_); // After the drop the native handle is not valid anymore columnFamilyHandle.nativeHandle_ = 0; } /** * <p>Flush all memory table data.</p> * * <p>Note: it must be ensured that the FlushOptions instance * is not GC'ed before this method finishes. If the wait parameter is * set to false, flush processing is asynchronous.</p> * * @param flushOptions {@link org.rocksdb.FlushOptions} instance. * @throws RocksDBException thrown if an error occurs within the native * part of the library. */ public void flush(FlushOptions flushOptions) throws RocksDBException { flush(nativeHandle_, flushOptions.nativeHandle_); } /** * <p>Flush all memory table data.</p> * * <p>Note: it must be ensured that the FlushOptions instance * is not GC'ed before this method finishes. If the wait parameter is * set to false, flush processing is asynchronous.</p> * * @param flushOptions {@link org.rocksdb.FlushOptions} instance. * @param columnFamilyHandle {@link org.rocksdb.ColumnFamilyHandle} instance. * @throws RocksDBException thrown if an error occurs within the native * part of the library. */ public void flush(FlushOptions flushOptions, ColumnFamilyHandle columnFamilyHandle) throws RocksDBException { flush(nativeHandle_, flushOptions.nativeHandle_, columnFamilyHandle.nativeHandle_); } /** * Private constructor. */ protected RocksDB() { super(); } // native methods protected native void open( long optionsHandle, String path) throws RocksDBException; protected native List<Long> open(long optionsHandle, String path, List<ColumnFamilyDescriptor> columnFamilyDescriptors, int columnFamilyDescriptorsLength) throws RocksDBException; protected native static List<byte[]> listColumnFamilies( long optionsHandle, String path) throws RocksDBException; protected native void openROnly( long optionsHandle, String path) throws RocksDBException; protected native List<Long> openROnly( long optionsHandle, String path, List<ColumnFamilyDescriptor> columnFamilyDescriptors, int columnFamilyDescriptorsLength) throws RocksDBException; protected native void put( long handle, byte[] key, int keyLen, byte[] value, int valueLen) throws RocksDBException; protected native void put( long handle, byte[] key, int keyLen, byte[] value, int valueLen, long cfHandle) throws RocksDBException; protected native void put( long handle, long writeOptHandle, byte[] key, int keyLen, byte[] value, int valueLen) throws RocksDBException; protected native void put( long handle, long writeOptHandle, byte[] key, int keyLen, byte[] value, int valueLen, long cfHandle) throws RocksDBException; protected native void write( long writeOptHandle, long batchHandle) throws RocksDBException; protected native boolean keyMayExist(byte[] key, int keyLen, StringBuffer stringBuffer); protected native boolean keyMayExist(byte[] key, int keyLen, long cfHandle, StringBuffer stringBuffer); protected native boolean keyMayExist(long optionsHandle, byte[] key, int keyLen, StringBuffer stringBuffer); protected native boolean keyMayExist(long optionsHandle, byte[] key, int keyLen, long cfHandle, StringBuffer stringBuffer); protected native void merge( long handle, byte[] key, int keyLen, byte[] value, int valueLen) throws RocksDBException; protected native void merge( long handle, byte[] key, int keyLen, byte[] value, int valueLen, long cfHandle) throws RocksDBException; protected native void merge( long handle, long writeOptHandle, byte[] key, int keyLen, byte[] value, int valueLen) throws RocksDBException; protected native void merge( long handle, long writeOptHandle, byte[] key, int keyLen, byte[] value, int valueLen, long cfHandle) throws RocksDBException; protected native int get( long handle, byte[] key, int keyLen, byte[] value, int valueLen) throws RocksDBException; protected native int get( long handle, byte[] key, int keyLen, byte[] value, int valueLen, long cfHandle) throws RocksDBException; protected native int get( long handle, long readOptHandle, byte[] key, int keyLen, byte[] value, int valueLen) throws RocksDBException; protected native int get( long handle, long readOptHandle, byte[] key, int keyLen, byte[] value, int valueLen, long cfHandle) throws RocksDBException; protected native List<byte[]> multiGet( long dbHandle, List<byte[]> keys, int keysCount); protected native List<byte[]> multiGet( long dbHandle, List<byte[]> keys, int keysCount, List<ColumnFamilyHandle> cfHandles); protected native List<byte[]> multiGet( long dbHandle, long rOptHandle, List<byte[]> keys, int keysCount); protected native List<byte[]> multiGet( long dbHandle, long rOptHandle, List<byte[]> keys, int keysCount, List<ColumnFamilyHandle> cfHandles); protected native byte[] get( long handle, byte[] key, int keyLen) throws RocksDBException; protected native byte[] get( long handle, byte[] key, int keyLen, long cfHandle) throws RocksDBException; protected native byte[] get( long handle, long readOptHandle, byte[] key, int keyLen) throws RocksDBException; protected native byte[] get( long handle, long readOptHandle, byte[] key, int keyLen, long cfHandle) throws RocksDBException; protected native void remove( long handle, byte[] key, int keyLen) throws RocksDBException; protected native void remove( long handle, byte[] key, int keyLen, long cfHandle) throws RocksDBException; protected native void remove( long handle, long writeOptHandle, byte[] key, int keyLen) throws RocksDBException; protected native void remove( long handle, long writeOptHandle, byte[] key, int keyLen, long cfHandle) throws RocksDBException; protected native String getProperty0(long nativeHandle, String property, int propertyLength) throws RocksDBException; protected native String getProperty0(long nativeHandle, long cfHandle, String property, int propertyLength) throws RocksDBException; protected native long getLongProperty(long nativeHandle, String property, int propertyLength) throws RocksDBException; protected native long getLongProperty(long nativeHandle, long cfHandle, String property, int propertyLength) throws RocksDBException; protected native long iterator0(long handle); protected native long iterator0(long handle, long cfHandle); protected native long[] iterators(long handle, List<ColumnFamilyHandle> columnFamilyNames) throws RocksDBException; protected native long getSnapshot(long nativeHandle); protected native void releaseSnapshot( long nativeHandle, long snapshotHandle); private native void disposeInternal(long handle); private native long createColumnFamily(long handle, ColumnFamilyDescriptor columnFamilyDescriptor) throws RocksDBException; private native void dropColumnFamily(long handle, long cfHandle) throws RocksDBException; private native void flush(long handle, long flushOptHandle) throws RocksDBException; private native void flush(long handle, long flushOptHandle, long cfHandle) throws RocksDBException; protected DBOptionsInterface options_; }
gpl-2.0
fer2d2/tomatito.io
src/app/shared/entities/clock-types.ts
81
export enum CLOCK_TYPES { POMODORO = 25, MINI_BREAK = 5, LONG_BREAK = 10 }
gpl-2.0
gfanti/P2P-PIR-Cpp
percyparams.cc
7728
// Percy++ Copyright 2007,2012,2013 Ian Goldberg <iang@cs.uwaterloo.ca>, // Casey Devet <cjdevet@cs.uwaterloo.ca>, // Paul Hendry <pshdenry@uwaterloo.ca>, // Ryan Henry <rhenry@cs.uwaterloo.ca> // // This program is free software; you can redistribute it and/or modify // it under the terms of version 2 of the GNU General Public License as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // There is a copy of the GNU General Public License in the COPYING file // packaged with this plugin; if you cannot find it, write to the Free // Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA // 02110-1301 USA #include <string.h> #include <fstream> #include "percyparams.h" #include "percyio.h" #ifdef SPIR_SUPPORT // Open the specified file, read in the PolyCommit parameters contained // within, create a new Params object from the parameters, and return it PolyCommitParams * pcparams_init(const char * filename) { if (!filename) { return NULL; } ifstream ifile(filename); if(!ifile.is_open()) { std::cerr << "Error: Cannot open params file." << endl; exit(1); } PolyCommitParams * pcparamsp = new PolyCommitParams(); ifile >> *pcparamsp; ifile.close(); return pcparamsp; } #endif PercyParams::PercyParams() { this->version = PERCY_VERSION; this->hybrid_protection = false; this->_tau = 0; this->do_spir = false; this->_words_per_block = 1; this->_num_blocks = 1; this->_max_unsynchronized = 0; this->_num_bins = 1; this->modulus = 257; this->mode = MODE_ZZ_P; this->pcparams_filename = NULL; #ifdef SPIR_SUPPORT this->pcparamsp = NULL; #endif create_ZZ_pContexts(); } PercyParams::PercyParams(dbsize_t words_per_block, dbsize_t num_blocks, dbsize_t max_unsynchronized, dbsize_t num_bins, nservers_t tau, ZZ modulus, PercyMode mode, char *pcparams_file, bool do_spir) { this->version = PERCY_VERSION; this->hybrid_protection = false; this->_tau = tau; this->do_spir = do_spir; this->_words_per_block = words_per_block; this->_num_blocks = num_blocks; this->_max_unsynchronized = max_unsynchronized; this->_num_bins = num_bins; this->modulus = modulus; this->mode = mode; this->pcparams_filename = pcparams_file; #ifdef SPIR_SUPPORT this->pcparamsp = pcparams_init(pcparams_file); #endif create_ZZ_pContexts(); } ostream& operator<<(ostream& os, const PercyParams &params) { unsigned char minibuf[4]; // Output the magic header os.write("PIRC", 4); //printf("SENT: PIRC\n"); // Output the version number and flags minibuf[0] = params.version; minibuf[1] = (params.hybrid_protection ? 1 : 0) | (params._tau ? 2 : 0); os.write((char *)minibuf, 2); // Output the SPIR flag minibuf[0] = params.do_spir; os.write((char *)minibuf, 1); // Output the mode minibuf[0] = params.mode; os.write((char *)minibuf, 1); // Output the words_per_block and num_blocks values PERCY_WRITE_LE_DBSIZE(os, params._words_per_block); PERCY_WRITE_LE_DBSIZE(os, params._num_blocks); // Output the max_unsynchronized value PERCY_WRITE_LE_DBSIZE(os, params._max_unsynchronized); PERCY_WRITE_LE_DBSIZE(os, params._num_bins); // Output the modulus percy_write_ZZ(os, params.modulus); // Output g, if appropriate if (params.hybrid_protection) { percy_write_ZZ(os, rep(params.g)); } return os; } istream& operator>>(istream& is, PercyParams &params) { unsigned char minibuf[4]; // Input the magic header is.read((char *)minibuf, 4); //printf("RECEIVED: %u %u %u %u\n", minibuf[0], minibuf[1], minibuf[2], minibuf[3]); if (memcmp(minibuf, "PIRC", 4)) { std::cerr << "Did not find expected PercyParams header.\n"; return is; } // Input the version number and flags is.read((char *)minibuf, 2); params.version = minibuf[0]; params.hybrid_protection = ( (minibuf[1] & 1) == 1 ); params._tau = ( (minibuf[1] & 2) == 2 ); if (params.version != PERCY_VERSION) { std::cerr << "Did not find expected PercyParams version number " << PERCY_VERSION << ".\n"; return is; } // Input the SPIR flag is.read((char *)minibuf, 1); params.do_spir = (PercyMode) minibuf[0]; // Input the mode is.read((char *)minibuf, 1); params.mode = (PercyMode) minibuf[0]; // Input the words_per_block and num_blocks values PERCY_READ_LE_DBSIZE(is, params._words_per_block); PERCY_READ_LE_DBSIZE(is, params._num_blocks); // Input the max_unsynchronized value PERCY_READ_LE_DBSIZE(is, params._max_unsynchronized); // Input the expansion factor value PERCY_READ_LE_DBSIZE(is, params._num_bins); // Input the modulus percy_read_ZZ(is, params.modulus); params.create_ZZ_pContexts(); // Input g, if appropriate if (params.hybrid_protection) { ZZ_pContext savectx; savectx.save(); params.modsqctx.restore(); ZZ gz; percy_read_ZZ(is, gz); params.g = to_ZZ_p(gz); savectx.restore(); } return is; } PercyClientParams::PercyClientParams(dbsize_t words_per_block, dbsize_t num_blocks, dbsize_t max_unsynchronized, dbsize_t num_bins, nservers_t tau, ZZ p, ZZ q) { init_hybrid(words_per_block, num_blocks, max_unsynchronized, num_bins, tau, p, q); } void PercyClientParams::init_hybrid(dbsize_t words_per_block, dbsize_t num_blocks, dbsize_t max_unsynchronized, dbsize_t num_bins, nservers_t tau, ZZ p, ZZ q) { this->version = PERCY_VERSION; this->hybrid_protection = true; this->_tau = tau; this->_words_per_block = words_per_block; this->_num_blocks = num_blocks; this->_max_unsynchronized = max_unsynchronized; this->_num_bins = num_bins; ZZ modulus; modulus = p * q; this->modulus = modulus; this->mode = MODE_ZZ_P; this->p1 = p; this->p2 = q; #ifdef SPIR_SUPPORT this->pcparamsp = NULL; #endif create_ZZ_pContexts(); // Generate the Paillier public and private parts ZZ pm1, qm1; pm1 = p - 1; qm1 = q - 1; this->lambda = pm1 * qm1 / GCD(pm1, qm1); ZZ_pContext savectx; savectx.save(); mod_modulussq(); random(this->g); ZZ muinv = rep(power(this->g, this->lambda) - 1) / modulus; mod_modulus(); this->mu = inv(to_ZZ_p(muinv)); savectx.restore(); } void PercyParams::create_ZZ_pContexts() { // Create the ZZ_pContexts ZZ_pContext modctx(modulus); ZZ_pContext modsqctx(modulus * modulus); this->modctx = modctx; this->modsqctx = modsqctx; } PercyClientParams::PercyClientParams(dbsize_t words_per_block, dbsize_t num_blocks, dbsize_t max_unsynchronized, dbsize_t num_bins, nservers_t tau, unsigned long modulus_bits) { // Pick the sizes for the primes unsigned long qsize = modulus_bits / 2; unsigned long psize = modulus_bits - qsize; // Generate random primes of the appropriate size. We ensure the // top two bits are set so that their product is of the right // bitlength. ZZ pbase, qbase, p, q; RandomBits(pbase, psize); if (psize >= 1) SetBit(pbase, psize-1); if (psize >= 2) SetBit(pbase, psize-2); NextPrime(p, pbase); RandomBits(qbase, qsize); if (qsize >= 1) SetBit(qbase, qsize-1); if (qsize >= 2) SetBit(qbase, qsize-2); NextPrime(q, qbase); init_hybrid(words_per_block, num_blocks, max_unsynchronized, num_bins, tau, p, q); }
gpl-2.0
balrajb/sbx_drupal_civicrm
sites/all/modules/contrib/civicrm/CRM/Report/Form/Member/Detail.php
18860
<?php /* +--------------------------------------------------------------------+ | CiviCRM version 4.6 | +--------------------------------------------------------------------+ | Copyright CiviCRM LLC (c) 2004-2015 | +--------------------------------------------------------------------+ | This file is a part of CiviCRM. | | | | CiviCRM is free software; you can copy, modify, and distribute it | | under the terms of the GNU Affero General Public License | | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. | | | | CiviCRM is distributed in the hope that it will be useful, but | | WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | | See the GNU Affero General Public License for more details. | | | | You should have received a copy of the GNU Affero General Public | | License and the CiviCRM Licensing Exception along | | with this program; if not, contact CiviCRM LLC | | at info[AT]civicrm[DOT]org. If you have questions about the | | GNU Affero General Public License or the licensing of CiviCRM, | | see the CiviCRM license FAQ at http://civicrm.org/licensing | +--------------------------------------------------------------------+ */ /** * * @package CRM * @copyright CiviCRM LLC (c) 2004-2015 * $Id$ * */ class CRM_Report_Form_Member_Detail extends CRM_Report_Form { protected $_addressField = FALSE; protected $_emailField = FALSE; protected $_phoneField = FALSE; protected $_contribField = FALSE; protected $_summary = NULL; protected $_customGroupExtends = array('Membership', 'Contribution'); protected $_customGroupGroupBy = FALSE; /** */ /** */ public function __construct() { // Check if CiviCampaign is a) enabled and b) has active campaigns $config = CRM_Core_Config::singleton(); $campaignEnabled = in_array("CiviCampaign", $config->enableComponents); if ($campaignEnabled) { $getCampaigns = CRM_Campaign_BAO_Campaign::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE); $this->activeCampaigns = $getCampaigns['campaigns']; asort($this->activeCampaigns); } $this->_columns = array( 'civicrm_contact' => array( 'dao' => 'CRM_Contact_DAO_Contact', 'fields' => array( 'sort_name' => array( 'title' => ts('Contact Name'), 'required' => TRUE, 'default' => TRUE, ), 'id' => array( 'no_display' => TRUE, 'required' => TRUE, ), 'first_name' => array( 'title' => ts('First Name'), ), 'id' => array( 'no_display' => TRUE, 'required' => TRUE, ), 'last_name' => array( 'title' => ts('Last Name'), ), 'contact_type' => array( 'title' => ts('Contact Type'), ), 'contact_sub_type' => array( 'title' => ts('Contact Subtype'), ), ), 'filters' => array( 'sort_name' => array( 'title' => ts('Contact Name'), 'operator' => 'like', ), 'id' => array('no_display' => TRUE), ), 'order_bys' => array( 'sort_name' => array( 'title' => ts('Last Name, First Name'), 'default' => '1', 'default_weight' => '0', 'default_order' => 'ASC', ), ), 'grouping' => 'contact-fields', ), 'civicrm_membership' => array( 'dao' => 'CRM_Member_DAO_Membership', 'fields' => array( 'membership_type_id' => array( 'title' => 'Membership Type', 'required' => TRUE, 'no_repeat' => TRUE, ), 'membership_start_date' => array( 'title' => ts('Start Date'), 'default' => TRUE, ), 'membership_end_date' => array( 'title' => ts('End Date'), 'default' => TRUE, ), 'join_date' => array( 'title' => ts('Join Date'), 'default' => TRUE, ), 'source' => array('title' => 'Source'), ), 'filters' => array( 'join_date' => array('operatorType' => CRM_Report_Form::OP_DATE), 'membership_start_date' => array('operatorType' => CRM_Report_Form::OP_DATE), 'membership_end_date' => array('operatorType' => CRM_Report_Form::OP_DATE), 'owner_membership_id' => array( 'title' => ts('Membership Owner ID'), 'operatorType' => CRM_Report_Form::OP_INT, ), 'tid' => array( 'name' => 'membership_type_id', 'title' => ts('Membership Types'), 'type' => CRM_Utils_Type::T_INT, 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Member_PseudoConstant::membershipType(), ), ), 'order_bys' => array( 'membership_type_id' => array( 'title' => ts('Membership Type'), 'default' => '0', 'default_weight' => '1', 'default_order' => 'ASC', ), ), 'grouping' => 'member-fields', ), 'civicrm_membership_status' => array( 'dao' => 'CRM_Member_DAO_MembershipStatus', 'alias' => 'mem_status', 'fields' => array( 'name' => array( 'title' => ts('Status'), 'default' => TRUE, ), ), 'filters' => array( 'sid' => array( 'name' => 'id', 'title' => ts('Status'), 'type' => CRM_Utils_Type::T_INT, 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label'), ), ), 'grouping' => 'member-fields', ), 'civicrm_address' => array( 'dao' => 'CRM_Core_DAO_Address', 'fields' => array( 'street_address' => NULL, 'city' => NULL, 'postal_code' => NULL, 'state_province_id' => array( 'title' => ts('State/Province'), ), 'country_id' => array( 'title' => ts('Country'), ), ), 'grouping' => 'contact-fields', ), 'civicrm_email' => array( 'dao' => 'CRM_Core_DAO_Email', 'fields' => array('email' => NULL), 'grouping' => 'contact-fields', ), 'civicrm_phone' => array( 'dao' => 'CRM_Core_DAO_Phone', 'fields' => array('phone' => NULL), 'grouping' => 'contact-fields', ), 'civicrm_contribution' => array( 'dao' => 'CRM_Contribute_DAO_Contribution', 'fields' => array( 'contribution_id' => array( 'name' => 'id', 'no_display' => TRUE, 'required' => TRUE, ), 'financial_type_id' => array('title' => ts('Financial Type')), 'contribution_status_id' => array('title' => ts('Contribution Status')), 'payment_instrument_id' => array('title' => ts('Payment Type')), 'currency' => array( 'required' => TRUE, 'no_display' => TRUE, ), 'trxn_id' => NULL, 'receive_date' => NULL, 'receipt_date' => NULL, 'fee_amount' => NULL, 'net_amount' => NULL, 'total_amount' => array( 'title' => ts('Payment Amount (most recent)'), 'statistics' => array('sum' => ts('Amount')), ), ), 'filters' => array( 'receive_date' => array('operatorType' => CRM_Report_Form::OP_DATE), 'financial_type_id' => array( 'title' => ts('Financial Type'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Contribute_PseudoConstant::financialType(), 'type' => CRM_Utils_Type::T_INT, ), 'payment_instrument_id' => array( 'title' => ts('Payment Type'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Contribute_PseudoConstant::paymentInstrument(), 'type' => CRM_Utils_Type::T_INT, ), 'currency' => array( 'title' => 'Currency', 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Core_OptionGroup::values('currencies_enabled'), 'default' => NULL, 'type' => CRM_Utils_Type::T_STRING, ), 'contribution_status_id' => array( 'title' => ts('Contribution Status'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Contribute_PseudoConstant::contributionStatus(), 'type' => CRM_Utils_Type::T_INT, ), 'total_amount' => array('title' => ts('Contribution Amount')), ), 'order_bys' => array( 'receive_date' => array( 'title' => ts('Receive Date'), 'default_weight' => '2', 'default_order' => 'DESC', ), ), 'grouping' => 'contri-fields', ), ); $this->_groupFilter = TRUE; $this->_tagFilter = TRUE; // If we have active campaigns add those elements to both the fields and filters if ($campaignEnabled && !empty($this->activeCampaigns)) { $this->_columns['civicrm_membership']['fields']['campaign_id'] = array( 'title' => ts('Campaign'), 'default' => 'false', ); $this->_columns['civicrm_membership']['filters']['campaign_id'] = array( 'title' => ts('Campaign'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => $this->activeCampaigns, ); $this->_columns['civicrm_membership']['order_bys']['campaign_id'] = array('title' => ts('Campaign')); } $this->_currencyColumn = 'civicrm_contribution_currency'; parent::__construct(); } public function preProcess() { $this->assign('reportTitle', ts('Membership Detail Report')); parent::preProcess(); } public function select() { $select = $this->_columnHeaders = array(); foreach ($this->_columns as $tableName => $table) { if (array_key_exists('fields', $table)) { foreach ($table['fields'] as $fieldName => $field) { if (!empty($field['required']) || !empty($this->_params['fields'][$fieldName])) { if ($tableName == 'civicrm_address') { $this->_addressField = TRUE; } elseif ($tableName == 'civicrm_email') { $this->_emailField = TRUE; } elseif ($tableName == 'civicrm_phone') { $this->_phoneField = TRUE; } elseif ($tableName == 'civicrm_contribution') { $this->_contribField = TRUE; } $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}"; if (array_key_exists('title', $field)) { $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title']; } $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field); } } } } $this->_select = "SELECT " . implode(', ', $select) . " "; } public function from() { $this->_from = " FROM civicrm_contact {$this->_aliases['civicrm_contact']} {$this->_aclFrom} INNER JOIN civicrm_membership {$this->_aliases['civicrm_membership']} ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_membership']}.contact_id AND {$this->_aliases['civicrm_membership']}.is_test = 0 LEFT JOIN civicrm_membership_status {$this->_aliases['civicrm_membership_status']} ON {$this->_aliases['civicrm_membership_status']}.id = {$this->_aliases['civicrm_membership']}.status_id "; //used when address field is selected if ($this->_addressField) { $this->_from .= " LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']} ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id AND {$this->_aliases['civicrm_address']}.is_primary = 1\n"; } //used when email field is selected if ($this->_emailField) { $this->_from .= " LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']} ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND {$this->_aliases['civicrm_email']}.is_primary = 1\n"; } //used when phone field is selected if ($this->_phoneField) { $this->_from .= " LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']} ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND {$this->_aliases['civicrm_phone']}.is_primary = 1\n"; } //used when contribution field is selected if ($this->_contribField) { $this->_from .= " LEFT JOIN civicrm_membership_payment cmp ON {$this->_aliases['civicrm_membership']}.id = cmp.membership_id LEFT JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']} ON cmp.contribution_id={$this->_aliases['civicrm_contribution']}.id\n"; } } public function postProcess() { $this->beginPostProcess(); // get the acl clauses built before we assemble the query $this->buildACLClause($this->_aliases['civicrm_contact']); $sql = $this->buildQuery(TRUE); $rows = array(); $this->buildRows($sql, $rows); $this->formatDisplay($rows); $this->doTemplateAssignment($rows); $this->endPostProcess($rows); } /** * Alter display of rows. * * Iterate through the rows retrieved via SQL and make changes for display purposes, * such as rendering contacts as links. * * @param array $rows * Rows generated by SQL, with an array for each row. */ public function alterDisplay(&$rows) { $entryFound = FALSE; $checkList = array(); $contributionTypes = CRM_Contribute_PseudoConstant::financialType(); $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(); $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument(); $repeatFound = FALSE; foreach ($rows as $rowNum => $row) { if ($repeatFound == FALSE || $repeatFound < $rowNum - 1 ) { unset($checkList); $checkList = array(); } if (!empty($this->_noRepeats) && $this->_outputMode != 'csv') { // not repeat contact display names if it matches with the one // in previous row foreach ($row as $colName => $colVal) { if (in_array($colName, $this->_noRepeats) && $rowNum > 0 ) { if ($rows[$rowNum][$colName] == $rows[$rowNum - 1][$colName] || (!empty($checkList[$colName]) && in_array($colVal, $checkList[$colName])) ) { $rows[$rowNum][$colName] = ""; // CRM-15917: Don't blank the name if it's a different contact if ($colName == 'civicrm_contact_exposed_id') { $rows[$rowNum]['civicrm_contact_sort_name'] = ""; } $repeatFound = $rowNum; } } if (in_array($colName, $this->_noRepeats)) { $checkList[$colName][] = $colVal; } } } if (array_key_exists('civicrm_membership_membership_type_id', $row)) { if ($value = $row['civicrm_membership_membership_type_id']) { $rows[$rowNum]['civicrm_membership_membership_type_id'] = CRM_Member_PseudoConstant::membershipType($value, FALSE); } $entryFound = TRUE; } if (array_key_exists('civicrm_address_state_province_id', $row)) { if ($value = $row['civicrm_address_state_province_id']) { $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value, FALSE); } $entryFound = TRUE; } if (array_key_exists('civicrm_address_country_id', $row)) { if ($value = $row['civicrm_address_country_id']) { $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE); } $entryFound = TRUE; } if (array_key_exists('civicrm_contact_sort_name', $row) && $rows[$rowNum]['civicrm_contact_sort_name'] && array_key_exists('civicrm_contact_id', $row) ) { $url = CRM_Utils_System::url("civicrm/contact/view", 'reset=1&cid=' . $row['civicrm_contact_id'], $this->_absoluteUrl ); $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url; $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contact Summary for this Contact."); $entryFound = TRUE; } if ($value = CRM_Utils_Array::value('civicrm_contribution_financial_type_id', $row)) { $rows[$rowNum]['civicrm_contribution_financial_type_id'] = $contributionTypes[$value]; $entryFound = TRUE; } if ($value = CRM_Utils_Array::value('civicrm_contribution_contribution_status_id', $row)) { $rows[$rowNum]['civicrm_contribution_contribution_status_id'] = $contributionStatus[$value]; $entryFound = TRUE; } if ($value = CRM_Utils_Array::value('civicrm_contribution_payment_instrument_id', $row)) { $rows[$rowNum]['civicrm_contribution_payment_instrument_id'] = $paymentInstruments[$value]; $entryFound = TRUE; } // Convert campaign_id to campaign title if (array_key_exists('civicrm_membership_campaign_id', $row)) { if ($value = $row['civicrm_membership_campaign_id']) { $rows[$rowNum]['civicrm_membership_campaign_id'] = $this->activeCampaigns[$value]; $entryFound = TRUE; } } if (!$entryFound) { break; } } } }
gpl-2.0
poulphunter/tempochat
get_chat.php
1757
<?php session_start(); require_once './functions.php'; arg_vide(); require_once './secu_session.php'; if (isset($_SESSION['room'])) { $_GET['room']=$_SESSION['room']; } foreach($_POST as $key=>$val) { $_GET[$key]=$val; } if (!isset($_GET['room'])) { exit; } if (isset($_GET['room'])) { $room=$_GET['room']; } else { exit; // $room=md5(mt_rand().mt_rand().mt_rand().mt_rand().mt_rand()); // erase_log($room); } // echo 1; $message=get_log($room); $hash=abs(crc32($message)); if (isset($_GET['hash']) && $_GET['hash']==$hash) { // echo strToHex(str_replace("\n",'<br/>',htmlentities(urldecode($message),ENT_QUOTES,"ISO-8859-1"))); // echo base64_encode(rc4Encrypt($room,base64_encode(str_replace("\n",'<br/>',htmlentities(urldecode($message),ENT_QUOTES,"ISO-8859-1"))))); // echo strToHex(rc4Encrypt($room,str_replace("\n",'<br/>',htmlentities(urldecode($message),ENT_QUOTES,"ISO-8859-1")))); // echo str_replace("\n",'<br/>',htmlentities(urldecode($message),ENT_QUOTES,"UTF-8")); // echo base64_encode(rc4Encrypt($room,base64_encode(str_replace("\n",'<br/>',htmlentities(urldecode($message),ENT_QUOTES,"UTF-8"))))); // $message=str_replace("\n",'<br/>',htmlentities(urldecode($message),ENT_QUOTES,"ISO-8859-1")); // $message=str_replace("\n",'<br/>',htmlentities(urldecode($message),ENT_QUOTES,"CP1552//IGNORE")); // $message=str_replace("\n",'<br/>',htmlentities(urldecode($message),ENT_QUOTES,"UTF-8//IGNORE")); // $message=str_replace("\n",'<br/>',htmlentities(urldecode($message),ENT_QUOTES,"UTF-8")); // $message=base64_encode($message); // $message=strToHex($message); // $message=strToHex(rc4Encrypt($room,$message)); // $message=strToHex(rc4Encrypt($room,'toto')); echo trim($message); } else { echo $hash; } // echo 1; ?>
gpl-2.0
pierrewillenbrock/dolphin
Source/Core/DolphinQt/Config/Mapping/IOWindow.cpp
23984
// Copyright 2017 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #include "DolphinQt/Config/Mapping/IOWindow.h" #include <optional> #include <thread> #include <QComboBox> #include <QDialogButtonBox> #include <QHeaderView> #include <QItemDelegate> #include <QLabel> #include <QLineEdit> #include <QPainter> #include <QPlainTextEdit> #include <QPushButton> #include <QSlider> #include <QSpinBox> #include <QTableWidget> #include <QVBoxLayout> #include "Core/Core.h" #include "DolphinQt/Config/Mapping/MappingCommon.h" #include "DolphinQt/Config/Mapping/MappingIndicator.h" #include "DolphinQt/Config/Mapping/MappingWidget.h" #include "DolphinQt/Config/Mapping/MappingWindow.h" #include "DolphinQt/QtUtils/BlockUserInputFilter.h" #include "DolphinQt/QtUtils/ModalMessageBox.h" #include "DolphinQt/Settings.h" #include "InputCommon/ControlReference/ControlReference.h" #include "InputCommon/ControlReference/ExpressionParser.h" #include "InputCommon/ControllerEmu/ControllerEmu.h" #include "InputCommon/ControllerInterface/ControllerInterface.h" constexpr int SLIDER_TICK_COUNT = 100; namespace { // TODO: Make sure these functions return colors that will be visible in the current theme. QTextCharFormat GetSpecialCharFormat() { QTextCharFormat format; format.setFontWeight(QFont::Weight::Bold); return format; } QTextCharFormat GetLiteralCharFormat() { QTextCharFormat format; format.setForeground(QBrush{Qt::darkMagenta}); return format; } QTextCharFormat GetInvalidCharFormat() { QTextCharFormat format; format.setUnderlineStyle(QTextCharFormat::WaveUnderline); format.setUnderlineColor(Qt::darkRed); return format; } QTextCharFormat GetControlCharFormat() { QTextCharFormat format; format.setForeground(QBrush{Qt::darkGreen}); return format; } QTextCharFormat GetVariableCharFormat() { QTextCharFormat format; format.setForeground(QBrush{Qt::darkYellow}); return format; } QTextCharFormat GetBarewordCharFormat() { QTextCharFormat format; format.setForeground(QBrush{Qt::darkBlue}); return format; } QTextCharFormat GetCommentCharFormat() { QTextCharFormat format; format.setForeground(QBrush{Qt::darkGray}); return format; } } // namespace ControlExpressionSyntaxHighlighter::ControlExpressionSyntaxHighlighter(QTextDocument* parent) : QSyntaxHighlighter(parent) { } void QComboBoxWithMouseWheelDisabled::wheelEvent(QWheelEvent* event) { // Do nothing } void ControlExpressionSyntaxHighlighter::highlightBlock(const QString&) { // TODO: This is going to result in improper highlighting with non-ascii characters: ciface::ExpressionParser::Lexer lexer(document()->toPlainText().toStdString()); std::vector<ciface::ExpressionParser::Token> tokens; const auto tokenize_status = lexer.Tokenize(tokens); using ciface::ExpressionParser::TokenType; const auto set_block_format = [this](int start, int count, const QTextCharFormat& format) { if (start + count <= currentBlock().position() || start >= currentBlock().position() + currentBlock().length()) { // This range is not within the current block. return; } int block_start = start - currentBlock().position(); if (block_start < 0) { count += block_start; block_start = 0; } setFormat(block_start, count, format); }; for (auto& token : tokens) { std::optional<QTextCharFormat> char_format; switch (token.type) { case TokenType::TOK_INVALID: char_format = GetInvalidCharFormat(); break; case TokenType::TOK_LPAREN: case TokenType::TOK_RPAREN: case TokenType::TOK_COMMA: char_format = GetSpecialCharFormat(); break; case TokenType::TOK_LITERAL: char_format = GetLiteralCharFormat(); break; case TokenType::TOK_CONTROL: char_format = GetControlCharFormat(); break; case TokenType::TOK_BAREWORD: char_format = GetBarewordCharFormat(); break; case TokenType::TOK_VARIABLE: char_format = GetVariableCharFormat(); break; case TokenType::TOK_COMMENT: char_format = GetCommentCharFormat(); break; default: if (token.IsBinaryOperator()) char_format = GetSpecialCharFormat(); break; } if (char_format.has_value()) set_block_format(int(token.string_position), int(token.string_length), *char_format); } // This doesn't need to be run for every "block", but it works. if (ciface::ExpressionParser::ParseStatus::Successful == tokenize_status) { ciface::ExpressionParser::RemoveInertTokens(&tokens); const auto parse_status = ciface::ExpressionParser::ParseTokens(tokens); if (ciface::ExpressionParser::ParseStatus::Successful != parse_status.status) { const auto token = *parse_status.token; set_block_format(int(token.string_position), int(token.string_length), GetInvalidCharFormat()); } } } class InputStateDelegate : public QItemDelegate { public: explicit InputStateDelegate(IOWindow* parent, int column, std::function<ControlState(int row)> state_evaluator); void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override; private: std::function<ControlState(int row)> m_state_evaluator; int m_column; }; class InputStateLineEdit : public QLineEdit { public: explicit InputStateLineEdit(std::function<ControlState()> state_evaluator); void SetShouldPaintStateIndicator(bool value); void paintEvent(QPaintEvent* event) override; private: std::function<ControlState()> m_state_evaluator; bool m_should_paint_state_indicator; }; IOWindow::IOWindow(MappingWidget* parent, ControllerEmu::EmulatedController* controller, ControlReference* ref, IOWindow::Type type) : QDialog(parent), m_reference(ref), m_original_expression(ref->GetExpression()), m_controller(controller), m_type(type) { CreateMainLayout(); connect(parent, &MappingWidget::Update, this, &IOWindow::Update); connect(parent->GetParent(), &MappingWindow::ConfigChanged, this, &IOWindow::ConfigChanged); connect(&Settings::Instance(), &Settings::ConfigChanged, this, &IOWindow::ConfigChanged); setWindowTitle(type == IOWindow::Type::Input ? tr("Configure Input") : tr("Configure Output")); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); ConfigChanged(); ConnectWidgets(); } std::shared_ptr<ciface::Core::Device> IOWindow::GetSelectedDevice() const { return m_selected_device; } void IOWindow::CreateMainLayout() { m_main_layout = new QVBoxLayout(); m_devices_combo = new QComboBox(); m_option_list = new QTableWidget(); m_select_button = new QPushButton(tr("Select")); m_detect_button = new QPushButton(tr("Detect"), this); m_test_button = new QPushButton(tr("Test"), this); m_button_box = new QDialogButtonBox(); m_clear_button = new QPushButton(tr("Clear")); m_range_slider = new QSlider(Qt::Horizontal); m_range_spinbox = new QSpinBox(); m_parse_text = new InputStateLineEdit([this] { const auto lock = m_controller->GetStateLock(); return m_reference->GetState<ControlState>(); }); m_parse_text->setReadOnly(true); m_expression_text = new QPlainTextEdit(); m_expression_text->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); new ControlExpressionSyntaxHighlighter(m_expression_text->document()); m_operators_combo = new QComboBoxWithMouseWheelDisabled(this); m_operators_combo->addItem(tr("Operators")); m_operators_combo->insertSeparator(1); if (m_type == Type::Input) { m_operators_combo->addItem(tr("! Not")); m_operators_combo->addItem(tr("* Multiply")); m_operators_combo->addItem(tr("/ Divide")); m_operators_combo->addItem(tr("% Modulo")); m_operators_combo->addItem(tr("+ Add")); m_operators_combo->addItem(tr("- Subtract")); m_operators_combo->addItem(tr("> Greater-than")); m_operators_combo->addItem(tr("< Less-than")); m_operators_combo->addItem(tr("& And")); m_operators_combo->addItem(tr("^ Xor")); } m_operators_combo->addItem(tr("| Or")); m_operators_combo->addItem(tr("$ User Variable")); if (m_type == Type::Input) { m_operators_combo->addItem(tr(", Comma")); } m_functions_combo = new QComboBoxWithMouseWheelDisabled(this); m_functions_combo->addItem(tr("Functions")); m_functions_combo->insertSeparator(1); m_functions_combo->addItem(QStringLiteral("if")); m_functions_combo->addItem(QStringLiteral("timer")); m_functions_combo->addItem(QStringLiteral("toggle")); m_functions_combo->addItem(QStringLiteral("deadzone")); m_functions_combo->addItem(QStringLiteral("smooth")); m_functions_combo->addItem(QStringLiteral("hold")); m_functions_combo->addItem(QStringLiteral("tap")); m_functions_combo->addItem(QStringLiteral("relative")); m_functions_combo->addItem(QStringLiteral("pulse")); m_functions_combo->addItem(QStringLiteral("sin")); m_functions_combo->addItem(QStringLiteral("cos")); m_functions_combo->addItem(QStringLiteral("tan")); m_functions_combo->addItem(QStringLiteral("asin")); m_functions_combo->addItem(QStringLiteral("acos")); m_functions_combo->addItem(QStringLiteral("atan")); m_functions_combo->addItem(QStringLiteral("atan2")); m_functions_combo->addItem(QStringLiteral("sqrt")); m_functions_combo->addItem(QStringLiteral("pow")); m_functions_combo->addItem(QStringLiteral("min")); m_functions_combo->addItem(QStringLiteral("max")); m_functions_combo->addItem(QStringLiteral("clamp")); m_variables_combo = new QComboBoxWithMouseWheelDisabled(this); m_variables_combo->addItem(tr("User Variables")); m_variables_combo->setToolTip( tr("User defined variables usable in the control expression.\nYou can use them to save or " "retrieve values between\ninputs and outputs of the same parent controller.")); m_variables_combo->insertSeparator(m_variables_combo->count()); m_variables_combo->addItem(tr("Reset Values")); m_variables_combo->insertSeparator(m_variables_combo->count()); // Devices m_main_layout->addWidget(m_devices_combo); // Range auto* range_hbox = new QHBoxLayout(); range_hbox->addWidget(new QLabel(tr("Range"))); range_hbox->addWidget(m_range_slider); range_hbox->addWidget(m_range_spinbox); m_range_slider->setMinimum(-500); m_range_slider->setMaximum(500); m_range_spinbox->setMinimum(-500); m_range_spinbox->setMaximum(500); m_main_layout->addLayout(range_hbox); // Options (Buttons, Outputs) and action buttons m_option_list->setTabKeyNavigation(false); if (m_type == Type::Input) { m_option_list->setColumnCount(2); m_option_list->setColumnWidth(1, 64); m_option_list->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Fixed); m_option_list->setItemDelegate(new InputStateDelegate(this, 1, [&](int row) { std::lock_guard lock(m_selected_device_mutex); // Clamp off negative values but allow greater than one in the text display. return std::max(GetSelectedDevice()->Inputs()[row]->GetState(), 0.0); })); } else { m_option_list->setColumnCount(1); } m_option_list->horizontalHeader()->hide(); m_option_list->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); m_option_list->verticalHeader()->hide(); m_option_list->verticalHeader()->setDefaultSectionSize( m_option_list->verticalHeader()->minimumSectionSize()); m_option_list->setEditTriggers(QAbstractItemView::NoEditTriggers); m_option_list->setSelectionBehavior(QAbstractItemView::SelectRows); m_option_list->setSelectionMode(QAbstractItemView::SingleSelection); auto* hbox = new QHBoxLayout(); auto* button_vbox = new QVBoxLayout(); hbox->addWidget(m_option_list, 8); hbox->addLayout(button_vbox, 1); button_vbox->addWidget(m_select_button); if (m_type == Type::Input) { m_test_button->hide(); button_vbox->addWidget(m_detect_button); } else { m_detect_button->hide(); button_vbox->addWidget(m_test_button); } button_vbox->addWidget(m_variables_combo); button_vbox->addWidget(m_operators_combo); if (m_type == Type::Input) button_vbox->addWidget(m_functions_combo); else m_functions_combo->hide(); m_main_layout->addLayout(hbox, 2); m_main_layout->addWidget(m_expression_text, 1); m_main_layout->addWidget(m_parse_text); // Button Box m_main_layout->addWidget(m_button_box); m_button_box->addButton(m_clear_button, QDialogButtonBox::ActionRole); m_button_box->addButton(QDialogButtonBox::Ok); setLayout(m_main_layout); } void IOWindow::ConfigChanged() { const QSignalBlocker blocker(this); const auto lock = ControllerEmu::EmulatedController::GetStateLock(); // ensure m_parse_text is in the right state UpdateExpression(m_reference->GetExpression(), UpdateMode::Force); m_expression_text->setPlainText(QString::fromStdString(m_reference->GetExpression())); m_expression_text->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor); m_range_spinbox->setValue(m_reference->range * SLIDER_TICK_COUNT); m_range_slider->setValue(m_reference->range * SLIDER_TICK_COUNT); if (m_devq.ToString().empty()) m_devq = m_controller->GetDefaultDevice(); UpdateDeviceList(); } void IOWindow::Update() { m_option_list->viewport()->update(); m_parse_text->update(); } void IOWindow::ConnectWidgets() { connect(m_select_button, &QPushButton::clicked, [this] { AppendSelectedOption(); }); connect(&Settings::Instance(), &Settings::ReleaseDevices, this, &IOWindow::ReleaseDevices); connect(&Settings::Instance(), &Settings::DevicesChanged, this, &IOWindow::UpdateDeviceList); connect(m_detect_button, &QPushButton::clicked, this, &IOWindow::OnDetectButtonPressed); connect(m_test_button, &QPushButton::clicked, this, &IOWindow::OnTestButtonPressed); connect(m_button_box, &QDialogButtonBox::clicked, this, &IOWindow::OnDialogButtonPressed); connect(m_devices_combo, &QComboBox::currentTextChanged, this, &IOWindow::OnDeviceChanged); connect(m_range_spinbox, qOverload<int>(&QSpinBox::valueChanged), this, &IOWindow::OnRangeChanged); connect(m_expression_text, &QPlainTextEdit::textChanged, [this] { UpdateExpression(m_expression_text->toPlainText().toStdString()); }); connect(m_variables_combo, qOverload<int>(&QComboBox::activated), [this](int index) { if (index == 0) return; // Reset button. 1 and 3 are separators. if (index == 2) { const auto lock = ControllerEmu::EmulatedController::GetStateLock(); m_controller->ResetExpressionVariables(); } else { m_expression_text->insertPlainText(QLatin1Char('$') + m_variables_combo->currentText()); } m_variables_combo->setCurrentIndex(0); }); connect(m_operators_combo, qOverload<int>(&QComboBox::activated), [this](int index) { if (index == 0) return; m_expression_text->insertPlainText(m_operators_combo->currentText().left(1)); m_operators_combo->setCurrentIndex(0); }); connect(m_functions_combo, qOverload<int>(&QComboBox::activated), [this](int index) { if (index == 0) return; m_expression_text->insertPlainText(m_functions_combo->currentText() + QStringLiteral("()")); m_functions_combo->setCurrentIndex(0); }); // revert the expression when the window closes without using the OK button connect(this, &IOWindow::finished, [this] { UpdateExpression(m_original_expression); }); } void IOWindow::AppendSelectedOption() { if (m_option_list->currentRow() < 0) return; m_expression_text->insertPlainText(MappingCommon::GetExpressionForControl( m_option_list->item(m_option_list->currentRow(), 0)->text(), m_devq, m_controller->GetDefaultDevice())); } void IOWindow::OnDeviceChanged() { const std::string device_name = m_devices_combo->count() > 0 ? m_devices_combo->currentData().toString().toStdString() : ""; m_devq.FromString(device_name); UpdateOptionList(); } void IOWindow::OnDialogButtonPressed(QAbstractButton* button) { if (button == m_clear_button) { m_expression_text->clear(); return; } const auto lock = ControllerEmu::EmulatedController::GetStateLock(); UpdateExpression(m_expression_text->toPlainText().toStdString()); m_original_expression = m_reference->GetExpression(); if (ciface::ExpressionParser::ParseStatus::SyntaxError == m_reference->GetParseStatus()) { ModalMessageBox::warning(this, tr("Error"), tr("The expression contains a syntax error.")); } // must be the OK button accept(); } void IOWindow::OnDetectButtonPressed() { const auto expression = MappingCommon::DetectExpression(m_detect_button, g_controller_interface, {m_devq.ToString()}, m_devq, MappingCommon::Quote::Off); if (expression.isEmpty()) return; const auto list = m_option_list->findItems(expression, Qt::MatchFixedString); // Try to select the first. If this fails, the last selected item would still appear as such if (!list.empty()) m_option_list->setCurrentItem(list[0]); } void IOWindow::OnTestButtonPressed() { MappingCommon::TestOutput(m_test_button, static_cast<OutputReference*>(m_reference)); } void IOWindow::OnRangeChanged(int value) { m_reference->range = static_cast<double>(value) / SLIDER_TICK_COUNT; m_range_spinbox->setValue(m_reference->range * SLIDER_TICK_COUNT); m_range_slider->setValue(m_reference->range * SLIDER_TICK_COUNT); } void IOWindow::ReleaseDevices() { std::lock_guard lock(m_selected_device_mutex); m_selected_device = nullptr; } void IOWindow::UpdateOptionList() { std::lock_guard lock(m_selected_device_mutex); m_selected_device = g_controller_interface.FindDevice(m_devq); m_option_list->setRowCount(0); if (m_selected_device == nullptr) return; if (m_reference->IsInput()) { int row = 0; for (const auto* input : m_selected_device->Inputs()) { m_option_list->insertRow(row); m_option_list->setItem(row, 0, new QTableWidgetItem(QString::fromStdString(input->GetName()))); ++row; } } else { int row = 0; for (const auto* output : m_selected_device->Outputs()) { m_option_list->insertRow(row); m_option_list->setItem(row, 0, new QTableWidgetItem(QString::fromStdString(output->GetName()))); ++row; } } } void IOWindow::UpdateDeviceList() { const QSignalBlocker blocker(m_devices_combo); const auto previous_device_name = m_devices_combo->currentData().toString().toStdString(); m_devices_combo->clear(); // Default to the default device or to the first device if there isn't a default. // Try to the keep the previous selected device, mark it as disconnected if it's gone, as it could // reconnect soon after if this is a devices refresh and it would be annoying to lose the value. const auto default_device_name = m_controller->GetDefaultDevice().ToString(); int default_device_index = -1; int previous_device_index = -1; for (const auto& name : g_controller_interface.GetAllDeviceStrings()) { QString qname = QString(); if (name == default_device_name) { default_device_index = m_devices_combo->count(); // Specify "default" even if we only have one device qname.append(QLatin1Char{'['} + tr("default") + QStringLiteral("] ")); } if (name == previous_device_name) { previous_device_index = m_devices_combo->count(); } qname.append(QString::fromStdString(name)); m_devices_combo->addItem(qname, QString::fromStdString(name)); } if (previous_device_index >= 0) { m_devices_combo->setCurrentIndex(previous_device_index); } else if (!previous_device_name.empty()) { const QString qname = QString::fromStdString(previous_device_name); QString adjusted_qname; if (previous_device_name == default_device_name) { adjusted_qname.append(QLatin1Char{'['} + tr("default") + QStringLiteral("] ")); } adjusted_qname.append(QLatin1Char{'['} + tr("disconnected") + QStringLiteral("] ")) .append(qname); m_devices_combo->addItem(adjusted_qname, qname); m_devices_combo->setCurrentIndex(m_devices_combo->count() - 1); } else if (default_device_index >= 0) { m_devices_combo->setCurrentIndex(default_device_index); } else if (m_devices_combo->count() > 0) { m_devices_combo->setCurrentIndex(0); } // The device object might have changed so we need to always refresh it OnDeviceChanged(); } void IOWindow::UpdateExpression(std::string new_expression, UpdateMode mode) { const auto lock = m_controller->GetStateLock(); if (mode != UpdateMode::Force && new_expression == m_reference->GetExpression()) return; const auto error = m_reference->SetExpression(std::move(new_expression)); const auto status = m_reference->GetParseStatus(); m_controller->UpdateSingleControlReference(g_controller_interface, m_reference); // This is the only place where we need to update the user variables. Keep the first 4 items. while (m_variables_combo->count() > 4) { m_variables_combo->removeItem(m_variables_combo->count() - 1); } for (const auto& expression : m_controller->GetExpressionVariables()) { m_variables_combo->addItem(QString::fromStdString(expression.first)); } if (error) { m_parse_text->SetShouldPaintStateIndicator(false); m_parse_text->setText(QString::fromStdString(*error)); } else if (status == ciface::ExpressionParser::ParseStatus::EmptyExpression) { m_parse_text->SetShouldPaintStateIndicator(false); m_parse_text->setText(QString()); } else if (status != ciface::ExpressionParser::ParseStatus::Successful) { m_parse_text->SetShouldPaintStateIndicator(false); m_parse_text->setText(tr("Invalid Expression.")); } else { m_parse_text->SetShouldPaintStateIndicator(true); m_parse_text->setText(QString()); } } InputStateDelegate::InputStateDelegate(IOWindow* parent, int column, std::function<ControlState(int row)> state_evaluator) : QItemDelegate(parent), m_state_evaluator(std::move(state_evaluator)), m_column(column) { } InputStateLineEdit::InputStateLineEdit(std::function<ControlState()> state_evaluator) : m_state_evaluator(std::move(state_evaluator)) { } static void PaintStateIndicator(QPainter& painter, const QRect& region, ControlState state) { const QString state_string = QString::number(state, 'g', 4); QRect meter_region = region; meter_region.setWidth(region.width() * std::clamp(state, 0.0, 1.0)); // Create a temporary indicator object to retreive color constants. MappingIndicator indicator; // Normal text. painter.setPen(indicator.GetTextColor()); painter.drawText(region, Qt::AlignCenter, state_string); // Input state meter. painter.fillRect(meter_region, indicator.GetAdjustedInputColor()); // Text on top of meter. painter.setPen(indicator.GetAltTextColor()); painter.setClipping(true); painter.setClipRect(meter_region); painter.drawText(region, Qt::AlignCenter, state_string); } void InputStateDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { QItemDelegate::paint(painter, option, index); if (index.column() != m_column) return; painter->save(); PaintStateIndicator(*painter, option.rect, m_state_evaluator(index.row())); painter->restore(); } void InputStateLineEdit::SetShouldPaintStateIndicator(bool value) { m_should_paint_state_indicator = value; } void InputStateLineEdit::paintEvent(QPaintEvent* event) { QLineEdit::paintEvent(event); if (!m_should_paint_state_indicator) return; QPainter painter(this); PaintStateIndicator(painter, this->rect(), m_state_evaluator()); }
gpl-2.0
AntojandoAndo/AntojandoAndo
wp-content/themes/Newspaper/includes/smart_lists/td_smart_list_7.php
3596
<?php class td_smart_list_7 extends td_smart_list { protected $use_pagination = true; // set this to true to use rela pagination on this template protected function render_before_list_wrap() { if(td_global::$cur_single_template_sidebar_pos == 'no_sidebar') { $td_class_nr_of_columns = ' td-3-columns '; } else { $td_class_nr_of_columns = ' td-2-columns '; } $buffy = ''; //wrapper with id for smart list wrapper type 7 $buffy .= '<div class="td_smart_list_7' . $td_class_nr_of_columns . '">'; return $buffy; } protected function render_list_item($item_array, $current_item_id, $current_item_number, $total_items_number) { //print_r($item_array); $buffy = ''; // render the pagination $buffy .= $this->callback_render_pagination(); //creating each slide $buffy .= '<div class="td-item">'; $buffy .= '<h2><span class="td-sml-current-item-title">' . $current_item_number. '. ' . $item_array['title'] . '</span></h2>'; //get image info $first_img_all_info = td_util::attachment_get_full_info($item_array['first_img_id']); //get image link target $first_img_link_target = $item_array['first_img_link_target']; //image caption $first_img_caption = $item_array['first_img_caption']; //adding description if(!empty($item_array['description'])) { $buffy .= '<span class="td-sml-description">' . $item_array['description'] . '</span>'; } // ad smart list 6 $buffy .= td_global_blocks::get_instance('td_block_ad_box')->render(array('spot_id' => 'smart_list_7')); if(td_global::$cur_single_template_sidebar_pos == 'no_sidebar') { $first_img_info = wp_get_attachment_image_src($item_array['first_img_id'], 'td_1068x0'); } else { $first_img_info = wp_get_attachment_image_src($item_array['first_img_id'], 'td_696x0'); } if (!empty($first_img_info[0])) { // class used by magnific popup $smart_list_lightbox = " td-lightbox-enabled"; // if a custom link is set use it if (!empty($item_array['first_img_link']) && $first_img_all_info['src'] != $item_array['first_img_link']) { $first_img_all_info['src'] = $item_array['first_img_link']; // remove the magnific popup class for custom links $smart_list_lightbox = ""; } $buffy .= ' <figure class="td-slide-smart-list-figure td-slide-smart-list-7' . $smart_list_lightbox . '"> <a class="td-sml-link-to-image" href="' . $first_img_all_info['src'] . '" data-caption="' . esc_attr($first_img_caption, ENT_QUOTES) . '" ' . $first_img_link_target . ' > <img src="' . $first_img_info[0] . '"/> </a> <figcaption class="td-sml-caption"><div>' . $first_img_caption . '</div></figcaption> </figure>'; } // render the pagination $buffy .= $this->callback_render_pagination(); $buffy .= '</div>'; return $buffy; } protected function render_after_list_wrap() { $buffy = ''; $buffy .= '</div>'; // /.td_smart_list_7 wrapper with id return $buffy; } }
gpl-2.0
ihcfan/NautiPlot
NautiHubMapServer/main.cpp
29582
/* * libwebsockets-test-server - libwebsockets test implementation * * Copyright (C) 2010-2011 Andy Green <andy@warmcat.com> * * 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: * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifdef CMAKE_BUILD #include "lws_config.h" #endif #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <getopt.h> #include <string.h> #include <sys/time.h> #include <sys/stat.h> #include <fcntl.h> #include <assert.h> #ifdef WIN32 #ifdef EXTERNAL_POLL #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <winsock2.h> #include <ws2tcpip.h> #include <stddef.h> #include "websock-w32.h" #endif #else // NOT WIN32 #include <syslog.h> #endif #include <signal.h> #include "../libwebsockets/lib/libwebsockets.h" static int close_testing; int max_poll_elements; struct pollfd *pollfds; int *fd_lookup; int count_pollfds; int force_exit = 0; /* * This demo server shows how to use libwebsockets for one or more * websocket protocols in the same server * * It defines the following websocket protocols: * * dumb-increment-protocol: once the socket is opened, an incrementing * ascii string is sent down it every 50ms. * If you send "reset\n" on the websocket, then * the incrementing number is reset to 0. * * lws-mirror-protocol: copies any received packet to every connection also * using this protocol, including the sender */ enum demo_protocols { /* always first */ PROTOCOL_HTTP = 0, PROTOCOL_DUMB_INCREMENT, PROTOCOL_LWS_MIRROR, /* always last */ DEMO_PROTOCOL_COUNT }; char *resource_path = "~/"; /* * We take a strict whitelist approach to stop ../ attacks */ struct serveable { const char *urlpath; const char *mimetype; }; struct per_session_data__http { int fd; }; /* * this is just an example of parsing handshake headers, you don't need this * in your code unless you will filter allowing connections by the header * content */ static void dump_handshake_info(struct libwebsocket *wsi) { int n; static const char *token_names[] = { /*[WSI_TOKEN_GET_URI] =*/ "GET URI", /*[WSI_TOKEN_POST_URI] =*/ "POST URI", /*[WSI_TOKEN_HOST] =*/ "Host", /*[WSI_TOKEN_CONNECTION] =*/ "Connection", /*[WSI_TOKEN_KEY1] =*/ "key 1", /*[WSI_TOKEN_KEY2] =*/ "key 2", /*[WSI_TOKEN_PROTOCOL] =*/ "Protocol", /*[WSI_TOKEN_UPGRADE] =*/ "Upgrade", /*[WSI_TOKEN_ORIGIN] =*/ "Origin", /*[WSI_TOKEN_DRAFT] =*/ "Draft", /*[WSI_TOKEN_CHALLENGE] =*/ "Challenge", /* new for 04 */ /*[WSI_TOKEN_KEY] =*/ "Key", /*[WSI_TOKEN_VERSION] =*/ "Version", /*[WSI_TOKEN_SWORIGIN] =*/ "Sworigin", /* new for 05 */ /*[WSI_TOKEN_EXTENSIONS] =*/ "Extensions", /* client receives these */ /*[WSI_TOKEN_ACCEPT] =*/ "Accept", /*[WSI_TOKEN_NONCE] =*/ "Nonce", /*[WSI_TOKEN_HTTP] =*/ "Http", "Accept:", "If-Modified-Since:", "Accept-Encoding:", "Accept-Language:", "Pragma:", "Cache-Control:", "Authorization:", "Cookie:", "Content-Length:", "Content-Type:", "Date:", "Range:", "Referer:", "Uri-Args:", /*[WSI_TOKEN_MUXURL] =*/ "MuxURL", }; char buf[256]; for (n = 0; n < sizeof(token_names) / sizeof(token_names[0]); n++) { if (!lws_hdr_total_length(wsi, (enum lws_token_indexes)n)) continue; lws_hdr_copy(wsi, buf, sizeof buf, (enum lws_token_indexes)n); fprintf(stderr, " %s = %s\n", token_names[n], buf); } } const char * get_mimetype(const char *file) { int n = strlen(file); if (n < 5) return NULL; if (!strcmp(&file[n - 4], ".ico")) return "image/x-icon"; if (!strcmp(&file[n - 4], ".png")) return "image/png"; if (!strcmp(&file[n - 5], ".html")) return "text/html"; return NULL; } /* this protocol server (always the first one) just knows how to do HTTP */ static int callback_http(struct libwebsocket_context *context, struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason, void *user, void *in, size_t len) { #if 0 char client_name[128]; char client_ip[128]; #endif char buf[256]; char leaf_path[1024]; char b64[64]; struct timeval tv; int n, m; unsigned char *p; char *other_headers; static unsigned char buffer[4096]; struct stat stat_buf; struct per_session_data__http *pss = (struct per_session_data__http *)user; const char *mimetype; #ifdef EXTERNAL_POLL int fd = (int)(long)in; #endif switch (reason) { case LWS_CALLBACK_HTTP: dump_handshake_info(wsi); if (len < 1) { libwebsockets_return_http_status(context, wsi, HTTP_STATUS_BAD_REQUEST, NULL); return -1; } /* this server has no concept of directories */ if (strchr((const char *)in + 1, '/')) { libwebsockets_return_http_status(context, wsi, HTTP_STATUS_FORBIDDEN, NULL); return -1; } /* if a legal POST URL, let it continue and accept data */ if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) return 0; /* check for the "send a big file by hand" example case */ if (!strcmp((const char *)in, "/leaf.jpg")) { if (strlen(resource_path) > sizeof(leaf_path) - 10) return -1; sprintf(leaf_path, "%s/leaf.jpg", resource_path); /* well, let's demonstrate how to send the hard way */ p = buffer; #ifdef WIN32 pss->fd = open(leaf_path, O_RDONLY | _O_BINARY); #else pss->fd = open(leaf_path, O_RDONLY); #endif if (pss->fd < 0) return -1; fstat(pss->fd, &stat_buf); /* * we will send a big jpeg file, but it could be * anything. Set the Content-Type: appropriately * so the browser knows what to do with it. */ p += sprintf((char *)p, "HTTP/1.0 200 OK\x0d\x0a" "Server: libwebsockets\x0d\x0a" "Content-Type: image/jpeg\x0d\x0a" "Content-Length: %u\x0d\x0a\x0d\x0a", (unsigned int)stat_buf.st_size); /* * send the http headers... * this won't block since it's the first payload sent * on the connection since it was established * (too small for partial) */ n = libwebsocket_write(wsi, buffer, p - buffer, LWS_WRITE_HTTP); if (n < 0) { close(pss->fd); return -1; } /* * book us a LWS_CALLBACK_HTTP_WRITEABLE callback */ libwebsocket_callback_on_writable(context, wsi); break; } /* if not, send a file the easy way */ strcpy(buf, resource_path); if (strcmp((const char *)in, "/")) { if (*((const char *)in) != '/') strcat(buf, "/"); strncat(buf, (const char *)in, sizeof(buf) - strlen(resource_path)); } else /* default file to serve */ strcat(buf, "/test.html"); buf[sizeof(buf) - 1] = '\0'; /* refuse to serve files we don't understand */ mimetype = get_mimetype(buf); if (!mimetype) { lwsl_err("Unknown mimetype for %s\n", buf); libwebsockets_return_http_status(context, wsi, HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL); return -1; } /* demostrates how to set a cookie on / */ other_headers = NULL; if (!strcmp((const char *)in, "/") && !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) { /* this isn't very unguessable but it'll do for us */ gettimeofday(&tv, NULL); sprintf(b64, "LWS_%u_%u_COOKIE", (unsigned int)tv.tv_sec, (unsigned int)tv.tv_usec); sprintf(leaf_path, "Set-Cookie: test=LWS_%u_%u_COOKIE;Max-Age=360000\x0d\x0a", (unsigned int)tv.tv_sec, (unsigned int)tv.tv_usec); other_headers = leaf_path; lwsl_err(other_headers); } if (libwebsockets_serve_http_file(context, wsi, buf, mimetype, other_headers)) return -1; /* through completion or error, close the socket */ /* * notice that the sending of the file completes asynchronously, * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when * it's done */ break; case LWS_CALLBACK_HTTP_BODY: strncpy(buf, (const char *)in, 20); buf[20] = '\0'; if (len < 20) buf[len] = '\0'; lwsl_notice("LWS_CALLBACK_HTTP_BODY: %s... len %d\n", (const char *)buf, (int)len); break; case LWS_CALLBACK_HTTP_BODY_COMPLETION: lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n"); /* the whole of the sent body arried, close the connection */ libwebsockets_return_http_status(context, wsi, HTTP_STATUS_OK, NULL); return -1; case LWS_CALLBACK_HTTP_FILE_COMPLETION: // lwsl_info("LWS_CALLBACK_HTTP_FILE_COMPLETION seen\n"); /* kill the connection after we sent one file */ return -1; case LWS_CALLBACK_HTTP_WRITEABLE: /* * we can send more of whatever it is we were sending */ do { n = read(pss->fd, buffer, sizeof buffer); /* problem reading, close conn */ if (n < 0) goto bail; /* sent it all, close conn */ if (n == 0) goto flush_bail; /* * because it's HTTP and not websocket, don't need to take * care about pre and postamble */ m = libwebsocket_write(wsi, buffer, n, LWS_WRITE_HTTP); if (m < 0) /* write failed, close conn */ goto bail; if (m != n) /* partial write, adjust */ lseek(pss->fd, m - n, SEEK_CUR); } while (!lws_send_pipe_choked(wsi)); libwebsocket_callback_on_writable(context, wsi); break; flush_bail: /* true if still partial pending */ if (lws_send_pipe_choked(wsi)) { libwebsocket_callback_on_writable(context, wsi); break; } bail: close(pss->fd); return -1; /* * callback for confirming to continue with client IP appear in * protocol 0 callback since no websocket protocol has been agreed * yet. You can just ignore this if you won't filter on client IP * since the default uhandled callback return is 0 meaning let the * connection continue. */ case LWS_CALLBACK_FILTER_NETWORK_CONNECTION: #if 0 libwebsockets_get_peer_addresses(context, wsi, (int)(long)in, client_name, sizeof(client_name), client_ip, sizeof(client_ip)); fprintf(stderr, "Received network connect from %s (%s)\n", client_name, client_ip); #endif /* if we returned non-zero from here, we kill the connection */ break; #ifdef EXTERNAL_POLL /* * callbacks for managing the external poll() array appear in * protocol 0 callback */ case LWS_CALLBACK_LOCK_POLL: /* * lock mutex to protect pollfd state * called before any other POLL related callback */ break; case LWS_CALLBACK_UNLOCK_POLL: /* * unlock mutex to protect pollfd state when * called after any other POLL related callback */ break; case LWS_CALLBACK_ADD_POLL_FD: if (count_pollfds >= max_poll_elements) { lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n"); return 1; } fd_lookup[fd] = count_pollfds; pollfds[count_pollfds].fd = fd; pollfds[count_pollfds].events = (int)(long)len; pollfds[count_pollfds++].revents = 0; break; case LWS_CALLBACK_DEL_POLL_FD: if (!--count_pollfds) break; m = fd_lookup[fd]; /* have the last guy take up the vacant slot */ pollfds[m] = pollfds[count_pollfds]; fd_lookup[pollfds[count_pollfds].fd] = m; break; case LWS_CALLBACK_SET_MODE_POLL_FD: pollfds[fd_lookup[fd]].events |= (int)(long)len; break; case LWS_CALLBACK_CLEAR_MODE_POLL_FD: pollfds[fd_lookup[fd]].events &= ~(int)(long)len; break; #endif default: break; } return 0; } /* dumb_increment protocol */ /* * one of these is auto-created for each connection and a pointer to the * appropriate instance is passed to the callback in the user parameter * * for this example protocol we use it to individualize the count for each * connection. */ struct per_session_data__dumb_increment { int number; }; static int callback_dumb_increment(struct libwebsocket_context *context, struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason, void *user, void *in, size_t len) { int n, m; unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 + LWS_SEND_BUFFER_POST_PADDING]; unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING]; struct per_session_data__dumb_increment *pss = (struct per_session_data__dumb_increment *)user; switch (reason) { case LWS_CALLBACK_ESTABLISHED: lwsl_info("callback_dumb_increment: " "LWS_CALLBACK_ESTABLISHED\n"); pss->number = 0; break; case LWS_CALLBACK_SERVER_WRITEABLE: n = sprintf((char *)p, "%d", pss->number++); m = libwebsocket_write(wsi, p, n, LWS_WRITE_TEXT); if (m < n) { lwsl_err("ERROR %d writing to di socket\n", n); return -1; } if (close_testing && pss->number == 50) { lwsl_info("close tesing limit, closing\n"); return -1; } break; case LWS_CALLBACK_RECEIVE: // fprintf(stderr, "rx %d\n", (int)len); if (len < 6) break; if (strcmp((const char *)in, "reset\n") == 0) pss->number = 0; break; /* * this just demonstrates how to use the protocol filter. If you won't * study and reject connections based on header content, you don't need * to handle this callback */ case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION: dump_handshake_info(wsi); /* you could return non-zero here and kill the connection */ break; default: break; } return 0; } /* lws-mirror_protocol */ #define MAX_MESSAGE_QUEUE 32 struct per_session_data__lws_mirror { struct libwebsocket *wsi; int ringbuffer_tail; }; struct a_message { void *payload; size_t len; }; static struct a_message ringbuffer[MAX_MESSAGE_QUEUE]; static int ringbuffer_head; static int callback_lws_mirror(struct libwebsocket_context *context, struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason, void *user, void *in, size_t len) { int n; struct per_session_data__lws_mirror *pss = (struct per_session_data__lws_mirror *)user; switch (reason) { case LWS_CALLBACK_ESTABLISHED: lwsl_info("callback_lws_mirror: LWS_CALLBACK_ESTABLISHED\n"); pss->ringbuffer_tail = ringbuffer_head; pss->wsi = wsi; break; case LWS_CALLBACK_PROTOCOL_DESTROY: lwsl_notice("mirror protocol cleaning up\n"); for (n = 0; n < sizeof ringbuffer / sizeof ringbuffer[0]; n++) if (ringbuffer[n].payload) free(ringbuffer[n].payload); break; case LWS_CALLBACK_SERVER_WRITEABLE: if (close_testing) break; while (pss->ringbuffer_tail != ringbuffer_head) { n = libwebsocket_write(wsi, (unsigned char *) ringbuffer[pss->ringbuffer_tail].payload + LWS_SEND_BUFFER_PRE_PADDING, ringbuffer[pss->ringbuffer_tail].len, LWS_WRITE_TEXT); if (n < 0) { lwsl_err("ERROR %d writing to mirror socket\n", n); return -1; } if (n < ringbuffer[pss->ringbuffer_tail].len) lwsl_err("mirror partial write %d vs %d\n", n, ringbuffer[pss->ringbuffer_tail].len); if (pss->ringbuffer_tail == (MAX_MESSAGE_QUEUE - 1)) pss->ringbuffer_tail = 0; else pss->ringbuffer_tail++; if (((ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1)) == (MAX_MESSAGE_QUEUE - 15)) libwebsocket_rx_flow_allow_all_protocol( libwebsockets_get_protocol(wsi)); // lwsl_debug("tx fifo %d\n", (ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1)); if (lws_send_pipe_choked(wsi)) { libwebsocket_callback_on_writable(context, wsi); break; } /* * for tests with chrome on same machine as client and * server, this is needed to stop chrome choking */ usleep(1); } break; case LWS_CALLBACK_RECEIVE: if (((ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1)) == (MAX_MESSAGE_QUEUE - 1)) { lwsl_err("dropping!\n"); goto choke; } if (ringbuffer[ringbuffer_head].payload) free(ringbuffer[ringbuffer_head].payload); ringbuffer[ringbuffer_head].payload = malloc(LWS_SEND_BUFFER_PRE_PADDING + len + LWS_SEND_BUFFER_POST_PADDING); ringbuffer[ringbuffer_head].len = len; memcpy((char *)ringbuffer[ringbuffer_head].payload + LWS_SEND_BUFFER_PRE_PADDING, in, len); if (ringbuffer_head == (MAX_MESSAGE_QUEUE - 1)) ringbuffer_head = 0; else ringbuffer_head++; if (((ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1)) != (MAX_MESSAGE_QUEUE - 2)) goto done; choke: lwsl_debug("LWS_CALLBACK_RECEIVE: throttling %p\n", wsi); libwebsocket_rx_flow_control(wsi, 0); // lwsl_debug("rx fifo %d\n", (ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1)); done: libwebsocket_callback_on_writable_all_protocol( libwebsockets_get_protocol(wsi)); break; /* * this just demonstrates how to use the protocol filter. If you won't * study and reject connections based on header content, you don't need * to handle this callback */ case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION: dump_handshake_info(wsi); /* you could return non-zero here and kill the connection */ break; default: break; } return 0; } /* list of supported protocols and callbacks */ static struct libwebsocket_protocols protocols[] = { /* first protocol must always be HTTP handler */ { "http-only", /* name */ callback_http, /* callback */ sizeof (struct per_session_data__http), /* per_session_data_size */ 0, /* max frame size / rx buffer */ }, { "dumb-increment-protocol", callback_dumb_increment, sizeof(struct per_session_data__dumb_increment), 10, }, { "lws-mirror-protocol", callback_lws_mirror, sizeof(struct per_session_data__lws_mirror), 128, }, { NULL, NULL, 0, 0 } /* terminator */ }; void sighandler(int sig) { force_exit = 1; } static struct option options[] = { { "help", no_argument, NULL, 'h' }, { "debug", required_argument, NULL, 'd' }, { "port", required_argument, NULL, 'p' }, { "ssl", no_argument, NULL, 's' }, { "allow-non-ssl", no_argument, NULL, 'a' }, { "interface", required_argument, NULL, 'i' }, { "closetest", no_argument, NULL, 'c' }, #ifndef LWS_NO_DAEMONIZE { "daemonize", no_argument, NULL, 'D' }, #endif { "resource_path", required_argument, NULL, 'r' }, { NULL, 0, 0, 0 } }; int main(int argc, char **argv) { char cert_path[1024]; char key_path[1024]; int n = 0; int use_ssl = 0; struct libwebsocket_context *context; int opts = 0; char interface_name[128] = ""; const char *iface = NULL; #ifndef WIN32 int syslog_options = LOG_PID | LOG_PERROR; #endif unsigned int oldus = 0; struct lws_context_creation_info info; int debug_level = 7; #ifndef LWS_NO_DAEMONIZE int daemonize = 0; #endif memset(&info, 0, sizeof info); info.port = 7681; while (n >= 0) { n = getopt_long(argc, argv, "ci:hsap:d:Dr:", options, NULL); if (n < 0) continue; switch (n) { #ifndef LWS_NO_DAEMONIZE case 'D': daemonize = 1; #ifndef WIN32 syslog_options &= ~LOG_PERROR; #endif break; #endif case 'd': debug_level = atoi(optarg); break; case 's': use_ssl = 1; break; case 'a': opts |= LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT; break; case 'p': info.port = atoi(optarg); break; case 'i': strncpy(interface_name, optarg, sizeof interface_name); interface_name[(sizeof interface_name) - 1] = '\0'; iface = interface_name; break; case 'c': close_testing = 1; fprintf(stderr, " Close testing mode -- closes on " "client after 50 dumb increments" "and suppresses lws_mirror spam\n"); break; case 'r': resource_path = optarg; printf("Setting resource path to \"%s\"\n", resource_path); break; case 'h': fprintf(stderr, "Usage: test-server " "[--port=<p>] [--ssl] " "[-d <log bitfield>] " "[--resource_path <path>]\n"); exit(1); } } #if !defined(LWS_NO_DAEMONIZE) && !defined(WIN32) /* * normally lock path would be /var/lock/lwsts or similar, to * simplify getting started without having to take care about * permissions or running as root, set to /tmp/.lwsts-lock */ if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) { fprintf(stderr, "Failed to daemonize\n"); return 1; } #endif signal(SIGINT, sighandler); #ifndef WIN32 /* we will only try to log things according to our debug_level */ setlogmask(LOG_UPTO (LOG_DEBUG)); openlog("lwsts", syslog_options, LOG_DAEMON); #endif /* tell the library what debug level to emit and to send it to syslog */ lws_set_log_level(debug_level, lwsl_emit_syslog); lwsl_notice("libwebsockets test server - " "(C) Copyright 2010-2013 Andy Green <andy@warmcat.com> - " "licensed under LGPL2.1\n"); #ifdef EXTERNAL_POLL max_poll_elements = getdtablesize(); pollfds = malloc(max_poll_elements * sizeof (struct pollfd)); fd_lookup = malloc(max_poll_elements * sizeof (int)); if (pollfds == NULL || fd_lookup == NULL) { lwsl_err("Out of memory pollfds=%d\n", max_poll_elements); return -1; } #endif info.iface = iface; info.protocols = protocols; #ifndef LWS_NO_EXTENSIONS info.extensions = libwebsocket_get_internal_extensions(); #endif if (!use_ssl) { info.ssl_cert_filepath = NULL; info.ssl_private_key_filepath = NULL; } else { if (strlen(resource_path) > sizeof(cert_path) - 32) { lwsl_err("resource path too long\n"); return -1; } sprintf(cert_path, "%s/libwebsockets-test-server.pem", resource_path); if (strlen(resource_path) > sizeof(key_path) - 32) { lwsl_err("resource path too long\n"); return -1; } sprintf(key_path, "%s/libwebsockets-test-server.key.pem", resource_path); info.ssl_cert_filepath = cert_path; info.ssl_private_key_filepath = key_path; } info.gid = -1; info.uid = -1; info.options = opts; context = libwebsocket_create_context(&info); if (context == NULL) { lwsl_err("libwebsocket init failed\n"); return -1; } n = 0; while (n >= 0 && !force_exit) { struct timeval tv; gettimeofday(&tv, NULL); /* * This provokes the LWS_CALLBACK_SERVER_WRITEABLE for every * live websocket connection using the DUMB_INCREMENT protocol, * as soon as it can take more packets (usually immediately) */ if (((unsigned int)tv.tv_usec - oldus) > 50000) { libwebsocket_callback_on_writable_all_protocol(&protocols[PROTOCOL_DUMB_INCREMENT]); oldus = tv.tv_usec; } #ifdef EXTERNAL_POLL /* * this represents an existing server's single poll action * which also includes libwebsocket sockets */ n = poll(pollfds, count_pollfds, 50); if (n < 0) continue; if (n) for (n = 0; n < count_pollfds; n++) if (pollfds[n].revents) /* * returns immediately if the fd does not * match anything under libwebsockets * control */ if (libwebsocket_service_fd(context, &pollfds[n]) < 0) goto done; #else /* * If libwebsockets sockets are all we care about, * you can use this api which takes care of the poll() * and looping through finding who needed service. * * If no socket needs service, it'll return anyway after * the number of ms in the second argument. */ n = libwebsocket_service(context, 50); #endif } #ifdef EXTERNAL_POLL done: #endif libwebsocket_context_destroy(context); lwsl_notice("libwebsockets-test-server exited cleanly\n"); #ifndef WIN32 closelog(); #endif return 0; }
gpl-2.0
githubupttik/upttik
media/com_hikashop/js/otree.js
54385
/* oTree : Obscurelighty Project ( http://www.obscurelighty.com/ ) Author: Jerome GLATIGNY <jerome@obscurelighty.com> Copyright (C) 2010-2016 Jerome GLATIGNY This file is part of Obscurelighty. Obscurelighty 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. Obscurelighty 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 Obscurelighty. If not, see <http://www.gnu.org/licenses/>. The open source license for Obscurelighty and its modules permits you to use the software at no charge under the condition that if you use in an application you redistribute, the complete source code for your application must be available and freely redistributable under reasonable conditions. If you do not want to release the source code for your application, you may purchase a proprietary license from his author. */ /** oTree * version: 0.9.8 * release date: 2014-09-14 */ (function(){ window.oTrees = []; /** oNode * @param id The identifier number * @param pid The parent identifier number * @param state The node State * 0 - final node * 1 - directory node closed * 2 - directory node open * 3 - directory node dynamic (closed) * 4 - empty directory node * 5 - root final node * @param name The displayed name * @param value The internal value for the node * @param url The link url (href) * @param icon The overloaded icon */ var oNode = function(id, pid, state, name, value, url, icon, checked, noselection) { var t = this; t.id = id; t.pid = pid; t.state = state; t.name = name; t.value = value; t.url = url; t.checked = checked || false; t.noselection = noselection || 0; t._isLast = -1; t.children = []; t.icon = icon || null; }; oNode.prototype = { /** Add a Child */ add: function(id) { this.children[this.children.length] = id; }, /** Remove a Child */ rem: function(id) { var t=this,f=false; for(var i = 0; i < t.children.length; i++) { if(f == true) t.children[i-1] = t.children[i]; else if(t.children[i] == id) f = true; } if(f == true) t.children.splice(t.children.length-1, 1); } }; window.oNode = oNode; /** oTree * @param id * @param conf * @param callbackFct * @param data * @param render */ var oTree = function(id, conf, callbackFct, data, render) { if(window.oTrees[id]) window.oTrees[id].destroy(); var t = this; if(!conf) conf = {}; t.config = { rootImg: conf.rootImg || '/media/com_hikashop/images/otree/', useSelection: (conf.useSelection === undefined) || conf.useSelection, checkbox: conf.checkbox || false, tricheckbox: conf.tricheckbox || false, showLoading: conf.showLoading || false, loadingText: conf.loadingText || '' }; t.icon = { loading : 'loading.gif', folder : 'folder.gif', folderOpen : 'folderopen.gif', node : 'page.gif', line : 'line.gif', join : 'join.gif', joinBottom : 'joinbottom.gif', plus : 'plus.gif', plusBottom : 'plusbottom.gif', minus : 'minus.gif', minusBottom : 'minusbottom.gif', option : 'option.gif' }; t.lNodes = []; t.tmp = { trichecks: [] }; t.selectedNode = null; t.selectedFound = false; t.written = false; t.lNodes[0] = new oNode(0,-1); t.nbRemovedNodes = 0; t.iconWidth = 18; t.id = id; t.callbackFct = callbackFct; t.callbackSelection = null; t.callbackCheck = null; window.oTrees[id] = t; if(data) t.load(data); if(render) t.render(render); }; oTree.prototype = { /** Destroy an oTree instance */ destroy: function() { var t = this; window.oTrees[t.id] = null; t.icon = null; t.config = null; t.lNodes = null; t.callbackFct = null; t.callbackSelection = null; t.loadingNode = null; t.nbRemovedNodes = 0; e = document.getElementById(t.id + '_otree'); if(!e) e = document.getElementById(t.id); if(e) e.innerHTML = ''; t.id = null; }, /** Add a new Icon in the configuration * @param name * @param url */ addIcon: function(name, url) { this.icon[name] = url; }, /** Create a new Node * @param pid * @param state * @param name * @param value * @param url * @param icon * @return id */ add: function(pid, state, name, value, url, icon, checked, noselection) { var t=this,id=0; if(!t.lNodes[pid]) return -1; if(t.nbRemovedNodes == 0) { id = t.lNodes.length; } else { for(var i = t.lNodes.length; i >= 1; i--) { if(t.lNodes[i] == null) { id = i; i = 0; t.nbRemovedNodes--; break; } } } t.lNodes[id] = new oNode(id, pid, state, name, value, url, icon, checked, noselection); t.lNodes[pid].add(id); return id; }, /** Load a serialized tree * @param data * @param pid */ load: function(data, pid) { if(typeof(data) != "object") return; if(typeof(pid) == "undefined") pid = 0; var nId = 0, i, l = data.length; for(var id = 0; id < l; id++) { if(typeof(data[id]) == "object" && data[id]) { i = data[id]; nId = this.add(pid, i.status, i.name, i.value, i.url, i.icon, i.checked, i.noselection); if(i.data) { this.load(i.data, nId); } } } }, /** Create a new Node and insert it for a specific identifier * @param id * @param pid * @param state * @param name * @param value * @param url * @param icon */ ins: function(id, pid, state, name, value, url, icon, checked, noselection) { if(!this.lNodes[id]) { this.lNodes[id] = new oNode(id, pid, state, name, value, url, icon, checked, noselection); this.lNodes[pid].add(id); } }, /** Insert a Node * @param node */ insertNode: function(node) { this.lNodes[node.id] = node; this.lNodes[node.pid].add(node.id); }, /** Set a Node. * like "insertNode" but does not create the link with the parent. * @param node */ setNode: function(node) { this.lNodes[node.id] = node; }, /** Move a Node * @param node * @param dest */ moveNode: function(node,dest) { var t = this; if(typeof(node) == "number") node = t.get(node); if(typeof(dest) == "number") dest = t.get(dest); var old = t.lNodes[node.pid]; if(old) { old.rem(node.id); dest.add(node.id); node.pid = dest.id; t.update(old); t.update(dest); } }, /** Remove a Node * @param node The node to destroy (Node Object or Node Id) * @param update Call an update on his parent or not * @param rec Do not pass this parameter which is used for recursivity */ rem: function(node,update,rec) { var t=this; if(typeof(node) == "number") node = t.get(node); if(typeof(update) == "undefined") update = true; var p = t.get(node.pid); if(node && node.children.length > 0) { var o; for(var i = node.children.length - 1; i >= 0; i--) { o = node.children[i]; t.rem(o, false, true); t.lNodes[o] = null; } node.children = []; } if(!rec) { var id = node.id; if(p) p.rem(id); t.lNodes[id] = null; } t.nbRemovedNodes++; if(update && p) t.update(p); }, /** Update a Node * This function will call a "render" * @param node The node to update (Node Object or Node Id) * @return boolean */ update: function(node) { if(node) { if(typeof(node) == "number") node = this.get(node); return this.render(this.id + '_d' + node.id, node.id); } return this.render(); }, /** Render the tree or just a part of it * @param dest The render target (HTML Object or name of its ID) * @param start The Node Id for the render root * @return boolean */ render: function(dest, start) { var t = this, d = document, str = '', n; if(typeof(start) == "number") n = t.lNodes[start]; else n = t.lNodes[0]; t.processLast(); t.tmp.trichecks = []; if(t.written == true || dest) { if(typeof(dest) == "boolean" || !dest) dest = t.id; if(t.written == false) { t.written = true; t.id = dest; } str = t.rnodes(n); var e = d.getElementById(dest + '_otree'); if(!e) e = d.getElementById(dest); if(!e) return false; e.innerHTML = str; } else { str = '<div id="' + t.id + '_otree" class="oTree">' + t.rnodes(n) + '</div>'; d.write(str); t.written = true; } if(t.config.tricheckbox && t.tmp.trichecks.length > 0) { var id, c; for(var i = t.tmp.trichecks.length - 1; i >= 0; i--) { id = t.tmp.trichecks[i]; c = d.getElementById(t.id+'_c'+id); if(c) c.indeterminate = true; } } t.tmp.trichecks = []; return true; }, /** Internal function */ rnodes: function(pNode) { var t=this,str = ''; if(!pNode) return str; for(var i = 0; i < pNode.children.length; i++) { var n = pNode.children[i]; if(t.lNodes[n]) str += t.rnode(t.lNodes[n]); } return str; }, /** Internal function */ rnode: function(node) { var t=this,str = '<div class="oTreeNode">', style = '', ret = '', toFind = node.pid, found = true; if(toFind > 0) { var white = 0; while(found) { found = false; if(toFind > 0 && toFind < t.lNodes.length && t.lNodes[toFind]) { if(t.lNodes[toFind]._isLast == -1) t.lNodes[toFind]._isLast = t.isLast(t.lNodes[toFind])?1:0; if(t.lNodes[toFind]._isLast == 1) { white++; if(white == 6) { ret = '<div class="e'+white+'"></div>' + ret; white = 0; } } else { if(white > 0) ret = '<div class="e'+white+'"></div>' + ret; white = 0; ret = '<img src="' + t.config.rootImg + t.icon.line + '" alt=""/>' + ret; } found = true; toFind = t.lNodes[toFind].pid; } } if(white > 0) ret = '<div class="e'+white+'"></div>' + ret; } str += ret; // Cursor var img, last = (node._isLast == 1); if(node.state == 0 || node.state == 4) { img = t.icon.join; if(last) img = t.icon.joinBottom; str += '<img src="' + t.config.rootImg + img + '" alt=""/>'; } else if(node.state == 1 || node.state == 3) { img = t.icon.plus; if(last) img = t.icon.plusBottom; str += '<a href="#" onclick="window.oTrees.' + t.id + '.s(' + node.id + ');return false;"><img id="'+t.id+'_j'+node.id+'" src="' + t.config.rootImg + img + '" alt=""/></a>'; } else if(node.state == 2) { img = t.icon.minus; if(last) img = t.icon.minusBottom; str += '<a href="#" onclick="window.oTrees.' + t.id + '.s(' + node.id + ');return false;"><img id="'+t.id+'_j'+node.id+'" src="' + t.config.rootImg + img + '" alt=""/></a>'; } if(t.config.checkbox && !node.noselection) { var attr = '', chkName = t.config.checkbox; if(typeof(chkName) == "string") { if(chkName == "-") chkName = ""; else if(chkName.substring(-1) != ']') chkName += '[]'; } else chkName = t.id+'[]'; if(node.checked) { if(t.config.tricheckbox && node.checked === 2) t.tmp.trichecks[t.tmp.trichecks.length] = node.id; else attr = ' checked="checked"'; } str += '<input type="checkbox" id="'+t.id+'_c'+node.id+'" onchange="window.oTrees.' + t.id + '.chk(' + node.id + ',this.checked);" name="' + chkName + '" value="' + node.value + '"' + attr + '/>'; } // Icon str += '<img id="' + t.id + '_i' + node.id + '" alt="" src="' + t.config.rootImg; var name = node.name; if(t.config.useSelection && node.url) name = '<a id="'+t.id+'_s'+node.id+'" class="node" href="' + node.url + '" onclick="window.oTrees.' + t.id + '.sel(' + node.id + ');">' + node.name + '</a>'; else if(node.url) name = '<a id="'+t.id+'_s'+node.id+'" class="node" href="' + node.url + '">' + node.name + '</a>'; else if((t.config.checkbox || t.config.useSelection) && !node.noselection) name = '<a id="'+t.id+'_s'+node.id+'" class="node" href="#" onclick="window.oTrees.' + t.id + '.sel(' + node.id + ');return false;">' + node.name + '</a>'; else name = '<span class="node">' + node.name + '</span>'; if(node.state == 0 || node.state == 5) { if(node.icon == null) str += t.icon.node + '"/>' + name; else str += t.icon[node.icon] + '"/>' + name; } else if(node.state == 1 || node.state == 3 || node.state == 4) { if(node.icon == null) str += t.icon.folder + '"/>' + name; else str += t.icon[node.icon] + '"/>' + name; style = 'style="display:none;"'; } else if(node.state == 2) { if(node.icon == null) str += t.icon.folderOpen + '"/>' + name; else str += t.icon[node.icon] + '"/>' + name; } str += '</div>'; if(node.state > 0) str += '<div id="' + t.id + '_d' + node.id + '" class="clip" ' + style + '>' + t.rnodes(node) + '</div>'; return str; }, /** Switch Node * Open or Close a Directory Node * @param node The node to switch (Node Object or Node Id) */ s: function(node) { if(typeof(node) == "number") node = this.get(node); if(node.state == 2) this.c(node); else this.o(node); }, /** Open a Node * @param node The node to open (Node Object or Node Id) */ o: function(node) { var t = this; if(typeof(node) == "number") node = t.get(node); // Closed Or Dynamic if(node && (node.state == 1 || node.state == 3)) { e = document.getElementById(t.id + '_d' + node.id); e.style.display = ''; // Dynamic if(node.state == 3) { node.children = []; if(t.config.showLoading) { if(!t.loadingNode) { t.loadingNode = new oNode(0,node.id,0,t.config.loadingText,null,null,'loading'); t.loadingNode._isLast = 1; } else t.loadingNode.pid = node.id; e.innerHTML = t.rnode(t.loadingNode); } if(t.callbackFct) t.callbackFct(this, node, e); } if(node.icon == null) { e = document.getElementById(t.id + '_i' + node.id); e.src = t.config.rootImg + t.icon.folderOpen; } e = document.getElementById(t.id + '_j' + node.id); if(t.isLast(node)) e.src = t.config.rootImg + t.icon.minusBottom; else e.src = t.config.rootImg + t.icon.minus; node.state = 2; } }, /** Close a Node * @param node The node to close (Node Object or Node Id) */ c: function(node) { if(typeof(node) == "number") node = this.get(node); // Open if(node && node.state == 2) { var t=this,d=document; e = d.getElementById(t.id + '_d' + node.id); e.style.display = 'none'; if(node.icon == null) { e = d.getElementById(t.id + '_i' + node.id); e.src = t.config.rootImg + t.icon.folder; } e = d.getElementById(t.id + '_j' + node.id); if(t.isLast(node)) e.src = t.config.rootImg + t.icon.plusBottom; else e.src = t.config.rootImg + t.icon.plus; node.state = 1; } }, /** Open To * @param node The node to open to... (Node Object or Node Id) */ oTo: function(node) { if(typeof(node) == "number") node = this.get(node); if(node) { var t=this,toOpId = node.pid; while(toOpId > 0 && toOpId < t.lNodes.length) { this.o(t.lNodes[toOpId]); toOpId = t.lNodes[toOpId].pid; } } }, /** Make a Selection * @param id The Node Id to select (could be a node object) */ sel: function(id) { if(id === null) return; if(typeof(id) != "number") id = id.id; var t=this,d=document,cn = t.lNodes[id]; if(!cn) return; if(!t.config.useSelection && !t.config.checkbox) return; if(t.config.checkbox) { t.chk(cn,-1); } if(!t.config.useSelection) return; if(t.selectedNode != id) { var e, previous = t.selectedNode; if(t.selectedNode || t.selectedNode == 0) { e = d.getElementById(t.id + '_s' + t.selectedNode); if(e) e.className = "node"; } e = d.getElementById(t.id + '_s' + id); if(e) e.className = "nodeSel"; t.selectedNode = id; if(t.callbackSelection) t.callbackSelection(this, t.selectedNode, previous); } else { var e = d.getElementById(t.id + '_s' + id); if(e) e.className = "nodeSel"; } }, /** * */ chk: function(id, value, call, fromP) { if(id === null) return; if(typeof(id) == "object") id = id.id; if(!this.config.checkbox) return; var t=this,d=document,cn=t.lNodes[id]; if(!cn) return; var oldState = cn.checked; if(typeof(value) == "number" && value < 0) { if(cn.checked == 2) cn.checked = true; else cn.checked = !cn.checked; } else cn.checked = value; var e = d.getElementById(t.id+'_c'+id); if(e) { e.checked = cn.checked; if(!t.config.tricheckbox) e.indeterminate = false; if(t.config.tricheckbox && oldState != cn.checked) { e.indeterminate = false; if(value === 2) { e.checked = false; e.indeterminate = true; cn.checked = 2; } else { // Check/uncheck all children for(var i = cn.children.length - 1; i >= 0; i--) { t.chk(cn.children[i], cn.checked, call, true); } } if(fromP === undefined) { // Check/uncheck parent if necessary var p = t.lNodes[cn.pid], o = null, cpt = 0; if(p) { for(var i = p.children.length - 1; i >= 0; i--) { o = t.lNodes[p.children[i]]; if(o && o.checked && o.checked === true) { cpt++; } } if(cpt == p.children.length || cpt == 0) { t.chk(p, cn.checked, call); } else { t.chk(p, 2, call); } } } } } if((call === undefined || call === null || call) && t.callbackCheck) t.callbackCheck(this, id, value); }, /** * */ chks: function(ids,call,useId) { var t = this; if(!t.config.checkbox) return; if(useId === undefined) useId = true; if(call === undefined) call = false; if(typeof(ids) == "string") { // Check all if(ids == "*") { for(var i = 0; i < t.lNodes.length; i++) { if(t.lNodes[i] && !t.lNodes[i].checked) t.chk(t.lNodes[i],true,call); } return; } ids = ids.split(","); } for(var i = 0; i < t.lNodes.length; i++) { if(t.lNodes[i] && t.lNodes[i].checked) t.chk(t.lNodes[i],false,call); } if(useId) { for(var j = ids.length -1; j >= 0; j--) { var v = parseInt(ids[j]); t.chk(v,true,call); } } else { for(var j = ids.length -1; j >= 0; j--) { for(var i = 0; i < t.lNodes.length; i++) { if(t.lNodes[i] && t.lNodes[i].value == ids[j]) { t.chk(i,true,call); break; } } } } }, /** * */ getChk: function() { var t = this, ret = []; if(!t.config.checkbox) return false; for(var i = 0; i < t.lNodes.length; i++) { if(t.lNodes[i] && t.lNodes[i].checked && t.lNodes[i].checked === true && t.lNodes[i].value) ret.push(t.lNodes[i].value); } return ret; }, /** Find a Node * @param value The value to found * @param mode The mode for node state * [null] - all nodes * 0 - Final nodes * 1 - Directory nodes * @return the first node object which matched */ find: function(value, mode) { if(typeof(mode) == "undefined") mode = -1; var t = this; for(var i = 0; i < t.lNodes.length; i++) { if(t.lNodes[i] && t.lNodes[i].value == value) { if(mode == -1) return t.lNodes[i]; if(mode == 0 && (t.lNodes[i].state == 0 || t.lNodes[i].state == 5)) return t.lNodes[i]; if(mode == 1 && t.lNodes[i].state >= 1 && t.lNodes[i].state != 5) return t.lNodes[i]; } } return null; }, /** Empty a directory * @param node The node to empty (Node Object or Node Id) */ emptyDirectory: function(node) { if(typeof(node) == "number") node = this.get(node); if(node.state == 1 || node.state == 2 || node.state == 3) { var t = this, d = document, e = d.getElementById(t.id + '_j' + node.id), a = e.parentNode; var src = t.config.rootImg + t.icon.join; if(node._isLast == 1) src = t.config.rootImg + t.icon.joinBottom; a.parentNode.replaceChild(e, a); e.src = src; node.state = 4; if(node.icon == null) { e = d.getElementById(t.id + '_i' + node.id); if(!e) return; e.src = t.config.rootImg + t.icon.folder; } e = d.getElementById(t.id + '_d' + node.id); if(!e) return; e.style.display = 'none'; e.innerHTML = ''; if(node && node.children.length > 0) { var o; for(var i = node.children.length - 1; i >= 0; i--) { o = node.children[i]; t.rem(o, false); t.lNodes[o] = null; } } node.children = []; } }, /** Get a node * @param id The node id * @return the node object */ get: function(id) { if(id >= 0 && id < this.lNodes.length && this.lNodes[id]) { try { return this.lNodes[id]; } catch(e) { return null; } } return null; }, /** Internal function */ isLast: function(node) { try { var pChildren = this.lNodes[node.pid].children; return (pChildren[pChildren.length - 1] == node.id); } catch(e) {} return true; }, /** Internal function * currently unused. Deprecated? */ cleanLast: function() { for(var i = this.lNodes.length - 1; i >= 0; i--) this.lNodes[i]._isLast = -1; }, /** Internal function */ processLast: function() { var t=this,n; for(var i = t.lNodes.length - 1; i >= 0; i--) { if(t.lNodes[i] && t.lNodes[i].children.length > 0) { n = t.lNodes[i].children[ t.lNodes[i].children.length - 1 ]; t.lNodes[n]._isLast = 1; for(var j = t.lNodes[i].children.length - 2; j >= 0; j--) { t.lNodes[ t.lNodes[i].children[ j ]]._isLast = 0; } } } }, /** * */ deep: function(node, max) { if(typeof(node) == "number") node = this.get(node); if(node == null) return -1; if(typeof(max) == "undefined") max = 100; var ret = 0, toFind = node.pid; if(toFind == -1) return ret; while(toFind > 0 && this.lNodes[toFind]) { ret++; toFind = this.lNodes[toFind].pid; if(ret >= max) return ret; } return ret; }, /** * */ search: function(text) { var t=this,d=document,r=null,e=null,pid=0; if(text) { r = new RegExp(text,"i"); for(var i = 0; i < t.lNodes.length; i++) { if(t.lNodes[i]) t.lNodes[i].search = -1; } for(var i = 0; i < t.lNodes.length; i++) { if(t.lNodes[i]) { if(r.test(t.lNodes[i].name)) { if(t.lNodes[i].search <= 0) { t.lNodes[i].search = 2; pid = t.lNodes[i].pid; while(pid > 0 && t.lNodes[pid] && t.lNodes[pid].search <= 0) { t.lNodes[pid].search = 1; pid = t.lNodes[pid].pid; } } else { t.lNodes[i].search = 2; } } else { if(t.lNodes[i].search < 0) t.lNodes[i].search = 0; } } } } for(var i = 0; i < t.lNodes.length; i++) { if(t.lNodes[i]) { e = d.getElementById(t.id + '_s' + t.lNodes[i].id); if(!text) { t.lNodes[i].search = null; if(e) { e.parentNode.style.display = ''; e.className = "node"; } } else { if(e) { e.className = "node"; if(t.lNodes[i].search > 0) { e.parentNode.style.display = ''; if(t.lNodes[i].search > 1) e.className = "nodeSel"; } else e.parentNode.style.display = 'none'; } } } } } }; oTree.version = 20140914; if(!window.oTree || window.oTree.version < oTree.version) window.oTree = oTree; })(); /** oList * version: 0.1.2 * release date: 2015-08-07 */ (function(){ window.oLists = []; /** oTree * @param id * @param conf * @param callbackFct * @param data * @param render */ var oList = function(id, conf, callbackFct, data, render) { if(window.oLists[id]) window.oLists[id].destroy(); var t = this; if(!conf) conf = {}; t.config = { hideBlocked: conf.hideBlocked || false, table: conf.table || false, defaultColumn: conf.defaultColumn || false, displayFormat: conf.displayFormat || false, gradientLoad: conf.gradientLoad || false }; t.written = false; t.id = id; t.callbackFct = callbackFct; t.callbackSelection = null; t.callbackScroll = null; t.highlighted = null; t._fct = {}; window.oLists[id] = t; if(data) t.load(data); if(render) t.render(render); }; oList.prototype = { /** Destroy an oTree instance */ destroy: function() { var t = this, d = document; window.oLists[t.id] = null; t.config = null; t.lData = []; t.callbackFct = null; t.callbackSelection = null; t.callbackScroll = null; t.highlighted = null; t.deinitScroll(); t._fct = {}; e = d.getElementById(t.id + '_olist'); if(!e) e = d.getElementById(t.id); if(e) e.innerHTML = ''; t.id = null; }, /** Load a serialized list * @param data * @param pid */ load: function(data) { if(typeof(data) != "object") return false; var t = this; t.lData = []; for(var d in data) { if(data.hasOwnProperty(d)) t.lData[ t.lData.length ] = t.getData(d, data[d]); } t.sort(); t.highlighted = null; return (t.lData.length > 0); }, /** * */ add: function(key, name) { this.lData[ this.lData.length ] = this.getData(key, name); }, /** * */ getData: function(key, data) { var t = this, o = {key: key}; if(!t.config.table) { o.name = data; return o; } for(var h in t.config.table) { if(!t.config.table.hasOwnProperty(h)) continue; o[h] = ''; if(data[h]) o[h] = data[h]; } return o; }, /** * */ sort: function(byKey) { var t = this; if(!t.lData || t.lData.length == 0) return false; if(byKey) { t.lData.sort(function(a,b){ var x = a.key.toLowerCase(), y = b.key.toLowerCase(); return x < y ? -1 : ((x > y) ? 1 : 0); }); return true; } if(!t.config.table) { t.lData.sort(function(a,b){ var x = a.name.toLowerCase(), y = b.name.toLowerCase(); return x < y ? -1 : ((x > y) ? 1 : 0); }); return true; } return false; }, /** Render the tree or just a part of it * @param dest The render target (HTML Object or name of its ID) * @param start The Node Id for the render root * @return boolean */ render: function(dest) { var t = this, d = document, str = ''; if(t.written == true || dest) { if(typeof(dest) == "boolean" || !dest) dest = t.id; if(t.written == false) { t.written = true; t.id = dest; } str = (!t.config.table) ? t.rlist() : t.rtable(); var e = d.getElementById(dest + '_olist'); if(!e) e = d.getElementById(dest); if(!e) return false; e.innerHTML = str; } else { str = '<div id="' + t.id + '_olist" class="oList">' + ((!t.config.table) ? t.rlist() : t.rtable()) + '</div>'; d.write(str); t.written = true; } if(t.config.gradientLoad) t.initScroll(); return true; }, rlist: function() { var t = this, l = t.lData.length, n = null, str = '<ul>'; for(var i = 0; i < l; i++) { n = t.lData[i]; if(n && !n.hidden && (!n.block || !t.config.hideBlocked)) { if(t.highlighted === null || t.highlighted != i) str += '<li>'; else str += '<li class="oListSelected">'; if(n.block) str += '<span>' + (n.display ? n.display : n.name) + '</span></li>'; else str += '<a href="#" onclick="window.oLists.' + t.id + '.sel(' + i + ');return false;">' + (n.display ? n.display : n.name) + '</a></li>'; } } if(l > 0 && t.config.gradientLoad) str += '<li class="oListLoadMore"><span></span></li>'; str += '<ul>'; return str; }, rtable: function() { var t = this, l = t.lData.length, n = null, str = '<table class="oListTable"><thead><tr>', extraClass = ''; for(var h in t.config.table) { if(!t.config.table.hasOwnProperty(h)) continue; str += '<th>'+t.config.table[h]+'</th>'; } str += '</tr></thead><tbody>'; for(var i = 0; i < l; i++) { n = t.lData[i]; if(n && !n.hidden && (!n.block || !t.config.hideBlocked)) { extraClass = (t.highlighted === null || t.highlighted != i) ? '' : ' oListSelected'; if(n.block) str += '<tr class="oListBlocked">'; else str += '<tr onclick="window.oLists.' + t.id + '.sel(' + i + ');return false;" class="oListLine'+extraClass+'">'; for(var h in t.config.table) { if(!t.config.table.hasOwnProperty(h)) continue; str += '<td>' + n[h] + '</td>'; } str += '</tr>'; } } if(l > 0 && t.config.gradientLoad) str += '<tr class="oListBlocked oListLoadMore"><td colspan="'+t.config.table.length+'"></td></tr>'; str += '</tbody></table>'; return str; }, initScroll: function(fct) { var t = this; if(!t.config.gradientLoad || t._fct['scroll']) return; if(!t.callbackScroll && fct !== undefined) t.callbackScroll = fct; if(!t.callbackScroll) return; var d = document, el = d.getElementById(t.id + '_olist'); if(!el) return; t._lastScroll = 0; t._fct['scroll'] = window.Oby.addEvent(el, 'scroll', function(evt) { if(el.scrollHeight > t._lastScroll && el.scrollTop >= (el.scrollHeight - el.offsetHeight - 25)) { if(t.callbackScroll) t.callbackScroll(t); t._lastScroll = el.scrollHeight; } }); }, deinitScroll: function() { var t = this; if(t.config && t.config.gradientLoad) t.config.gradientLoad = false; if(!t._fct['scroll']) return; t.callbackScroll = null; var d = document, el = d.getElementById(t.id + '_list'); if(!el) return; window.Oby.removeEvent(el, t._fct['scroll']); }, /** Get a node * @param id The node id * @return the node object */ get: function(id) { if(id >= 0 && id < this.lData.length && this.lData[id]) { try { return this.lData[id]; } catch(e) { return null; } } return null; }, /** Make a Selection * @param id The Node Id to select (could be a node object) */ sel: function(id) { if(id === null || id === undefined) return; var t=this,d=document,cn=t.lData[id]; if(!cn) return; if(t.config.table) { if(t.config.displayFormat) cn = window.oNamebox.format(cn, t.config.displayFormat); else if(t.config.defaultColumn) cn = cn[t.config.defaultColumn]; } if(t.callbackSelection) t.callbackSelection(this, id, cn); }, /** * */ block: function(value) { var t = this, p = false, m = (typeof(value) == 'object'), l = null; if(m) l = (value.length-1); for(var i = t.lData.length - 1; i >= 0; i--) { if(!m) { if(t.lData[i].key == value) { t.lData[i].block = true; p = true; } } else { for(var j = l; j >= 0; j--) { if(t.lData[i].key == value[j]) { t.lData[i].block = true; p = true; j = -1; } } } } if(p) t.render(); }, /** * */ unblock: function(value) { var t = this, p = false; for(var i = t.lData.length - 1; i >= 0; i--) { if(value === true || t.lData[i].key == value) { delete t.lData[i].block; p = true; } } if(p) t.render(); }, /** * */ find: function(text) { var t=this; text = text.toLowerCase(); for(var i = t.lData.length - 1; i >= 0; i--) { if(t.lData[i].name.toLowerCase() == text) return i; } return null; }, /** * */ search: function(text) { var t=this,d=document,r=null,e=null,dataLng=0; if(text) { text = text.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); r = new RegExp("(" + text + ")","i"); for(var i = t.lData.length - 1; i >= 0; i--) { if(!t.lData[i]) continue; if(!t.config.table) { if(r.test(t.lData[i].name)) { t.lData[i].hidden = false; dataLng++; t.lData[i].display = t.lData[i].name.replace(r, '<em>$1</em>'); } else { t.lData[i].hidden = true; delete t.lData[i].display; } } else { var test = false; for(var v in t.lData[i]) { if(v != 'key' && t.lData[i].hasOwnProperty(v) && typeof(t.lData[i][v]) == 'string') test = r.test(t.lData[i][v]); if(test) break; } if(test) { t.lData[i].hidden = false; dataLng++; } else { t.lData[i].hidden = true; delete t.lData[i].display; } } } } else { for(var i = t.lData.length - 1; i >= 0; i--) { if(t.lData[i]) { delete t.lData[i].display; delete t.lData[i].hidden; } } dataLng = null; } t._dataLng = dataLng; t.highlighted = null; t.render(); }, highlightSet: function(id) { var t=this; if(t.highlighted === id) return true; if(id === null) { t.highlighted = null; return true; } if(!t.lData[id] || t.lData[id].hidden) return false; t.highlighted = id; t.render(); // Force the ajax loading when we select the last element in the list if(t.lData.length > 5 && id == (t.lData.length - 1) && t.config.gradientLoad) window.oNameboxes[t.id].loadMore(t); var d = document, container = d.getElementById(t.id + '_olist'), el = null, e = null; if(!container) e = d.getElementById(t.id); if(!container) return true; el = container.firstChild; if(t.config.table) el = el.lastChild.firstChild; for(var i = el.children.length - 1; i >= 0; i--) { e = el.children[i]; if(e.className != 'oListSelected') continue; if(container.scrollTop > e.offsetTop) container.scrollTop = e.offsetTop; else if((container.scrollTop + container.clientHeight) < (e.offsetTop + e.clientHeight)) container.scrollTop = e.offsetTop + e.clientHeight - container.clientHeight; } return true; }, highlightGet: function() { return this.highlighted; }, highlightMove: function(inc, cpt) { var t=this,init=false,min=null; if(t.highlighted === null) { if(inc > 0) t.highlighted = -1; else t.highlighted = t.lData.length; init = true; } if(cpt !== undefined && cpt > 0) cpt--; else cpt = 0; for(var i = t.highlighted + inc; i >= 0 && i < t.lData.length; i += inc) { if(!t.lData[i] || t.lData[i].hidden || t.lData[i].block) continue; if(cpt-- > 0) { min = i; continue; } return t.highlightSet(i); } if(min !== null) return t.highlightSet(min); if(init) t.highlighted = null; return false; }, highlightNext: function(cpt) { return this.highlightMove(1,cpt); }, highlightPrevious: function(cpt) { return this.highlightMove(-1,cpt); }, }; oList.version = 20150807; if(!window.oList || window.oList.version < oList.version) window.oList = oList; })(); /** * oNamebox * version: 0.1.2 * release date: 2015-08-07 */ (function(){ window.oNameboxes = []; /** * * @param {Object} id * @param {Object} data * @param {Object} conf */ var oNamebox = function(id, data, conf) { var t = this; t.id = id; t.data = data; t.cache = {}; conf = conf || {}; t._conf = conf; t._fct = {}; t._ctrlKey = false; t.config = { add: conf.add || false, add_url: conf.add_url || '', default_text: conf.default_text || '', default_value: conf.default_value || '', img_dir: conf.img_dir || '', onlyNode: conf.onlyNode || false, map: conf.map || '', min: conf.min || 3, sort: conf.sort || false, tree_url: conf.tree_url || '', tree_key: conf.tree_key || 'NODEID', url_keyword: conf.url_keyword || 'SEARCH', url_pagination: conf.url_pagination || 'PAGE', olist: conf.olist || {} }; t.mode = conf.mode || 'list'; t.multiple = (conf.multiple === undefined || conf.multiple === true); t.content = null; t.url = conf.url || ''; t.cb = {}; t.init(); window.oNameboxes[id] = t; }; /** * */ oNamebox.deleteId = function(id) { var d = document, el = id; if(typeof(id) == "string") el = d.getElementById(id); if(!el) return; el.parentNode.removeChild(el); }; oNamebox.cancelEvent = function(e) { return window.Oby.cancelEvent(e); }; /** * */ oNamebox.treeCbFct = function(t,url,keyword,tree,node,ev) { var o = window.Oby; o.xRequest(url.replace(keyword, node.value), null, function(xhr,params) { var json = o.evalJSON(xhr.responseText); if(json.length == 0) return tree.emptyDirectory(node); var s = json.length, n; for(var i = 0; i < s; i++) { n = json[i]; tree.add(node.id, n.status, n.name, n.value, n.url, n.icon); } tree.update(node); if(tree.selectOnOpen) { n = tree.find(tree.selectOnOpen); if(n) tree.sel(n); tree.selectOnOpen = null; } }, function(xhr, params) { tree.add(node.id, 0, "error"); tree.update(node); } ); return false; }; /** * */ oNamebox.format = function(obj, format) { var m = format.match(/{[_a-zA-Z0-9]+}/g); if(!m) return obj; var ret = ''+format, r = null, v = '', k = ''; for(var i = m.length - 1; i >= 0; i--) { r = new RegExp(m[i], 'g'); k = m[i].replace(/{|}/g,''); v = ''; if(obj[k]) v = obj[k]; ret = ret.replace(r, v); } return ret; }; /** * */ oNamebox.prototype = { /** * */ init: function() { var t = this, d = document; if(t.mode == 'list') { t.container = d.getElementById(t.id+'_olist'); t.content = new window.oList(t.id,t.config.olist,null,t.data,false); t.content.callbackSelection = function(ol,id,value) { var d = document, node = ol.get(id); if(node.key && node.name) t.set(node.name, node.key); else if(t.content.config.table && node.key) t.set(value, node.key); var c = d.getElementById(t.id+"_olist"); if(c) c.style.display = "none"; c = d.getElementById(t.id+"_text"); if(c) c.value = ""; ol.sel(null); if(t._ctrlKey && c) c.focus(); }; if(t.config.olist && t.config.olist.gradientLoad) t.content.callbackScroll = function(el) { t.loadMore(el); }; } else { t.container = d.getElementById(t.id+'_otree'); var options = {rootImg:(t.config.img_dir+'otree/'), showLoading:false}; t.content = new window.oTree(t.id, options, null, t.data, false); t.content.addIcon("world","world.png"); if(t.config.tree_url) { t.content.callbackFct = function(tree,node,ev) { return window.oNamebox.treeCbFct(t.content, t.config.tree_url, t.config.tree_key, tree, node, ev); }; } t.content.callbackSelection = function(tree,id) { var d = document, node = tree.get(id); if(!t.config.onlyNode || node.state == 0) { if(node.value && node.name) t.set(node.name, node.value); } else if(node.state >= 1 && node.state <= 4) { tree.s(node); return; } var c = d.getElementById(t.id+"_otree"); if(c) c.style.display = "none"; c = d.getElementById(t.id+"_text"); if(c) c.value = ""; tree.sel(0); if(t._ctrlKey && c) c.focus(); }; } t.content.render(true); t.initKeyboard(); if(t.config.sort) { if(!window.hkjQuery && !window.jQuery) return; if(!window.hkjQuery) window.hkjQuery = window.jQuery; hkjQuery(document).ready(function($) { $('#'+t.id).sortable({ cursor: "move", items: "div", stop: function(event, ui) { $("#"+t.id+" .nametext").appendTo("#"+t.id); $("#"+t.id+"hikaclear").appendTo("#"+t.id); } }); $("#"+t.id).disableSelection(); }); } }, initKeyboard: function() { var t = this, d = document, w = window, o = w.Oby, c = t.content; t._fct['doc.keydown'] = o.addEvent(d, 'keydown', function(evt) { if(!evt) var evt = w.event; if(evt.keyCode == 17) t._ctrlKey = true; }); t._fct['doc.keyup'] = o.addEvent(d, 'keyup', function(evt) { if(!evt) var evt = w.event; if(evt.keyCode == 17) t._ctrlKey = false; }); var input_elem = d.getElementById(t.id + "_text"); if(t.mode != 'list' || !input_elem) return; t._fct['keypress'] = o.addEvent(input_elem, 'keypress', function(evt) { if(!evt) var evt = w.event; if(evt.keyCode == 13) o.cancelEvent(evt); }); t._fct['keydown'] = o.addEvent(input_elem, 'keydown', function(evt) { if(!evt) var evt = w.event; if(evt.keyCode == 8 && t.multiple && (t._inputEmpty === undefined || t._inputEmpty === null)) t._inputEmpty = (this.value == ''); else if(evt.keyCode == 13) t._inputEnter = true; else if(evt.keyCode == 33 || evt.keyCode == 34) o.cancelEvent(evt); }); t._fct['keyup'] = o.addEvent(input_elem, 'keyup', function(evt) { if(!evt) var evt = w.event; if(evt.keyCode == 13) { // Enter if(!t._inputEnter) return; delete t._inputEnter; o.cancelEvent(evt); var id = c.highlightGet(), node = null; if(id == null && input_elem.value != '') id = t.content.find(input_elem.value); if(id === null && ((t.content._dataLng !== null && t.content._dataLng == 1) || t.content.lData.length == 1)) { for(var i = 0; i < t.content.lData.length - 1; i++) { if(!t.content.lData[i] || t.content.lData[i].block || t.content.lData[i].hidden) continue; id = i; break; } } if(id !== null) node = c.get(id); if(id !== null && node) { if(!node.block && !node.hidden && node.key && node.name) { t.set(node.name, node.key); } else if(!node.block && !node.hidden && c.config.table && node.key) { var value = node.value; if(c.config.displayFormat) value = w.oNamebox.format(node, c.config.displayFormat); else if(t.config.defaultColumn) value = node[c.config.defaultColumn]; t.set(value, node.key); } if(input_elem.value != '') { input_elem.value = ''; t.content.search(null); } } else if(input_elem.value != '' && t.config.add_url) { var add = d.getElementById(t.id + '_add'); if(add) t.create(add.firstChild, true); } } else if(evt.keyCode == 40) { // Down c.highlightNext(); o.cancelEvent(evt); } else if(evt.keyCode == 38) { // Up c.highlightPrevious(); o.cancelEvent(evt); } else if(evt.keyCode == 34) { // Page down c.highlightNext(5); o.cancelEvent(evt); } else if(evt.keyCode == 33) { // Page up c.highlightPrevious(5); o.cancelEvent(evt); } else if(evt.keyCode == 8 && t.multiple) { // backspace if(!t._inputEmpty) { t._inputEmpty = null; return; } t._inputEmpty = null; if(input_elem.value != '') return; // If multi, delete the last element var values = t.get(); if(!values && !values.length) return; var v = values.pop(), cur = d.getElementById(t.id + "-" + v.value); if(cur && cur.firstChild) t.unset(cur.firstChild, v.value); o.cancelEvent(evt); } }); }, /** * */ set: function(name, value) { var t = this, d = document; if(t.multiple) { var blocks = {map: (t.config.map + "[]"), key: value, name: name}, cur = d.getElementById(t.id + "-" + value); if(t.config.map == '') blocks['map'] = ''; if(!cur) t.dup(t.id + "tpl", blocks, t.id + "-" + value); if(t.mode == 'list') t.content.block(value); } else { var v = d.getElementById(t.id+"_valuehidden"), n = d.getElementById(t.id+"_valuetext"), a = d.getElementById(t.id+'_add'); if(v) v.value = value; if(n) n.innerHTML = name; if(a) a.style.display = 'none'; } t.cache.lastSearch = false; if(t.modifiedData) { t.loadData(false); t.modifiedData = false; } t.fire('set', {el:t,name:name,value:value}); }, /** * */ unset: function(el, value) { var t = this, w = window; w.oNamebox.deleteId(el.parentNode); if(t.multiple && t.mode == 'list') t.content.unblock(value); t.fire('unset', {el:t,obj:el,value:value}); }, /** * */ get: function() { var t = this, d = document, ret = null; if(t.multiple) { ret = []; var tplElem = d.getElementById(t.id + "tpl"); if(!tplElem) return ret; var container = tplElem.parentNode, elems = container.getElementsByTagName('input'); for(var i = 0; i < elems.length; i++) { if(elems[i].type.toLowerCase() != 'hidden' || elems[i].name.substring(0,1) == '{') continue; var txt = elems[i].nextSibling, c = ''; if(txt && txt.nodeType == 3) { if(txt.textContent) c = txt.textContent; else if(txt.nodeValue) c = txt.nodeValue; else if(txt.data) c = txt.data; } ret[ ret.length ] = { 'name': c, 'value': elems[i].value }; } } else { ret = {'value':null,'name':null}; var v = d.getElementById(t.id+"_valuehidden"), n = d.getElementById(t.id+"_valuetext"); if(v) ret.value = v.value; if(n) ret.name = n.innerHTML; } return ret; }, /** * */ changeUrl: function(url, others) { var t = this; if(t.url == url) return false; t.url = url; if(others !== undefined && others) { if(others.tree) t.config.tree_url = others.tree; if(others.add) t.config.add_url = others.add; } t.clear(); if(t.content && t.mode == 'list') { t.content.load({}); window.Oby.xRequest( t.url.replace(t.config.url_keyword, ''), {}, function(xhr){ data = window.Oby.evalJSON(xhr.responseText); if(data) { t.content.load(data); t.data = data; } },function(xhr){}); } t.fire('changeUrl', {el:t,url:url,others:others}); }, /** * */ destroy: function() { var t = this, w = window, d = document, input_elem = d.getElementById(t.id + "_text"); for(var f in t._fct) { if(!t._fct.hasOwnProperty(f)) continue; if(f.substring(0, 4) != 'doc.') w.Oby.removeEvent(input_elem, t._fct[f]); else w.Oby.removeEvent(d, t._fct[f]); } if(t.content) t.content.destroy(); delete t._fct; delete t._conf; delete t.data; delete t.config; delete t.cache; }, /** * */ search: function(el) { var t = this, d = document, w = window, s = d.getElementById(t.id+"_span"); if(typeof(el) == "string") el = d.getElementById(el); if(!el) return false; s.innerHTML = el.value; el.style.width = s.offsetWidth + 30 + "px"; if(!t.content) return false; if(t.cache.lastSearch == el.value) return false; if(t.config.add) { var add_el = d.getElementById(t.id+'_add'); if(add_el) add_el.style.display = (el.value.length == 0) ? 'none' : ''; } if(!t.url) { t.content.search(el.value); } else { if(el.value.length < t.config.min) { if(t.modifiedData) { t.loadData(false); t.modifiedData = false; } t.content.search(el.value); } else { var url = t.url.replace(t.config.url_keyword, el.value); if(t.config.url_pagination) url.replace(t.config.url_pagination, 0); w.Oby.xRequest( url, null, function(xhr,params) { t.modifiedData = true; var p = w.Oby.evalJSON(xhr.responseText), data = (p.data ? p.data : p); t.loadData(data); if(data && data.length) t.content.config.gradientLoad = true; }, function(xhr,params) { t.content.search(el.value); } ); } } t.cache.lastSearch = el.value; }, /** * */ loadMore: function(el) { if(!this.url) { el.deinitScroll(); return false; } var t = this, d = document, w = window, input = d.getElementById(t.id + "_text"), url = t.url.replace(t.config.url_keyword, input.value); if(t.config.url_pagination) url = url.replace(t.config.url_pagination, t.content.lData.length); w.Oby.xRequest( url, null, function(xhr,params) { var p = w.Oby.evalJSON(xhr.responseText), data = ((p.data) ? p.data : p), u = false, i = (input.value == ''); if(data.length == 0) { t.content.config.gradientLoad = false; if(i) { t.url = ''; t.content.render(); } return; } for(var k in data) { if(!data.hasOwnProperty(k)) continue; if(i && !t.data[k]) { t.data[k] = data[k]; u = true; } else if(!i && !t.content.lData[k]) { t.content.lData[k] = data[k]; u = true; } } if(u && i) { // Keep the highlight selection var hl = t.content.highlightGet(); t.loadData(false); t.content.highlightSet(hl); } if(u && !i) t.content.render(); }, function(xhr,params) {} ); }, /** * */ loadData: function(data) { var t = this; d = data || t.data; if(t.mode == 'list') { t.content.load(d); if(t.url) t.content.config.gradientLoad = true; t.content.render(); } else { delete t.content.lNodes; t.content.lNodes = []; t.content.lNodes[0] = new window.oNode(0,-1); t.content.load(d); t.content.render(); } }, /** * */ focus: function(el) { var d = document, w = window, t = this, c = d.getElementById(t.id); if(typeof(el) == "string") el = d.getElementById(el); if(el) el.focus(); if(t.content) t.content.search(el.value); if(!t.container) return false; t.container.style.display = ""; t.fire('focus', {el: t, input: el}); var f = null; f = function(evt) { if (!evt) var evt = window.event; var trg = (window.event) ? evt.srcElement : evt.target; while(trg != null) { if(trg == el || trg == t.container || trg == c) return; trg = trg.parentNode; } t.container.style.display = "none"; t.fire('blur', {el: t, input: el}); window.Oby.removeEvent(document, "mousedown", f); }; window.Oby.addEvent(document, "mousedown", f); return false; }, /** * */ clear: function() { var d = document, t = this, el = d.getElementById(t.id), e = null; delete t.cache; t.cache = {}; if(!el) return false; if(t.multiple) { for(var i = el.children.length - 1; i >= 0; i--) { e = el.children[i]; if(e.tagName.toLowerCase() == 'div' && e.className == 'namebox' && e.style.display != 'none') el.removeChild(e); } if(t.mode == 'list') t.content.unblock(true); } else t.set(t.config.default_text, t.config.default_value); }, /** * */ clean: function(el, text) { var t = this; t.set(text, t.config.default_value); window.Oby.cancelEvent(); }, /** * */ create: function(el,conf) { var t = this, d = document, w = window; window.Oby.cancelEvent(); if(!t.config.add || !t.config.add_url) return false; var n = d.getElementById(t.id+"_text"), l = d.getElementById(t.id+'_loading'); value = null; if(!n || !n.value || n.value.length == 0) return false; var check = t.content.find(n.value, true); if(check !== null) { var node = t.content.get(check); t.set(node.name, node.value); n.value = ''; return; } if(conf && !confirm(encodeURIComponent(n.value) + ' ?')) return false; value = 'value=' + encodeURIComponent(n.value); n.value = ''; if(el) el.style.display = 'none'; if(l) l.style.display = ''; w.Oby.xRequest(t.config.add_url,{mode:'POST',data:value},function(xhr,params){ if(l) l.style.display = 'none'; if(el) el.style.display = ''; if(el) el.parentNode.style.display = 'none'; if(xhr.responseText) { var data = w.Oby.evalJSON(xhr.responseText); if(data && data.value && data.name) { if(t.mode == 'list') t.content.add(data.value, data.name); t.set(data.name, data.value); t.data[data.value] = data.name; } } },function(xhr,params){ if(l) l.style.display = 'none'; if(el) el.style.display = ''; if(el) el.parentNode.style.display = 'none'; }); return false; }, /** * * @param {Object} tplName * @param {Object} htmlblocks * @param {Object} id * @param {Object} extraData * @param {Object} appendTo */ dup: function(tplName, htmlblocks, id, extraData, appendTo) { var d = document, tplElem = d.getElementById(tplName); if(!tplElem) return; var container = tplElem.parentNode; elem = tplElem.cloneNode(true); if(!appendTo) { container.insertBefore(elem, tplElem); } else { if(typeof(appendTo) == "string") appendTo = d.getElementById(appendTo); appendTo.appendChild(elem); } elem.style.display = ""; elem.id = ''; if(id) elem.id = id; for(var k in htmlblocks) { elem.innerHTML = elem.innerHTML.replace(new RegExp("{"+k+"}","g"), htmlblocks[k]); elem.innerHTML = elem.innerHTML.replace(new RegExp("%7B"+k+"%7D","g"), htmlblocks[k]); } if(extraData) { for(var k in extraData) { elem.innerHTML = elem.innerHTML.replace(new RegExp('{'+k+'}','g'), extraData[k]); elem.innerHTML = elem.innerHTML.replace(new RegExp('%7B'+k+'%7D','g'), extraData[k]); } } }, fire: function(name, params) { var t = this, ev; if(t.cb[name] === undefined) return false; for(var e in t.cb[name]) { if( e != '_id' ) { ev = t.cb[name][e]; ev(params); } } return true; }, register: function(name, fct) { var t = this; if(t.cb[name] === undefined ) t.cb[name] = {'_id':0}; var id = t.cb[name]['_id']; t.cb[name]['_id'] += 1; t.cb[name][id] = fct; return id; }, unregister: function(name, id) { if(t.cb[name] === undefined || t.cb[name][id] === undefined) return false; t.cb[name][id] = null; return true; }, }; oNamebox.version = 20150807; if(!window.oNamebox || !window.oNamebox.version || window.oNamebox.version < oNamebox.version) window.oNamebox = oNamebox; })();
gpl-2.0
feeef/pencil
core_lib/tool/movetool.cpp
10554
#include "editor.h" #include "toolmanager.h" #include "scribblearea.h" #include "layervector.h" #include "layermanager.h" #include "movetool.h" MoveTool::MoveTool(QObject *parent) : BaseTool(parent) { } ToolType MoveTool::type() { return MOVE; } void MoveTool::loadSettings() { properties.width = -1; properties.feather = -1; properties.useFeather = -1; properties.inpolLevel = -1; properties.useAA = -1; } QCursor MoveTool::cursor() { return Qt::ArrowCursor; } void MoveTool::mousePressEvent( QMouseEvent *event ) { Layer *layer = mEditor->layers()->currentLayer(); if ( layer == NULL ) { return; } if ( event->button() == Qt::LeftButton ) { // ---------------------------------------------------------------------- if ( (layer->type() == Layer::BITMAP || layer->type() == Layer::VECTOR) ) { mEditor->backup( tr( "Move" ) ); mScribbleArea->setMoveMode( ScribbleArea::MIDDLE ); if ( mScribbleArea->somethingSelected ) // there is an area selection { if ( BezierCurve::mLength( getLastPoint() - mScribbleArea->myTransformedSelection.topLeft() ) < 6 ) { mScribbleArea->setMoveMode( ScribbleArea::TOPLEFT ); } if ( BezierCurve::mLength( getLastPoint() - mScribbleArea->myTransformedSelection.topRight() ) < 6 ) { mScribbleArea->setMoveMode( ScribbleArea::TOPRIGHT ); } if ( BezierCurve::mLength( getLastPoint() - mScribbleArea->myTransformedSelection.bottomLeft() ) < 6 ) { mScribbleArea->setMoveMode( ScribbleArea::BOTTOMLEFT ); } if ( BezierCurve::mLength( getLastPoint() - mScribbleArea->myTransformedSelection.bottomRight() ) < 6 ) { mScribbleArea->setMoveMode( ScribbleArea::BOTTOMRIGHT ); } } if ( mScribbleArea->getMoveMode() == ScribbleArea::MIDDLE ) { if ( event->modifiers() == Qt::ControlModifier ) // --- rotation { mScribbleArea->setMoveMode( ScribbleArea::ROTATION ); //qDebug() << "ROTATION"; } else if (event->modifiers() == Qt::AltModifier ) // --- symmetry { mScribbleArea->setMoveMode(ScribbleArea::SYMMETRY ); //qDebug() << "SYMMETRY"; } if ( layer->type() == Layer::BITMAP ) { if ( !(mScribbleArea->myTransformedSelection.contains( getLastPoint() )) ) // click is outside the transformed selection with the MOVE tool { applyChanges(); } } else if ( layer->type() == Layer::VECTOR ) { VectorImage *vectorImage = ((LayerVector *)layer)->getLastVectorImageAtFrame( mEditor->currentFrame(), 0 ); if ( mScribbleArea->mClosestCurves.size() > 0 ) // the user clicks near a curve { // editor->backup(); if ( !vectorImage->isSelected( mScribbleArea->mClosestCurves ) ) { if ( event->modifiers() != Qt::ShiftModifier ) { applyChanges(); } vectorImage->setSelected( mScribbleArea->mClosestCurves, true ); mScribbleArea->setSelection( vectorImage->getSelectionRect(), true ); mScribbleArea->update(); } } else { int areaNumber = vectorImage->getLastAreaNumber( getLastPoint() ); if ( areaNumber != -1 ) // the user clicks on an area { if ( !vectorImage->isAreaSelected( areaNumber ) ) { if ( event->modifiers() != Qt::ShiftModifier ) { applyChanges(); } vectorImage->setAreaSelected( areaNumber, true ); //setSelection( vectorImage->getSelectionRect() ); mScribbleArea->setSelection( QRectF( 0, 0, 0, 0 ), true ); mScribbleArea->update(); } } else // the user doesn't click near a curve or an area { if ( !(mScribbleArea->myTransformedSelection.contains( getLastPoint() )) ) // click is outside the transformed selection with the MOVE tool { applyChanges(); } } } } } } } } void MoveTool::mouseReleaseEvent( QMouseEvent* ) { mScribbleArea->myTransformedSelection = mScribbleArea->myTempTransformedSelection; // Don't do anything more on mouse release. // The modifications are only applied on deslect or press enter. } void MoveTool::mouseMoveEvent( QMouseEvent *event ) { Layer* layer = mEditor->layers()->currentLayer(); if ( layer == NULL ) { return; } if ( layer->type() != Layer::BITMAP && layer->type() != Layer::VECTOR ) { return; } if ( event->buttons() & Qt::LeftButton ) // the user is also pressing the mouse (dragging) { if ( mScribbleArea->somethingSelected ) // there is something selected { qreal xOffset = mScribbleArea->mOffset.x(); qreal yOffset = mScribbleArea->mOffset.y(); if ( event->modifiers() == Qt::ShiftModifier ) // (makes resize proportional, move linear) { qreal factor = mScribbleArea->mySelection.width() / mScribbleArea->mySelection.height(); if (mScribbleArea->mMoveMode == ScribbleArea::TOPLEFT || mScribbleArea->mMoveMode == ScribbleArea::BOTTOMRIGHT) { yOffset = xOffset / factor; } else if (mScribbleArea->mMoveMode == ScribbleArea::TOPRIGHT || mScribbleArea->mMoveMode == ScribbleArea::BOTTOMLEFT) { yOffset = -(xOffset / factor); } else if (mScribbleArea->mMoveMode == ScribbleArea::MIDDLE) { qreal absX = xOffset; if (absX < 0) {absX = -absX;} qreal absY = yOffset; if (absY < 0) {absY = -absY;} if (absX > absY) { yOffset = 0; } if (absY > absX) { xOffset = 0; } } } switch ( mScribbleArea->mMoveMode ) { case ScribbleArea::MIDDLE: if ( QLineF( getLastPressPixel(), getCurrentPixel() ).length() > 4 ) { mScribbleArea->myTempTransformedSelection = mScribbleArea->myTransformedSelection.translated( QPointF(xOffset, yOffset) ); } break; case ScribbleArea::TOPRIGHT: mScribbleArea->myTempTransformedSelection = mScribbleArea->myTransformedSelection.adjusted( 0, yOffset, xOffset, 0 ); break; case ScribbleArea::TOPLEFT: mScribbleArea->myTempTransformedSelection = mScribbleArea->myTransformedSelection.adjusted( xOffset, yOffset, 0, 0 ); break; // TOPRIGHT XXX case ScribbleArea::BOTTOMLEFT: mScribbleArea->myTempTransformedSelection = mScribbleArea->myTransformedSelection.adjusted( xOffset, 0, 0, yOffset ); break; case ScribbleArea::BOTTOMRIGHT: mScribbleArea->myTempTransformedSelection = mScribbleArea->myTransformedSelection.adjusted( 0, 0, xOffset, yOffset ); break; case ScribbleArea::ROTATION: mScribbleArea->myTempTransformedSelection = mScribbleArea->myTransformedSelection; // @ necessary? mScribbleArea->myRotatedAngle = getCurrentPixel().x() - getLastPressPixel().x(); //qDebug() << "rotation" << m_pScribbleArea->myRotatedAngle; break; } mScribbleArea->calculateSelectionTransformation(); mScribbleArea->paintTransformedSelection(); } else // there is nothing selected { // we switch to the select tool mEditor->tools()->setCurrentTool( SELECT ); mScribbleArea->mMoveMode = ScribbleArea::MIDDLE; mScribbleArea->mySelection.setTopLeft( getLastPoint() ); mScribbleArea->mySelection.setBottomRight( getLastPoint() ); mScribbleArea->setSelection( mScribbleArea->mySelection, true ); } } else // the user is moving the mouse without pressing it { if ( layer->type() == Layer::VECTOR ) { auto layerVector = static_cast< LayerVector* >( layer ); VectorImage* pVecImg = layerVector->getLastVectorImageAtFrame( mEditor->currentFrame(), 0 ); mScribbleArea->mClosestCurves = pVecImg->getCurvesCloseTo( getCurrentPoint(), mScribbleArea->tol / mEditor->view()->scaling() ); } mScribbleArea->update(); } } bool MoveTool::keyPressEvent(QKeyEvent *event) { switch ( event->key() ) { case Qt::Key_Escape: cancelChanges(); break; default: break; } // Follow the generic behaviour anyway // return false; } void MoveTool::cancelChanges() { mScribbleArea->cancelTransformedSelection(); } void MoveTool::applyChanges() { mScribbleArea->applyTransformedSelection(); } void MoveTool::leavingThisTool(){ applyChanges(); } void MoveTool::switchingLayers(){ applyChanges(); }
gpl-2.0
RTRindex/raleigh-triangle-index
raleigh-triangle-index/examples/ContributionsPageExample.cpp
15864
/* Copyright 2012. Bloomberg Finance L.P. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: The above * copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <blpapi_correlationid.h> #include <blpapi_defs.h> #include <blpapi_event.h> #include <blpapi_eventformatter.h> #include <blpapi_exception.h> #include <blpapi_identity.h> #include <blpapi_message.h> #include <blpapi_name.h> #include <blpapi_providersession.h> #include <blpapi_request.h> #include <blpapi_topiclist.h> #include <blpapi_service.h> #include <blpapi_topic.h> #include <cstdlib> #include <cstring> #include <ctime> #include <iostream> #include <iterator> #include <list> #include <map> #include <string> #include "BlpThreadUtil.h" using namespace BloombergLP; using namespace blpapi; namespace { Name TOKEN_SUCCESS("TokenGenerationSuccess"); Name TOKEN_FAILURE("TokenGenerationFailure"); Name AUTHORIZATION_SUCCESS("AuthorizationSuccess"); Name TOKEN("token"); Name SESSION_TERMINATED("SessionTerminated"); const std::string AUTH_USER = "AuthenticationType=OS_LOGON"; const std::string AUTH_APP_PREFIX = "AuthenticationMode=APPLICATION_ONLY;ApplicationAuthenticationType=APPNAME_AND_KEY;ApplicationName="; const std::string AUTH_DIR_PREFIX = "AuthenticationType=DIRECTORY_SERVICE;DirSvcPropertyName="; const char* AUTH_OPTION_NONE = "none"; const char* AUTH_OPTION_USER = "user"; const char* AUTH_OPTION_APP = "app="; const char* AUTH_OPTION_DIR = "dir="; volatile bool g_running = true; Mutex g_lock; enum AuthorizationStatus { WAITING, AUTHORIZED, FAILED }; std::map<CorrelationId, AuthorizationStatus> g_authorizationStatus; } class MyStream { std::string d_id; Topic d_topic; public: MyStream() : d_id("") {}; MyStream(std::string const& id) : d_id(id) {} void setTopic(Topic const& topic) {d_topic = topic;} std::string const& getId() {return d_id;} Topic const& getTopic() {return d_topic;} }; typedef std::list<MyStream*> MyStreams; void printMessages(const Event& event) { MessageIterator iter(event); while (iter.next()) { Message msg = iter.message(); MutexGuard guard(&g_lock); msg.print(std::cout); if (event.eventType() == Event::SESSION_STATUS) { if (msg.messageType() == SESSION_TERMINATED) { g_running = false; } continue; } if (g_authorizationStatus.find(msg.correlationId()) != g_authorizationStatus.end()) { if (msg.messageType() == AUTHORIZATION_SUCCESS) { g_authorizationStatus[msg.correlationId()] = AUTHORIZED; } else { g_authorizationStatus[msg.correlationId()] = FAILED; } } } } class MyEventHandler : public ProviderEventHandler { public: bool processEvent(const Event& event, ProviderSession* session); }; bool MyEventHandler::processEvent(const Event& event, ProviderSession* session) { printMessages(event); return true; } class ContributionsPageExample { std::vector<std::string> d_hosts; int d_port; std::string d_service; std::string d_topic; std::string d_authOptions; int d_contributorId; void printUsage() { std::cout << "Publish on a topic. " << std::endl << "Usage:" << std::endl << "\t[-ip <ipAddress>] \tserver name or IP (default: localhost)" << std::endl << "\t[-p <tcpPort>] \tserver port (default: 8194)" << std::endl << "\t[-s <service>] \tservice name (default: //blp/mpfbapi)" << std::endl << "\t[-t <topic>] \ttopic (default: 220/660/1)" << std::endl << "\t[-c <contributorId>]\tcontributor id (default: 8563)" << std::endl << "\t[-auth <option>] \tauthentication option: user|none|app=<app>|dir=<property> (default: user)" << std::endl; } bool parseCommandLine(int argc, char **argv) { for (int i = 1; i < argc; ++i) { if (!std::strcmp(argv[i], "-ip") && i + 1 < argc) d_hosts.push_back(argv[++i]); else if (!std::strcmp(argv[i], "-p") && i + 1 < argc) d_port = std::atoi(argv[++i]); else if (!std::strcmp(argv[i], "-s") && i + 1 < argc) d_service = argv[++i]; else if (!std::strcmp(argv[i], "-t") && i + 1 < argc) d_topic = argv[++i]; else if (!std::strcmp(argv[i], "-c") && i + 1 < argc) d_contributorId = std::atoi(argv[++i]); else if (!std::strcmp(argv[i], "-auth") && i + 1 < argc) { ++i; if (!std::strcmp(argv[i], AUTH_OPTION_NONE)) { d_authOptions.clear(); } else if (!std::strcmp(argv[i], AUTH_OPTION_USER)) { d_authOptions.assign(AUTH_USER); } else if (strncmp(argv[i], AUTH_OPTION_APP, strlen(AUTH_OPTION_APP)) == 0) { d_authOptions.clear(); d_authOptions.append(AUTH_APP_PREFIX); d_authOptions.append(argv[i] + strlen(AUTH_OPTION_APP)); } else if (strncmp(argv[i], AUTH_OPTION_DIR, strlen(AUTH_OPTION_DIR)) == 0) { d_authOptions.clear(); d_authOptions.append(AUTH_DIR_PREFIX); d_authOptions.append(argv[i] + strlen(AUTH_OPTION_DIR)); } else { printUsage(); return false; } } else { printUsage(); return false; } } if (d_hosts.empty()) { d_hosts.push_back("localhost"); } return true; } public: ContributionsPageExample() : d_port(8194) , d_service("//blp/mpfbapi") , d_authOptions(AUTH_USER) , d_topic("220/660/1") , d_contributorId(8563) { } bool authorize(const Service& authService, Identity *providerIdentity, ProviderSession *session, const CorrelationId& cid) { { MutexGuard guard(&g_lock); g_authorizationStatus[cid] = WAITING; } EventQueue tokenEventQueue; session->generateToken(CorrelationId(), &tokenEventQueue); std::string token; Event event = tokenEventQueue.nextEvent(); if (event.eventType() == Event::TOKEN_STATUS || event.eventType() == Event::REQUEST_STATUS) { MessageIterator iter(event); while (iter.next()) { Message msg = iter.message(); { MutexGuard guard(&g_lock); msg.print(std::cout); } if (msg.messageType() == TOKEN_SUCCESS) { token = msg.getElementAsString(TOKEN); } else if (msg.messageType() == TOKEN_FAILURE) { break; } } } if (token.length() == 0) { MutexGuard guard(&g_lock); std::cout << "Failed to get token" << std::endl; return false; } Request authRequest = authService.createAuthorizationRequest(); authRequest.set(TOKEN, token.c_str()); session->sendAuthorizationRequest( authRequest, providerIdentity, cid); time_t startTime = time(0); const int WAIT_TIME_SECONDS = 10; while (true) { { MutexGuard guard(&g_lock); if (WAITING != g_authorizationStatus[cid]) { return AUTHORIZED == g_authorizationStatus[cid]; } } time_t endTime = time(0); if (endTime - startTime > WAIT_TIME_SECONDS) { return false; } SLEEP(1); } } void run(int argc, char **argv) { if (!parseCommandLine(argc, argv)) return; SessionOptions sessionOptions; for (size_t i = 0; i < d_hosts.size(); ++i) { sessionOptions.setServerAddress(d_hosts[i].c_str(), d_port, i); } sessionOptions.setServerPort(d_port); sessionOptions.setAuthenticationOptions(d_authOptions.c_str()); sessionOptions.setAutoRestartOnDisconnection(true); sessionOptions.setNumStartAttempts(d_hosts.size()); std::cout << "Connecting to port " << d_port << " on "; std::copy(d_hosts.begin(), d_hosts.end(), std::ostream_iterator<std::string>(std::cout, " ")); std::cout << std::endl; MyEventHandler myEventHandler; ProviderSession session(sessionOptions, &myEventHandler, 0); if (!session.start()) { std::cerr <<"Failed to start session." << std::endl; return; } Identity providerIdentity = session.createIdentity(); if (!d_authOptions.empty()) { bool isAuthorized = false; const char* authServiceName = "//blp/apiauth"; if (session.openService(authServiceName)) { Service authService = session.getService(authServiceName); isAuthorized = authorize(authService, &providerIdentity, &session, CorrelationId((void *)"auth")); } if (!isAuthorized) { std::cerr << "No authorization" << std::endl; return; } } TopicList topicList; topicList.add(((d_service + "/") + d_topic).c_str(), CorrelationId(new MyStream(d_topic))); session.createTopics( &topicList, ProviderSession::AUTO_REGISTER_SERVICES, providerIdentity); MyStreams myStreams; for (size_t i = 0; i < topicList.size(); ++i) { MyStream *stream = reinterpret_cast<MyStream*>( topicList.correlationIdAt(i).asPointer()); int resolutionStatus = topicList.statusAt(i); if (resolutionStatus == TopicList::CREATED) { Topic topic = session.getTopic(topicList.messageAt(i)); stream->setTopic(topic); myStreams.push_back(stream); } else { std::cout << "Stream '" << stream->getId() << "': topic not resolved, status = " << resolutionStatus << std::endl; } } Service service = session.getService(d_service.c_str()); // Now we will start publishing while (g_running) { Event event = service.createPublishEvent(); EventFormatter eventFormatter(event); for (MyStreams::iterator iter = myStreams.begin(); iter != myStreams.end(); ++iter) { eventFormatter.appendMessage("PageData", (*iter)->getTopic()); eventFormatter.pushElement("rowUpdate"); eventFormatter.appendElement(); eventFormatter.setElement("rowNum", 1); eventFormatter.pushElement("spanUpdate"); eventFormatter.appendElement(); eventFormatter.setElement("startCol", 20); eventFormatter.setElement("length", 4); eventFormatter.setElement("text", "TEST"); eventFormatter.popElement(); eventFormatter.appendElement(); eventFormatter.setElement("startCol", 25); eventFormatter.setElement("length", 4); eventFormatter.setElement("text", "PAGE"); eventFormatter.popElement(); char buffer[10]; time_t rawtime; std::time(&rawtime); int length = (int)std::strftime(buffer, 10, "%X", std::localtime(&rawtime)); eventFormatter.appendElement(); eventFormatter.setElement("startCol", 30); eventFormatter.setElement("length", length); eventFormatter.setElement("text", buffer); eventFormatter.setElement("attr", "BLINK"); eventFormatter.popElement(); eventFormatter.popElement(); eventFormatter.popElement(); eventFormatter.appendElement(); eventFormatter.setElement("rowNum", 2); eventFormatter.pushElement("spanUpdate"); eventFormatter.appendElement(); eventFormatter.setElement("startCol", 20); eventFormatter.setElement("length", 9); eventFormatter.setElement("text", "---------"); eventFormatter.setElement("attr", "UNDERLINE"); eventFormatter.popElement(); eventFormatter.popElement(); eventFormatter.popElement(); eventFormatter.appendElement(); eventFormatter.setElement("rowNum", 3); eventFormatter.pushElement("spanUpdate"); eventFormatter.appendElement(); eventFormatter.setElement("startCol", 10); eventFormatter.setElement("length", 9); eventFormatter.setElement("text", "TEST LINE"); eventFormatter.popElement(); eventFormatter.appendElement(); eventFormatter.setElement("startCol", 23); eventFormatter.setElement("length", 5); eventFormatter.setElement("text", "THREE"); eventFormatter.popElement(); eventFormatter.popElement(); eventFormatter.popElement(); eventFormatter.popElement(); eventFormatter.setElement("contributorId", d_contributorId); eventFormatter.setElement("productCode", 1); eventFormatter.setElement("pageNumber", 1); } printMessages(event); session.publish(event); SLEEP(10); } session.stop(); } }; int main(int argc, char **argv) { std::cout << "ContributionsPageExample" << std::endl; ContributionsPageExample example; try { example.run(argc, argv); } catch (Exception &e) { std::cerr << "Library Exception!!! " << e.description() << std::endl; } // wait for enter key to exit application std::cout << "Press ENTER to quit" << std::endl; char dummy[2]; std::cin.getline(dummy, 2); return 0; }
gpl-2.0
tavaron/swt
src/Model.cpp
1131
/* * Model.cpp * * Created on: 02.07.2014 * Author: patrick */ #include "Model.hpp" template <class T, class Data> Model<T,Data>::Model(Data* _data) : notifyFunc( boost::phoenix::bind( &T::Refresh, boost::phoenix::arg_names::arg1 ) ) , data( _data ) { } template <class T, class Data> Model<T,Data>::Model(boost::function<void(T*)> func, Data* _data) : notifyFunc( func ) , data( _data ) { } template <class T, class Data> Data* Model<T,Data>::Register(T* view) { try { viewList.push_back(view); } catch(...) { ErrorOut::Out(30); return 0; } return data; } template <class T, class Data> bool Model<T,Data>::Deregister(T* view) { try { viewList.remove(view); } catch(...) { ErrorOut::Out(31); return false; } return true; } template <class T, class Data> bool Model<T,Data>::Notify () { try { for ( viewListIterator=viewList.begin(); viewListIterator!=viewList.end(); viewListIterator++ ) { notifyFunc(*viewListIterator); } } catch(...) { ErrorOut::Out(32); return false; } return true; } template class Model< IView, std::map< std::string, double > >;
gpl-2.0
mdavid/IKVM.NET-cvs-clone
reflect/Reader/ModuleReader.cs
28389
/* Copyright (C) 2009-2010 Jeroen Frijters This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jeroen Frijters jeroen@frijters.net */ using System; using System.IO; using System.Text; using System.Collections.Generic; using IKVM.Reflection.Metadata; namespace IKVM.Reflection.Reader { sealed class StreamHeader { internal uint Offset; internal uint Size; internal string Name; internal void Read(BinaryReader br) { Offset = br.ReadUInt32(); Size = br.ReadUInt32(); byte[] buf = new byte[32]; byte b; int len = 0; while ((b = br.ReadByte()) != 0) { buf[len++] = b; } Name = Encoding.UTF8.GetString(buf, 0, len); ; int padding = -1 + ((len + 4) & ~3) - len; br.BaseStream.Seek(padding, SeekOrigin.Current); } } sealed class ModuleReader : Module { internal readonly Stream stream; private readonly string location; private readonly AssemblyReader assembly; private readonly PEReader peFile = new PEReader(); private readonly CliHeader cliHeader = new CliHeader(); private string imageRuntimeVersion; private int metadataStreamVersion; private byte[] stringHeap; private byte[] blobHeap; private byte[] userStringHeap; private byte[] guidHeap; private TypeDefImpl[] typeDefs; private TypeDefImpl moduleType; private Assembly[] assemblyRefs; private Type[] typeRefs; private Type[] typeSpecs; private FieldInfo[] fields; private MethodBase[] methods; private MemberInfo[] memberRefs; private Dictionary<int, string> strings = new Dictionary<int, string>(); private Dictionary<string, Type> types = new Dictionary<string, Type>(); private Dictionary<string, LazyForwardedType> forwardedTypes = new Dictionary<string, LazyForwardedType>(); private sealed class LazyForwardedType { private readonly int assemblyRef; private Type type; internal LazyForwardedType(int assemblyRef) { this.assemblyRef = assemblyRef; } internal Type GetType(ModuleReader module, string typeName) { if (type == null) { Assembly asm = module.ResolveAssemblyRef(assemblyRef); type = asm.GetType(typeName, true); } return type; } } internal ModuleReader(AssemblyReader assembly, Universe universe, Stream stream, string location) : base(universe) { this.stream = stream; this.location = location; Read(); if (assembly == null && AssemblyTable.records.Length != 0) { assembly = new AssemblyReader(location, this); } this.assembly = assembly; } private void Read() { BinaryReader br = new BinaryReader(stream); peFile.Read(br); stream.Seek(peFile.RvaToFileOffset(peFile.GetComDescriptorVirtualAddress()), SeekOrigin.Begin); cliHeader.Read(br); stream.Seek(peFile.RvaToFileOffset(cliHeader.MetaDataRVA), SeekOrigin.Begin); foreach (StreamHeader sh in ReadStreamHeaders(br, out imageRuntimeVersion)) { switch (sh.Name) { case "#Strings": stringHeap = ReadHeap(stream, sh); break; case "#Blob": blobHeap = ReadHeap(stream, sh); break; case "#US": userStringHeap = ReadHeap(stream, sh); break; case "#GUID": guidHeap = ReadHeap(stream, sh); break; case "#~": stream.Seek(peFile.RvaToFileOffset(cliHeader.MetaDataRVA + sh.Offset), SeekOrigin.Begin); ReadTables(br); break; default: throw new BadImageFormatException("Unsupported stream: " + sh.Name); } } } private static StreamHeader[] ReadStreamHeaders(BinaryReader br, out string Version) { uint Signature = br.ReadUInt32(); if (Signature != 0x424A5342) { throw new BadImageFormatException("Invalid metadata signature"); } ushort MajorVersion = br.ReadUInt16(); ushort MinorVersion = br.ReadUInt16(); uint Reserved = br.ReadUInt32(); uint Length = br.ReadUInt32(); byte[] buf = br.ReadBytes((int)Length); Version = Encoding.UTF8.GetString(buf).TrimEnd('\u0000'); ushort Flags = br.ReadUInt16(); ushort Streams = br.ReadUInt16(); StreamHeader[] streamHeaders = new StreamHeader[Streams]; for (int i = 0; i < streamHeaders.Length; i++) { streamHeaders[i] = new StreamHeader(); streamHeaders[i].Read(br); } return streamHeaders; } private void ReadTables(BinaryReader br) { Table[] tables = GetTables(); uint Reserved0 = br.ReadUInt32(); byte MajorVersion = br.ReadByte(); byte MinorVersion = br.ReadByte(); metadataStreamVersion = MajorVersion << 16 | MinorVersion; byte HeapSizes = br.ReadByte(); byte Reserved7 = br.ReadByte(); ulong Valid = br.ReadUInt64(); ulong Sorted = br.ReadUInt64(); // we require that the GenericParam table is sorted const ulong mask = (1UL << GenericParamTable.Index); if ((Valid & Sorted & mask) != (Valid & mask)) { throw new NotImplementedException(); } for (int i = 0; i < 64; i++) { if ((Valid & (1UL << i)) != 0) { tables[i].RowCount = br.ReadInt32(); } else if (tables[i] != null) { tables[i].RowCount = 0; } } MetadataReader mr = new MetadataReader(this, br, HeapSizes); for (int i = 0; i < 64; i++) { if ((Valid & (1UL << i)) != 0) { tables[i].Read(mr); } } } private byte[] ReadHeap(Stream stream, StreamHeader sh) { byte[] buf = new byte[sh.Size]; stream.Seek(peFile.RvaToFileOffset(cliHeader.MetaDataRVA + sh.Offset), SeekOrigin.Begin); for (int pos = 0; pos < buf.Length; ) { int read = stream.Read(buf, pos, buf.Length - pos); if (read == 0) { throw new BadImageFormatException(); } pos += read; } return buf; } internal void SeekRVA(int rva) { stream.Seek(peFile.RvaToFileOffset((uint)rva), SeekOrigin.Begin); } internal override void GetTypesImpl(List<Type> list) { PopulateTypeDef(); foreach (TypeDefImpl type in typeDefs) { if (type != moduleType) { list.Add(type); } } } private void PopulateTypeDef() { if (typeDefs == null) { typeDefs = new TypeDefImpl[TypeDef.records.Length]; for (int i = 0; i < typeDefs.Length; i++) { TypeDefImpl type = new TypeDefImpl(this, i); typeDefs[i] = type; if (type.IsModulePseudoType) { moduleType = type; } else { types.Add(type.FullName, type); } } // add forwarded types to forwardedTypes dictionary (because Module.GetType(string) should return them) for (int i = 0; i < ExportedType.records.Length; i++) { int implementation = ExportedType.records[i].Implementation; if (implementation >> 24 == AssemblyRefTable.Index) { string typeName = GetTypeName(ExportedType.records[i].TypeNamespace, ExportedType.records[i].TypeName); forwardedTypes.Add(typeName, new LazyForwardedType((implementation & 0xFFFFFF) - 1)); } } } } internal string GetString(int index) { if (index == 0) { return null; } string str; if (!strings.TryGetValue(index, out str)) { int len = 0; while (stringHeap[index + len] != 0) { len++; } str = Encoding.UTF8.GetString(stringHeap, index, len); strings.Add(index, str); } return str; } private static int ReadCompressedInt(byte[] buffer, ref int offset) { byte b1 = buffer[offset++]; if (b1 <= 0x7F) { return b1; } else if ((b1 & 0xC0) == 0x80) { byte b2 = buffer[offset++]; return ((b1 & 0x3F) << 8) | b2; } else { byte b2 = buffer[offset++]; byte b3 = buffer[offset++]; byte b4 = buffer[offset++]; return ((b1 & 0x3F) << 24) + (b2 << 16) + (b3 << 8) + b4; } } internal byte[] GetBlobCopy(int blobIndex) { int len = ReadCompressedInt(blobHeap, ref blobIndex); byte[] buf = new byte[len]; Buffer.BlockCopy(blobHeap, blobIndex, buf, 0, len); return buf; } internal override ByteReader GetBlob(int blobIndex) { return ByteReader.FromBlob(blobHeap, blobIndex); } public override string ResolveString(int metadataToken) { string str; if (!strings.TryGetValue(metadataToken, out str)) { if ((metadataToken >> 24) != 0x70) { throw new ArgumentOutOfRangeException(); } int index = metadataToken & 0xFFFFFF; int len = ReadCompressedInt(userStringHeap, ref index) & ~1; str = Encoding.Unicode.GetString(userStringHeap, index, len); strings.Add(metadataToken, str); } return str; } internal Type ResolveType(int metadataToken, IGenericContext context) { switch (metadataToken >> 24) { case TypeDefTable.Index: PopulateTypeDef(); return typeDefs[(metadataToken & 0xFFFFFF) - 1]; case TypeRefTable.Index: { if (typeRefs == null) { typeRefs = new Type[TypeRef.records.Length]; } int index = (metadataToken & 0xFFFFFF) - 1; if (typeRefs[index] == null) { int scope = TypeRef.records[index].ResolutionScope; switch (scope >> 24) { case AssemblyRefTable.Index: { Assembly assembly = ResolveAssemblyRef((scope & 0xFFFFFF) - 1); string typeName = GetTypeName(TypeRef.records[index].TypeNameSpace, TypeRef.records[index].TypeName); Type type = assembly.GetType(typeName); if (type == null) { throw new TypeLoadException(String.Format("Type '{0}' not found in assembly '{1}'", typeName, assembly.FullName)); } typeRefs[index] = type; break; } case TypeRefTable.Index: { Type outer = ResolveType(scope, null); typeRefs[index] = outer.GetNestedType(GetString(TypeRef.records[index].TypeName), BindingFlags.Public | BindingFlags.NonPublic); break; } case ModuleTable.Index: if (scope != 0 && scope != 1) { throw new NotImplementedException("self reference scope?"); } typeRefs[index] = GetType(GetTypeName(TypeRef.records[index].TypeNameSpace, TypeRef.records[index].TypeName)); break; case ModuleRefTable.Index: { Module module = ResolveModuleRef(ModuleRef.records[(scope & 0xFFFFFF) - 1]); string typeName = GetTypeName(TypeRef.records[index].TypeNameSpace, TypeRef.records[index].TypeName); Type type = assembly.GetType(typeName); if (type == null) { throw new TypeLoadException(String.Format("Type '{0}' not found in module '{1}'", typeName, module.Name)); } typeRefs[index] = type; break; } default: throw new NotImplementedException("ResolutionScope = " + scope.ToString("X")); } } return typeRefs[index]; } case TypeSpecTable.Index: { if (typeSpecs == null) { typeSpecs = new Type[TypeSpec.records.Length]; } int index = (metadataToken & 0xFFFFFF) - 1; Type type = typeSpecs[index]; if (type == null) { TrackingGenericContext tc = context == null ? null : new TrackingGenericContext(context); type = Signature.ReadTypeSpec(this, ByteReader.FromBlob(blobHeap, TypeSpec.records[index]), tc); if (tc == null || !tc.IsUsed) { typeSpecs[index] = type; } } return type; } default: throw new NotImplementedException(String.Format("0x{0:X}", metadataToken)); } } private Module ResolveModuleRef(int moduleNameIndex) { string moduleName = GetString(moduleNameIndex); Module module = assembly.GetModule(moduleName); if (module == null) { throw new FileNotFoundException(moduleName); } return module; } private sealed class TrackingGenericContext : IGenericContext { private readonly IGenericContext context; private bool used; internal TrackingGenericContext(IGenericContext context) { this.context = context; } internal bool IsUsed { get { return used; } } public Type GetGenericTypeArgument(int index) { used = true; return context.GetGenericTypeArgument(index); } public Type GetGenericMethodArgument(int index) { used = true; return context.GetGenericMethodArgument(index); } } public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { if ((metadataToken >> 24) == TypeSpecTable.Index) { return ResolveType(metadataToken, new GenericContext(genericTypeArguments, genericMethodArguments)); } else { return ResolveType(metadataToken, null); } } private string GetTypeName(int typeNamespace, int typeName) { if (typeNamespace == 0) { return GetString(typeName); } else { return GetString(typeNamespace) + "." + GetString(typeName); } } private Assembly ResolveAssemblyRef(int index) { if (assemblyRefs == null) { assemblyRefs = new Assembly[AssemblyRef.RowCount]; } if (assemblyRefs[index] == null) { assemblyRefs[index] = ResolveAssemblyRefImpl(ref AssemblyRef.records[index]); } return assemblyRefs[index]; } private Assembly ResolveAssemblyRefImpl(ref AssemblyRefTable.Record rec) { const int PublicKey = 0x0001; string name = String.Format("{0}, Version={1}.{2}.{3}.{4}, Culture={5}, {6}={7}", GetString(rec.Name), rec.MajorVersion, rec.MinorVersion, rec.BuildNumber, rec.RevisionNumber, rec.Culture == 0 ? "neutral" : GetString(rec.Culture), (rec.Flags & PublicKey) == 0 ? "PublicKeyToken" : "PublicKey", PublicKeyOrTokenToString(rec.PublicKeyOrToken)); return universe.Load(name, this.Assembly, true); } private string PublicKeyOrTokenToString(int publicKeyOrToken) { if (publicKeyOrToken == 0) { return "null"; } ByteReader br = GetBlob(publicKeyOrToken); if (br.Length == 0) { return "null"; } StringBuilder sb = new StringBuilder(br.Length * 2); while (br.Length > 0) { sb.AppendFormat("{0:x2}", br.ReadByte()); } return sb.ToString(); } public override Guid ModuleVersionId { get { byte[] buf = new byte[16]; Buffer.BlockCopy(guidHeap, 16 * (ModuleTable.records[0].Mvid - 1), buf, 0, 16); return new Guid(buf); } } public override string FullyQualifiedName { get { return location ?? "<Unknown>"; } } public override string Name { get { return location == null ? "<Unknown>" : System.IO.Path.GetFileName(location); } } public override Assembly Assembly { get { return assembly; } } internal override Type GetTypeImpl(string typeName) { PopulateTypeDef(); Type type; if (!types.TryGetValue(typeName, out type)) { LazyForwardedType fw; if (forwardedTypes.TryGetValue(typeName, out fw)) { return fw.GetType(this, typeName); } } return type; } public override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { switch (metadataToken >> 24) { case FieldTable.Index: return ResolveField(metadataToken, genericTypeArguments, genericMethodArguments); case MemberRefTable.Index: return GetMemberRef((metadataToken & 0xFFFFFF) - 1, genericTypeArguments, genericMethodArguments); case MethodDefTable.Index: case MethodSpecTable.Index: return ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments); } throw new ArgumentOutOfRangeException(); } internal FieldInfo GetFieldAt(TypeDefImpl owner, int index) { if (fields == null) { fields = new FieldInfo[Field.records.Length]; } if (fields[index] == null) { fields[index] = new FieldDefImpl(this, owner ?? FindFieldOwner(index), index); } return fields[index]; } public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { if ((metadataToken >> 24) == FieldTable.Index) { int index = (metadataToken & 0xFFFFFF) - 1; return GetFieldAt(null, index); } else if ((metadataToken >> 24) == MemberRefTable.Index) { FieldInfo field = GetMemberRef((metadataToken & 0xFFFFFF) - 1, genericTypeArguments, genericMethodArguments) as FieldInfo; if (field != null) { return field; } } throw new ArgumentOutOfRangeException(); } private TypeDefImpl FindFieldOwner(int fieldIndex) { // TODO use binary search? for (int i = 0; i < TypeDef.records.Length; i++) { int field = TypeDef.records[i].FieldList - 1; int end = TypeDef.records.Length > i + 1 ? TypeDef.records[i + 1].FieldList - 1 : Field.records.Length; if (field <= fieldIndex && fieldIndex < end) { PopulateTypeDef(); return typeDefs[i]; } } throw new InvalidOperationException(); } internal MethodBase GetMethodAt(TypeDefImpl owner, int index) { if (methods == null) { methods = new MethodBase[MethodDef.records.Length]; } if (methods[index] == null) { MethodDefImpl method = new MethodDefImpl(this, owner ?? FindMethodOwner(index), index); methods[index] = method.IsConstructor ? new ConstructorInfoImpl(method) : (MethodBase)method; } return methods[index]; } private sealed class GenericContext : IGenericContext { private readonly Type[] genericTypeArguments; private readonly Type[] genericMethodArguments; internal GenericContext(Type[] genericTypeArguments, Type[] genericMethodArguments) { this.genericTypeArguments = genericTypeArguments; this.genericMethodArguments = genericMethodArguments; } public Type GetGenericTypeArgument(int index) { return genericTypeArguments[index]; } public Type GetGenericMethodArgument(int index) { return genericMethodArguments[index]; } } public override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { if ((metadataToken >> 24) == MethodDefTable.Index) { int index = (metadataToken & 0xFFFFFF) - 1; return GetMethodAt(null, index); } else if ((metadataToken >> 24) == MemberRefTable.Index) { int index = (metadataToken & 0xFFFFFF) - 1; MethodBase method = GetMemberRef(index, genericTypeArguments, genericMethodArguments) as MethodBase; if (method != null) { return method; } } else if ((metadataToken >> 24) == MethodSpecTable.Index) { int index = (metadataToken & 0xFFFFFF) - 1; MethodInfo method = (MethodInfo)ResolveMethod(MethodSpec.records[index].Method, genericTypeArguments, genericMethodArguments); ByteReader instantiation = ByteReader.FromBlob(blobHeap, MethodSpec.records[index].Instantiation); return method.MakeGenericMethod(Signature.ReadMethodSpec(this, instantiation, new GenericContext(genericTypeArguments, genericMethodArguments))); } throw new ArgumentOutOfRangeException(); } public override Type[] __ResolveOptionalParameterTypes(int metadataToken) { if ((metadataToken >> 24) == MemberRefTable.Index) { int index = (metadataToken & 0xFFFFFF) - 1; int sig = MemberRef.records[index].Signature; return Signature.ReadOptionalParameterTypes(this, GetBlob(sig)); } else if ((metadataToken >> 24) == MethodDefTable.Index) { // for convenience, we support passing a MethodDef token as well, because in some places // it makes sense to have a vararg method that is referred to by its methoddef (e.g. ldftn). // Note that MethodSpec doesn't make sense, because generic methods cannot be vararg. return Type.EmptyTypes; } throw new ArgumentOutOfRangeException(); } public override string ScopeName { get { return GetString(ModuleTable.records[0].Name); } } private TypeDefImpl FindMethodOwner(int methodIndex) { // TODO use binary search? for (int i = 0; i < TypeDef.records.Length; i++) { int method = TypeDef.records[i].MethodList - 1; int end = TypeDef.records.Length > i + 1 ? TypeDef.records[i + 1].MethodList - 1 : MethodDef.records.Length; if (method <= methodIndex && methodIndex < end) { PopulateTypeDef(); return typeDefs[i]; } } throw new InvalidOperationException(); } private MemberInfo GetMemberRef(int index, Type[] genericTypeArguments, Type[] genericMethodArguments) { if (memberRefs == null) { memberRefs = new MemberInfo[MemberRef.records.Length]; } if (memberRefs[index] == null) { int owner = MemberRef.records[index].Class; int sig = MemberRef.records[index].Signature; string name = GetString(MemberRef.records[index].Name); switch (owner >> 24) { case MethodDefTable.Index: return GetMethodAt(null, (owner & 0xFFFFFF) - 1); case ModuleRefTable.Index: memberRefs[index] = ResolveTypeMemberRef(ResolveModuleType(owner), name, ByteReader.FromBlob(blobHeap, sig), genericTypeArguments, genericMethodArguments); break; case TypeDefTable.Index: case TypeRefTable.Index: memberRefs[index] = ResolveTypeMemberRef(ResolveType(owner), name, ByteReader.FromBlob(blobHeap, sig), genericTypeArguments, genericMethodArguments); break; case TypeSpecTable.Index: return ResolveTypeMemberRef(ResolveType(owner, genericTypeArguments, genericMethodArguments), name, ByteReader.FromBlob(blobHeap, sig), genericTypeArguments, genericMethodArguments); default: throw new BadImageFormatException(); } } return memberRefs[index]; } private Type ResolveModuleType(int token) { int index = (token & 0xFFFFFF) - 1; string name = GetString(ModuleRef.records[index]); Module module = assembly.GetModule(name); if (module == null || module.IsResource()) { throw new BadImageFormatException(); } return module.GetModuleType(); } private MemberInfo ResolveTypeMemberRef(Type type, string name, ByteReader sig, Type[] genericTypeArguments, Type[] genericMethodArguments) { IGenericContext context; if ((genericTypeArguments == null && genericMethodArguments == null) || type.IsGenericType) { context = type; } else { context = new GenericContext(genericTypeArguments, genericMethodArguments); } if (sig.PeekByte() == Signature.FIELD) { Type org = type; FieldSignature fieldSig = FieldSignature.ReadSig(this, sig, context); do { FieldInfo field = type.FindField(name, fieldSig); if (field != null) { return field; } type = type.BaseType; } while (type != null); throw new MissingFieldException(org.ToString(), name); } else { Type org = type; MethodSignature methodSig = MethodSignature.ReadSig(this, sig, context); do { MethodBase method = type.FindMethod(name, methodSig); if (method != null) { return method; } type = type.BaseType; } while (type != null); throw new MissingMethodException(org.ToString(), name); } } internal new ByteReader ResolveSignature(int metadataToken) { if ((metadataToken >> 24) == StandAloneSigTable.Index) { int index = (metadataToken & 0xFFFFFF) - 1; return ByteReader.FromBlob(blobHeap, StandAloneSig.records[index]); } throw new ArgumentOutOfRangeException(); } public override __StandAloneMethodSig __ResolveStandAloneMethodSig(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { return MethodSignature.ReadStandAloneMethodSig(this, ResolveSignature(metadataToken), new GenericContext(genericTypeArguments, genericMethodArguments)); } internal MethodInfo GetEntryPoint() { if (cliHeader.EntryPointToken != 0 && (cliHeader.Flags & CliHeader.COMIMAGE_FLAGS_NATIVE_ENTRYPOINT) == 0) { return (MethodInfo)ResolveMethod((int)cliHeader.EntryPointToken); } return null; } internal string[] GetManifestResourceNames() { string[] names = new string[ManifestResource.records.Length]; for (int i = 0; i < ManifestResource.records.Length; i++) { names[i] = GetString(ManifestResource.records[i].Name); } return names; } internal ManifestResourceInfo GetManifestResourceInfo(string resourceName) { for (int i = 0; i < ManifestResource.records.Length; i++) { if (resourceName == GetString(ManifestResource.records[i].Name)) { return new ManifestResourceInfo(this, i); } } return null; } internal Stream GetManifestResourceStream(string resourceName) { for (int i = 0; i < ManifestResource.records.Length; i++) { if (resourceName == GetString(ManifestResource.records[i].Name)) { if (ManifestResource.records[i].Implementation != 0x26000000) { throw new NotImplementedException(); } SeekRVA((int)cliHeader.ResourcesRVA + ManifestResource.records[i].Offset); BinaryReader br = new BinaryReader(stream); int length = br.ReadInt32(); return new MemoryStream(br.ReadBytes(length)); } } throw new FileNotFoundException(); } internal AssemblyName[] GetReferencedAssemblies() { List<AssemblyName> list = new List<AssemblyName>(); for (int i = 0; i < AssemblyRef.records.Length; i++) { AssemblyName name = new AssemblyName(); name.Name = GetString(AssemblyRef.records[i].Name); name.Version = new Version( AssemblyRef.records[i].MajorVersion, AssemblyRef.records[i].MinorVersion, AssemblyRef.records[i].BuildNumber, AssemblyRef.records[i].RevisionNumber); if (AssemblyRef.records[i].PublicKeyOrToken != 0) { byte[] keyOrToken = GetBlobCopy(AssemblyRef.records[i].PublicKeyOrToken); const int PublicKey = 0x0001; if ((AssemblyRef.records[i].Flags & PublicKey) != 0) { name.SetPublicKey(keyOrToken); } else { name.SetPublicKeyToken(keyOrToken); } } if (AssemblyRef.records[i].Culture != 0) { name.CultureInfo = new System.Globalization.CultureInfo(GetString(AssemblyRef.records[i].Culture)); } else { name.CultureInfo = System.Globalization.CultureInfo.InvariantCulture; } name.Flags = (AssemblyNameFlags)AssemblyRef.records[i].Flags; list.Add(name); } return list.ToArray(); } internal override Type GetModuleType() { PopulateTypeDef(); return moduleType; } internal string ImageRuntimeVersion { get { return imageRuntimeVersion; } } public override int MDStreamVersion { get { return metadataStreamVersion; } } public override void __GetDataDirectoryEntry(int index, out int rva, out int length) { peFile.GetDataDirectoryEntry(index, out rva, out length); } public override long __RelativeVirtualAddressToFileOffset(int rva) { return peFile.RvaToFileOffset((uint)rva); } public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine) { peKind = 0; if ((cliHeader.Flags & CliHeader.COMIMAGE_FLAGS_ILONLY) != 0) { peKind |= PortableExecutableKinds.ILOnly; } if ((cliHeader.Flags & CliHeader.COMIMAGE_FLAGS_32BITREQUIRED) != 0) { peKind |= PortableExecutableKinds.Required32Bit; } if (peFile.OptionalHeader.Magic == IMAGE_OPTIONAL_HEADER.IMAGE_NT_OPTIONAL_HDR64_MAGIC) { peKind |= PortableExecutableKinds.PE32Plus; } machine = (ImageFileMachine)peFile.FileHeader.Machine; } public override int __Subsystem { get { return peFile.OptionalHeader.Subsystem; } } internal override void Dispose() { stream.Close(); } } }
gpl-2.0
avijitdeb/flatterbox.com
wp-content/plugins/woocommerce-shipping-multiple-addresses/class.ms_compat.php
11028
<?php /** * WooCommerce Plugin Compatibility * * This source file is subject to the GNU General Public License v3.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://www.gnu.org/licenses/gpl-3.0.html * 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@skyverge.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade the plugin to newer * versions in the future. If you wish to customize the plugin for your * needs please refer to http://www.skyverge.com * * @author SkyVerge * @copyright Copyright (c) 2013-2014, SkyVerge, Inc. * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly if ( ! class_exists( 'WC_MS_Compatibility' ) ) : /** * WooCommerce Compatibility Utility Class * * The unfortunate purpose of this class is to provide a single point of * compatibility functions for dealing with supporting multiple versions * of WooCommerce. * * The recommended procedure is to rename this file/class, replacing "my plugin" * with the particular plugin name, so as to avoid clashes between plugins. * Over time we expect to remove methods from this class, using the current * ones directly, as support for older versions of WooCommerce is dropped. * * Current Compatibility: 2.1.x - 2.2 * * @version 2.0 */ class WC_MS_Compatibility { /** * Get the WC Order instance for a given order ID or order post * * Introduced in WC 2.2 as part of the Order Factory so the 2.1 version is * not an exact replacement. * * If no param is passed, it will use the global post. Otherwise pass an * the order post ID or post object. * * @since 2.0.0 * @param bool|int|string|\WP_Post $the_order * @return bool|\WC_Order */ public static function wc_get_order( $the_order = false ) { if ( self::is_wc_version_gte_2_2() ) { return wc_get_order( $the_order ); } else { global $post; if ( false === $the_order ) { $order_id = $post->ID; } elseif ( $the_order instanceof WP_Post ) { $order_id = $the_order->ID; } elseif ( is_numeric( $the_order ) ) { $order_id = $the_order; } return new WC_Order( $order_id ); } } /** * Transparently backport the `post_status` WP Query arg used by WC 2.2 * for order statuses to the `shop_order_status` taxonomy query arg used by * WC 2.1 * * @since 2.0.0 * @param array $args WP_Query args * @return array */ public static function backport_order_status_query_args( $args ) { if ( ! self::is_wc_version_gte_2_2() ) { // convert post status arg to taxonomy query compatible with WC 2.1 if ( ! empty( $args['post_status'] ) ) { $order_statuses = array(); foreach ( (array) $args['post_status'] as $order_status ) { $order_statuses[] = str_replace( 'wc-', '', $order_status ); } $args['post_status'] = 'publish'; $tax_query = array( 'taxonomy' => 'shop_order_status', 'field' => 'slug', 'terms' => $order_statuses, 'operator' => 'IN', ); $args['tax_query'] = array_merge( isset( $args['tax_query'] ) ? $args['tax_query'] : array(), $tax_query ); } } return $args; } /** * Get the user ID for an order * * @since 2.0.0 * @param \WC_Order $order * @return int */ public static function get_order_user_id( WC_Order $order ) { if ( self::is_wc_version_gte_2_2() ) { return $order->get_user_id(); } else { return $order->customer_user ? $order->customer_user : 0; } } /** * Get the user for an order * * @since 2.0.0 * @param \WC_Order $order * @return bool|WP_User */ public static function get_order_user( WC_Order $order ) { if ( self::is_wc_version_gte_2_2() ) { return $order->get_user(); } else { return self::get_order_user_id( $order ) ? get_user_by( 'id', self::get_order_user_id( $order ) ) : false; } } /** * The the Order's status * @param WC_Order $order * @return string */ public static function get_order_status( WC_Order $order ) { if ( self::is_wc_version_gte_2_2() ) { return $order->get_status(); } else { return $order->status; } } /** * Get the WC Product instance for a given product ID or post * * get_product() is soft-deprecated in WC 2.2 * * @since 2.0.0 * @param bool|int|string|\WP_Post $the_product * @param array $args * @return WC_Product */ public static function wc_get_product( $the_product = false, $args = array() ) { if ( self::is_wc_version_gte_2_2() ) { return wc_get_product( $the_product, $args ); } else { return get_product( $the_product, $args ); } } /** * Return an array of formatted item meta in format: * * array( * $meta_key => array( * 'label' => $label, * 'value' => $value * ) * ) * * e.g. * * array( * 'pa_size' => array( * 'label' => 'Size', * 'value' => 'Medium', * ) * ) * * Backports the get_formatted() method to WC 2.1 * * @since 2.0.0 * @see WC_Order_Item_Meta::get_formatted() * @param \WC_Order_Item_Meta $item_meta order item meta class instance * @param string $hide_prefix exclude meta when key is prefixed with this, defaults to `_` * @return array */ public static function get_formatted_item_meta( WC_Order_Item_Meta $item_meta, $hide_prefix = '_' ) { if ( self::is_wc_version_gte_2_2() ) { return $item_meta->get_formatted( $hide_prefix ); } else { if ( empty( $item_meta->meta ) ) { return array(); } $formatted_meta = array(); foreach ( (array) $item_meta->meta as $meta_key => $meta_values ) { if ( empty( $meta_values ) || ! is_array( $meta_values ) || ( ! empty( $hide_prefix ) && substr( $meta_key, 0, 1 ) == $hide_prefix ) ) { continue; } foreach ( $meta_values as $meta_value ) { // Skip serialised meta if ( is_serialized( $meta_value ) ) { continue; } $attribute_key = urldecode( str_replace( 'attribute_', '', $meta_key ) ); // If this is a term slug, get the term's nice name if ( taxonomy_exists( $attribute_key ) ) { $term = get_term_by( 'slug', $meta_value, $attribute_key ); if ( ! is_wp_error( $term ) && is_object( $term ) && $term->name ) { $meta_value = $term->name; } // If we have a product, and its not a term, try to find its non-sanitized name } elseif ( $item_meta->product ) { $product_attributes = $item_meta->product->get_attributes(); if ( isset( $product_attributes[ $attribute_key ] ) ) { $meta_key = wc_attribute_label( $product_attributes[ $attribute_key ]['name'] ); } } $formatted_meta[ $meta_key ] = array( 'label' => wc_attribute_label( $attribute_key ), 'value' => apply_filters( 'woocommerce_order_item_display_meta_value', $meta_value ), ); } } return $formatted_meta; } } /** * Get the full path to the log file for a given $handle * * @since 2.0.0 * @param string $handle log handle * @return string */ public static function wc_get_log_file_path( $handle ) { if ( self::is_wc_version_gte_2_2() ) { return wc_get_log_file_path( $handle ); } else { return sprintf( '%s/plugins/woocommerce/logs/%s-%s.txt', WP_CONTENT_DIR, $handle, sanitize_file_name( wp_hash( $handle ) ) ); } } /** * Helper method to get the version of the currently installed WooCommerce * * @since 1.0.0 * @return string woocommerce version number or null */ private static function get_wc_version() { return defined( 'WC_VERSION' ) && WC_VERSION ? WC_VERSION : null; } /** * Returns true if the installed version of WooCommerce is 2.2 or greater * * @since 2.0.0 * @return boolean true if the installed version of WooCommerce is 2.2 or greater */ public static function is_wc_version_gte_2_2() { return self::get_wc_version() && version_compare( self::get_wc_version(), '2.2', '>=' ); } /** * Returns true if the installed version of WooCommerce is greater than $version * * @since 1.0.0 * @param string $version the version to compare * @return boolean true if the installed version of WooCommerce is > $version */ public static function is_wc_version_gt( $version ) { return self::get_wc_version() && version_compare( self::get_wc_version(), $version, '>' ); } } endif; // Class exists check
gpl-2.0
alexanderfefelov/nav
tests/integration/snmptrapd_test.py
2564
import ConfigParser import pytest from unittest import TestCase import signal import time from nav.buildconf import sysconfdir from nav.snmptrapd.plugin import load_handler_modules class SnmptrapdPluginTest(TestCase): """Implementation tests for plugins""" def test_loading_plugin_with_initialize_method_raises_no_exception(self): loader = load_handler_modules(['nav.snmptrapd.handlers.weathergoose']) assert loader[0] == __import__('nav.snmptrapd.handlers.weathergoose', globals(), locals(), ['weathergoose']) assert hasattr(loader[0], 'initialize') def test_plugin_loader_raises_no_exception_if_plugin_has_no_initialize_method(self): loader = load_handler_modules(['nav.snmptrapd.handlers.airespace']) assert loader[0] == __import__('nav.snmptrapd.handlers.airespace', globals(), locals(), 'airespace') assert not hasattr(loader[0], 'initialize') def test_plugin_loader_reading_in_modules_from_config_file(self): configfile = sysconfdir + "/snmptrapd.conf" config = ConfigParser.ConfigParser() config.read(configfile) list_from_config = config.get('snmptrapd', 'handlermodules').split(',') assert type(list_from_config) == list if len(list_from_config) <= 0: pytest.skip("Requires at least one plugin in snmptrapd.conf to run" + " this integration test with loading plugins") loaded_modules = load_handler_modules(list_from_config) assert len(list_from_config) == len(loaded_modules) class SnmptrapdSignalTest(TestCase): class TestIsOk(Exception): pass def setUp(self): def second_alarm(*_): print "Second ALRM signal received" raise self.TestIsOk() def first_alarm(*_): print "First ALRM signal received" signal.signal(signal.SIGALRM, second_alarm) signal.alarm(1) signal.signal(signal.SIGALRM, first_alarm) def tearDown(self): signal.signal(signal.SIGALRM, signal.SIG_DFL) def test_traplistener_does_not_raise_error_on_signals(self): from nav.snmptrapd.agent_pynetsnmp import TrapListener handler = TrapListener(('127.0.0.1', 0)) signal.alarm(1) time.sleep(0.5) handler.open() try: self.assertRaises(self.TestIsOk, handler.listen, 'public', lambda x, y: None) finally: handler.close()
gpl-2.0
joshmoore/openmicroscopy
components/tools/OmeroJava/test/integration/ImporterTest.java
47694
/* * $Id$ * * Copyright 2006-2010 University of Dundee. All rights reserved. * Use is subject to license terms supplied in LICENSE.txt */ package integration; import java.awt.Color; import java.io.File; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import ome.xml.model.OME; import omero.api.IRoiPrx; import omero.api.RoiOptions; import omero.api.RoiResult; import omero.model.Annotation; import omero.model.Arc; import omero.model.BooleanAnnotation; import omero.model.Channel; import omero.model.CommentAnnotation; import omero.model.Detector; import omero.model.DetectorSettings; import omero.model.Dichroic; import omero.model.Experiment; import omero.model.Filament; import omero.model.Filter; import omero.model.IObject; import omero.model.Image; import omero.model.ImageAnnotationLink; import omero.model.ImagingEnvironment; import omero.model.Instrument; import omero.model.Laser; import omero.model.LightEmittingDiode; import omero.model.LightPath; import omero.model.LightSettings; import omero.model.LightSource; import omero.model.LogicalChannel; import omero.model.LongAnnotation; import omero.model.MicrobeamManipulation; import omero.model.Microscope; import omero.model.OTF; import omero.model.Objective; import omero.model.ObjectiveSettings; import omero.model.Pixels; import omero.model.PlaneInfo; import omero.model.Plate; import omero.model.PlateAcquisition; import omero.model.Reagent; import omero.model.Roi; import omero.model.Screen; import omero.model.Shape; import omero.model.StageLabel; import omero.model.TagAnnotation; import omero.model.TermAnnotation; import omero.model.TransmittanceRange; import omero.model.Well; import omero.model.WellReagentLink; import omero.model.WellSample; import omero.sys.ParametersI; /** * Collection of tests to import images. * * @author Jean-Marie Burel &nbsp;&nbsp;&nbsp;&nbsp; * <a href="mailto:j.burel@dundee.ac.uk">j.burel@dundee.ac.uk</a> * @author Donald MacDonald &nbsp;&nbsp;&nbsp;&nbsp; * <a href="mailto:donald@lifesci.dundee.ac.uk">donald@lifesci.dundee.ac.uk</a> * @version 3.0 * <small> * (<b>Internal version:</b> $Revision: $Date: $) * </small> * @since 3.0-Beta4 */ @Test(groups = {"import", "integration"}) public class ImporterTest extends AbstractTest { /** The collection of files that have to be deleted. */ private List<File> files; /** * Attempts to create a Java timestamp from an XML date/time string. * @param value An <i>xsd:dateTime</i> string. * @return A value Java timestamp for <code>value</code> or * <code>null</code> if timestamp parsing failed. The error will be logged * at the <code>ERROR</code> log level. */ private Timestamp timestampFromXmlString(String value) { try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss"); return new Timestamp(sdf.parse(value).getTime()); } catch (ParseException e) { log.error(String.format( "Parsing timestamp '%s' failed!", value), e); } return null; } /** * Validates if the inserted object corresponds to the XML object. * * @param objective The objective to check. * @param xml The XML version. */ private void validateObjective(Objective objective, ome.xml.model.Objective xml) { assertEquals(objective.getManufacturer().getValue(), xml.getManufacturer()); assertEquals(objective.getModel().getValue(), xml.getModel()); assertEquals(objective.getSerialNumber().getValue(), xml.getSerialNumber()); assertEquals(objective.getLotNumber().getValue(), xml.getLotNumber()); assertEquals(objective.getCalibratedMagnification().getValue(), xml.getCalibratedMagnification().doubleValue()); assertTrue(objective.getCorrection().getValue().getValue().equals( xml.getCorrection().getValue())); assertTrue(objective.getImmersion().getValue().getValue().equals( xml.getImmersion().getValue())); assertEquals(objective.getIris().getValue(), xml.getIris().booleanValue()); assertEquals(objective.getLensNA().getValue(), xml.getLensNA().doubleValue()); assertEquals(objective.getNominalMagnification().getValue(), xml.getNominalMagnification().getValue().intValue()); assertEquals(objective.getWorkingDistance().getValue(), xml.getWorkingDistance()); } /** * Validates if the inserted object corresponds to the XML object. * * @param detector The detector to check. * @param xml The XML version. */ private void validateDetector(Detector detector, ome.xml.model.Detector xml) { assertEquals(detector.getManufacturer().getValue(), xml.getManufacturer()); assertEquals(detector.getModel().getValue(), xml.getModel()); assertEquals(detector.getSerialNumber().getValue(), xml.getSerialNumber()); assertEquals(detector.getLotNumber().getValue(), xml.getLotNumber()); assertEquals(detector.getAmplificationGain().getValue(), xml.getAmplificationGain().doubleValue()); assertEquals(detector.getGain().getValue(), xml.getGain()); } /** * Validates if the inserted object corresponds to the XML object. * * @param arc The arc to check. * @param xml The XML version. */ private void validateArc(Arc arc, ome.xml.model.Arc xml) { assertEquals(arc.getManufacturer().getValue(), xml.getManufacturer()); assertEquals(arc.getModel().getValue(), xml.getModel()); assertEquals(arc.getSerialNumber().getValue(), xml.getSerialNumber()); assertEquals(arc.getLotNumber().getValue(), xml.getLotNumber()); assertEquals(arc.getPower().getValue(), xml.getPower()); assertTrue(arc.getType().getValue().getValue().equals( XMLMockObjects.ARC_TYPE.getValue())); } /** * Validates if the inserted object corresponds to the XML object. * * @param laser The laser to check. * @param xml The XML version. */ private void validateLaser(Laser laser, ome.xml.model.Laser xml) { assertEquals(laser.getManufacturer().getValue(), xml.getManufacturer()); assertEquals(laser.getModel().getValue(), xml.getModel()); assertEquals(laser.getSerialNumber().getValue(), xml.getSerialNumber()); assertEquals(laser.getLotNumber().getValue(), xml.getLotNumber()); assertEquals(laser.getPower().getValue(), xml.getPower()); assertTrue(laser.getType().getValue().getValue().equals( XMLMockObjects.LASER_TYPE.getValue())); } /** * Validates if the inserted object corresponds to the XML object. * * @param filament The filament to check. * @param xml The XML version. */ private void validateFilament(Filament filament, ome.xml.model.Filament xml) { assertEquals(filament.getManufacturer().getValue(), xml.getManufacturer()); assertEquals(filament.getModel().getValue(), xml.getModel()); assertEquals(filament.getSerialNumber().getValue(), xml.getSerialNumber()); assertEquals(filament.getLotNumber().getValue(), xml.getLotNumber()); assertEquals(filament.getPower().getValue(), xml.getPower()); assertTrue(filament.getType().getValue().getValue().equals( XMLMockObjects.FILAMENT_TYPE.getValue())); } /** * Validates if the inserted object corresponds to the XML object. * * @param filter The filter to check. * @param xml The XML version. */ private void validateFilter(Filter filter, ome.xml.model.Filter xml) { assertEquals(filter.getManufacturer().getValue(), xml.getManufacturer()); assertEquals(filter.getModel().getValue(), xml.getModel()); assertEquals(filter.getLotNumber().getValue(), xml.getLotNumber()); assertEquals(filter.getSerialNumber().getValue(), xml.getSerialNumber()); assertTrue(filter.getType().getValue().getValue().equals( xml.getType().getValue())); TransmittanceRange tr = filter.getTransmittanceRange(); ome.xml.model.TransmittanceRange xmlTr = xml.getTransmittanceRange(); assertEquals(tr.getCutIn().getValue(), xmlTr.getCutIn().getValue().intValue()); assertEquals(tr.getCutOut().getValue(), xmlTr.getCutOut().getValue().intValue()); assertEquals(tr.getCutInTolerance().getValue(), xmlTr.getCutInTolerance().getValue().intValue()); assertEquals(tr.getCutOutTolerance().getValue(), xmlTr.getCutOutTolerance().getValue().intValue()); } /** * Validates if the inserted object corresponds to the XML object. * * @param dichroic The dichroic to check. * @param xml The XML version. */ private void validateDichroic(Dichroic dichroic, ome.xml.model.Dichroic xml) { assertEquals(dichroic.getManufacturer().getValue(), xml.getManufacturer()); assertEquals(dichroic.getModel().getValue(), xml.getModel()); assertEquals(dichroic.getLotNumber().getValue(), xml.getLotNumber()); assertEquals(dichroic.getSerialNumber().getValue(), xml.getSerialNumber()); } /** * Validates if the inserted object corresponds to the XML object. * * @param diode The light emitting diode to check. * @param xml The XML version. */ private void validateLightEmittingDiode(LightEmittingDiode diode, ome.xml.model.LightEmittingDiode xml) { assertEquals(diode.getManufacturer().getValue(), xml.getManufacturer()); assertEquals(diode.getModel().getValue(), xml.getModel()); assertEquals(diode.getSerialNumber().getValue(), xml.getSerialNumber()); assertEquals(diode.getLotNumber().getValue(), xml.getLotNumber()); assertEquals(diode.getPower().getValue(), xml.getPower()); } /** * Validates if the inserted object corresponds to the XML object. * * @param settings The settings to check. * @param xml The XML version. */ private void validateDetectorSettings(DetectorSettings settings, ome.xml.model.DetectorSettings xml) { assertEquals(settings.getBinning().getValue().getValue(), xml.getBinning().getValue()); assertEquals(settings.getGain().getValue(), xml.getGain()); assertEquals(settings.getOffsetValue().getValue(), xml.getOffset()); assertEquals(settings.getReadOutRate().getValue(), xml.getReadOutRate()); assertEquals(settings.getVoltage().getValue(), xml.getVoltage()); } /** * Validates if the inserted object corresponds to the XML object. * * @param settings The settings to check. * @param xml The XML version. */ private void validateObjectiveSettings(ObjectiveSettings settings, ome.xml.model.ObjectiveSettings xml) { assertEquals(settings.getCorrectionCollar().getValue(), xml.getCorrectionCollar().doubleValue()); assertEquals(settings.getRefractiveIndex().getValue(), xml.getRefractiveIndex().doubleValue()); assertEquals(settings.getMedium().getValue().getValue(), xml.getMedium().getValue()); } /** * Validates if the inserted object corresponds to the XML object. * * @param settings The settings to check. * @param xml The XML version. */ private void validateLightSourceSettings(LightSettings settings, ome.xml.model.LightSourceSettings xml) { assertEquals(settings.getAttenuation().getValue(), xml.getAttenuation().getValue().doubleValue()); assertEquals(settings.getWavelength().getValue(), xml.getWavelength().getValue().intValue()); } /** * Validates if the inserted object corresponds to the XML object. * * @param env The environment to check. * @param xml The XML version. */ private void validateImagingEnvironment(ImagingEnvironment env, ome.xml.model.ImagingEnvironment xml) { assertEquals(env.getAirPressure().getValue(), xml.getAirPressure().doubleValue()); assertEquals(env.getCo2percent().getValue(), xml.getCO2Percent().getValue().doubleValue()); assertEquals(env.getHumidity().getValue(), xml.getHumidity().getValue().doubleValue()); assertEquals(env.getTemperature().getValue(), xml.getTemperature().doubleValue()); } /** * Validates if the inserted object corresponds to the XML object. * * @param label The label to check. * @param xml The XML version. */ private void validateStageLabel(StageLabel label, ome.xml.model.StageLabel xml) { assertEquals(label.getName().getValue(), xml.getName()); assertEquals(label.getPositionX().getValue(), xml.getX().doubleValue()); assertEquals(label.getPositionY().getValue(), xml.getY().doubleValue()); assertEquals(label.getPositionZ().getValue(), xml.getZ().doubleValue()); } /** * Validates if the inserted object corresponds to the XML object. * * @param microscope The microscope to check. * @param xml The XML version. */ private void validateMicroscope(Microscope microscope, ome.xml.model.Microscope xml) { assertEquals(microscope.getManufacturer().getValue(), xml.getManufacturer()); assertEquals(microscope.getModel().getValue(), xml.getModel()); assertEquals(microscope.getSerialNumber().getValue(), xml.getSerialNumber()); assertEquals(microscope.getLotNumber().getValue(), xml.getLotNumber()); assertEquals(microscope.getType().getValue().getValue(), xml.getType().getValue()); } /** * Validates if the inserted object corresponds to the XML object. * * @param lc The logical channel to check. * @param xml The XML version. */ private void validateChannel(LogicalChannel lc, ome.xml.model.Channel xml) { assertEquals(lc.getName().getValue(), xml.getName()); assertEquals(lc.getIllumination().getValue().getValue(), xml.getIlluminationType().getValue()); assertEquals(lc.getMode().getValue().getValue(), xml.getAcquisitionMode().getValue()); assertEquals(lc.getContrastMethod().getValue().getValue(), xml.getContrastMethod().getValue()); assertEquals(lc.getEmissionWave().getValue(), xml.getEmissionWavelength().getValue().intValue()); assertEquals(lc.getExcitationWave().getValue(), xml.getExcitationWavelength().getValue().intValue()); assertEquals(lc.getFluor().getValue(), xml.getFluor()); assertEquals(lc.getNdFilter().getValue(), xml.getNDFilter()); assertEquals(lc.getPockelCellSetting().getValue(), xml.getPockelCellSetting().intValue()); } /** * Validates if the inserted object corresponds to the XML object. * * @param plate The plate to check. * @param xml The XML version. */ private void validatePlate(Plate plate, ome.xml.model.Plate xml) { assertEquals(plate.getName().getValue(), xml.getName()); assertEquals(plate.getDescription().getValue(), xml.getDescription()); assertEquals(plate.getRowNamingConvention().getValue(), xml.getRowNamingConvention().getValue()); assertEquals(plate.getColumnNamingConvention().getValue(), xml.getColumnNamingConvention().getValue()); assertEquals(plate.getRows().getValue(), xml.getRows().getValue().intValue()); assertEquals(plate.getColumns().getValue(), xml.getColumns().getValue().intValue()); assertEquals(plate.getExternalIdentifier().getValue(), xml.getExternalIdentifier()); assertEquals(plate.getWellOriginX().getValue(), xml.getWellOriginX().doubleValue()); assertEquals(plate.getWellOriginY().getValue(), xml.getWellOriginY().doubleValue()); assertEquals(plate.getStatus().getValue(), xml.getStatus()); } /** * Validates if the inserted object corresponds to the XML object. * * @param screen The screen to check. * @param xml The XML version. */ private void validateScreen(Screen screen, ome.xml.model.Screen xml) { assertEquals(screen.getName().getValue(), xml.getName()); assertEquals(screen.getDescription().getValue(), xml.getDescription()); } /** * Validates if the inserted object corresponds to the XML object. * * @param reagent The reagent to check. * @param xml The XML version. */ private void validateReagent(Reagent reagent, ome.xml.model.Reagent xml) { assertEquals(reagent.getName().getValue(), xml.getName()); assertEquals(reagent.getDescription().getValue(), xml.getDescription()); assertEquals(reagent.getReagentIdentifier().getValue(), xml.getReagentIdentifier()); } /** * Validates if the inserted object corresponds to the XML object. * * @param well The plate to check. * @param xml The XML version. */ private void validateWell(Well well, ome.xml.model.Well xml) { assertEquals(well.getColumn().getValue(), xml.getColumn().getValue().intValue()); assertEquals(well.getRow().getValue(), xml.getRow().getValue().intValue()); assertEquals(well.getExternalDescription().getValue(), xml.getExternalDescription()); assertEquals(well.getExternalIdentifier().getValue(), xml.getExternalIdentifier()); Color xmlColor = new Color(xml.getColor()); assertEquals(well.getAlpha().getValue(), xmlColor.getAlpha()); assertEquals(well.getRed().getValue(), xmlColor.getRed()); assertEquals(well.getGreen().getValue(), xmlColor.getGreen()); assertEquals(well.getBlue().getValue(), xmlColor.getBlue()); } /** * Validates if the inserted object corresponds to the XML object. * * @param ws The well sample to check. * @param xml The XML version. */ private void validateWellSample(WellSample ws, ome.xml.model.WellSample xml) { assertEquals(ws.getPosX().getValue(), xml.getPositionX().doubleValue()); assertEquals(ws.getPosY().getValue(), xml.getPositionY().doubleValue()); Timestamp ts = timestampFromXmlString(xml.getTimepoint()); assertEquals(ws.getTimepoint().getValue(), ts.getTime()); } /** * Validates if the inserted object corresponds to the XML object. * * @param pa The plate acquisition to check. * @param xml The XML version. */ private void validatePlateAcquisition(PlateAcquisition pa, ome.xml.model.PlateAcquisition xml) { assertEquals(pa.getName().getValue(), xml.getName()); assertEquals(pa.getDescription().getValue(), xml.getDescription()); Timestamp ts = timestampFromXmlString(xml.getEndTime()); assertNotNull(ts); assertNotNull(pa.getEndTime()); assertEquals(pa.getEndTime().getValue(), ts.getTime()); ts = timestampFromXmlString(xml.getStartTime()); assertNotNull(ts); assertNotNull(pa.getStartTime()); assertEquals(pa.getStartTime().getValue(), ts.getTime()); } /** * Validates if the inserted object corresponds to the XML object. * * @param mm The microbeam manipulation to check. * @param xml The XML version. */ private void validateMicrobeamManipulation(MicrobeamManipulation mm, ome.xml.model.MicrobeamManipulation xml) { assertEquals(mm.getType().getValue().getValue(), xml.getType().getValue()); List<LightSettings> settings = mm.copyLightSourceSettings(); assertEquals(1, mm.sizeOfLightSourceSettings()); assertEquals(1, settings.size()); validateLightSourceSettings(settings.get(0), xml.getLightSourceSettings(0)); } /** * Validates if the inserted object corresponds to the XML object. * * @param experiment The microbeam manipulation to check. * @param xml The XML version. */ private void validateExperiment(Experiment experiment, ome.xml.model.Experiment xml) { assertEquals(experiment.getType().getValue().getValue(), xml.getType().getValue()); assertEquals(experiment.getDescription().getValue(), xml.getDescription()); } /** * Validates if the inserted object corresponds to the XML object. * * @param otf The otf to check. * @param xml The XML version. */ private void validateOTF(OTF otf, ome.xml.model.OTF xml) { assertEquals(otf.getOpticalAxisAveraged().getValue(), xml.getOpticalAxisAveraged().booleanValue()); assertEquals(otf.getSizeX().getValue(), xml.getSizeX().getValue().intValue()); assertEquals(otf.getSizeY().getValue(), xml.getSizeY().getValue().intValue()); assertEquals(otf.getPixelsType().getValue().getValue(), xml.getType().getValue()); } /** * Overridden to initialize the list. * @see AbstractTest#setUp() */ @Override @BeforeClass protected void setUp() throws Exception { super.setUp(); files = new ArrayList<File>(); } /** * Overridden to delete the files. * @see AbstractTest#tearDown() */ @Override @AfterClass public void tearDown() throws Exception { Iterator<File> i = files.iterator(); while (i.hasNext()) { i.next().delete(); } files.clear(); } /** * Tests the import of a <code>JPEG</code>, <code>PNG</code> * @throws Exception Thrown if an error occurred. */ @Test public void testImportGraphicsImages() throws Exception { File f; List<String> failures = new ArrayList<String>(); for (int i = 0; i < ModelMockFactory.FORMATS.length; i++) { f = File.createTempFile("testImportGraphicsImages" +ModelMockFactory.FORMATS[i], "."+ModelMockFactory.FORMATS[i]); mmFactory.createImageFile(f, ModelMockFactory.FORMATS[i]); files.add(f); try { importFile(f, ModelMockFactory.FORMATS[i]); } catch (Throwable e) { failures.add(ModelMockFactory.FORMATS[i]); } } if (failures.size() > 0) { Iterator<String> j = failures.iterator(); String s = ""; while (j.hasNext()) { s += j.next(); s += " "; } fail("Cannot import the following formats:"+s); } assertTrue("File Imported", failures.size() == 0); } /** * Tests the import of an OME-XML file with one image. * @throws Exception Thrown if an error occurred. */ @Test public void testImportSimpleImage() throws Exception { File f = File.createTempFile("testImportSimpleImage", "."+OME_FORMAT); files.add(f); XMLMockObjects xml = new XMLMockObjects(); XMLWriter writer = new XMLWriter(); writer.writeFile(f, xml.createImage(), true); List<Pixels> pixels = null; try { pixels = importFile(f, OME_FORMAT); } catch (Throwable e) { throw new Exception("cannot import image", e); } Pixels p = pixels.get(0); int size = XMLMockObjects.SIZE_Z*XMLMockObjects.SIZE_C*XMLMockObjects.SIZE_T; //test the pixels assertTrue(p.getSizeX().getValue() == XMLMockObjects.SIZE_X); assertTrue(p.getSizeY().getValue() == XMLMockObjects.SIZE_Y); assertTrue(p.getSizeZ().getValue() == XMLMockObjects.SIZE_Z); assertTrue(p.getSizeC().getValue() == XMLMockObjects.SIZE_C); assertTrue(p.getSizeT().getValue() == XMLMockObjects.SIZE_T); assertTrue(p.getPixelsType().getValue().getValue().equals( XMLMockObjects.PIXEL_TYPE.getValue())); assertTrue(p.getDimensionOrder().getValue().getValue().equals( XMLMockObjects.DIMENSION_ORDER.getValue())); //Check the plane info String sql = "select p from PlaneInfo as p where pixels.id = :pid"; ParametersI param = new ParametersI(); param.addLong("pid", p.getId().getValue()); List<IObject> l = iQuery.findAllByQuery(sql, param); assertEquals(size, l.size()); Iterator<IObject> i; PlaneInfo plane; int found = 0; for (int z = 0; z < XMLMockObjects.SIZE_Z; z++) { for (int t = 0; t < XMLMockObjects.SIZE_T; t++) { for (int c = 0; c < XMLMockObjects.SIZE_C; c++) { i = l.iterator(); while (i.hasNext()) { plane = (PlaneInfo) i.next(); if (plane.getTheC().getValue() == c && plane.getTheZ().getValue() == z && plane.getTheT().getValue() == t) found++; } } } } assertTrue(found == size); } /** * Tests the import of an OME-XML file with one image w/o binary data. * @throws Exception Thrown if an error occurred. */ @Test public void testImportSimpleImageMetadataOnly() throws Exception { File f = File.createTempFile("testImportSimpleImageMetadataOnly", "."+OME_FORMAT); files.add(f); XMLMockObjects xml = new XMLMockObjects(); XMLWriter writer = new XMLWriter(); writer.writeFile(f, xml.createImage(), true); try { importFile(f, OME_FORMAT, true); } catch (Throwable e) { throw new Exception("cannot import image", e); } } /** * Tests the import of an OME-XML file with one image w/o binary data. * @throws Exception Thrown if an error occurred. */ @Test(enabled = true) public void testImportSimpleImageMetadataOnlyNoBinaryInFile() throws Exception { File f = File.createTempFile( "testImportSimpleImageMetadataOnlyNoBinaryInFile", "."+OME_FORMAT); files.add(f); XMLMockObjects xml = new XMLMockObjects(); XMLWriter writer = new XMLWriter(); writer.writeFile(f, xml.createImage(), false); try { importFile(f, OME_FORMAT, true); } catch (Throwable e) { throw new Exception("cannot import image", e); } } /** * Tests the import of an OME-XML file with an annotated image. * @throws Exception Thrown if an error occurred. */ @Test public void testImportAnnotatedImage() throws Exception { File f = File.createTempFile("testImportAnnotatedImage", "."+OME_FORMAT); files.add(f); XMLMockObjects xml = new XMLMockObjects(); XMLWriter writer = new XMLWriter(); writer.writeFile(f, xml.createAnnotatedImage(), true); List<Pixels> pixels = null; try { pixels = importFile(f, OME_FORMAT); } catch (Throwable e) { throw new Exception("cannot import image", e); } Pixels p = pixels.get(0); long id = p.getImage().getId().getValue(); String sql = "select l from ImageAnnotationLink as l "; sql += "left outer join fetch l.parent as p "; sql += "join fetch l.child "; sql += "where p.id = :id"; ParametersI param = new ParametersI(); param.addId(id); List<IObject> l = iQuery.findAllByQuery(sql, param); //always companion file. if (l.size() < XMLMockObjects.ANNOTATIONS.length) { fail(String.format("%d < ANNOTATION count %d", l.size(), XMLMockObjects.ANNOTATIONS.length)); } int count = 0; Annotation a; for (IObject object : l) { a = ((ImageAnnotationLink) object).getChild(); if (a instanceof CommentAnnotation) count++; else if (a instanceof TagAnnotation) count++; else if (a instanceof TermAnnotation) count++; else if (a instanceof BooleanAnnotation) count++; else if (a instanceof LongAnnotation) count++; } assertEquals(XMLMockObjects.ANNOTATIONS.length, count); } /** * Tests the import of an OME-XML file with an image with acquisition data. * @throws Exception Thrown if an error occurred. */ @Test(enabled = true) public void testImportImageWithAcquisitionData() throws Exception { File f = File.createTempFile("testImportImageWithAcquisitionData", "."+OME_FORMAT); files.add(f); XMLMockObjects xml = new XMLMockObjects(); XMLWriter writer = new XMLWriter(); OME ome = xml.createImageWithAcquisitionData(); writer.writeFile(f, ome, true); List<Pixels> pixels = null; try { pixels = importFile(f, OME_FORMAT); } catch (Throwable e) { throw new Exception("cannot import image", e); } Pixels p = pixels.get(0); long id = p.getImage().getId().getValue(); //Method already tested in PojosServiceTest ParametersI po = new ParametersI(); po.acquisitionData(); List<Long> ids = new ArrayList<Long>(1); ids.add(id); List images = factory.getContainerService().getImages( Image.class.getName(), ids, po); assertEquals(1, images.size()); Image image = (Image) images.get(0); //load the image and make we have everything assertNotNull(image.getImagingEnvironment()); validateImagingEnvironment(image.getImagingEnvironment(), xml.createImageEnvironment()); assertNotNull(image.getStageLabel()); validateStageLabel(image.getStageLabel(), xml.createStageLabel()); ObjectiveSettings settings = image.getObjectiveSettings(); assertNotNull(settings); validateObjectiveSettings(image.getObjectiveSettings(), xml.createObjectiveSettings(0)); Instrument instrument = image.getInstrument(); assertNotNull(instrument); //check the instrument instrument = factory.getMetadataService().loadInstrument( instrument.getId().getValue()); assertNotNull(instrument); ome.xml.model.Laser xmlLaser = (ome.xml.model.Laser) xml.createLightSource(ome.xml.model.Laser.class.getName(), 0); ome.xml.model.Arc xmlArc = (ome.xml.model.Arc) xml.createLightSource(ome.xml.model.Arc.class.getName(), 0); ome.xml.model.Filament xmlFilament = (ome.xml.model.Filament) xml.createLightSource(ome.xml.model.Filament.class.getName(), 0); ome.xml.model.LightEmittingDiode xmlDiode = (ome.xml.model.LightEmittingDiode) xml.createLightSource(ome.xml.model.LightEmittingDiode.class.getName(), 0); ome.xml.model.Objective xmlObjective = xml.createObjective(0); ome.xml.model.Detector xmlDetector = xml.createDetector(0); ome.xml.model.Filter xmlFilter = xml.createFilter(0, XMLMockObjects.CUT_IN, XMLMockObjects.CUT_OUT); ome.xml.model.Dichroic xmlDichroic = xml.createDichroic(0); assertEquals(XMLMockObjects.NUMBER_OF_OBJECTIVES, instrument.sizeOfObjective()); assertEquals(XMLMockObjects.NUMBER_OF_DECTECTORS, instrument.sizeOfDetector()); assertEquals(XMLMockObjects.NUMBER_OF_DICHROICS, instrument.sizeOfDichroic()); assertEquals(XMLMockObjects.NUMBER_OF_FILTERS, instrument.sizeOfFilter()); assertEquals(1, instrument.sizeOfFilterSet()); assertEquals(1, instrument.sizeOfOtf()); List<Detector> detectors = instrument.copyDetector(); List<Long> detectorIds = new ArrayList<Long>(); Detector de; Iterator j = detectors.iterator(); while (j.hasNext()) { de = (Detector) j.next(); detectorIds.add(de.getId().getValue()); validateDetector(de, xmlDetector); } List<Objective> objectives = instrument.copyObjective(); j = objectives.iterator(); while (j.hasNext()) { validateObjective((Objective) j.next(), xmlObjective); } List<Filter> filters = instrument.copyFilter(); j = filters.iterator(); while (j.hasNext()) { validateFilter((Filter) j.next(), xmlFilter); } List<Dichroic> dichroics = instrument.copyDichroic(); j = dichroics.iterator(); while (j.hasNext()) { validateDichroic((Dichroic) j.next(), xmlDichroic); } List<LightSource> lights = instrument.copyLightSource(); j = lights.iterator(); List<Long> lightIds = new ArrayList<Long>(); LightSource src; while (j.hasNext()) { src = (LightSource) j.next(); if (src instanceof Laser) validateLaser((Laser) src, xmlLaser); else if (src instanceof Arc) validateArc((Arc) src, xmlArc); else if (src instanceof Filament) validateFilament((Filament) src, xmlFilament); lightIds.add(src.getId().getValue()); } p = factory.getPixelsService().retrievePixDescription( p.getId().getValue()); ids.clear(); ome.xml.model.Channel xmlChannel = xml.createChannel(0); Channel channel; List<Channel> channels = p.copyChannels(); Iterator<Channel> i = channels.iterator(); //assertTrue(xmlChannel.getColor().intValue() == // XMLMockObjects.DEFAULT_COLOR.getRGB()); Color c; while (i.hasNext()) { channel = i.next(); assertEquals(channel.getAlpha().getValue(), XMLMockObjects.DEFAULT_COLOR.getAlpha()); assertEquals(channel.getRed().getValue(), XMLMockObjects.DEFAULT_COLOR.getRed()); assertEquals(channel.getGreen().getValue(), XMLMockObjects.DEFAULT_COLOR.getGreen()); assertEquals(channel.getBlue().getValue(), XMLMockObjects.DEFAULT_COLOR.getBlue()); ids.add(channel.getLogicalChannel().getId().getValue()); } List<LogicalChannel> l = factory.getMetadataService().loadChannelAcquisitionData(ids); assertEquals(channels.size(), l.size()); LogicalChannel lc; DetectorSettings ds; LightSettings ls; ome.xml.model.DetectorSettings xmlDs = xml.createDetectorSettings(0); ome.xml.model.LightSourceSettings xmlLs = xml.createLightSourceSettings(0); ome.xml.model.MicrobeamManipulation xmlMM = xml.createMicrobeamManipulation(0); ome.xml.model.Experiment xmlExp = ome.getExperiment(0); ome.xml.model.OTF xmlOTF = ome.getInstrument(0).getOTF(0); // Validate experiment (initial checks) assertNotNull(image.getExperiment()); Experiment exp = (Experiment) factory.getQueryService().findByQuery( "select e from Experiment as e " + "join fetch e.type " + "left outer join fetch e.microbeamManipulation as mm " + "join fetch mm.type " + "left outer join fetch mm.lightSourceSettings as lss " + "left outer join fetch lss.lightSource " + "where e.id = :id", new ParametersI().addId( image.getExperiment().getId().getValue())); assertNotNull(exp); assertEquals(1, exp.sizeOfMicrobeamManipulation()); MicrobeamManipulation mm = exp.copyMicrobeamManipulation().get(0); validateExperiment(exp, xmlExp); validateMicrobeamManipulation(mm, xmlMM); LightPath path; Iterator<LogicalChannel> k = l.iterator(); while (k.hasNext()) { lc = k.next(); validateChannel(lc, xmlChannel); assertNotNull(lc.getOtf()); validateOTF(lc.getOtf(), xmlOTF); ds = lc.getDetectorSettings(); assertNotNull(ds); assertNotNull(ds.getDetector()); assertTrue(detectorIds.contains( ds.getDetector().getId().getValue())); validateDetectorSettings(ds, xmlDs); ls = lc.getLightSourceSettings(); assertNotNull(ls); assertNotNull(ls.getLightSource()); assertTrue(lightIds.contains( ls.getLightSource().getId().getValue())); validateLightSourceSettings(ls, xmlLs); path = lc.getLightPath(); assertNotNull(lc); assertNotNull(path.getDichroic()); } } /** * Tests the import of an OME-XML file with an image with ROI. * @throws Exception Thrown if an error occurred. */ public void testImportImageWithROI() throws Exception { File f = File.createTempFile("testImportImageWithROI", "."+OME_FORMAT); files.add(f); XMLMockObjects xml = new XMLMockObjects(); XMLWriter writer = new XMLWriter(); writer.writeFile(f, xml.createImageWithROI(), true); List<Pixels> pixels = null; try { pixels = importFile(f, OME_FORMAT); } catch (Throwable e) { throw new Exception("cannot import image", e); } Pixels p = pixels.get(0); long id = p.getImage().getId().getValue(); //load the image and make the ROI //Method tested in ROIServiceTest IRoiPrx svc = factory.getRoiService(); RoiResult r = svc.findByImage(id, new RoiOptions()); assertNotNull(r); List<Roi> rois = r.rois; assertNotNull(rois); assertTrue(rois.size() == XMLMockObjects.SIZE_C); Iterator<Roi> i = rois.iterator(); Roi roi; List<Shape> shapes; while (i.hasNext()) { roi = i.next(); shapes = roi.copyShapes(); assertNotNull(shapes); assertTrue(shapes.size() == XMLMockObjects.SHAPES.length); } } /** * Tests the import of an OME-XML file with a fully populated plate. * @throws Exception Thrown if an error occurred. */ @Test public void testImportPlate() throws Exception { File f = File.createTempFile("testImportPlate", "."+OME_FORMAT); files.add(f); XMLMockObjects xml = new XMLMockObjects(); XMLWriter writer = new XMLWriter(); OME ome = xml.createPopulatedPlate(0); writer.writeFile(f, ome, true); List<Pixels> pixels = null; try { pixels = importFile(f, OME_FORMAT); } catch (Throwable e) { throw new Exception("cannot import the plate", e); } Pixels p = pixels.get(0); WellSample ws = getWellSample(p); validateWellSample(ws, ome.getPlate(0).getWell(0).getWellSample(0)); Well well = ws.getWell(); assertNotNull(well); validateWell(well, ome.getPlate(0).getWell(0)); Plate plate = ws.getWell().getPlate(); assertNotNull(plate); validatePlate(plate, ome.getPlate(0)); } /** * Tests the import of an OME-XML file with a screen and * a fully populated plate. * @throws Exception Thrown if an error occurred. */ @Test public void testImportScreenWithOnePlate() throws Exception { File f = File.createTempFile("testImportScreenWithOnePlate", "."+OME_FORMAT); files.add(f); XMLMockObjects xml = new XMLMockObjects(); XMLWriter writer = new XMLWriter(); int rows = 2; int columns = 2; int fields = 2; int acquisition = 3; int plates = 1; OME ome = xml.createPopulatedScreen(plates, rows, columns, fields, acquisition); writer.writeFile(f, ome, true); List<Pixels> pixels = null; try { pixels = importFile(f, OME_FORMAT); } catch (Throwable e) { throw new Exception("cannot import the plate", e); } Pixels pp = pixels.get(0); WellSample ws = getWellSample(pp); validateWellSample(ws, ome.getPlate(0).getWell(0).getWellSample(0)); Well well = ws.getWell(); assertNotNull(well); validateWell(well, ome.getPlate(0).getWell(0)); Plate plate = ws.getWell().getPlate(); assertNotNull(plate); validatePlate(plate, ome.getPlate(0)); validateScreen(plate.copyScreenLinks().get(0).getParent(), ome.getScreen(0)); PlateAcquisition pa; Map<Long, Set<Long>> ppaMap = new HashMap<Long, Set<Long>>(); Map<Long, Set<Long>> pawsMap = new HashMap<Long, Set<Long>>(); Set<Long> wsIds; Set<Long> paIds; for (Pixels p : pixels) { ws = getWellSample(p); assertNotNull(ws); well = ws.getWell(); assertNotNull(well); plate = ws.getWell().getPlate(); pa = ws.getPlateAcquisition(); wsIds = pawsMap.get(pa.getId().getValue()); if (wsIds == null) { wsIds = new HashSet<Long>(); pawsMap.put(pa.getId().getValue(), wsIds); } wsIds.add(ws.getId().getValue()); paIds = ppaMap.get(plate.getId().getValue()); if (paIds == null) { paIds = new HashSet<Long>(); ppaMap.put(plate.getId().getValue(), paIds); } paIds.add(pa.getId().getValue()); assertNotNull(plate); validateScreen(plate.copyScreenLinks().get(0).getParent(), ome.getScreen(0)); } assertEquals(plates, ppaMap.size()); assertEquals(plates*acquisition, pawsMap.size()); Entry entry; Iterator i = ppaMap.entrySet().iterator(); Long id, idw; Set<Long> l; Set<Long> wsList; Iterator<Long> j, k; List<Long> plateIds = new ArrayList<Long>(); List<Long> wsListIds = new ArrayList<Long>(); while (i.hasNext()) { entry = (Entry) i.next(); l = (Set<Long>) entry.getValue(); assertEquals(acquisition, l.size()); j = l.iterator(); while (j.hasNext()) { id = j.next(); assertFalse(plateIds.contains(id)); plateIds.add(id); wsList = pawsMap.get(id); assertEquals(rows*columns*fields, wsList.size()); k = wsList.iterator(); while (k.hasNext()) { idw = k.next(); assertFalse(wsListIds.contains(idw)); wsListIds.add(idw); } } } assertEquals(rows*columns*fields*plates*acquisition, wsListIds.size()); } /** * Tests the import of an OME-XML file with a screen and * two fully populated plates. * @throws Exception Thrown if an error occurred. */ @Test(enabled=true) public void testImportScreenWithTwoPlates() throws Exception { File f = File.createTempFile("testImportScreenWithTwoPlates", "."+OME_FORMAT); files.add(f); XMLMockObjects xml = new XMLMockObjects(); XMLWriter writer = new XMLWriter(); int rows = 2; int columns = 2; int fields = 2; int acquisition = 2; int plates = 2; OME ome = xml.createPopulatedScreen(plates, rows, columns, fields, acquisition); //We should have 2 plates //each plate will have 2 plate acquisitions //2x2x2 fields writer.writeFile(f, ome, true); List<Pixels> pixels = null; try { pixels = importFile(f, OME_FORMAT); } catch (Throwable e) { throw new Exception("cannot import the plate", e); } WellSample ws; Well well; Plate plate; PlateAcquisition pa; Map<Long, Set<Long>> ppaMap = new HashMap<Long, Set<Long>>(); Map<Long, Set<Long>> pawsMap = new HashMap<Long, Set<Long>>(); Set<Long> wsIds; Set<Long> paIds; for (Pixels p : pixels) { ws = getWellSample(p); assertNotNull(ws); well = ws.getWell(); assertNotNull(well); plate = ws.getWell().getPlate(); pa = ws.getPlateAcquisition(); wsIds = pawsMap.get(pa.getId().getValue()); if (wsIds == null) { wsIds = new HashSet<Long>(); pawsMap.put(pa.getId().getValue(), wsIds); } wsIds.add(ws.getId().getValue()); paIds = ppaMap.get(plate.getId().getValue()); if (paIds == null) { paIds = new HashSet<Long>(); ppaMap.put(plate.getId().getValue(), paIds); } paIds.add(pa.getId().getValue()); assertNotNull(plate); validateScreen(plate.copyScreenLinks().get(0).getParent(), ome.getScreen(0)); } assertEquals(plates, ppaMap.size()); assertEquals(plates*acquisition, pawsMap.size()); Entry entry; Iterator i = ppaMap.entrySet().iterator(); Long id, idw; Set<Long> l; Set<Long> wsList; Iterator<Long> j, k; List<Long> plateIds = new ArrayList<Long>(); List<Long> wsListIds = new ArrayList<Long>(); while (i.hasNext()) { entry = (Entry) i.next(); l = (Set<Long>) entry.getValue(); assertEquals(acquisition, l.size()); j = l.iterator(); while (j.hasNext()) { id = j.next(); assertFalse(plateIds.contains(id)); plateIds.add(id); wsList = pawsMap.get(id); assertEquals(rows*columns*fields, wsList.size()); k = wsList.iterator(); while (k.hasNext()) { idw = k.next(); assertFalse(wsListIds.contains(idw)); wsListIds.add(idw); } } } assertEquals(rows*columns*fields*plates*acquisition, wsListIds.size()); } /** * Tests the import of an OME-XML file with a fully populated plate * with a plate acquisition. * @throws Exception Thrown if an error occurred. */ @Test public void testImportPlateOnePlateAcquisition() throws Exception { File f = File.createTempFile("testImportPlateOnePlateAcquisition", "."+OME_FORMAT); files.add(f); XMLMockObjects xml = new XMLMockObjects(); XMLWriter writer = new XMLWriter(); OME ome = xml.createPopulatedPlate(1); writer.writeFile(f, ome, true); List<Pixels> pixels = null; try { pixels = importFile(f, OME_FORMAT); } catch (Throwable e) { throw new Exception("cannot import the plate", e); } Pixels p = pixels.get(0); long id = p.getImage().getId().getValue(); String sql = "select ws from WellSample as ws "; sql += "join fetch ws.plateAcquisition as pa "; sql += "join fetch ws.well as w "; sql += "join fetch w.plate as p "; sql += "where ws.image.id = :id"; ParametersI param = new ParametersI(); param.addId(id); List<IObject> results = iQuery.findAllByQuery(sql, param); assertTrue(results.size() == 1); WellSample ws = (WellSample) results.get(0); assertNotNull(ws.getWell()); assertNotNull(ws.getWell().getPlate()); PlateAcquisition pa = ws.getPlateAcquisition(); assertNotNull(pa); validatePlateAcquisition(pa, ome.getPlate(0).getPlateAcquisition(0)); } /** * Tests the import of an OME-XML file with a fully populated plate * with a plate acquisition. * @throws Exception Thrown if an error occurred. */ @Test public void testImportPlateMultiplePlateAcquisitions() throws Exception { File f = File.createTempFile( "testImportPlateMultiplePlateAcquisitions", "."+OME_FORMAT); files.add(f); int n = 3; int fields = 3; XMLMockObjects xml = new XMLMockObjects(); XMLWriter writer = new XMLWriter(); OME ome = xml.createPopulatedPlate(n, fields); writer.writeFile(f, ome, true); List<Pixels> pixels = null; try { pixels = importFile(f, OME_FORMAT); } catch (Throwable e) { throw new Exception("cannot import the plate", e); } Pixels p = pixels.get(0); long id = p.getImage().getId().getValue(); String sql = "select ws from WellSample as ws "; sql += "join fetch ws.plateAcquisition as pa "; sql += "join fetch ws.well as w "; sql += "join fetch w.plate as p "; sql += "where ws.image.id = :id"; ParametersI param = new ParametersI(); param.addId(id); List<IObject> results = iQuery.findAllByQuery(sql, param); WellSample ws = (WellSample) results.get(0); assertNotNull(ws.getWell()); Plate plate = ws.getWell().getPlate(); sql = "select ws from WellSample as ws "; sql += "join fetch ws.plateAcquisition as pa "; sql += "join fetch ws.well as w "; sql += "join fetch w.plate as p "; sql += "where p.id = :id"; param = new ParametersI(); param.addId(plate.getId().getValue()); assertEquals(fields*n, iQuery.findAllByQuery(sql, param).size()); sql = "select pa from PlateAcquisition as pa "; sql += "where pa.plate.id = :id"; List<IObject> pas = iQuery.findAllByQuery(sql, param); assertEquals(n, pas.size()); Iterator<IObject> j = pas.iterator(); sql = "select ws from WellSample as ws "; sql += "join fetch ws.plateAcquisition as pa "; sql += "where pa.id = :id"; IObject obj; while (j.hasNext()) { obj = j.next(); param = new ParametersI(); param.addId(obj.getId().getValue()); assertEquals(fields, iQuery.findAllByQuery(sql, param).size()); } } /** * Tests the import of an OME-XML file with a plate * with wells linked to a reagent. * @throws Exception Thrown if an error occurred. */ @Test public void testImportPlateWithReagent() throws Exception { File f = File.createTempFile("testImportPlateWithReagent", "."+OME_FORMAT); files.add(f); XMLMockObjects xml = new XMLMockObjects(); XMLWriter writer = new XMLWriter(); OME ome = xml.createBasicPlateWithReagent(); writer.writeFile(f, ome, true); List<Pixels> pixels = null; try { pixels = importFile(f, OME_FORMAT); } catch (Throwable e) { throw new Exception("cannot import the plate", e); } Pixels p = pixels.get(0); long id = p.getImage().getId().getValue(); String sql = "select ws from WellSample as ws "; sql += "left outer join fetch ws.plateAcquisition as pa "; sql += "join fetch ws.well as w "; sql += "join fetch w.plate as p "; sql += "where ws.image.id = :id"; ParametersI param = new ParametersI(); param.addId(id); List<IObject> results = iQuery.findAllByQuery(sql, param); assertEquals(1, results.size()); WellSample ws = (WellSample) results.get(0); //assertNotNull(ws.getPlateAcquisition()); assertNotNull(ws.getWell()); id = ws.getWell().getId().getValue(); sql = "select l from WellReagentLink as l "; sql += "join fetch l.child as c "; sql += "join fetch l.parent as p "; sql += "where p.id = :id"; param = new ParametersI(); param.addId(id); WellReagentLink wr = (WellReagentLink) iQuery.findByQuery(sql, param); assertNotNull(wr); assertNotNull(wr.getParent()); assertNotNull(wr.getChild()); validateReagent(wr.getChild(), ome.getScreen(0).getReagent(0)); id = wr.getChild().getId().getValue(); sql = "select s from Screen as s "; sql += "join fetch s.reagents as r "; sql += "where r.id = :id"; param = new ParametersI(); param.addId(id); omero.model.Screen screen = (omero.model.Screen) iQuery.findByQuery(sql, param); assertNotNull(screen); assertEquals(1, screen.sizeOfReagents()); assertEquals(wr.getChild().getId().getValue(), screen.copyReagents().get(0).getId().getValue()); } }
gpl-2.0
martymcguire/epluribus
config/initializers/devise.rb
12471
# Use this hook to configure devise mailer, warden hooks and so forth. # Many of these configuration options can be set straight in your model. Devise.setup do |config| # The secret key used by Devise. Devise uses this key to generate # random tokens. Changing this key will render invalid all existing # confirmation, reset password and unlock tokens in the database. config.secret_key = '90af4f2d06de501aac69470ffc96e40a78c7c7b6aae9f2fea58b07c4334986c74d40f120351dbd7ae217d3c78aa3c57e28eae36e75890d68aa7265bc65af97c9' # ==> Mailer Configuration # Configure the e-mail address which will be shown in Devise::Mailer, # note that it will be overwritten if you use your own mailer class # with default "from" parameter. config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com' # Configure the class responsible to send e-mails. # config.mailer = 'Devise::Mailer' # ==> ORM configuration # Load and configure the ORM. Supports :active_record (default) and # :mongoid (bson_ext recommended) by default. Other ORMs may be # available as additional gems. require 'devise/orm/active_record' # ==> Configuration for any authentication mechanism # Configure which keys are used when authenticating a user. The default is # just :email. You can configure it to use [:username, :subdomain], so for # authenticating a user, both parameters are required. Remember that those # parameters are used only when authenticating and not when retrieving from # session. If you need permissions, you should implement that in a before filter. # You can also supply a hash where the value is a boolean determining whether # or not authentication should be aborted when the value is not present. # config.authentication_keys = [ :email ] # Configure parameters from the request object used for authentication. Each entry # given should be a request method and it will automatically be passed to the # find_for_authentication method and considered in your model lookup. For instance, # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. # The same considerations mentioned for authentication_keys also apply to request_keys. # config.request_keys = [] # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. config.case_insensitive_keys = [ :email ] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. config.strip_whitespace_keys = [ :email ] # Tell if authentication through request.params is enabled. True by default. # It can be set to an array that will enable params authentication only for the # given strategies, for example, `config.params_authenticatable = [:database]` will # enable it only for database (email + password) authentication. # config.params_authenticatable = true # Tell if authentication through HTTP Auth is enabled. False by default. # It can be set to an array that will enable http authentication only for the # given strategies, for example, `config.http_authenticatable = [:database]` will # enable it only for database authentication. The supported strategies are: # :database = Support basic authentication with authentication key + password # config.http_authenticatable = false # If http headers should be returned for AJAX requests. True by default. # config.http_authenticatable_on_xhr = true # The realm used in Http Basic Authentication. 'Application' by default. # config.http_authentication_realm = 'Application' # It will change confirmation, password recovery and other workflows # to behave the same regardless if the e-mail provided was right or wrong. # Does not affect registerable. # config.paranoid = true # By default Devise will store the user in session. You can skip storage for # particular strategies by setting this option. # Notice that if you are skipping storage for all authentication paths, you # may want to disable generating routes to Devise's sessions controller by # passing :skip => :sessions to `devise_for` in your config/routes.rb config.skip_session_storage = [:http_auth] # By default, Devise cleans up the CSRF token on authentication to # avoid CSRF token fixation attacks. This means that, when using AJAX # requests for sign in and sign up, you need to get a new CSRF token # from the server. You can disable this option at your own risk. # config.clean_up_csrf_token_on_authentication = true # ==> Configuration for :database_authenticatable # For bcrypt, this is the cost for hashing the password and defaults to 10. If # using other encryptors, it sets how many times you want the password re-encrypted. # # Limiting the stretches to just one in testing will increase the performance of # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use # a value less than 10 in other environments. config.stretches = Rails.env.test? ? 1 : 10 # Setup a pepper to generate the encrypted password. # config.pepper = 'bb0bef67d1cf22075fc8f3cfff768e7d41c37bbd168be77b159f33580e48443647e6884de3defeb58d063a5bf5a28f97ea0fe25ac60541f46d171de47f75cc38' # ==> Configuration for :confirmable # A period that the user is allowed to access the website even without # confirming his account. For instance, if set to 2.days, the user will be # able to access the website for two days without confirming his account, # access will be blocked just in the third day. Default is 0.days, meaning # the user cannot access the website without confirming his account. # config.allow_unconfirmed_access_for = 2.days # A period that the user is allowed to confirm their account before their # token becomes invalid. For example, if set to 3.days, the user can confirm # their account within 3 days after the mail was sent, but on the fourth day # their account can't be confirmed with the token any more. # Default is nil, meaning there is no restriction on how long a user can take # before confirming their account. # config.confirm_within = 3.days # If true, requires any email changes to be confirmed (exactly the same way as # initial account confirmation) to be applied. Requires additional unconfirmed_email # db field (see migrations). Until confirmed new email is stored in # unconfirmed email column, and copied to email column on successful confirmation. config.reconfirmable = true # Defines which key will be used when confirming an account # config.confirmation_keys = [ :email ] # ==> Configuration for :rememberable # The time the user will be remembered without asking for credentials again. # config.remember_for = 2.weeks # If true, extends the user's remember period when remembered via cookie. # config.extend_remember_period = false # Options to be passed to the created cookie. For instance, you can set # :secure => true in order to force SSL only cookies. # config.rememberable_options = {} # ==> Configuration for :validatable # Range for password length. Default is 8..128. config.password_length = 8..128 # Email regex used to validate email formats. It simply asserts that # one (and only one) @ exists in the given string. This is mainly # to give user feedback and not to assert the e-mail validity. # config.email_regexp = /\A[^@]+@[^@]+\z/ # ==> Configuration for :timeoutable # The time you want to timeout the user session without activity. After this # time the user will be asked for credentials again. Default is 30 minutes. # config.timeout_in = 30.minutes # If true, expires auth token on session timeout. # config.expire_auth_token_on_timeout = false # ==> Configuration for :lockable # Defines which strategy will be used to lock an account. # :failed_attempts = Locks an account after a number of failed attempts to sign in. # :none = No lock strategy. You should handle locking by yourself. # config.lock_strategy = :failed_attempts # Defines which key will be used when locking and unlocking an account # config.unlock_keys = [ :email ] # Defines which strategy will be used to unlock an account. # :email = Sends an unlock link to the user email # :time = Re-enables login after a certain amount of time (see :unlock_in below) # :both = Enables both strategies # :none = No unlock strategy. You should handle unlocking by yourself. # config.unlock_strategy = :both # Number of authentication tries before locking an account if lock_strategy # is failed attempts. # config.maximum_attempts = 20 # Time interval to unlock the account if :time is enabled as unlock_strategy. # config.unlock_in = 1.hour # Warn on the last attempt before the account is locked. # config.last_attempt_warning = false # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account # config.reset_password_keys = [ :email ] # Time interval you can reset your password with a reset password key. # Don't put a too small interval or your users won't have the time to # change their passwords. config.reset_password_within = 6.hours # ==> Configuration for :encryptable # Allow you to use another encryption algorithm besides bcrypt (default). You can use # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1, # :authlogic_sha512 (then you should set stretches above to 20 for default behavior) # and :restful_authentication_sha1 (then you should set stretches to 10, and copy # REST_AUTH_SITE_KEY to pepper). # # Require the `devise-encryptable` gem when using anything other than bcrypt # config.encryptor = :sha512 # ==> Scopes configuration # Turn scoped views on. Before rendering "sessions/new", it will first check for # "users/sessions/new". It's turned off by default because it's slower if you # are using only default views. # config.scoped_views = false # Configure the default scope given to Warden. By default it's the first # devise role declared in your routes (usually :user). # config.default_scope = :user # Set this configuration to false if you want /users/sign_out to sign out # only the current scope. By default, Devise signs out all scopes. # config.sign_out_all_scopes = true # ==> Navigation configuration # Lists the formats that should be treated as navigational. Formats like # :html, should redirect to the sign in page when the user does not have # access, but formats like :xml or :json, should return 401. # # If you have any extra navigational formats, like :iphone or :mobile, you # should add them to the navigational formats lists. # # The "*/*" below is required to match Internet Explorer requests. # config.navigational_formats = ['*/*', :html] # The default HTTP method used to sign out a resource. Default is :delete. config.sign_out_via = :delete # ==> OmniAuth # Add a new OmniAuth provider. Check the wiki for more information on setting # up on your models and hooks. config.omniauth :google_oauth2, ENV["GOOGLE_KEY"], ENV["GOOGLE_SECRET"] #, :scope => 'email,profile' # ==> Warden configuration # If you want to use other strategies, that are not supported by Devise, or # change the failure app, you can configure them inside the config.warden block. # # config.warden do |manager| # manager.intercept_401 = false # manager.default_strategies(:scope => :user).unshift :some_external_strategy # end # ==> Mountable engine configurations # When using Devise inside an engine, let's call it `MyEngine`, and this engine # is mountable, there are some extra configurations to be taken into account. # The following options are available, assuming the engine is mounted as: # # mount MyEngine, at: '/my_engine' # # The router that invoked `devise_for`, in the example above, would be: # config.router_name = :my_engine # # When using omniauth, Devise cannot automatically set Omniauth path, # so you need to do it manually. For the users scope, it would be: # config.omniauth_path_prefix = '/my_engine/users/auth' end
gpl-2.0
olabimaker/siteolabi
src/wp-content/plugins/related-posts-lite/includes/textcache.class.php
2230
<?php /* * Creates a cache file from a text * * @author Ernest Marcinko <ernest.marcinko@wp-dreams.com> * @version 1.0 * @link http://wp-dreams.com, http://codecanyon.net/user/anago/portfolio * @copyright Copyright (c) 2012, Ernest Marcinko */ if (!class_exists('wpdreamsTextCache')) { class wpdreamsTextCache { function __construct($file, $time) { $this->file = $file; $this->time = $time; $this->method = $this->can_get_file(); } function getCache($file="") { if ($file!="") $this->file = $file; if ($this->method==false) return false; if (file_exists($this->file)) { $filetime = filemtime($this->file); } else { return false; } $current_time = time(); if (($current_time-$filetime)>$this->time) return false; return file_get_contents($this->file); } function setCache($content, $file="") { if ($file!="") $this->file = $file; if ($this->method===false) return false; if (file_exists($this->file)) { $filetime = filemtime($this->file); } else { $filetime = 0; } $current_time = time(); if (($current_time-$filetime)>$this->time) { file_put_contents($this->file,$content); } } function _ckdir($fn) { if (strpos($fn,"/") !== false) { $p=substr($fn,0,strrpos($fn,"/")); if (!is_dir($p)) { //_o("Mkdir: ".$p); mkdir($p,0777,true); } } } function can_get_file() { if (function_exists('curl_init')){ return 1; } else if (ini_get('allow_url_fopen')==true) { return 2; } return false; } function url_get_contents($Url, $method) { if ($method==2) { return file_get_contents($Url); } else if ($method==1) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $Url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch); curl_close($ch); return $output; } } } }
gpl-2.0
thalespf/demos-alura
demo-android-cadastro/src/com/thalespf/demo/android/presentation/ui/ListExamActivity.java
754
/** * */ package com.thalespf.demo.android.presentation.ui; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import com.thalespf.demo.R; import com.thalespf.demo.android.presentation.ui.fragment.ListExamFragment; /** * @author Thales Ferreira / l.thales.x@gmail.com * */ public class ListExamActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_exams); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.exams_view, new ListExamFragment(), "listExams"); transaction.commit(); } }
gpl-2.0
FlorianPO/SpriteEditor
SQT/GeneratedFiles/Release/moc_InfoPanel_copy.cpp
3689
/**************************************************************************** ** Meta object code from reading C++ file 'InfoPanel_copy.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.5.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../Source Files/Widget/Gui/InfoPanel/InfoPanel_copy.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'InfoPanel_copy.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.5.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_InfoPanel_copy_t { QByteArrayData data[6]; char stringdata0[39]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_InfoPanel_copy_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_InfoPanel_copy_t qt_meta_stringdata_InfoPanel_copy = { { QT_MOC_LITERAL(0, 0, 14), // "InfoPanel_copy" QT_MOC_LITERAL(1, 15, 4), // "bind" QT_MOC_LITERAL(2, 20, 0), // "" QT_MOC_LITERAL(3, 21, 5), // "Copy&" QT_MOC_LITERAL(4, 27, 4), // "copy" QT_MOC_LITERAL(5, 32, 6) // "unbind" }, "InfoPanel_copy\0bind\0\0Copy&\0copy\0unbind" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_InfoPanel_copy[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 2, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 1, 24, 2, 0x08 /* Private */, 5, 0, 27, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, 0x80000000 | 3, 4, QMetaType::Void, 0 // eod }; void InfoPanel_copy::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { InfoPanel_copy *_t = static_cast<InfoPanel_copy *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->bind((*reinterpret_cast< Copy(*)>(_a[1]))); break; case 1: _t->unbind(); break; default: ; } } } const QMetaObject InfoPanel_copy::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_InfoPanel_copy.data, qt_meta_data_InfoPanel_copy, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *InfoPanel_copy::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *InfoPanel_copy::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_InfoPanel_copy.stringdata0)) return static_cast<void*>(const_cast< InfoPanel_copy*>(this)); return QWidget::qt_metacast(_clname); } int InfoPanel_copy::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 2) qt_static_metacall(this, _c, _id, _a); _id -= 2; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 2) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 2; } return _id; } QT_END_MOC_NAMESPACE
gpl-2.0
morrischapman/tweetmadesimple
action.manageTemplate.php
2030
<?php if (!isset($gCms)) exit; /* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Code for DocumentsLibrary "manageTemplate" admin action -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Typically, this will display something from a template or do some other task. */ // ROCK AND LOAD if (isset($params['template']) && $params['template'] != '') { $title = $params['template']; if (isset($params['submitbutton']) || isset($params['applybutton'])) { $this->SetTemplate($params['template'], $params['templatedetails']); if (isset($params['submitbutton'])) { $this->Redirect($id, 'defaultadmin', $returnid, array('active_tab' => 'templates')); } } } else { $title = ''; } // DETAILS $this->smarty->assign('form_start', $this->CreateFormStart($id, 'manageTemplate', $returnid)); $this->smarty->assign('title_template', $this->Lang('title_template')); $this->smarty->assign('input_template',$this->CreateInputText($id, 'template', $title, 50)); if (isset($params['restore'])) { $templatecode = $this->GetTemplateFromFile('timeline'); } elseif (isset($params['template']) && $params['template'] != '') { $templatecode = $this->GetTemplate($params['template']); } else { $templatecode = ''; } $this->smarty->assign('code_template', $this->Lang('code')); $this->smarty->assign('textarea_template', $this->CreateTextArea(true, $id, $templatecode, 'templatedetails', 'pagebigtextarea', '','', '', 90, 15, 'EditArea')); $this->smarty->assign('form_details_submit', $this->CreateInputSubmit($id, 'submitbutton', $this->Lang('submit'))); $this->smarty->assign('form_details_apply', $this->CreateInputSubmit($id, 'applybutton', $this->Lang('apply'))); $this->smarty->assign('form_details_restore', $this->CreateInputSubmit($id, 'restore', $this->Lang('restore'))); $this->smarty->assign('form_end',$this->CreateFormEnd()); echo $this->ProcessTemplate('managetemplate.tpl'); ?>
gpl-2.0
mali/kdevplatform
plugins/filetemplates/debug.cpp
872
/* * This file is part of KDevelop * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library 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. */ #include "debug.h" Q_LOGGING_CATEGORY(PLUGIN_FILETEMPLATES, "kdevplatform.plugins.filetemplates")
gpl-2.0
Scalechange/scalesite
wp-content/plugins/popups/admin/views/metabox-help.php
3091
<?php // Exit if accessed directly if ( !defined( 'ABSPATH' ) ) exit; ?> <p><?php _e( 'You have three social shortcodes to use that will print a Facebook like, a Google+ Follow and a Twitter follow. Check the available options and <strong>configure them with your social accounts</strong>:', $this->plugin_slug );?></p> <p><strong>Facebook:</strong></p> <p> [spu-facebook href="" layout="" show_faces="" share="" action="" width=""] </p> <a href="fb-opts" onclick="jQuery('#fb-opts').slideToggle();return false;"><?php _e( 'View Facebook Options', $this->plugin_slug );?></a> <ul id="fb-opts" style="display:none;"> <li><b>href:</b> <?php _e( 'Your facebook page url', $this->plugin_slug );?></li> <li><b>layout:</b> <?php _e( 'standard, box_count, button <b>Default value:</b> button_count', $this->plugin_slug );?></li> <li><b>show_faces:</b> <?php _e( 'true <b>Default value:</b> false', $this->plugin_slug );?></li> <li><b>share:</b> <?php _e( 'true <b>Default value:</b> false', $this->plugin_slug );?></li> <li><b>action:</b> <?php _e( 'recommend <b>Default value:</b> like', $this->plugin_slug );?></li> <li><b>width:</b></li> </ul> <p><strong>Google+:</strong></p> <p> [spu-google url="" size="" annotation=""] </p> <a href="go-opts" onclick="jQuery('#go-opts').slideToggle();return false;"><?php _e( 'View Google+ Options', $this->plugin_slug );?></a> <ul id="go-opts" style="display:none;"> <li><b>url:</b> <?php _e( 'Your Google+ url', $this->plugin_slug );?></li> <li><b>size:</b> <?php _e( 'small, standard, tall <b>Default value:</b> medium', $this->plugin_slug );?></li> <li><b>annotation:</b> <?php _e( 'inline, none <b>Default value:</b> bubble', $this->plugin_slug );?></li> </ul> <p><strong>Twitter:</strong></p> <p> [spu-twitter user="" show_count="" size="" lang=""] </p> <a href="tw-opts" onclick="jQuery('#tw-opts').slideToggle();return false;"><?php _e( 'View Twitter Options', $this->plugin_slug );?></a> <ul id="tw-opts" style="display:none;"> <li><b>user:</b> <?php _e( 'Your Twitter user <b>Default chifli</b>iiii', $this->plugin_slug );?></li> <li><b>show_count:</b> <?php _e( 'false <b>Default value:</b> true', $this->plugin_slug );?></li> <li><b>size:</b> <?php _e( 'large <b>Default value:</b> ""', $this->plugin_slug );?></li> <li><b>lang:</b> </li> </ul> <h3 style="padding-left:0;margin: 20px 0;"><strong><?php _e('Other available Shortcodes:', $this->plugin_slug );?><strong></h3> <p><strong>Close Button:</strong></p> <p> [spu-close class="" text="" align=""] </p> <a href="close-opts" onclick="jQuery('#close-opts').slideToggle();return false;"><?php _e( 'View Close shortcode Options', $this->plugin_slug );?></a> <ul id="close-opts" style="display:none;"> <li><b>class:</b> <?php _e( 'Pass a custom class to style your button', $this->plugin_slug );?></li> <li><b>text:</b> <?php _e( 'Button label - <b>Default value:</b> Close', $this->plugin_slug );?></li> <li><b>align:</b> <?php _e( 'left, right, center, none - <b>Default value:</b> center', $this->plugin_slug );?></li> </ul>
gpl-2.0
weiqiangdragonite/MyQtProject
learning_code/getting_started_qt_creator/Qt Creator快速入门_代码/src/09/9-3/myButton/mybutton.cpp
89
#include "mybutton.h" MyButton::MyButton(QWidget *parent) : QPushButton(parent) { }
gpl-2.0
ISKonst88/winebosom
src/main/java/com/winebosom/dict/mapper/DictionaryMapper.java
713
package com.winebosom.dict.mapper; import com.winebosom.common.dto.SearchDto; import com.winebosom.dict.dto.DictionaryDto; import com.winebosom.dict.entity.Dictionary; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface DictionaryMapper { int deleteByPrimaryKey(Dictionary dictionary); // int insert(Dictionary record); int insertSelective(Dictionary record); DictionaryDto selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Dictionary record); // int updateByPrimaryKey(Dictionary record); List<DictionaryDto> selectByDictKey(Dictionary dictionary); List<DictionaryDto> selectAllDicts(SearchDto searchDto); }
gpl-2.0
ibrahim-netto/FabricaDados
FabricaDados/src/com/ibrahimnetto/FabricaDados/Maquinas/MaquinaCortar.java
3730
package com.ibrahimnetto.FabricaDados.Maquinas; import com.ibrahimnetto.FabricaDados.Interfaces.MaquinaCorte; import com.ibrahimnetto.FabricaDados.Fabrica; import com.ibrahimnetto.FabricaDados.Pedido; /** * Created by Ibrahim on 07/10/14. */ public class MaquinaCortar extends Thread implements MaquinaCorte { Fabrica fabrica; boolean power; Pedido pedido; public Object lockPedido; public MaquinaCortar(Fabrica fabrica) { this.fabrica = fabrica; this.setName("MaquinaCortar"); power = true; lockPedido = fabrica.controleProducao.lockPedido; } @Override public int producaoChapasSimples(int qtdeChapas, int tipo) { if (tipo == 0) { for (int i = 0; i < qtdeChapas; i++) { System.out.println("MaquinaCortar: Processando Dado " + i + "..."); try { sleep(100); } catch (InterruptedException e) { } } System.out.println("MaquinaCortar: Corte Completo."); } if (tipo == 1) { for (int i = 0; i < qtdeChapas; i++) { System.out.println("MaquinaCortar: Processando Dado " + i + "..."); try { sleep(200); } catch (InterruptedException e) { } } System.out.println("MaquinaCortar: Corte Completo."); } if (tipo == 2) { for (int i = 0; i < qtdeChapas; i++) { System.out.println("MaquinaCortar: Processando Dado " + i + "..."); try { sleep(500); } catch (InterruptedException e) { } } System.out.println("MaquinaCortar: Corte Completo."); } return qtdeChapas; } @Override public int producaoChapasQualidade(int qtdeChapas, int tipo) { if(tipo==3){ for(int i=0;i<qtdeChapas;i++){ System.out.println("MaquinaCortar: Processando Dado " + i + "..."); try{ sleep(2000); } catch(InterruptedException e){ } } System.out.println("MaquinaCortar: Corte Completo."); } return qtdeChapas; } @Override public int producaoChapasEspeciais(int qtdeChapas, int tipo) { if(tipo==4){ for(int i=0;i<qtdeChapas;i++){ System.out.println("MaquinaCortar: Processando Dado " + i + "..."); try{ sleep(2000); } catch(InterruptedException e){ } } System.out.println("MaquinaCortar: Corte Completo."); } return qtdeChapas; } public void run() { while (power) { synchronized (lockPedido) { pedido = fabrica.controleProducao.pedido; if (pedido != null && pedido.moldado && pedido.marcado && !pedido.cortado) { //System.out.println("MaquinaCortar: Pedido Recebido."); producaoChapasSimples(pedido.qtde, pedido.tipo); pedido.cortado = true; lockPedido.notifyAll(); } else { try { //System.out.println("MaquinaCortar: Aguardando..."); lockPedido.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } }
gpl-2.0
Pengfei-Gao/source-Insight-3-for-centos7
SourceInsight3/NetFramework/IconEditor.cs
980
public class IconEditor : UITypeEditor { // Constructors public IconEditor() {} // Methods public virtual object EditValue(System.ComponentModel.ITypeDescriptorContext context, System.IServiceProvider provider, object value) {} public virtual UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context) {} public virtual bool GetPaintValueSupported(System.ComponentModel.ITypeDescriptorContext context) {} public virtual void PaintValue(PaintValueEventArgs e) {} public object EditValue(System.IServiceProvider provider, object value) {} public UITypeEditorEditStyle GetEditStyle() {} public bool GetPaintValueSupported() {} public void PaintValue(object value, System.Drawing.Graphics canvas, System.Drawing.Rectangle rectangle) {} public Type GetType() {} public virtual string ToString() {} public virtual bool Equals(object obj) {} public virtual int GetHashCode() {} // Properties public bool IsDropDownResizable { get{} } }
gpl-2.0
ia-toki/judgels-sandalphon
app/org/iatoki/judgels/sandalphon/controllers/securities/HasRole.java
584
package org.iatoki.judgels.sandalphon.controllers.securities; import org.iatoki.judgels.sandalphon.SandalphonUtils; import play.mvc.Http; import play.mvc.Result; import play.mvc.Security; public class HasRole extends Security.Authenticator { @Override public String getUsername(Http.Context context) { return SandalphonUtils.getRolesFromSession(); } @Override public Result onUnauthorized(Http.Context context) { return redirect(org.iatoki.judgels.sandalphon.controllers.routes.ApplicationController.authRole(context.request().uri())); } }
gpl-2.0
tov/gsc
server_root/html/js/loader.ts
528
'use strict'; let exports: any let module = { get exports() { return require('boo!') } } let require = (_: string): any => { throw new Error('Loader not ready') } const prepareLoader = (moduleMap: any): any => { exports = {} module = {exports: exports} require = (moduleName: string): any => { if (moduleName in moduleMap) { return moduleMap[moduleName] } else { throw new Error(`Unknown module: ${moduleName}`) } } return exports }
gpl-2.0
f3at/feat
src/feat/web/markup/base.py
13863
# F3AT - Flumotion Asynchronous Autonomous Agent Toolkit # Copyright (C) 2010,2011 Flumotion Services, S.A. # 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. # See "LICENSE.GPL" in the source distribution for more information. # Headers in this file shall remain intact. from xml.sax import saxutils from twisted.python import failure from zope.interface import implements from feat.common import defer from feat.web import document from feat.web.markup.interface import * ### classes ### class BasePolicy(object): implements(IPolicy) name = "base" content_separator = None def adapt_tag(self, tag): return tag.lower() def is_leaf(self, tag): return False def needs_no_closing(self, tag): return False def is_self_closing(self, tag): return True def adapt_attr(self, attr): return attr.lower() def convert_attr(self, obj): return unicode(obj) def write_attr(self, doc, value): doc.write(saxutils.quoteattr(value)) return defer.succeed(doc) def convert_content(self, obj): return unicode(obj) def write_separator(self, doc): if self.content_separator: doc.write(self.content_separator) return defer.succeed(doc) def write_content(self, doc, value): doc.write(saxutils.escape(value)) return defer.succeed(doc) def resolve_attr_error(self, failure): return failure def resolve_content_error(self, failure): return failure class ElementContent(object): __slots__ = ("element", "_policy", "_children") implements(IElementContent) def __init__(self, element, policy): self.element = element self._policy = policy self._children = [] ### IElementContent ### def __call__(self, *elements): for element in elements: self.append(element) return self.element def __len__(self): return len(self._children) def __getitem__(self, index): return self._unwrap_child(self._children[index]) def __iter__(self): return (self._unwrap_child(v) for v in self._children) def append(self, value): self._children.append(self._wrap_child(value)) def render(self, doc): d = defer.succeed(document.IWritableDocument(doc)) separate = False for child in self._children: if separate: d.addCallback(self._policy.write_separator) d.addCallback(self._render_child, child) separate = True return d def close(self): return self.element.close() ### private ### def _render_child(self, doc, child): if isinstance(child, defer.Deferred): d = defer.Deferred() args = (doc, d) child.addCallbacks(self._got_value, self._value_error, callbackArgs=args, errbackArgs=args) return d if IElement.providedBy(child): return child.render(doc) return self._policy.write_content(doc, child) def _got_value(self, value, doc, trigger=None): d = defer.succeed(doc) d.addCallback(self._render_child, value) if trigger is not None: d.addCallback(trigger.callback) d.addCallback(defer.override_result, value) return d def _value_error(self, failure, _doc, trigger=None): if trigger is not None: trigger.errback(failure) return failure def _wrap_child(self, value): if isinstance(value, failure.Failure): return value if isinstance(value, defer.Deferred): value.addCallbacks(self._wrap_callback, self._wrap_errback) return value return self._process_child(value) def _wrap_callback(self, element): return self._process_child(element) def _wrap_errback(self, failure): return self._wrap_child(self._policy.resolve_content_error(failure)) def _process_child(self, element): if IElementContent.providedBy(element): element = element.element if IElement.providedBy(element): return element return self._policy.convert_content(element) def _unwrap_child(self, value): if isinstance(value, defer.Deferred): d = defer.Deferred() value.addCallbacks(self._unwrap_callback, self._unwrap_errback, callbackArgs=(d, ), errbackArgs=(d, )) return d return value def _unwrap_callback(self, param, d): d.callback(param) return param def _unwrap_errback(self, failure, d): d.errback(failure) return failure class Element(object): __slots__ = ("_tag", "_policy", "_attrs", "_content", "context", "parent") implements(IElement) content_factory = ElementContent def __init__(self, name, policy, parent=None, context=None): self.parent = IElement(parent) if parent is not None else None self.context = IContext(context) if context is not None else None self._policy = IPolicy(policy) self._tag = policy.adapt_tag(name) self._attrs = {} self._content = None if not self.is_leaf: self._content = self.content_factory(self, self._policy) ### IElement ### @property def tag(self): return self._tag @property def is_leaf(self): return self._policy.is_leaf(self._tag) @property def needs_no_closing(self): return self._policy.needs_no_closing(self._tag) @property def is_self_closing(self): return self._policy.is_self_closing(self._tag) @property def content(self): if self._content is None: raise MarkupError("With %s markup policy, '%s' tags do not have " "content" % (self._policy.name, self._tag)) return self._content def __call__(self, **kwargs): for k, v in kwargs.iteritems(): self.__setitem__(k, v) return self if self._content is None else self._content def __len__(self): return len(self._attrs) def __contains__(self, attr): adapted_attr = self._policy.adapt_attr(attr) return adapted_attr in self._attrs def __getitem__(self, attr): adapted_attr = self._policy.adapt_attr(attr) return self._unwrap_value(self._attrs[adapted_attr]) def __setitem__(self, attr, value): adapted_attr = self._policy.adapt_attr(attr) self._attrs[adapted_attr] = self._wrap_value(value) def __iter__(self): return iter(self._attrs) def close(self): if self.context is None: raise MarkupError("cannot close element '%s', " "it do not have context" % (self._tag, )) return self.context.close_element(self) def render(self, doc): def start_tag(doc, name): doc.writelines(["<", name]) return doc def start_attr(doc, name, value): doc.writelines([" ", name]) if isinstance(value, defer.Deferred): d = defer.Deferred() args = (doc, d) value.addCallbacks(self._got_value, self._value_error, callbackArgs=args, errbackArgs=args) return d if value is not None: doc.write("=") return self._policy.write_attr(doc, value) return doc def close_tag(doc, name): if self.is_leaf: if self.needs_no_closing: doc.write(">") elif not self.is_self_closing: doc.writelines(["></", name, ">"]) else: doc.write(" />") elif self.content: doc.write(">") elif not self.is_self_closing: doc.writelines(["></", name, ">"]) else: doc.write(" />") return doc def close_element(doc, name): doc.writelines(["</", name, ">"]) return doc doc = document.IWritableDocument(doc) d = defer.succeed(doc) d.addCallback(start_tag, self._tag) keys = self._attrs.keys() keys.sort() for name in keys: d.addCallback(start_attr, name, self._attrs[name]) d.addCallback(close_tag, self._tag) if self._content: d.addCallback(self.content.render) d.addCallback(close_element, self._tag) return d def as_string(self, mime_type=None, encoding=None): doc = document.WritableDocument(mime_type, encoding) d = self.render(doc) d.addCallback(document.WritableDocument.get_data) return d ### private ### def _got_value(self, value, doc, trigger=None): if value is not None: doc.write("=") d = defer.succeed(doc) d.addCallback(self._policy.write_attr, value) if trigger is not None: d.addCallback(trigger.callback) d.addCallback(defer.override_result, value) return d trigger.callback(doc) return value def _value_error(self, failure, _doc, trigger=None): if trigger is not None: trigger.errback(failure) return failure def _wrap_value(self, value): if isinstance(value, failure.Failure): return value if isinstance(value, defer.Deferred): value.addCallbacks(self._wrap_callback, self._wrap_errback) return value return self._process_value(value) def _wrap_callback(self, value): return self._process_value(value) def _wrap_errback(self, failure): return self._wrap_value(self._policy.resolve_attr_error(failure)) def _process_value(self, value): if (IElement.providedBy(value) or IElementContent.providedBy(value)): raise MarkupError("Attribute values cannot be markup elements") if value is None: return None return self._policy.convert_attr(value) def _unwrap_value(self, value): if isinstance(value, defer.Deferred): d = defer.Deferred() value.addCallbacks(self._unwrap_callback, self._unwrap_errback, callbackArgs=(d, ), errbackArgs=(d, )) return d return value def _unwrap_callback(self, param, d): d.callback(param) return param def _unwrap_errback(self, failure, d): d.errback(failure) return failure class ElementBuilder(object): __slots__ = ("_policy", ) element_factory = Element def __init__(self, policy): self._policy = IPolicy(policy) def __getattr__(self, attr): if attr.startswith("__"): raise AttributeError(attr) return self.element_factory(attr, self._policy) class Document(object): """Helper class to keep element hierarchy context.""" __slots__ = ("_policy", "_elements", "_current") implements(IContext) element_factory = Element def __init__(self, policy): self._policy = IPolicy(policy) self._elements = [] self._current = None def __getattr__(self, attr): if attr.startswith("__"): raise AttributeError(attr) element = self.element_factory(attr, policy=self._policy, parent=self._current, context=self) if self._current is None: self._elements.append(element) else: self._current.content.append(element) if not element.is_leaf: self._current = element return element def render(self, doc): """Render all elements using specified document. @param doc: the writable document to render to. @type doc: document.IWritableDocument @return: a deferred fired with the specified document when the rendering is done. @rtype: defer.Deferred """ d = defer.succeed(doc) for element in self._elements: d.addCallback(element.render) return d def as_string(self, mime_type=None, encoding=None): doc = document.WritableDocument(mime_type, encoding) d = self.render(doc) d.addCallback(document.WritableDocument.get_data) return d ### IContext ### def close_element(self, element): if self._current is None: raise MarkupError("Ask to close tag '%s' when there is no " "current element" % (element.tag, )) if element is not self._current: raise MarkupError("Ask to close tag '%s' when the current one is " "'%s'" % (element.tag, self._current.tag)) self._current = element.parent return self._current
gpl-2.0
tuxis-ie/nsedit
jquery-ui/ui/widget.js
15816
/*! * jQuery UI Widget @VERSION * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/jQuery.widget/ */ (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { var widget_uuid = 0, widget_slice = Array.prototype.slice; $.cleanData = (function( orig ) { return function( elems ) { var events, elem, i; for ( i = 0; (elem = elems[i]) != null; i++ ) { try { // Only trigger remove when necessary to save time events = $._data( elem, "events" ); if ( events && events.remove ) { $( elem ).triggerHandler( "remove" ); } // http://bugs.jquery.com/ticket/8235 } catch ( e ) {} } orig( elems ); }; })( $.cleanData ); $.widget = function( name, base, prototype ) { var fullName, existingConstructor, constructor, basePrototype, // proxiedPrototype allows the provided prototype to remain unmodified // so that it can be used as a mixin for multiple widgets (#8876) proxiedPrototype = {}, namespace = name.split( "." )[ 0 ]; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { return !!$.data( elem, fullName ); }; $[ namespace ] = $[ namespace ] || {}; existingConstructor = $[ namespace ][ name ]; constructor = $[ namespace ][ name ] = function( options, element ) { // allow instantiation without "new" keyword if ( !this._createWidget ) { return new constructor( options, element ); } // allow instantiation without initializing for simple inheritance // must use "new" keyword (the code above always passes args) if ( arguments.length ) { this._createWidget( options, element ); } }; // extend with the existing constructor to carry over any static properties $.extend( constructor, existingConstructor, { version: prototype.version, // copy the object used to create the prototype in case we need to // redefine the widget later _proto: $.extend( {}, prototype ), // track widgets that inherit from this widget in case this widget is // redefined after a widget inherits from it _childConstructors: [] }); basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from basePrototype.options = $.widget.extend( {}, basePrototype.options ); $.each( prototype, function( prop, value ) { if ( !$.isFunction( value ) ) { proxiedPrototype[ prop ] = value; return; } proxiedPrototype[ prop ] = (function() { var _super = function() { return base.prototype[ prop ].apply( this, arguments ); }, _superApply = function( args ) { return base.prototype[ prop ].apply( this, args ); }; return function() { var __super = this._super, __superApply = this._superApply, returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, arguments ); this._super = __super; this._superApply = __superApply; return returnValue; }; })(); }); constructor.prototype = $.widget.extend( basePrototype, { // TODO: remove support for widgetEventPrefix // always use the name + a colon as the prefix, e.g., draggable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name }, proxiedPrototype, { constructor: constructor, namespace: namespace, widgetName: name, widgetFullName: fullName }); // If this widget is being redefined then we need to find all widgets that // are inheriting from it and redefine all of them so that they inherit from // the new version of this widget. We're essentially trying to replace one // level in the prototype chain. if ( existingConstructor ) { $.each( existingConstructor._childConstructors, function( i, child ) { var childPrototype = child.prototype; // redefine the child widget using the same prototype that was // originally used, but inherit from the new version of the base $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); }); // remove the list of existing child constructors from the old constructor // so the old child constructors can be garbage collected delete existingConstructor._childConstructors; } else { base._childConstructors.push( constructor ); } $.widget.bridge( name, constructor ); return constructor; }; $.widget.extend = function( target ) { var input = widget_slice.call( arguments, 1 ), inputIndex = 0, inputLength = input.length, key, value; for ( ; inputIndex < inputLength; inputIndex++ ) { for ( key in input[ inputIndex ] ) { value = input[ inputIndex ][ key ]; if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { // Clone objects if ( $.isPlainObject( value ) ) { target[ key ] = $.isPlainObject( target[ key ] ) ? $.widget.extend( {}, target[ key ], value ) : // Don't extend strings, arrays, etc. with objects $.widget.extend( {}, value ); // Copy everything else by reference } else { target[ key ] = value; } } } } return target; }; $.widget.bridge = function( name, object ) { var fullName = object.prototype.widgetFullName || name; $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = widget_slice.call( arguments, 1 ), returnValue = this; if ( isMethodCall ) { this.each(function() { var methodValue, instance = $.data( this, fullName ); if ( options === "instance" ) { returnValue = instance; return false; } if ( !instance ) { return $.error( "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'" ); } if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { return $.error( "no such method '" + options + "' for " + name + " widget instance" ); } methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue && methodValue.jquery ? returnValue.pushStack( methodValue.get() ) : methodValue; return false; } }); } else { // Allow multiple hashes to be passed on init if ( args.length ) { options = $.widget.extend.apply( null, [ options ].concat(args) ); } this.each(function() { var instance = $.data( this, fullName ); if ( instance ) { instance.option( options || {} ); if ( instance._init ) { instance._init(); } } else { $.data( this, fullName, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( /* options, element */ ) {}; $.Widget._childConstructors = []; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "<div>", options: { disabled: false, // callbacks create: null }, _createWidget: function( options, element ) { element = $( element || this.defaultElement || this )[ 0 ]; this.element = $( element ); this.uuid = widget_uuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.bindings = $(); this.hoverable = $(); this.focusable = $(); if ( element !== this ) { $.data( element, this.widgetFullName, this ); this._on( true, this.element, { remove: function( event ) { if ( event.target === element ) { this.destroy(); } } }); this.document = $( element.style ? // element within the document element.ownerDocument : // element is window or document element.document || element ); this.window = $( this.document[0].defaultView || this.document[0].parentWindow ); } this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); this._create(); this._trigger( "create", null, this._getCreateEventData() ); this._init(); }, _getCreateOptions: $.noop, _getCreateEventData: $.noop, _create: $.noop, _init: $.noop, destroy: function() { this._destroy(); // we can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .unbind( this.eventNamespace ) .removeData( this.widgetFullName ) // support: jquery <1.6.3 // http://bugs.jquery.com/ticket/9413 .removeData( $.camelCase( this.widgetFullName ) ); this.widget() .unbind( this.eventNamespace ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetFullName + "-disabled " + "ui-state-disabled" ); // clean up events and states this.bindings.unbind( this.eventNamespace ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); }, _destroy: $.noop, widget: function() { return this.element; }, option: function( key, value ) { var options = key, parts, curOption, i; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.widget.extend( {}, this.options ); } if ( typeof key === "string" ) { // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } options = {}; parts = key.split( "." ); key = parts.shift(); if ( parts.length ) { curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); for ( i = 0; i < parts.length - 1; i++ ) { curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; curOption = curOption[ parts[ i ] ]; } key = parts.pop(); if ( arguments.length === 1 ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( arguments.length === 1 ) { return this.options[ key ] === undefined ? null : this.options[ key ]; } options[ key ] = value; } } this._setOptions( options ); return this; }, _setOptions: function( options ) { var key; for ( key in options ) { this._setOption( key, options[ key ] ); } return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() .toggleClass( this.widgetFullName + "-disabled", !!value ); // If the widget is becoming disabled, then nothing is interactive if ( value ) { this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); } } return this; }, enable: function() { return this._setOptions({ disabled: false }); }, disable: function() { return this._setOptions({ disabled: true }); }, _on: function( suppressDisabledCheck, element, handlers ) { var delegateElement, instance = this; // no suppressDisabledCheck flag, shuffle arguments if ( typeof suppressDisabledCheck !== "boolean" ) { handlers = element; element = suppressDisabledCheck; suppressDisabledCheck = false; } // no element argument, shuffle and use this.element if ( !handlers ) { handlers = element; element = this.element; delegateElement = this.widget(); } else { element = delegateElement = $( element ); this.bindings = this.bindings.add( element ); } $.each( handlers, function( event, handler ) { function handlerProxy() { // allow widgets to customize the disabled handling // - disabled as an array instead of boolean // - disabled class as method for disabling individual parts if ( !suppressDisabledCheck && ( instance.options.disabled === true || $( this ).hasClass( "ui-state-disabled" ) ) ) { return; } return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } // copy the guid so direct unbinding works if ( typeof handler !== "string" ) { handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++; } var match = event.match( /^([\w:-]*)\s*(.*)$/ ), eventName = match[1] + instance.eventNamespace, selector = match[2]; if ( selector ) { delegateElement.delegate( selector, eventName, handlerProxy ); } else { element.bind( eventName, handlerProxy ); } }); }, _off: function( element, eventName ) { eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; element.unbind( eventName ).undelegate( eventName ); // Clear the stack to avoid memory leaks (#10056) this.bindings = $( this.bindings.not( element ).get() ); this.focusable = $( this.focusable.not( element ).get() ); this.hoverable = $( this.hoverable.not( element ).get() ); }, _delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } var instance = this; return setTimeout( handlerProxy, delay || 0 ); }, _hoverable: function( element ) { this.hoverable = this.hoverable.add( element ); this._on( element, { mouseenter: function( event ) { $( event.currentTarget ).addClass( "ui-state-hover" ); }, mouseleave: function( event ) { $( event.currentTarget ).removeClass( "ui-state-hover" ); } }); }, _focusable: function( element ) { this.focusable = this.focusable.add( element ); this._on( element, { focusin: function( event ) { $( event.currentTarget ).addClass( "ui-state-focus" ); }, focusout: function( event ) { $( event.currentTarget ).removeClass( "ui-state-focus" ); } }); }, _trigger: function( type, event, data ) { var prop, orig, callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // the original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction( callback ) && callback.apply( this.element[0], [ event ].concat( data ) ) === false || event.isDefaultPrevented() ); } }; $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { if ( typeof options === "string" ) { options = { effect: options }; } var hasOptions, effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect; options = options || {}; if ( typeof options === "number" ) { options = { duration: options }; } hasOptions = !$.isEmptyObject( options ); options.complete = callback; if ( options.delay ) { element.delay( options.delay ); } if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { element[ method ]( options ); } else if ( effectName !== method && element[ effectName ] ) { element[ effectName ]( options.duration, options.easing, callback ); } else { element.queue(function( next ) { $( this )[ method ](); if ( callback ) { callback.call( element[ 0 ] ); } next(); }); } }; }); return $.widget; }));
gpl-2.0
umlsynco/umlsync
django_server/easynav/diagramsview/views.py
4137
# Create your views here. from easynav.diagramsview.models import Diagram, DiagramsView from django.http import HttpResponse from django.utils import simplejson # throw DiagramsView.DoesntExist if path doesn't exist def _get_diagrams_viewid(request, path): try : root_folder = DiagramsView.objects.filter(base_id=None, owner=request.user)[0:1].get() except DiagramsView.DoesNotExist: root_folder = DiagramsView.objects.create(name="root", base_id=None, owner=request.user) root_folder.save() if path == None : return root_folder key = root_folder path_items = path.rsplit("/") for i in path_items : print "loking for " + i v = DiagramsView.objects.filter(base_id=key, name=i, owner=request.user)[0:1].get() print "found" key = v return key def save_diagram(request): print request.POST if 'diagram' in request.POST: items = request.POST['diagram'] n = request.POST['name'] p = None if 'path' in request.POST: p = request.POST['path'] desc = request.POST['description'] v = None key = None try : key = _get_diagrams_viewid(request, p) except DiagramsView.DoesNotExist: print "PATH doesn't exists" return HttpResponse("FAILED") try : d = Diagram.objects.get(name=n, owner=request.user, viewid=key) if items: d.json = items if desc: d.description = desc except Diagram.DoesNotExist: d = Diagram.objects.create(name=n, owner=request.user, description=desc, status='d', json=items, viewid=key) d.save() return HttpResponse("SAVED") def new_diagram_folder(request): response = [] if 'name' in request.GET: n = request.GET['name'] p = None if 'path' in request.GET: p = request.GET['path'] key = None try : key = _get_diagrams_viewid(request, p) except Diagram.DoesNotExist: return HttpResponse("{}", mimetype='application/json') try : v = DiagramsView.objects.get(name=n, base_id=key, owner=request.user) except DiagramsView.DoesNotExist: v = DiagramsView.objects.create(name=n, base_id=key, owner=request.user) v.save() response.append({'title': n, 'isLazy': 'true', 'isFolder': 'true', 'addClass':'folderclass' }) json = simplejson.dumps(response) return HttpResponse(json, mimetype='application/json') def get_user_diagram(request): response = [] if 'name' in request.GET: n = request.GET['name'] p = None if 'path' in request.GET: p = request.GET['path'] try : key = _get_diagrams_viewid(request, p) d = Diagram.objects.get(name=n, viewid=key, owner=request.user) response = d.json; except Diagram.DoesNotExist: return HttpResponse("{}", mimetype='application/json') return HttpResponse(response, mimetype='application/json') def remove_user_diagram(request): response = [] if 'name' in request.GET: n = request.GET['name'] p = None if 'path' in request.GET: p = request.GET['path'] try : key = _get_diagrams_viewid(request, p) Diagram.objects.get(name=n, owner=request.user, viewid=key).delete() except Diagram.DoesNotExist: print "DIAGRAM DOESN't EXIST" return HttpResponse(response, mimetype='application/json') def get_user_diagrams(request): response = [] p = None if 'key' in request.GET: p = request.GET['key'] if p == 'start': p = None print "Get 1" key = None try : key = _get_diagrams_viewid(request, p) print "Get 2" except DiagramsView.DoesNotExist: print "requested path doesn't exist" return HttpResponse("{}", mimetype='application/json') print "Get 3" try : print key udf = DiagramsView.objects.filter(owner=request.user, base_id=key) print "Get 4" print "Get 412" if udf != None: for r in udf: print "------------------------------>" response.append({'title': r.name, 'isFolder':'true', 'isLazy': 'true' }) except DiagramsView.DoesNotExist : print "No folders in requested path" print "Get 5" user_diagrams = Diagram.objects.filter(owner=request.user, viewid=key) for r in user_diagrams: response.append({'title': r.name, 'isLazy': 'false', 'addClass':'diagramclass' }) json = simplejson.dumps(response) return HttpResponse(json, mimetype='application/json')
gpl-2.0
mirzinho-dev/elkom
sites/all/themes/flatastic/templates/view/portfolio/views-view-fields--related-portfolio--block-related.tpl.php
3812
<?php /** * @file * Default simple view template to all the fields as a row. * * - $view: The view in use. * - $fields: an array of $field objects. Each one contains: * - $field->content: The output of the field. * - $field->raw: The raw data for the field, if it exists. This is NOT output safe. * - $field->class: The safe class id to use. * - $field->handler: The Views field handler object controlling this field. Do not use * var_export to dump this object, as it can't handle the recursion. * - $field->inline: Whether or not the field should be inline. * - $field->inline_html: either div or span based on the above flag. * - $field->wrapper_prefix: A complete wrapper containing the inline_html to use. * - $field->wrapper_suffix: The closing tag for the wrapper. * - $field->separator: an optional separator that may appear before a field. * - $field->label: The wrap label text to use. * - $field->label_html: The full HTML of the label to use including * configured element type. * - $row: The raw result object from the query, with all data it fetched. * * @ingroup views_templates */ $iframe = ''; if(!empty($row->field_field_video) && isset($fields['field_video'])){ $iframe = $row->field_field_video[0]['raw']['value']; } global $base_url ?> <figure class="d_xs_inline_b d_mxs_block"> <div class="photoframe with_buttons relative shadow r_corners wrapper m_bottom_15"> <?php if(isset($fields['field_single_image'])):?> <img src="<?php print strip_tags($fields['field_single_image']->content);?>" class="tr_all_long_hover"> <?php endif;?> <div class="open_buttons clearfix"> <?php if(!empty($row->field_field_video) && isset($fields['field_video'])):?> <div class="f_left f_size_large tr_all_hover"><a href="<?php print $iframe;?>" data-thumbnail="<?php print strip_tags($fields['field_single_image_1']->content);?>" role="button" class="color_light button_type_13 r_corners box_s_none d_block jackbox" data-group="portfolio" data-title="<?php print $row->node_title;?>"><i class="fa fa-video-camera"></i></a></div> <?php else:?> <div class="f_left f_size_large tr_all_hover"><a href="<?php print strip_tags($fields['field_single_image_1']->content);?>" role="button" class="color_light button_type_13 r_corners box_s_none d_block jackbox" data-group="portfolio" data-title="<?php print $row->node_title;?>"><i class="fa fa-camera"></i></a></div> <?php endif;?> <div class="f_left m_left_10 f_size_large tr_all_hover"><a href="<?php print $base_url.'/'.drupal_get_path_alias('node/'.$row->nid);?>" role="button" class="color_light button_type_13 r_corners box_s_none d_block"><i class="fa fa-link"></i></a></div> </div> </div> <figcaption class="t_xs_align_l"> <?php if(isset($fields['title'])): print $fields['title']->content; endif;?> <?php if(isset($fields['field_portfolio_categories'])): print $fields['field_portfolio_categories']->content; endif;?> </figcaption> </figure> <?php unset($fields['title']);?> <?php unset($fields['field_portfolio_categories']);?> <?php unset($fields['field_single_image']);?> <?php unset($fields['field_single_image_1']);?> <?php unset($fields['field_video']);?> <?php foreach ($fields as $id => $field): ?> <?php if (!empty($field->separator)): ?> <?php print $field->separator; ?> <?php endif; ?> <?php print $field->wrapper_prefix; ?> <?php print $field->label_html; ?> <?php print $field->content; ?> <?php print $field->wrapper_suffix; ?> <?php endforeach; ?>
gpl-2.0
sunlightzxl/mypro
smart4j/chapter1/src/main/java/org/mypro/smart4j/chapter1/HelloServlet.java
993
package org.mypro.smart4j.chapter1; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by zhaoxuliang on 15/12/31. * There is no servlet context in web.xml because of Annotation WebServlet provide by Servlet3.0 * */ @WebServlet("/hello") public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String currentTime = dateFormat.format(new Date()); req.setAttribute("currentTime", currentTime); req.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(req, resp); } }
gpl-2.0
derekhargest/guntherandco
wp-content/plugins/nextgen-gallery-plus/ngg-plus.php
12069
<?php if(preg_match('#' . basename(__FILE__) . '#', $_SERVER['PHP_SELF'])) { die('You are not allowed to call this page directly.'); } /* * Plugin Name: NextGEN Plus by Photocrati * Description: A premium add-on for NextGEN Gallery with beautiful new gallery displays and a fullscreen, responsive Pro Lightbox with social sharing and commenting. * Version: 1.3.14 * Plugin URI: http://www.nextgen-gallery.com * Author: Photocrati Media * Author URI: http://www.photocrati.com * License: GPLv2 */ // in case bcmath isn't enabled we provide these wrappers if (!function_exists('bcadd')) { function bcadd($one, $two, $scale) { return $one + $two; }} if (!function_exists('bcmul')) { function bcmul($one, $two, $scale) { return $one * $two; }} if (!function_exists('bcdiv')) { function bcdiv($one, $two, $scale) { return $one / $two; }} if (!function_exists('bcsub')) { function bcsub($one, $two, $scale) { return $one - $two; }} if (!function_exists('bcmod')) { function bcmod($one, $two) { return $one % $two; }} class NextGen_Plus { static $minimum_ngg_version = '2.0.63'; static $product_loaded = FALSE; // Initialize the plugin function __construct() { // We only load the plugin if we're outside of the activation request, loaded in an iframe // by WordPress. Reason being, if WP_DEBUG is enabled, and another Pope-based plugin (such as // the photocrati theme or NextGEN Pro/Plus), then PHP will output strict warnings if ($this->is_not_activating()) { define('NGG_PLUS_PLUGIN_BASENAME', plugin_basename(__FILE__)); define('NGG_PLUS_MODULE_URL', plugins_url(path_join(basename(dirname(__FILE__)), 'modules'))); define('NGG_PLUS_PLUGIN_VERSION', '1.3.14'); if (class_exists('C_Component_Registry') && did_action('load_nextgen_gallery_modules')) { add_action('init', array(get_class(), 'load_product')); } else { add_action('load_nextgen_gallery_modules', array(get_class(), 'load_product')); } } $this->_register_hooks(); } /** * Loads the product providing NextGEN Gallery Pro functionality * @param C_Component_Registry $registry */ function load_product($registry = NULL) { $retval = FALSE; if (!self::$product_loaded) { // version mismatch: do not load if (!defined('NGG_PLUGIN_VERSION') || version_compare(NGG_PLUGIN_VERSION, self::$minimum_ngg_version) == -1) return; // Don't load Pro if Plus was recently activated if (defined('NGG_PRO_PLUGIN_VERSION') OR get_option('photocrati_pro_recently_activated', FALSE)) { return; } // Get the component registry if one wasn't provided if (!$registry) $registry = C_Component_Registry::get_instance(); // Tell the registry where it can find our products/modules $dir = dirname(__FILE__); $registry->add_module_path($dir, TRUE, TRUE); $registry->initialize_all_modules(); $retval = self::$product_loaded = TRUE; if (is_admin()) $registry->del_adapter('I_Page_Manager', 'A_NextGen_Pro_Upgrade_Page'); } else { $retval = self::$product_loaded; } return $retval; } function is_activating() { $retval = strpos($_SERVER['REQUEST_URI'], 'plugins.php') !== FALSE && isset($_REQUEST['action']) && $_REQUEST['action'] == 'activate'; if (!$retval && strpos($_SERVER['REQUEST_URI'], 'update.php') !== FALSE && isset($_REQUEST['action']) && $_REQUEST['action'] == 'install-plugin' && isset($_REQUEST['plugin']) && strpos($_REQUEST['plugin'], 'nextgen-gallery-plus') === 0) { $retval = TRUE; } if (!$retval && strpos($_SERVER['REQUEST_URI'], 'update.php') !== FALSE && isset($_REQUEST['action']) && $_REQUEST['action'] == 'activate-plugin' && isset($_REQUEST['plugin']) && strpos($_REQUEST['plugin'], 'nextgen-gallery-plus') === 0) { $retval = TRUE; } if (!$retval && strpos($_SERVER['REQUEST_URI'], 'plugins.php') !== FALSE && isset($_REQUEST['action']) && $_REQUEST['action'] == 'activate-selected' && isset($_REQUEST['checked']) && is_array($_REQUEST['checked']) && in_array('nextgen-gallery-pro/nggallery-plus.php', $_REQUEST['checked'])) { $retval = TRUE; } return $retval; } function is_not_activating() { return !$this->is_activating(); } function _register_hooks() { add_action('activate_' . plugin_basename(__FILE__), array(get_class(), 'activate')); add_action('deactivate_' . plugin_basename(__FILE__), array(get_class(), 'deactivate')); add_action('plugins_loaded', array($this, 'remove_ngg_third_party_compat_hook')); // hooks for showing available updates add_action('after_plugin_row_' . plugin_basename(__FILE__), array(get_class(), 'after_plugin_row')); add_action('admin_notices', array(&$this, 'admin_notices')); add_action('admin_init', array(&$this, 'deactivate_pro')); add_action('in_admin_header', array(&$this, 'hide_ngg_pro_ecommerce'), PHP_INT_MAX - 1); } /** * This is ugly, but needed with 2.0.79 * TODO: Remove this! */ function remove_ngg_third_party_compat_hook() { if (class_exists('M_Third_Party_Compat')) { $filter_found = FALSE; global $wp_filter; if (isset($wp_filter['ngg_non_minified_modules'])) { foreach ($wp_filter['ngg_non_minified_modules'] as $priority => $hooks) { foreach ($hooks as $key => $params) { $params = $params['function']; if (is_object($params[0]) && get_class($params[0]) == 'M_Third_Party_Compat') { remove_filter('ngg_non_minified_modules', array($params[0], $params[1]), $priority); $filter_found = TRUE; } if ($filter_found) break; } if ($filter_found) break; } } // Exclude modules $registry = C_Component_Registry::get_instance(); if ($registry->is_module_loaded('photocrati-nextgen-plus')) { add_filter('ngg_non_minified_modules', array(&$this, 'do_not_minify')); } } } function do_not_minify($modules) { $modules += P_Photocrati_NextGen_Plus::$modules; return $modules; } function deactivate_pro() { if (get_option('photocrati_plus_recently_activated', FALSE) && defined('NGG_PRO_PLUGIN_BASENAME')) { deactivate_plugins(NGG_PRO_PLUGIN_BASENAME); } } function hide_ngg_pro_ecommerce() { if (get_option('photocrati_plus_recently_activated') && strpos($_SERVER['REQUEST_URI'], 'plugins.php') !== FALSE) { delete_option('photocrati_plus_recently_activated'); echo '<script id="hide_ngg_pro_ecommerce" type="text/javascript">jQuery(\'#toplevel_page_ngg_ecommerce_options\').remove();</script>'; } } static function activate() { // admin_notices will check for this later update_option('photocrati_plus_recently_activated', 'true'); } static function deactivate() { if (class_exists('C_Photocrati_Installer')) { C_Photocrati_Installer::uninstall('photocrati-nextgen-plus'); } } static function _get_update_admin() { if (class_exists('C_Component_Registry') && method_exists('C_Component_Registry', 'get_instance')) { $registry = C_Component_Registry::get_instance(); $update_admin = $registry->get_module('photocrati-auto_update-admin'); return $update_admin; } return null; } static function _get_update_message() { $update_admin = self::_get_update_admin(); if ($update_admin != NULL && method_exists($update_admin, 'get_update_page_url')) { $url = $update_admin->get_update_page_url(); return sprintf(__('There are updates available. You can <a href="%s">Update Now</a>.', 'nextgen-gallery-pro'), $url); } return null; } static function has_updates() { $update_admin = self::_get_update_admin(); if ($update_admin != NULL && method_exists($update_admin, '_get_update_list')) { $list = $update_admin->_get_update_list(); if ($list != NULL) { $ngg_pro_count = 0; foreach ($list as $update) { if (isset($update['info']['product-id']) && $update['info']['product-id'] == 'photocrati-nextgen-plus') { $ngg_pro_count++; } } if ($ngg_pro_count > 0) { return true; } } } return false; } static function after_plugin_row() { if (self::has_updates()) { $update_message = self::_get_update_message(); if ($update_message != NULL) { echo '<tr style=""><td colspan="5" style="padding: 6px 8px; ">' . $update_message . '</td></tr>'; } } } function admin_notices() { $nextgen_found = FALSE; if (defined('NGG_PLUGIN_VERSION')) $nextgen_found = 'NGG_PLUGIN_VERSION'; if (defined('NEXTGEN_GALLERY_PLUGIN_VERSION')) $nextgen_found = 'NEXTGEN_GALLERY_PLUGIN_VERSION'; $nextgen_version = @constant($nextgen_found); if (FALSE == $nextgen_found) { $message = __('Please install &amp; activate <a href="http://wordpress.org/plugins/nextgen-gallery/" target="_blank">NextGEN Gallery</a> to allow NextGEN Pro to work.', 'nextgen-gallery-pro'); echo '<div class="updated"><p>' . $message . '</p></div>'; } else if (version_compare($nextgen_version, self::$minimum_ngg_version) == -1) { $ngg_pro_version = NGG_PLUS_PLUGIN_VERSION; $upgrade_url = admin_url('/plugin-install.php?tab=plugin-information&plugin=nextgen-gallery&section=changelog&TB_iframe=true&width=640&height=250'); $message = sprintf( __("NextGEN Gallery %s is incompatible with NextGEN Pro %s. Please update <a class='thickbox' href='%s'>NextGEN Gallery</a> to version %s or higher. NextGEN Pro has been deactivated.", 'nextgen-gallery-pro'), $nextgen_version, $ngg_pro_version, $upgrade_url, self::$minimum_ngg_version ); echo '<div class="updated"><p>' . $message . '</p></div>'; deactivate_plugins(NGG_PLUS_PLUGIN_BASENAME); } elseif (delete_option('photocrati_plus_recently_activated')) { $message = __('To activate the NextGEN Pro Lightbox please go to Gallery > Other Options > Lightbox Effects.', 'nextgen-gallery-pro'); echo '<div class="updated"><p>' . $message . '</p></div>'; } if (class_exists('C_Page_Manager')) { $pages = C_Page_Manager::get_instance(); if (isset($_REQUEST['page'])) { if (in_array($_REQUEST['page'], array_keys($pages->get_all())) || preg_match("/^nggallery-/", $_REQUEST['page']) || $_REQUEST['page'] == 'nextgen-gallery') { if (self::has_updates()) { $update_message = self::_get_update_message(); echo '<div class="updated"><p>' . $update_message . '</p></div>'; } } } } } } new NextGen_Plus();
gpl-2.0
AgelxNash/DocLister
assets/snippets/DocLister/core/lang/english/core.inc.php
155
<?php if ( ! defined('MODX_BASE_PATH')) { die('What are you doing? Get out of here!'); } $_lang = array(); $_lang['hello'] = 'hello'; return $_lang;
gpl-2.0
dssailo/stockpileshop
public_html/admin/model/tool/backup.php
11932
<?php /*------------------------------------------------------------------------------ $Id$ AbanteCart, Ideal OpenSource Ecommerce Solution http://www.AbanteCart.com Copyright © 2011-2015 Belavier Commerce LLC This source file is subject to Open Software License (OSL 3.0) License details is bundled with this package in the file LICENSE.txt. It is also available at this URL: <http://www.opensource.org/licenses/OSL-3.0> UPGRADE NOTE: Do not edit or add to this file if you wish to upgrade AbanteCart to newer versions in the future. If you wish to customize AbanteCart for your needs please refer to http://www.AbanteCart.com for more information. ------------------------------------------------------------------------------*/ if (!defined('DIR_CORE') || !IS_ADMIN) { header('Location: static_pages/'); } class ModelToolBackup extends Model { public $errors = array(); public $backup_filename; private $eta = array(); /** * @var int raw size of backup directory/ needed for calculation of eta of compression */ private $est_backup_size = 0; //TODO: need to solve issue (memory overflow) with large sql-scripts /** * @param string $sql */ public function restore($sql) { $this->db->query("SET SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO'"); // to prevent auto increment for 0 value of id $qr = explode(";\n", $sql); foreach ($qr as $sql) { $sql = trim($sql); if ($sql) { $this->db->query($sql); } } $this->db->query("SET SQL_MODE = ''"); } /** * @param string $xml_source - xml as string or full filename to xml-file * @param string $mode * @return bool */ public function load($xml_source,$mode='string') { if($mode=='string'){ $xml_obj = simplexml_load_string($xml_source); }elseif($mode=='file'){ $xml_obj = simplexml_load_file($xml_source); } if ($xml_obj) { $xmlname = $xml_obj->getName(); if ($xmlname == 'template_layouts') { $load = new ALayoutManager(); $load->loadXML(array('xml' => $xml_source)); } elseif ($xmlname == 'datasets') { $load = new ADataset(); $load->loadXML(array('xml' => $xml_source)); } elseif ($xmlname == 'forms') { $load = new AFormManager(); $load->loadXML(array('xml' => $xml_source)); } else { return false; } } else { return false; } return true; } /** * function returns table list of abantecart * @return array|bool */ public function getTables() { $table_data = array(); $prefix_len = strlen(DB_PREFIX); $query = $this->db->query("SHOW TABLES FROM `" . DB_DATABASE . "`", true); if(!$query){ $sql = "SELECT TABLE_NAME FROM information_schema.TABLES WHERE information_schema.TABLES.table_schema = '".DB_DATABASE."' "; $query = $this->db->query( $sql, true ); } if(!$query){ return false; } foreach ($query->rows as $result) { $table_name = $result['Tables_in_' . DB_DATABASE]; //if database prefix present - select only abantecart tables. If not - select all if (DB_PREFIX && substr($table_name,0,$prefix_len) != DB_PREFIX ) { continue; } $table_data[] = $result['Tables_in_' . DB_DATABASE]; } return $table_data; } /** * @param array $tables * @param bool|true $rl * @param bool|false $config * @param string $sql_dump_mode * @return bool */ public function backup($tables, $rl = true, $config = false, $sql_dump_mode = 'data_only') { $bkp = new ABackup('manual_backup' .'_'. date('Y-m-d-H-i-s')); if($bkp->error){ return false; } // do sql dump if(!in_array($sql_dump_mode, array('data_only','recreate') )){ $sql_dump_mode = 'data_only'; } $bkp->sql_dump_mode = $sql_dump_mode; $bkp->dumpTables($tables); if ($rl) { $bkp->backupDirectory(DIR_RESOURCE, false); } if ($config) { $bkp->backupFile(DIR_ROOT . '/system/config.php', false); } $result = $bkp->archive(DIR_BACKUP . $bkp->getBackupName() . '.tar.gz', DIR_BACKUP, $bkp->getBackupName()); if (!$result) { $this->errors[] = $bkp->error; } else { $this->backup_filename = $bkp->getBackupName(); } return $result; } /** * @param string $task_name * @param array $data * @return array|bool */ public function createBackupTask($task_name, $data = array()){ if(!$task_name){ $this->errors[] = 'Can not to create task. Empty task name given'; } //NOTE: remove temp backup dir before process to prevent progressive increment of directory date if some backup-steps will be failed $bkp = new ABackup('manual_backup'); $bkp->removeBackupDirectory(); unset($bkp); $tm = new ATaskManager(); //1. create new task $task_id = $tm->addTask( array( 'name' => $task_name, 'starter' => 1, //admin-side is starter 'created_by' => $this->user->getId(), //get starter id 'status' => 1, // shedule it! 'start_time' => date('Y-m-d H:i:s', mktime(0,0,0, date('m'), date('d')+1, date('Y')) ), 'last_time_run' => '0000-00-00 00:00:00', 'progress' => '0', 'last_result' => '0', 'run_interval' => '0', 'max_execution_time' => '0' ) ); if(!$task_id){ $this->errors = array_merge($this->errors,$tm->errors); return false; } //create step for table backup if($data['table_list'] ){ //calculate estimate time for dumping of tables // get sizes of tables $table_list = array(); foreach($data['table_list'] as $table){ if(!is_string($table)){ continue; } // clean $table_list[] = $this->db->escape($table); } $sql = "SELECT SUM(data_length + index_length - data_free) AS 'db_size' FROM information_schema.TABLES WHERE information_schema.TABLES.table_schema = '".DB_DATABASE."' AND TABLE_NAME IN ('".implode("','",$data['table_list'])."') "; if($prefix_len){ $sql .= " AND TABLE_NAME like '".DB_PREFIX."%'"; } $result = $this->db->query($sql); $db_size = $result->row['db_size']; //size in bytes $step_id = $tm->addStep( array( 'task_id' => $task_id, 'sort_order' => 1, 'status' => 1, 'last_time_run' => '0000-00-00 00:00:00', 'last_result' => '0', 'max_execution_time' => ceil($db_size/2794843)*4, 'controller' => 'task/tool/backup/dumptables', 'settings' => array( 'table_list' => $data['table_list'], 'sql_dump_mode'=> $data['sql_dump_mode'] ) )); if(!$step_id){ $this->errors = array_merge($this->errors,$tm->errors); return false; }else{ // get eta in seconds. 2794843 - "bytes per seconds" of dumping for Pentium(R) Dual-Core CPU E5200 @ 2.50GHz × 2 $this->eta[$step_id] = ceil($db_size/2794843)*4; $this->est_backup_size += ceil($db_size*1.61); // size of sql-file of output } } //create step for content-files backup if($data['backup_code']){ //calculate estimate time for copying of code $dirs_size = $this->getCodeSize(); $step_id = $tm->addStep( array( 'task_id' => $task_id, 'sort_order' => 2, 'status' => 1, 'last_time_run' => '0000-00-00 00:00:00', 'last_result' => '0', 'max_execution_time' => ceil($dirs_size/28468838), 'controller' => 'task/tool/backup/backupCodeFiles', 'settings' => array('interrupt_on_step_fault' =>false) )); if(!$step_id){ $this->errors = array_merge($this->errors,$tm->errors); return false; }else{ //// get eta in seconds. 28468838 - "bytes per seconds" of copiing of files for SATA III hdd $this->eta[$step_id] = ceil($dirs_size/28468838); $this->est_backup_size += $dirs_size; } } //create step for content-files backup if($data['backup_content']){ //calculate estimate time for copying of content files $dirs_size = $this->getContentSize(); $step_id = $tm->addStep( array( 'task_id' => $task_id, 'sort_order' => 3, 'status' => 1, 'last_time_run' => '0000-00-00 00:00:00', 'last_result' => '0', 'max_execution_time' => ceil($dirs_size/28468838), 'controller' => 'task/tool/backup/backupContentFiles', 'settings' => array('interrupt_on_step_fault' =>false) )); if(!$step_id){ $this->errors = array_merge($this->errors,$tm->errors); return false; }else{ //// get eta in seconds. 28468838 - "bytes per seconds" of copiing of files for SATA III hdd $this->eta[$step_id] = ceil($dirs_size/28468838); $this->est_backup_size += $dirs_size; } } //create last step for compressing backup if($data['compress_backup']){ $step_id = $tm->addStep(array( 'task_id' => $task_id, 'sort_order' => 4, 'status' => 1, 'last_time_run' => '0000-00-00 00:00:00', 'last_result' => '0', 'max_execution_time' => ceil($this->est_backup_size/18874368), 'controller' => 'task/tool/backup/compressbackup' )); if(!$step_id){ $this->errors = array_merge($this->errors, $tm->errors); return false; }else{ //// get eta in seconds. 18874368 - "bytes per seconds" of gz-compression, level 1 on // AMD mobile Athlon XP2400+ 512 MB RAM Linux 2.6.12-rc4 gzip 1.3.3 $this->eta[$step_id] = ceil($this->est_backup_size/18874368); } } $task_details = $tm->getTaskById($task_id); if($task_details){ foreach($this->eta as $step_id => $eta){ $task_details['steps'][$step_id]['eta'] = $eta; } return $task_details; }else{ $this->errors[] = 'Can not to get task details for execution'; $this->errors = array_merge($this->errors,$tm->errors); return false; } } /** * @param array $table_list * @return array */ public function getTableSizes($table_list=array()){ $tables = array(); foreach($table_list as $table){ if(!is_string($table)){ continue; } // clean $tables[] = $this->db->escape($table); } $sql = "SELECT TABLE_NAME AS 'table_name', table_rows AS 'num_rows', (data_length + index_length - data_free) AS 'size' FROM information_schema.TABLES WHERE information_schema.TABLES.table_schema = '".DB_DATABASE."' AND TABLE_NAME IN ('".implode("','",$tables)."') "; $result = $this->db->query($sql); $output = array(); foreach($result->rows as $row){ if($row['size']>1048576){ $text = round(($row['size']/1048576),1) .'Mb'; }else{ $text = round($row['size']/1024,1) .'Kb'; } $output[ $row['table_name'] ] = array( 'bytes' => $row['size'], 'text' => $text ); } return $output; } /** * @return int */ public function getCodeSize(){ $code_dirs = array( 'admin', 'core', 'storefront', 'extensions', 'system', 'static_pages' ); $dirs_size = 0; foreach($code_dirs as $d){ $dirs_size += $this->_get_directory_size(DIR_ROOT.'/'.$d); } return $dirs_size; } /** * @return int */ public function getContentSize(){ $content_dirs = array( // white list 'resources', 'image', 'download' ); $dirs_size = 0; foreach($content_dirs as $d){ $dirs_size += $this->_get_directory_size(DIR_ROOT.'/'.$d); } return $dirs_size; } /** * @param string $dir * @return int */ private function _get_directory_size($dir){ $count_size = 0; $count = 0; $dir_array = scandir($dir); foreach($dir_array as $key => $filename){ //skip backup, cache and logs if(is_int(strpos($dir . "/" . $filename,'/backup')) || is_int(strpos($dir . "/" . $filename,'/cache')) || is_int(strpos($dir . "/" . $filename,'/logs'))){ continue; } if($filename != ".." && $filename != "."){ if(is_dir($dir . "/" . $filename)){ $new_dirsize = $this->_get_directory_size($dir . "/" . $filename); $count_size = $count_size + $new_dirsize; } else if(is_file($dir . "/" . $filename)){ $count_size = $count_size + filesize($dir . "/" . $filename); $count++; } } } return $count_size; } }
gpl-2.0
thebluepotato/Jackett
src/Jackett.Common/Indexers/LostFilm.cs
35369
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using AngleSharp.Dom; using AngleSharp.Html.Parser; using Jackett.Common.Models; using Jackett.Common.Models.IndexerConfig; using Jackett.Common.Services.Interfaces; using Jackett.Common.Utils; using Jackett.Common.Utils.Clients; using Newtonsoft.Json.Linq; using NLog; namespace Jackett.Common.Indexers { [ExcludeFromCodeCoverage] internal class LostFilm : BaseWebIndexer { private static readonly Regex parsePlayEpisodeRegex = new Regex("PlayEpisode\\('(?<id>\\d{1,3})(?<season>\\d{3})(?<episode>\\d{3})'\\)", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static readonly Regex parseReleaseDetailsRegex = new Regex("Видео:\\ (?<quality>.+).\\ Размер:\\ (?<size>.+).\\ Перевод", RegexOptions.Compiled | RegexOptions.IgnoreCase); private string LoginUrl => SiteLink + "login"; // http://www.lostfilm.tv/login private string ApiUrl => SiteLink + "ajaxik.php"; // http://www.lostfilm.tv/new private string DiscoveryUrl => SiteLink + "new"; // http://www.lostfilm.tv/search?q=breaking+bad private string SearchUrl => SiteLink + "search"; // PlayEpisode function produce urls like this: // https://www.lostfilm.tv/v_search.php?c=119&s=5&e=16 private string ReleaseUrl => SiteLink + "v_search.php"; internal class TrackerUrlDetails { internal string seriesId { get; private set; } internal string season { get; private set; } internal string episode { get; private set; } internal TrackerUrlDetails(string seriesId, string season, string episode) { this.seriesId = seriesId; this.season = season; this.episode = episode; } internal TrackerUrlDetails(IElement button) { var trigger = button.GetAttribute("onclick"); var match = parsePlayEpisodeRegex.Match(trigger); seriesId = match.Groups["id"].Value.TrimStart('0'); season = match.Groups["season"].Value.TrimStart('0'); episode = match.Groups["episode"].Value.TrimStart('0'); } // TODO: see if query.GetEpisodeString() is sufficient internal string GetEpisodeString() { var result = string.Empty; if (!string.IsNullOrEmpty(season) && season != "0" && season != "999") { result += "S" + season; if (!string.IsNullOrEmpty(episode) && episode != "0" && episode != "999") { result += "E" + episode; } } return result; } } private new ConfigurationDataCaptchaLogin configData { get => (ConfigurationDataCaptchaLogin)base.configData; set => base.configData = value; } public LostFilm(IIndexerConfigurationService configService, WebClient wc, Logger l, IProtectionService ps) : base(id: "lostfilm", name: "LostFilm.tv", description: "Unique portal about foreign series", link: "https://www.lostfilm.tv/", caps: TorznabUtil.CreateDefaultTorznabTVCaps(), configService: configService, client: wc, logger: l, p: ps, configData: new ConfigurationDataCaptchaLogin()) { Encoding = Encoding.UTF8; Language = "ru-ru"; Type = "semi-private"; } public override async Task<ConfigurationData> GetConfigurationForSetup() { // looks like after some failed login attempts there's a captcha var loginPage = await RequestStringWithCookies(LoginUrl, string.Empty); var parser = new HtmlParser(); var document = parser.ParseDocument(loginPage.Content); var qCaptchaImg = document.QuerySelector("img#captcha_pictcha"); if (qCaptchaImg != null) { var captchaUrl = SiteLink + qCaptchaImg.GetAttribute("src"); var captchaImage = await RequestBytesWithCookies(captchaUrl, loginPage.Cookies); configData.CaptchaImage.Value = captchaImage.Content; } else { configData.CaptchaImage.Value = new byte[0]; } configData.CaptchaCookie.Value = loginPage.Cookies; UpdateCookieHeader(loginPage.Cookies); return configData; } public override async Task<IndexerConfigurationStatus> ApplyConfiguration(JToken configJson) { logger.Debug("Applying configuration"); LoadValuesFromJson(configJson); if (!configData.Username.Value.Contains("@")) throw new ExceptionWithConfigData("Username must be an e-mail address", configData); // Performing Logout is required to invalidate previous session otherwise the `{"error":1,"result":"ok"}` will be returned. await Logout(); var data = new Dictionary<string, string> { { "act", "users" }, { "type", "login" }, { "mail", configData.Username.Value }, { "pass", configData.Password.Value }, { "rem", "1" } }; if (!string.IsNullOrWhiteSpace(configData.CaptchaText.Value)) { data.Add("need_captcha", "1"); data.Add("captcha", configData.CaptchaText.Value); } var result = await RequestLoginAndFollowRedirect(ApiUrl, data, CookieHeader, true, SiteLink, ApiUrl, true); await ConfigureIfOK(result.Cookies, result.Content != null && result.Content.Contains("\"success\":true"), () => { var errorMessage = result.Content; if (errorMessage.Contains("\"error\":2")) errorMessage = "Captcha is incorrect"; if (errorMessage.Contains("\"error\":3")) errorMessage = "E-mail or password is incorrect"; throw new ExceptionWithConfigData(errorMessage, configData); }); return IndexerConfigurationStatus.RequiresTesting; } private async Task<bool> Logout() { logger.Info("Performing logout"); var data = new Dictionary<string, string> { { "act", "users" }, { "type", "logout" } }; var response = await PostDataWithCookies(url: ApiUrl, data: data); logger.Debug("Logout result: " + response.Content); var isOK = response.Status == System.Net.HttpStatusCode.OK; if (!isOK) { logger.Error("Logout failed with response: " + response.Content); } return isOK; } #region Query protected override async Task<IEnumerable<ReleaseInfo>> PerformQuery(TorznabQuery query) { logger.Debug("PerformQuery: " + query.GetQueryString()); // If the search string is empty use the latest releases if (query.IsTest || string.IsNullOrWhiteSpace(query.SearchTerm)) { return await FetchNewReleases(); } else { return await PerformSearch(query); } } private async Task<WebClientStringResult> RequestStringAndRelogin(string url) { var results = await RequestStringWithCookies(url); if (results.Content.Contains("503 Service")) { throw new ExceptionWithConfigData(results.Content, configData); } else if (results.Content.Contains("href=\"/login\"")) { // Re-login await ApplyConfiguration(null); return await RequestStringWithCookies(url); } else { return results; } } private async Task<List<ReleaseInfo>> PerformSearch(TorznabQuery query) { logger.Debug("PerformSearch: " + query.SanitizedSearchTerm + " [" + query.QueryType + "]"); var releases = new List<ReleaseInfo>(); /* Torznab query for some series could contains sanitized title. E.g. "Star Wars: The Clone Wars" will become "Star Wars The Clone Wars". Search API on LostFilm.tv doesn't return anything on such search query so the query should be "morphed" even for "tvsearch" queries. Also the queries to Specials is a union of Series and Episode titles. E.g.: "Breaking Bad - El Camino: A Breaking Bad Movie". The algorythm works in the following way: 1. Search with the full SearchTerm. Just for example, let's search for episode by it's name - {Star Wars The Clone Wars To Catch a Jedi} 2. [loop] If none were found, repeat search with SearchTerm reduced by 1 word from the end. Fail search if no words left and no results were obtained - {Star Wars The Clone Wars To Catch a} Jedi - {Star Wars The Clone Wars To Catch} a Jedi - ... - {Star Wars} The Clone Wars To Catch a Jedi 3. When we got few results, try to filter them with the words excluded before - [Star Wars: The Clone Wars, Star Wars Rebels, Star Wars: Forces of Destiny] .filterBy(The Clone Wars To Catch a Jedi) 4. [loop] Reduce filterTerm by 1 word from the end. Fail search if no words left and no results were obtained .filterBy(The Clone Wars To Catch a) / Jedi .filterBy(The Clone Wars To Catch) / a Jedi ... .filterBy(The Clone Wars) / To Catch a Jedi 5. [loop] Now we know that series we're looking for is called "Star Wars The Clone Wars". Fetch series detail page for it and try to apply remaining words as episode filter, reducing filter by 1 word each time we get no results: - .episodes().filteredBy(To Catch a Jedi) - .episodes().filteredBy(To Catch a) / Jedi - ... - .episodes() / To Catch a Jedi Test queries: - "Star Wars The Clone Wars To Catch a Jedi" -> S05E19 - "Breaking Bad El Camino A Breaking Bad Movie" -> Special - "The Magicians (2015)" -> Year should be ignored */ // Search query words. Consists of Series keywords that will be used for series search request, and Episode keywords that will be used for episode filtering. var keywords = query.SanitizedSearchTerm.Split(' ').ToList(); // Keywords count related to Series Search. var searchKeywords = keywords.Count; // Keywords count related to Series Filter. var serieFilterKeywords = 0; // Overall (keywords.count - searchKeywords - serieFilterKeywords) are related to episode filter do { var searchString = string.Join(" ", keywords.Take(searchKeywords)); var data = new Dictionary<string, string> { { "act", "common" }, { "type", "search" }, { "val", searchString } }; logger.Debug("> Searching: " + searchString); var response = await PostDataWithCookies(url: ApiUrl, data: data); if (response.Content == null) { logger.Debug("> Empty series response for query: " + searchString); continue; } try { var json = JToken.Parse(response.Content); if (json == null || json.Type == JTokenType.Array) { logger.Debug("> Invalid response for query: " + searchString); continue; // Search loop } // Protect from {"data":false,"result":"ok"} var jsonData = json["data"]; if (jsonData.Type != JTokenType.Object) continue; // Search loop var jsonSeries = jsonData["series"]; if (jsonSeries == null || !jsonSeries.HasValues) continue; // Search loop var series = jsonSeries.ToList(); logger.Debug("> Found " + series.Count().ToString() + " series: [" + string.Join(", ", series.Select(s => s["title_orig"].Value<string>())) + "]"); // Filter found series if (series.Count() > 1) { serieFilterKeywords = keywords.Count - searchKeywords; do { var serieFilter = string.Join(" ", keywords.GetRange(searchKeywords, serieFilterKeywords)); logger.Debug("> Filtering: " + serieFilter); var filteredSeries = series.Where(s => s["title_orig"].Value<string>().Contains(serieFilter)).ToList(); if (filteredSeries.Count() > 0) { logger.Debug("> Series filtered: [" + string.Join(", ", filteredSeries.Select(s => s["title_orig"].Value<string>())) + "]"); series = filteredSeries; break; // Serie Filter loop } } while (--serieFilterKeywords > 0); } foreach (var serie in series) { var link = serie["link"].ToString(); var season = query.Season == 0 ? "/seasons" : "/season_" + query.Season.ToString(); var url = SiteLink + link.TrimStart('/') + season; if (!string.IsNullOrEmpty(query.Episode)) // Fetch single episode releases { // TODO: Add a togglable Quick Path via v_search.php in Indexer Settings url += "/episode_" + query.Episode; var taskReleases = await FetchEpisodeReleases(url); releases.AddRange(taskReleases); } else // Fetch the whole series OR episode with filter applied { var episodeKeywords = keywords.Skip(searchKeywords + serieFilterKeywords); var episodeFilterKeywords = episodeKeywords.Count(); // Search for episodes dropping 1 filter word each time when no results has found. // Last search will be performed with empty filter do { var filter = string.Join(" ", episodeKeywords.Take(episodeFilterKeywords)); logger.Debug("> Searching episodes with filter [" + filter + "]"); var taskReleases = await FetchSeriesReleases(url, query, filter); if (taskReleases.Count() > 0) { logger.Debug("> Found " + taskReleases.Count().ToString() + " episodes"); releases.AddRange(taskReleases); break; // Episodes Filter loop } } while (--episodeFilterKeywords >= 0); } } break; // Search loop } catch (Exception ex) { OnParseError(response.Content, ex); } } while (--searchKeywords > 0); return releases; } #endregion #region Page parsing private async Task<List<ReleaseInfo>> FetchNewReleases() { var url = DiscoveryUrl; logger.Debug("FetchNewReleases: " + url); var results = await RequestStringAndRelogin(url); var releases = new List<ReleaseInfo>(); try { var parser = new HtmlParser(); var document = parser.ParseDocument(results.Content); var rows = document.QuerySelectorAll("div.row"); foreach (var row in rows) { var link = row.QuerySelector("a").GetAttribute("href"); var episodeUrl = SiteLink + link.TrimStart('/'); var episodeReleases = await FetchEpisodeReleases(episodeUrl); releases.AddRange(episodeReleases); } } catch (Exception ex) { OnParseError(results.Content, ex); } return releases; } private async Task<List<ReleaseInfo>> FetchEpisodeReleases(string url) { logger.Debug("FetchEpisodeReleases: " + url); var results = await RequestStringAndRelogin(url); var releases = new List<ReleaseInfo>(); try { var parser = new HtmlParser(); var document = parser.ParseDocument(results.Content); var playButton = document.QuerySelector("div.external-btn"); if (playButton != null && !playButton.ClassList.Contains("inactive")) { var comments = new Uri(url); var dateString = document.QuerySelector("div.title-block > div.details-pane > div.left-box").TextContent; dateString = TrimString(dateString, "eng: ", " г."); // '... Дата выхода eng: 09 марта 2012 г. ...' -> '09 марта 2012' DateTime date; if (dateString.Length == 4) //dateString might be just a year, e.g. https://www.lostfilm.tv/series/Ghosted/season_1/episode_14/ { date = DateTime.ParseExact(dateString, "yyyy", CultureInfo.InvariantCulture).ToLocalTime(); } else { date = DateTime.Parse(dateString, new CultureInfo(Language)); // dd mmmm yyyy } var urlDetails = new TrackerUrlDetails(playButton); var episodeReleases = await FetchTrackerReleases(urlDetails); foreach (var release in episodeReleases) { release.Comments = comments; release.PublishDate = date; } releases.AddRange(episodeReleases); } } catch (Exception ex) { OnParseError(results.Content, ex); } return releases; } private async Task<List<ReleaseInfo>> FetchSeriesReleases(string url, TorznabQuery query, string filter) { logger.Debug("FetchSeriesReleases: " + url + " S: " + query.Season.ToString() + " E: " + query.Episode + " Filter: " + filter); var releases = new List<ReleaseInfo>(); var results = await RequestStringWithCookies(url); try { var parser = new HtmlParser(); var document = parser.ParseDocument(results.Content); var seasons = document.QuerySelectorAll("div.serie-block"); var rowSelector = "table.movie-parts-list > tbody > tr"; foreach (var season in seasons) { // Could ne null if serie-block is for Extras var seasonButton = season.QuerySelector("div.movie-details-block > div.external-btn"); // Process only season we're searching for if (seasonButton != null && query.Season > 0) { // If seasonButton in "inactive" it will not contain "onClick" handler. Better to parse element which always exists. var watchedButton = season.QuerySelector("div.movie-details-block > div.haveseen-btn"); var buttonCode = watchedButton.GetAttribute("data-code"); var currentSeason = buttonCode.Substring(buttonCode.IndexOf('-') + 1); if (currentSeason != query.Season.ToString()) { continue; // Can't match season by regex OR season not matches to a searched one } // Stop parsing season episodes if season pack was required but it's not available yet. if (seasonButton.ClassList.Contains("inactive")) { logger.Debug("> No season pack is found for S" + query.Season.ToString()); break; } } // Fetch season pack releases if no episode filtering is required. // If seasonButton implements "inactive" class there are no season pack available and each episode should be fetched separately. if (string.IsNullOrEmpty(query.Episode) && string.IsNullOrEmpty(filter) && seasonButton != null && !seasonButton.ClassList.Contains("inactive")) { var lastEpisode = season.QuerySelector(rowSelector); var dateColumn = lastEpisode.QuerySelector("td.delta"); var date = DateFromEpisodeColumn(dateColumn); var comments = new Uri(url); // Current season(-s) page url var urlDetails = new TrackerUrlDetails(seasonButton); var seasonReleases = await FetchTrackerReleases(urlDetails); foreach (var release in seasonReleases) { release.Comments = comments; release.PublishDate = date; } releases.AddRange(seasonReleases); if (query.Season > 0) { break; // Searched season was processed } // Skip parsing separate episodes if season pack was added if (seasonReleases.Count() > 0) { continue; } } // No season filtering was applied OR season pack in not available var rows = season.QuerySelectorAll(rowSelector).Where(s => !s.ClassList.Contains("not-available")); foreach (var row in rows) { var couldBreak = false; // Set to `true` if searched episode was found try { if (!string.IsNullOrEmpty(filter)) { var titles = row.QuerySelector("td.gamma > div"); if (titles.TextContent.IndexOf(filter, StringComparison.OrdinalIgnoreCase) == -1) { continue; } } var playButton = row.QuerySelector("td.zeta > div.external-btn"); if (!string.IsNullOrEmpty(query.Episode)) { var match = parsePlayEpisodeRegex.Match(playButton.GetAttribute("onclick")); var episode = match.Groups["episode"]; if (episode == null || episode.Value != query.Episode) { continue; } couldBreak = true; } var dateColumn = row.QuerySelector("td.delta"); // Contains both Date and EpisodeURL var date = DateFromEpisodeColumn(dateColumn); var link = dateColumn.GetAttribute("onclick"); // goTo('/series/Prison_Break/season_5/episode_9/',false) link = TrimString(link, '\'', '\''); var episodeUrl = SiteLink + link.TrimStart('/'); var comments = new Uri(episodeUrl); var urlDetails = new TrackerUrlDetails(playButton); var episodeReleases = await FetchTrackerReleases(urlDetails); foreach (var release in episodeReleases) { release.Comments = comments; release.PublishDate = date; } releases.AddRange(episodeReleases); } catch (Exception ex) { logger.Error(string.Format("{0}: Error while parsing row '{1}':\n\n{2}", Id, row.OuterHtml, ex)); } if (couldBreak) { break; } } } } catch (Exception ex) { OnParseError(results.Content, ex); } return releases; } #endregion #region Tracker parsing private async Task<List<ReleaseInfo>> FetchTrackerReleases(TrackerUrlDetails details) { var queryCollection = new NameValueCollection { { "c", details.seriesId }, { "s", details.season }, { "e", string.IsNullOrEmpty(details.episode) ? "999" : details.episode } // 999 is a synonym for the whole serie }; var url = ReleaseUrl + "?" + queryCollection.GetQueryString(); logger.Debug("FetchTrackerReleases: " + url); // Get redirection page with generated link on it. This link can't be constructed manually as it contains Hash field and hashing algo is unknown. var results = await RequestStringWithCookies(url); if (results.Content == null) { throw new ExceptionWithConfigData("Empty response from " + url, configData); } if (results.Content == "log in first") { throw new ExceptionWithConfigData(results.Content, configData); } try { var parser = new HtmlParser(); var document = parser.ParseDocument(results.Content); var meta = document.QuerySelector("meta"); var metaContent = meta.GetAttribute("content"); // Follow redirection defined by async url.replace var redirectionUrl = metaContent.Substring(metaContent.IndexOf("http")); return await FollowTrackerRedirection(redirectionUrl, details); } catch (Exception ex) { OnParseError(results.Content, ex); } // Failure path return new List<ReleaseInfo>(); } private async Task<List<ReleaseInfo>> FollowTrackerRedirection(string url, TrackerUrlDetails details) { logger.Debug("FollowTrackerRedirection: " + url); var results = await RequestStringWithCookies(url); var releases = new List<ReleaseInfo>(); try { var parser = new HtmlParser(); var document = parser.ParseDocument(results.Content); var rows = document.QuerySelectorAll("div.inner-box--item"); logger.Debug("> Parsing " + rows.Count().ToString() + " releases"); var serieTitle = document.QuerySelector("div.inner-box--subtitle").TextContent; serieTitle = serieTitle.Substring(0, serieTitle.LastIndexOf(',')); var episodeInfo = document.QuerySelector("div.inner-box--text").TextContent; var episodeName = TrimString(episodeInfo, '(', ')'); foreach (var row in rows) { try { var detailsInfo = row.QuerySelector("div.inner-box--desc").TextContent; var releaseDetails = parseReleaseDetailsRegex.Match(detailsInfo); // ReSharper states "Expression is always false" // TODO Refactor to get the intended operation if (releaseDetails == null) { throw new FormatException("Failed to map release details string: " + detailsInfo); } /* * For supported qualities see: * - TvCategoryParser.cs * - https://github.com/SickRage/SickRage/wiki/Quality-Settings#quality-names-to-recognize-the-quality-of-a-file */ var quality = releaseDetails.Groups["quality"].Value.Trim(); // Adapt shitty quality format for common algorythms quality = Regex.Replace(quality, "-Rip", "Rip", RegexOptions.IgnoreCase); quality = Regex.Replace(quality, "WEB-DLRip", "WEBDL", RegexOptions.IgnoreCase); quality = Regex.Replace(quality, "WEB-DL", "WEBDL", RegexOptions.IgnoreCase); quality = Regex.Replace(quality, "HDTVRip", "HDTV", RegexOptions.IgnoreCase); // Fix forgotten p-Progressive suffix in resolution index quality = Regex.Replace(quality, "1080 ", "1080p ", RegexOptions.IgnoreCase); quality = Regex.Replace(quality, "720 ", "720p ", RegexOptions.IgnoreCase); var techComponents = new[] { "rus", quality, "(LostFilm)" }; var techInfo = string.Join(" ", techComponents.Where(s => !string.IsNullOrEmpty(s))); // Ru title: downloadLink.TextContent.Replace("\n", ""); // En title should be manually constructed. var titleComponents = new string[] { serieTitle, details.GetEpisodeString(), episodeName, techInfo }; var downloadLink = row.QuerySelector("div.inner-box--link > a"); var sizeString = releaseDetails.Groups["size"].Value.ToUpper(); sizeString = sizeString.Replace("ТБ", "TB"); // untested sizeString = sizeString.Replace("ГБ", "GB"); sizeString = sizeString.Replace("МБ", "MB"); sizeString = sizeString.Replace("КБ", "KB"); // untested var link = new Uri(downloadLink.GetAttribute("href")); // TODO this feels sparse compared to other trackers. Expand later var release = new ReleaseInfo { Category = new[] { TorznabCatType.TV.ID }, Title = string.Join(" - ", titleComponents.Where(s => !string.IsNullOrEmpty(s))), Link = link, Guid = link, Size = ReleaseInfo.GetBytes(sizeString), // add missing torznab fields not available from results Seeders = 1, Peers = 2, DownloadVolumeFactor = 0, UploadVolumeFactor = 1, MinimumRatio = 1, MinimumSeedTime = 172800 // 48 hours }; // TODO Other trackers don't have this log line. Remove or add to other trackers? logger.Debug("> Add: " + release.Title); releases.Add(release); } catch (Exception ex) { logger.Error(string.Format("{0}: Error while parsing row '{1}':\n\n{2}", Id, row.OuterHtml, ex)); } } } catch (Exception ex) { OnParseError(results.Content, ex); } return releases; } #endregion #region Helpers private string TrimString(string s, char startChar, char endChar) { var start = s.IndexOf(startChar); var end = s.LastIndexOf(endChar); return (start != -1 && end != -1) ? s.Substring(start + 1, end - start - 1) : null; } private string TrimString(string s, string startString, string endString) { var start = s.IndexOf(startString); var end = s.LastIndexOf(endString); return (start != -1 && end != -1) ? s.Substring(start + startString.Length, end - start - startString.Length) : null; } private DateTime DateFromEpisodeColumn(IElement dateColumn) { var dateString = dateColumn.QuerySelector("span").TextContent; dateString = dateString.Substring(dateString.IndexOf(":") + 2); // 'Eng: 23.05.2017' -> '23.05.2017' var date = DateTime.Parse(dateString, new CultureInfo(Language)); // dd.mm.yyyy return date; } #endregion } }
gpl-2.0
Ratchette/Rummikub
src/rummikub/HintClient.java
5012
package rummikub; import java.util.ArrayList; import java.util.Scanner; public class HintClient extends Thread{ private final int playerIndex; private Scanner keyboard; private GameInfo game; private Hand hand; private boolean initialMeld; private int round; // ********************************************************** // Constructors // ********************************************************** public HintClient(boolean initialMeldMade){ game = null; hand = null; initialMeld = initialMeldMade; round = 0; // TODO Change to something more meaningful? playerIndex = GameInfo.PLAYER1; keyboard = new Scanner(System.in); } // ********************************************************** // Main + User input validation // ********************************************************** public static void main(String[] args){ boolean initial = false; if(args[0].equalsIgnoreCase("true")) initial = true; else if(args[0].equalsIgnoreCase("false")) initial = false; else{ System.out.println("Invalid usage of this program.Proper syntax is:"); System.out.println("\nProper syntax of this program is "); System.out.println("\tHintClient.java <initial meld played>"); System.out.println("\tinitial meld played defaults to false"); System.exit(1); } (new HintClient(initial)).run(); } // ********************************************************** // Starting a Game // ********************************************************** /** * Initialize a new game * @throws Exception */ private void startGame(){ String userInput; game = new GameInfo(2); while(hand == null){ System.out.print("Please enter your initial hand: "); userInput = keyboard.nextLine(); try { hand = new Hand(userInput); } catch (Exception e) { hand = null; System.out.println("\t[ INVALID HAND ]: " + userInput); System.out.println(""); } } System.out.println("You entered: " + hand.toString()); } // ********************************************************** // Playing a game // ********************************************************** public void run(){ String message; ArrayList<Meld> play, trivialPlay; Boolean playMade; try{ startGame(); while (hand.getNumTiles() > 0) { updateRound(); playMade = false; System.out.print("Enter the current state of the board: "); message = keyboard.nextLine().trim(); if(message.endsWith("]")) message = message + ", "; message = message + hand.getNumTiles() + " 14"; game = new GameInfo(message); System.out.println("Current Hand : " + hand.toString()); System.out.println(game.displayGame()); if(initialMeld){ // find if you have any plays to make in your hand trivialPlay = hand.getMeldsFromHand(); if(trivialPlay.size() > 0){ game.addMelds(trivialPlay); game.setHand(playerIndex, hand.getNumTiles()); playMade = true; for(int i=0; i<trivialPlay.size(); i++){ System.out.println("Play: " + trivialPlay.get(i).toString()); } } play = game.getAdjacentPlay(hand, playerIndex); if(play != null){ playMade = true; } else if (trivialPlay.size() > 0) play = trivialPlay; } else{ play = hand.getInitialMeld(); if(play != null){ game.addMelds(play); game.setHand(playerIndex, hand.getNumTiles()); initialMeld = true; playMade = true; for(int i=0; i<play.size(); i++){ System.out.println("Play: " + play.get(i).toString()); } } } // there is no play to make if(!playMade){ System.out.println("Could not make a meld"); System.out.print("Please enter new tile or hand: "); message = keyboard.nextLine().trim(); if(message.startsWith("[")) hand = new Hand(message); else hand.addTile(new Tile(message)); game.setHand(playerIndex, hand.getNumTiles()); } else{ // // you can make a move // //// System.out.println("Play : "); //// System.out.println(game.displayGame()); // System.out.println(); } System.out.println("========================================================\n"); System.out.println("The game is now: "); System.out.println(game.displayGame()); System.out.println("Hand : " + hand.toString()); System.out.println("Score: " + hand.getScore()); } }catch(Exception e){ e.printStackTrace(); } } // ********************************************************** // Ending a Game // ********************************************************** private void updateRound(){ round++; System.out.println("\n\n========================================================"); System.out.printf( "------------------ Round %2d ------------------\n", round); System.out.println("========================================================\n"); } }
gpl-2.0
renovatio-comunicacion/object-container
widgets/renovatio-widget-social/lib/simplepie/tests/oldtests/first_item_date/SPtests/rss/2.0/dc/1.1/date.php
390
<?php class SimplePie_First_Item_Date_Test_RSS_20_DC_11_Date extends SimplePie_First_Item_Date_Test { function data() { $this->data = '<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"> <channel> <item> <dc:date>2007-01-11T16:00:00Z</dc:date> </item> </channel> </rss>'; } function expected() { $this->expected = 1168531200; } } ?>
gpl-2.0
srbsnkr/sellingonlinemadesimple
administrator/components/com_csvi/views/process/tmpl/com_virtuemart/export/default_shippingrate.php
716
<?php /** * Export shipping rates options * * @package CSVI * @subpackage Import * @author Roland Dalmulder * @link http://www.csvimproved.com * @copyright Copyright (C) 2006 - 2012 RolandD Cyber Produksi * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html * @version $Id: default_manufacturer.php 1924 2012-03-02 11:32:38Z RolandD $ */ defined( '_JEXEC' ) or die; ?> <fieldset> <legend><?php echo JText::_('COM_CSVI_OPTIONS'); ?></legend> <ul> <li><div class="option_label"><?php echo $this->form->getLabel('language', 'general'); ?></div> <div class="option_value"><?php echo $this->form->getInput('language', 'general'); ?></div></li> </ul> </fieldset>
gpl-2.0
mobbler/mobbler
src/mobblertrackbase.cpp
11143
/* Mobbler, a Last.fm mobile scrobbler for Symbian smartphones. Copyright (C) 2008, 2009, 2010, 2011 Michael Coffey Copyright (C) 2008, 2009, 2010 Hugo van Kemenade http://code.google.com/p/mobbler This file is part of Mobbler. Mobbler 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. Mobbler 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 Mobbler. If not, see <http://www.gnu.org/licenses/>. */ #include "mobblerappui.h" #include "mobblerstring.h" #include "mobblertracer.h" #include "mobblertrackbase.h" #include "mobblerutility.h" CMobblerTrackBase* CMobblerTrackBase::NewL(const CMobblerTrackBase& aTrack) { TRACER_AUTO; CMobblerTrackBase* self(new(ELeave) CMobblerTrackBase); CleanupStack::PushL(self); self->BaseConstructL(aTrack); CleanupStack::Pop(self); return self; } CMobblerTrackBase* CMobblerTrackBase::NewL(RReadStream& aReadStream) { TRACER_AUTO; CMobblerTrackBase* self(new(ELeave) CMobblerTrackBase); CleanupStack::PushL(self); self->InternalizeL(aReadStream); CleanupStack::Pop(self); return self; } CMobblerTrackBase::CMobblerTrackBase() { // TRACER_AUTO; } CMobblerTrackBase::CMobblerTrackBase(TTimeIntervalSeconds aTrackLength, TBool aLoved) :iLove(aLoved ? ELoved : ENoLove), iTrackNumber(KErrUnknown), iStartTimeUTC(Time::NullTTime()), iTrackLength(aTrackLength), iTotalPlayed(0), iInitialPlaybackPosition(KErrUnknown), iExpiry(Time::NullTTime()) { // TRACER_AUTO; } void CMobblerTrackBase::BaseConstructL(const TDesC8& aTitle, const TDesC8& aArtist, const TDesC8& aAlbum, const TDesC8& aStreamId) { TRACER_AUTO; iArtist = CMobblerString::NewL(aArtist); iTitle = CMobblerString::NewL(aTitle); iAlbum = CMobblerString::NewL(aAlbum); iStreamId = aStreamId.AllocL(); } void CMobblerTrackBase::BaseConstructL(const CMobblerTrackBase& aTrack) { TRACER_AUTO; iArtist = CMobblerString::NewL(aTrack.Artist().String()); iTitle = CMobblerString::NewL(aTrack.Title().String()); iAlbum = CMobblerString::NewL(aTrack.Album().String()); iTrackLength = aTrack.iTrackLength; iStreamId = aTrack.iStreamId->AllocL(); iTrackNumber = aTrack.iTrackNumber; iStartTimeUTC = aTrack.iStartTimeUTC; iLove = aTrack.iLove; iTotalPlayed = aTrack.iTotalPlayed; iInitialPlaybackPosition = aTrack.iInitialPlaybackPosition; iPlaybackPosition = aTrack.iPlaybackPosition; iScrobbled = aTrack.iScrobbled; iTrackPlaying = aTrack.iTrackPlaying; } CMobblerTrackBase::~CMobblerTrackBase() { TRACER_AUTO; if (iLoveObserverHelper) { iLoveObserverHelper->SetNotOwned(); } delete iArtist; delete iTitle; delete iAlbum; delete iStreamId; } TBool CMobblerTrackBase::operator==(const CMobblerTrackBase& aTrack) const { // check that the artist, album, and track name are the same return (iArtist->String().Compare(aTrack.iArtist->String()) == 0) && (iTitle->String().Compare(aTrack.iTitle->String()) == 0) && (iAlbum->String().Compare(aTrack.iAlbum->String()) == 0); } void CMobblerTrackBase::InternalizeL(RReadStream& aReadStream) { TRACER_AUTO; TInt high(aReadStream.ReadInt32L()); TInt low(aReadStream.ReadInt32L()); iStartTimeUTC = MAKE_TINT64(high, low); iTrackLength = aReadStream.ReadInt32L(); delete iArtist; delete iTitle; iArtist = CMobblerString::NewL(*HBufC8::NewLC(aReadStream, KMaxTInt)); CleanupStack::PopAndDestroy(); iTitle = CMobblerString::NewL(*HBufC8::NewLC(aReadStream, KMaxTInt)); CleanupStack::PopAndDestroy(); iLove = static_cast<TMobblerLove>(aReadStream.ReadInt8L()); delete iStreamId; iStreamId = HBufC8::NewL(aReadStream, KMaxTInt); delete iAlbum; iAlbum = CMobblerString::NewL(*HBufC8::NewLC(aReadStream, KMaxTInt)); CleanupStack::PopAndDestroy(); } void CMobblerTrackBase::ExternalizeL(RWriteStream& aWriteStream) const { TRACER_AUTO; aWriteStream.WriteInt32L(I64HIGH(iStartTimeUTC.Int64())); aWriteStream.WriteInt32L(I64LOW(iStartTimeUTC.Int64())); aWriteStream.WriteInt32L(iTrackLength.Int()); aWriteStream << iArtist->String8(); aWriteStream << iTitle->String8(); aWriteStream.WriteInt8L(iLove); aWriteStream << *iStreamId; aWriteStream << iAlbum->String8(); } HBufC8* CMobblerTrackBase::UrlLC(const TInt aCommand) { // Get the local Last.fm domain for this phone's language TBuf8<KMaxMobblerTextSize> base8; base8.Copy(MobblerUtility::LocalLastFmDomainL(EFalse)); HBufC8* base(base8.AllocLC()); // Format in the names TInt urlLength(base->Length() + iArtist->String8().Length()); _LIT8(KArtistUrlFormat, "%Smusic/%S"); _LIT8(KTrackUrlFormat, "%Smusic/%S/_/%S"); _LIT8(KAlbumUrlFormat, "%Smusic/%S/%S"); switch (aCommand) { case EMobblerCommandArtistShare: urlLength += KArtistUrlFormat().Length(); break; case EMobblerCommandTrackShare: urlLength += KTrackUrlFormat().Length() + iTitle->String8().Length(); break; case EMobblerCommandAlbumShare: urlLength += KAlbumUrlFormat().Length() + iAlbum->String8().Length(); break; default: break; } HBufC8* url(HBufC8::NewL(urlLength)); TPtr8 basePtr(base->Des()); switch (aCommand) { case EMobblerCommandArtistShare: url->Des().Format(KArtistUrlFormat, &basePtr, &iArtist->String8()); break; case EMobblerCommandTrackShare: url->Des().Format(KTrackUrlFormat, &basePtr, &iArtist->String8(), &iTitle->String8()); break; case EMobblerCommandAlbumShare: url->Des().Format(KAlbumUrlFormat, &basePtr, &iArtist->String8(), &iAlbum->String8()); break; default: break; } CleanupStack::Pop(base); // Replace space with '+' to make the URL prettier _LIT8(KSpace, " "); _LIT8(KPlus, "+"); TPtr8 urlPtr(url->Des()); TInt position(urlPtr.Find(KSpace)); while (position != KErrNotFound) { urlPtr.Replace(position, 1, KPlus); position = urlPtr.Find(KSpace); } // Encode and return the URL HBufC8* urlEncoded(MobblerUtility::URLEncodeLC(urlPtr)); return urlEncoded; } void CMobblerTrackBase::SetAlbumL(const TDesC& aAlbum) { // TRACER_AUTO; delete iAlbum; iAlbum = CMobblerString::NewL(aAlbum); } void CMobblerTrackBase::SetStartTimeUTC(const TTime& aStartTimeUTC) { // TRACER_AUTO; iStartTimeUTC = aStartTimeUTC; iTrackPlaying = ETrue; } const TTime& CMobblerTrackBase::StartTimeUTC() const { // TRACER_AUTO; return iStartTimeUTC; } const CMobblerString& CMobblerTrackBase::Artist() const { // TRACER_AUTO; return *iArtist; } const CMobblerString& CMobblerTrackBase::Title() const { // TRACER_AUTO; return *iTitle; } const CMobblerString& CMobblerTrackBase::Album() const { // TRACER_AUTO; return *iAlbum; } TInt CMobblerTrackBase::TrackNumber() const { // TRACER_AUTO; return iTrackNumber; } void CMobblerTrackBase::SetTrackNumber(TInt aTrackNumber) { // TRACER_AUTO; iTrackNumber = aTrackNumber; } const TDesC8& CMobblerTrackBase::StreamId() const { TRACER_AUTO; return *iStreamId; } void CMobblerTrackBase::DataL(CMobblerFlatDataObserverHelper* aObserver, const TDesC8& /*aData*/, TInt aTransactionError) { TRACER_AUTO; if (aObserver == iLoveObserverHelper && aTransactionError == CMobblerLastFmConnection::ETransactionErrorNone) { iLove = ELoved; } } void CMobblerTrackBase::LoveTrackL() { TRACER_AUTO; if (iLove != ELoved) { iLove = ELove; // we have not already told Last.fm about this so do it now delete iLoveObserverHelper; iLoveObserverHelper = CMobblerFlatDataObserverHelper::NewL(static_cast<CMobblerAppUi*>(CEikonEnv::Static()->AppUi())->LastFmConnection(), *this, EFalse); static_cast<CMobblerAppUi*>(CEikonEnv::Static()->AppUi())->LastFmConnection().QueryLastFmL(EMobblerCommandTrackLove, Artist().String8(), KNullDesC8, Title().String8(), KNullDesC8, *iLoveObserverHelper); } } CMobblerTrackBase::TMobblerLove CMobblerTrackBase::Love() const { // TRACER_AUTO; return iLove; } void CMobblerTrackBase::SetExpiry(const TTime& aExpiry) { iExpiry = aExpiry; } TTime CMobblerTrackBase::Expiry() const { return iExpiry; } void CMobblerTrackBase::SetTrackLength(TTimeIntervalSeconds aTrackLength) { // TRACER_AUTO; iTrackLength = aTrackLength; } TTimeIntervalSeconds CMobblerTrackBase::TrackLength() const { // TRACER_AUTO; return iTrackLength.Int() == 0 ? 1 : iTrackLength; } TBool CMobblerTrackBase::IsMusicPlayerTrack() const { // TRACER_AUTO; return (iStreamId->Compare(KNullDesC8) == 0); } TTimeIntervalSeconds CMobblerTrackBase::ScrobbleDuration() const { TRACER_AUTO; TInt scrobblePercent(static_cast<CMobblerAppUi*>(CEikonEnv::Static()->AppUi())->ScrobblePercent()); return (TTimeIntervalSeconds)Min(240, (TrackLength().Int() * scrobblePercent / 100)); } TTimeIntervalSeconds CMobblerTrackBase::InitialPlaybackPosition() const { TRACER_AUTO; if (iInitialPlaybackPosition.Int() == KErrUnknown) { return 0; } else { return iInitialPlaybackPosition; } } TTimeIntervalSeconds CMobblerTrackBase::PlaybackPosition() const { // TRACER_AUTO; return iPlaybackPosition; } void CMobblerTrackBase::SetPlaybackPosition(TTimeIntervalSeconds aPlaybackPosition) { TRACER_AUTO; iPlaybackPosition = aPlaybackPosition; if (iInitialPlaybackPosition.Int() == KErrUnknown) { iInitialPlaybackPosition = aPlaybackPosition; // Only need to correct music player tracks, because // iInitialPlaybackPosition may be up to 5 seconds off if (IsMusicPlayerTrack()) { TTimeIntervalSeconds offset(0); TTime now; now.UniversalTime(); TInt error(now.SecondsFrom(StartTimeUTC(), offset)); if (error == KErrNone && offset.Int() > 0) { iInitialPlaybackPosition = Max(0, iInitialPlaybackPosition.Int() - offset.Int()); } } } } void CMobblerTrackBase::SetTotalPlayed(TTimeIntervalSeconds aTotalPlayed) { // TRACER_AUTO; iTotalPlayed = aTotalPlayed; iTrackPlaying = EFalse; } TTimeIntervalSeconds CMobblerTrackBase::TotalPlayed() const { // TRACER_AUTO; return iTotalPlayed; } void CMobblerTrackBase::SetScrobbled() { // TRACER_AUTO; iScrobbled = ETrue; } TBool CMobblerTrackBase::Scrobbled() const { // TRACER_AUTO; return iScrobbled; } void CMobblerTrackBase::SetTrackPlaying(TBool aTrackPlaying) { // TRACER_AUTO; iTrackPlaying = aTrackPlaying; } TBool CMobblerTrackBase::TrackPlaying() const { // TRACER_AUTO; return iTrackPlaying; } // End of file
gpl-2.0
dpinney/omf
omf/scratch/weatherNoaa.py
5869
import requests, csv, json, time, collections DEFAULT_TOKEN = 'JkyCcxgvGhNUdDCvHCeBeaZQdDNQEJtw' def checkDatasets(token, zipCode): # Returns the list of datasets and dates available for a given zipcode. url = ('https://www.ncdc.noaa.gov/cdo-web/api/v2/datasets?locationid=ZIP:' + zipCode + '&limit=1000') r = requests.get(url, headers={'token':DEFAULT_TOKEN}) # jsonData = json.loads(str(r.text)) # size =jsonData['metadata']['resultset']['count'] # for x in range(size): # print jsonData['results'][x]['id'] return r.json() def pullOneDayHourly(token, zipCode, year, month, day): '''Return all metrics at hourly level for the given day.''' url = ('https://www.ncdc.noaa.gov/cdo-web/api/v2/data?datasetid=NORMAL_HLY&datatype=HLY-TEMP-NORMAL&locationid=ZIP:' + zipCode + \ '&units=metric&startdate=' + year + '-' + month + '-' + day + 'T00:00:00&enddate=' + \ year + '-' + month + '-' + day + 'T23:00:00&limit=1000') r = requests.get(url, headers={'token':token}) return r.json() def annualDataHourlyToCsv(token, zipCode, dataSet, dataTypeList, csvPath): '''Write a CSV at csvPath with a year of hourly data with columns of each datatype in the dataTypeList.''' #TODO: implement dataTypeList # print 'Starting annualDataHourlyToCsv' url = ('https://www.ncdc.noaa.gov/cdo-web/api/v2/datasets?locationid=ZIP:' + zipCode + '&limit=1000') #for x in range(numDataTypes): # This checks if data is available for the Zip entered and returns the dates it is available r = requests.get(url, headers={'token':DEFAULT_TOKEN}) x = str(r.text) jsonData = json.loads(str(r.text)) size =jsonData['metadata']['resultset']['count'] for x in range(size): if jsonData['results'][x]['id'] == dataSet: startDate = jsonData['results'][x]['mindate'] endDate = jsonData['results'][x]['maxdate'] dataAvailable = 1 # print 'Data Found' # Stores the number of days in each month calendar = collections.OrderedDict() calendar['01'] = 31 calendar['02'] = 28 calendar['03'] = 31 calendar['04'] = 30 calendar['05'] = 31 calendar['06'] = 30 calendar['07'] = 31 calendar['08'] = 31 calendar['09'] = 30 calendar['10'] = 31 calendar['11'] = 30 calendar['12'] = 31 try: year = startDate.partition('-')[0] except: raise Exception('No Data Available for that zipcode') # Pull the full dataset and write it. if type(dataTypeList) is str: numDataTypes = 1 elif type(dataTypeList) is list: numDataTypes = len(dataTypeList) #print type(dataTypeList) if dataAvailable == 1: if numDataTypes == 1: data = [] elif numDataTypes == 2: data = [] data1 = [] elif numDataTypes == 3: data = [] data1 = [] data2 = [] elif numDataTypes == 4: data = [] data1 = [] data2 = [] data3 = [] elif numDataTypes == 5: data = [] data1 = [] data2 = [] data3 = [] data4 = [] with open(csvPath,'w', newline='') as file: writer = csv.writer(file,lineterminator = '\n') for month in calendar: for day in range(calendar[month]): day = day+1 if len(str(day)) == 1: day = '0' + str(day) else: day = str(day) url = ('https://www.ncdc.noaa.gov/cdo-web/api/v2/data?datasetid=NORMAL_HLY&datatype=HLY-TEMP-NORMAL&locationid=ZIP:' + zipCode + '&units=metric&startdate=' + year + '-' + month + '-' + day + 'T00:00:00&enddate=' + year + '-' + month + '-' + day + 'T23:00:00&limit=1000') time.sleep(0.2) #SET TO 0.2 WHEN NOT TESTING r = requests.get(url, headers={'token':DEFAULT_TOKEN}) text = r.text jsonData = json.loads(str(r.text)) size = jsonData['metadata']['resultset']['count'] if numDataTypes == 1: for x in range(size): if jsonData['results'][x]['datatype'] == dataTypeList: data.append(str(jsonData['results'][x]['value'])) else: for y in dataTypeList: for x in range(size): if jsonData['results'][x]['datatype'] == y: if dataTypeList.index(y) == 0: data.append(str(jsonData['results'][x]['value'])) elif dataTypeList.index(y) == 1: data1.append(str(jsonData['results'][x]['value'])) elif dataTypeList.index(y) == 2: data2.append(str(jsonData['results'][x]['value'])) elif dataTypeList.index(y) == 3: data3.append(str(jsonData['results'][x]['value'])) elif dataTypeList.index(y) == 4: data4.append(str(jsonData['results'][x]['value'])) # if dataTypeList.index(y) == 0: # data[0].append([str(jsonData['results'][x]['value'])]) # else: # data[1].append([str(jsonData['results'][x]['value'])]) #data[dataTypeList.index(y)].append([str(jsonData['results'][x]['value'])]) #data.append([str(jsonData['results'][x]['value'])]) #writer.writerow([str(jsonData['results'][x]['value'])]) if numDataTypes == 1: for x in range(8760): writer.writerow([data[x]]) elif numDataTypes == 2: for x in range(8760): writer.writerow([data[x],data1[x]]) elif numDataTypes == 3: for x in range(8760): writer.writerow([data[x],data1[x],data2[x]]) elif numDataTypes == 4: for x in range(8760): writer.writerow([data[x],data1[x],data2[x],data3[x]]) elif numDataTypes == 5: for x in range(8760): writer.writerow([data[x],data1[x],data2[x],data3[x],data4[x]]) #writer.writerows(data) def _tests(): print(checkDatasets(DEFAULT_TOKEN, '40510')) #Lexington, KY (LEX airport) print(pullOneDayHourly(DEFAULT_TOKEN, '22202', '2010','01','01')) #annualDataHourlyToCsv(DEFAULT_TOKEN, '11430', [], 'weatherNoaaTemp.csv') #annualDataHourlyToCsv(DEFAULT_TOKEN, '40510', 'NORMAL_HLY', 'HLY-TEMP-NORMAL', 'weatherNoaaTemp.csv') #annualDataHourlyToCsv(DEFAULT_TOKEN, '40510', 'NORMAL_HLY', ['HLY-TEMP-NORMAL','HLY-WIND-1STPCT'], 'weatherNoaaTemp.csv') if __name__ == '__main__': _tests()
gpl-2.0
yugandhargangu/JspMyAdmin2
application/jspmyadmin/src/main/java/com/jspmyadmin/app/database/routine/beans/RoutineInfo.java
2595
/** * */ package com.jspmyadmin.app.database.routine.beans; import java.io.Serializable; /** * @author Yugandhar Gangu * @created_at 2016/03/03 * */ public class RoutineInfo implements Serializable { private static final long serialVersionUID = 1L; private String name = null; private String returns = null; private String routine_body = null; private String deterministic = null; private String data_access = null; private String security_type = null; private String definer = null; private String comments = null; /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the returns */ public String getReturns() { return returns; } /** * @param returns * the returns to set */ public void setReturns(String returns) { this.returns = returns; } /** * @return the routine_body */ public String getRoutine_body() { return routine_body; } /** * @param routine_body * the routine_body to set */ public void setRoutine_body(String routine_body) { this.routine_body = routine_body; } /** * @return the deterministic */ public String getDeterministic() { return deterministic; } /** * @param deterministic * the deterministic to set */ public void setDeterministic(String deterministic) { this.deterministic = deterministic; } /** * @return the data_access */ public String getData_access() { return data_access; } /** * @param data_access * the data_access to set */ public void setData_access(String data_access) { this.data_access = data_access; } /** * @return the security_type */ public String getSecurity_type() { return security_type; } /** * @param security_type * the security_type to set */ public void setSecurity_type(String security_type) { this.security_type = security_type; } /** * @return the definer */ public String getDefiner() { return definer; } /** * @param definer * the definer to set */ public void setDefiner(String definer) { this.definer = definer; } /** * @return the comments */ public String getComments() { return comments; } /** * @param comments * the comments to set */ public void setComments(String comments) { this.comments = comments; } /** * @return the serialversionuid */ public static long getSerialversionuid() { return serialVersionUID; } }
gpl-2.0
BluePsyduck/ManiaScript
src/ManiaScript/Builder/Event/Handler/AbstractHandler.php
4674
<?php namespace ManiaScript\Builder\Event\Handler; use ManiaScript\Builder; use ManiaScript\Builder\Code; use ManiaScript\Builder\PriorityQueue; use ManiaScript\Builder\Event\AbstractEvent; /** * The abstract base class of all event handlers. * * @author Marcel <marcel@mania-community.de> * @license http://opensource.org/licenses/GPL-2.0 GPL v2 */ abstract class AbstractHandler { /** * The builder instance. * @var \ManiaScript\Builder */ protected $builder; /** * The queue holding all the events of the handler. * @var \ManiaScript\Builder\PriorityQueue */ protected $events; /** * The code to be inserted in the global scope of the ManiaScript. * @var string */ protected $globalCode; /** * The code to be inserted directly in the event handling loop of the ManiaScript. * @var string */ protected $inlineCode; /** * All the handler function names currently used. Keys are the names, and values are the related events. * @var array */ protected $handlerFunctionNames = array(); /** * Initializes the event handler. * @param \ManiaScript\Builder The builder instance. */ public function __construct(Builder $builder) { $this->builder = $builder; $this->events = new PriorityQueue(); } /** * Adds a new event ot the handler. * @param \ManiaScript\Builder\Event\AbstractEvent $event The event. * @return $this Implementing fluent interface. */ public function addEvent(AbstractEvent $event) { $this->events->add($event); return $this; } /** * Prepares the handlers, having the code built. * @return $this Implementing fluent interface. */ public function prepare() { $this->inlineCode = $this->buildInlineCode(); $this->addGlobalCode($this->buildGlobalCode()); return $this; } /** * Builds the code to be inserted directly in the event handling loop of the ManiaScript. * @return string The internal code. */ protected function buildInlineCode() { return ''; } /** * Builds the code to be inserted in the global scope of the ManiaScript. * @return string The global code. */ protected function buildGlobalCode() { return ''; } /** * Adds global code to the builder. * @param string $globalCode The global code. * @param int $priority The priority of the code. Defaults to PHP_INT_MAX to add the code to the end of the script. * @return $this Implementing fluent interface. */ protected function addGlobalCode($globalCode, $priority = PHP_INT_MAX) { if (!empty($globalCode)) { $code = new Code(); $code->setCode($globalCode) ->setPriority($priority); $this->builder->addGlobalCode($code); } return $this; } /** * Returns the code to be inserted directly in the event handling loop of the ManiaScript. * @return string The inline code. */ public function getInlineCode() { return $this->inlineCode; } /** * Returns the name of the handler function to be used for the specified event. * @param \ManiaScript\Builder\Event\AbstractEvent The event. * @return string The handler function name. */ protected function getHandlerFunctionName(AbstractEvent $event) { $name = array_search($event, $this->handlerFunctionNames); if ($name === false) { $functionPrefix = $this->builder->getOptions()->getFunctionPrefix(); $parts = explode('\\', get_class($event)); $class = end($parts); $name = $functionPrefix . '_Handle' . $class . count($this->handlerFunctionNames); $this->handlerFunctionNames[$name] = $event; } return $name; } /** * Builds the handler function of the event. * @param \ManiaScript\Builder\Event\AbstractEvent $event The event. * @return string THe handler function. */ protected function buildHandlerFunction($event) { return 'Void ' . $this->getHandlerFunctionName($event) . '() {' . PHP_EOL . $event->getCode() . PHP_EOL . '}' . PHP_EOL; } /** * Builds the call of the handler function of the event. * @param \ManiaScript\Builder\Event\AbstractEvent $event The event. * @return string The handler function call. */ protected function buildHandlerFunctionCall($event) { return $this->getHandlerFunctionName($event) . '();' . PHP_EOL; } }
gpl-2.0
codelibs/n2dms
src/main/java/com/openkm/ws/endpoint/PropertyGroupService.java
10223
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * 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. */ package com.openkm.ws.endpoint; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.openkm.automation.AutomationException; import com.openkm.bean.PropertyGroup; import com.openkm.bean.form.CheckBox; import com.openkm.bean.form.FormElement; import com.openkm.bean.form.Input; import com.openkm.bean.form.Option; import com.openkm.bean.form.Select; import com.openkm.bean.form.SuggestBox; import com.openkm.bean.form.TextArea; import com.openkm.core.AccessDeniedException; import com.openkm.core.DatabaseException; import com.openkm.core.LockException; import com.openkm.core.NoSuchGroupException; import com.openkm.core.NoSuchPropertyException; import com.openkm.core.ParseException; import com.openkm.core.PathNotFoundException; import com.openkm.core.RepositoryException; import com.openkm.extension.core.ExtensionException; import com.openkm.module.ModuleManager; import com.openkm.module.PropertyGroupModule; import com.openkm.ws.util.FormElementComplex; import com.openkm.ws.util.StringPair; @WebService(name = "OKMPropertyGroup", serviceName = "OKMPropertyGroup", targetNamespace = "http://ws.openkm.com") public class PropertyGroupService { private static Logger log = LoggerFactory.getLogger(PropertyGroupService.class); @WebMethod public void addGroup(@WebParam(name = "token") String token, @WebParam(name = "nodePath") String nodePath, @WebParam(name = "grpName") String grpName) throws NoSuchGroupException, LockException, PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException, ExtensionException, AutomationException { log.debug("addGroup({}, {}, {})", new Object[] { token, nodePath, grpName }); PropertyGroupModule cm = ModuleManager.getPropertyGroupModule(); cm.addGroup(token, nodePath, grpName); log.debug("addGroup: void"); } @WebMethod public void removeGroup(@WebParam(name = "token") String token, @WebParam(name = "nodePath") String nodePath, @WebParam(name = "grpName") String grpName) throws AccessDeniedException, NoSuchGroupException, LockException, PathNotFoundException, RepositoryException, DatabaseException, ExtensionException { log.debug("removeGroup({}, {}, {})", new Object[] { token, nodePath, grpName }); PropertyGroupModule cm = ModuleManager.getPropertyGroupModule(); cm.removeGroup(token, nodePath, grpName); log.debug("removeGroup: void"); } @WebMethod public PropertyGroup[] getGroups(@WebParam(name = "token") String token, @WebParam(name = "nodePath") String nodePath) throws IOException, ParseException, AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getGroups({}, {})", token, nodePath); PropertyGroupModule cm = ModuleManager.getPropertyGroupModule(); List<PropertyGroup> col = cm.getGroups(token, nodePath); PropertyGroup[] result = col.toArray(new PropertyGroup[col.size()]); log.debug("getGroups: {}", result); return result; } @WebMethod public PropertyGroup[] getAllGroups(@WebParam(name = "token") String token) throws IOException, ParseException, AccessDeniedException, RepositoryException, DatabaseException { log.debug("getAllGroups({})", token); PropertyGroupModule cm = ModuleManager.getPropertyGroupModule(); List<PropertyGroup> col = cm.getAllGroups(token); PropertyGroup[] result = col.toArray(new PropertyGroup[col.size()]); log.debug("getAllGroups: {} ", result); return result; } @WebMethod public FormElementComplex[] getProperties(@WebParam(name = "token") String token, @WebParam(name = "nodePath") String nodePath, @WebParam(name = "grpName") String grpName) throws IOException, ParseException, NoSuchGroupException, AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getProperties({}, {}, {})", new Object[] { token, nodePath, grpName }); PropertyGroupModule cm = ModuleManager.getPropertyGroupModule(); List<FormElement> col = cm.getProperties(token, nodePath, grpName); FormElementComplex[] result = new FormElementComplex[col.size()]; for (int i = 0; i < col.size(); i++) { result[i] = FormElementComplex.toFormElementComplex(col.get(i)); } log.debug("getProperties: {}", result); return result; } @WebMethod public FormElementComplex[] getPropertyGroupForm(@WebParam(name = "token") String token, @WebParam(name = "grpName") String grpName) throws IOException, ParseException, NoSuchGroupException, AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getPropertyGroupForm({}, {})", new Object[] { token, grpName }); PropertyGroupModule cm = ModuleManager.getPropertyGroupModule(); List<FormElement> col = cm.getPropertyGroupForm(token, grpName); FormElementComplex[] result = new FormElementComplex[col.size()]; for (int i = 0; i < col.size(); i++) { result[i] = FormElementComplex.toFormElementComplex(col.get(i)); } log.debug("getPropertyGroupForm: {}", result); return result; } @WebMethod public void setProperties(@WebParam(name = "token") String token, @WebParam(name = "nodePath") String nodePath, @WebParam(name = "grpName") String grpName, @WebParam(name = "properties") FormElementComplex[] properties) throws IOException, ParseException, NoSuchPropertyException, NoSuchGroupException, LockException, PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException, ExtensionException, AutomationException { log.debug("setProperties({}, {}, {}, {})", new Object[] { token, nodePath, grpName, properties }); PropertyGroupModule cm = ModuleManager.getPropertyGroupModule(); List<FormElement> al = new ArrayList<FormElement>(); for (int i = 0; i < properties.length; i++) { al.add(FormElementComplex.toFormElement(properties[i])); } cm.setProperties(token, nodePath, grpName, al); log.debug("setProperties: void"); } @WebMethod public void setPropertiesSimple(@WebParam(name = "token") String token, @WebParam(name = "nodePath") String nodePath, @WebParam(name = "grpName") String grpName, @WebParam(name = "properties") StringPair[] properties) throws IOException, ParseException, NoSuchPropertyException, NoSuchGroupException, LockException, PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException, ExtensionException, AutomationException { log.debug("setPropertiesSimple({}, {}, {}, {})", new Object[] { token, nodePath, grpName, properties }); PropertyGroupModule cm = ModuleManager.getPropertyGroupModule(); List<FormElement> al = new ArrayList<FormElement>(); HashMap<String, String> mapProps = new HashMap<String, String>(); // Unmarshall HashMap for (StringPair sp : properties) { mapProps.put(sp.getKey(), sp.getValue()); } for (FormElement fe : cm.getProperties(token, nodePath, grpName)) { String value = mapProps.get(fe.getName()); if (value != null) { if (fe instanceof Input) { ((Input) fe).setValue(value); } else if (fe instanceof SuggestBox) { ((SuggestBox) fe).setValue(value); } else if (fe instanceof TextArea) { ((TextArea) fe).setValue(value); } else if (fe instanceof CheckBox) { ((CheckBox) fe).setValue(Boolean.valueOf(value)); } else if (fe instanceof Select) { Select sel = (Select) fe; for (Option opt : sel.getOptions()) { if (opt.getValue().equals(value)) { opt.setSelected(true); } else { opt.setSelected(false); } } } al.add(fe); } } cm.setProperties(token, nodePath, grpName, al); log.debug("setPropertiesSimple: void"); } @WebMethod public boolean hasGroup(@WebParam(name = "token") String token, @WebParam(name = "nodePath") String nodePath, @WebParam(name = "grpName") String grpName) throws IOException, ParseException, AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("hasGroup({}, {}, {})", new Object[] { token, nodePath, grpName }); PropertyGroupModule cm = ModuleManager.getPropertyGroupModule(); boolean ret = cm.hasGroup(token, nodePath, grpName); log.debug("hasGroup: {}", ret); return ret; } }
gpl-2.0
lsilvestre/Jogre
games/go/src/org/jogre/go/common/CommGoMove.java
2829
/* * JOGRE (Java Online Gaming Real-time Engine) - Chess * Copyright (C) 2004 Bob Marks (marksie531@yahoo.com) * http://jogre.sourceforge.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.jogre.go.common; import nanoxml.XMLElement; import org.jogre.common.comm.CommTableMessage; /** * Communication class for executing a go move. * * @author Bob Marks * @version Beta 0.3 */ public class CommGoMove extends CommTableMessage { public static final int TYPE_MOVE = 1; public static final int TYPE_PASS = 2; public static final int TYPE_MARK = 3; public static final int TYPE_HAPPY = 4; public static final int TYPE_UNHAPPY = 5; // Constants public static final String XML_NAME = "go_move"; public static final String XML_ATT_X = "x"; public static final String XML_ATT_Y = "y"; // xy corindates private int x = -1, y = -1; /** * Constructor which takes a status (type) * * @param type Type e.g. TYPE_PASS * @param username Username of player. */ public CommGoMove (int type, String username) { super (type, username); } /** * Constructor which takes an x and y. * * @param type Type e.g. TYPE_PASS * @param username Username of player. * @param x X co-ordinate * @param y y co-ordinate */ public CommGoMove (int type, String username, int x, int y) { super (type, username); this.x = x; this.y = y; } /** * Constructor for a chess execute move which takes a String. * * @param message Go move as XML message. */ public CommGoMove (XMLElement message) { super (message); this.x = message.getIntAttribute("x"); this.y = message.getIntAttribute("y"); } /** * Return x co-ordinate. * * @return */ public int getX () { return this.x; } /** * Return y co-ordinate. * * @return */ public int getY () { return this.y; } /** * Flatten the String. * * @see org.jogre.common.comm.ITransmittable#flatten() */ public XMLElement flatten() { XMLElement message = flatten (XML_NAME); message.setIntAttribute ("x", this.x); message.setIntAttribute ("y", this.y); return message; } }
gpl-2.0
surevine/chat
chat_client/src/main/java/com/surevine/chat/view/client/rooms/ui/open/OpenSecureRoomPresenter.java
2809
/* * Chat Client * Copyright (C) 2010 Surevine Limited * * 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/}. */ package com.surevine.chat.view.client.rooms.ui.open; import com.calclab.emite.core.client.xmpp.session.XmppSession; import com.calclab.emite.core.client.xmpp.stanzas.XmppURI; import com.calclab.hablar.core.client.mvp.HablarEventBus; import com.surevine.chat.common.xmpp.security.XmppSecurityLabelExtensionFactory; import com.surevine.chat.view.client.rooms.SecureRoomFactory; import com.surevine.chat.view.client.security.ISecurityLabelManager; /** * The presenter for the page which opens a new room with a security label */ public abstract class OpenSecureRoomPresenter extends EditSecureRoomPresenter { /** * The factory class which will be used to create room instances */ private final SecureRoomFactory roomFactory; private XmppSession session; /** * Creates a new presenter. * * @param type * the hablar page type for this page. * @param eventBus * the hablar event bus. * @param display * the view for this presenter. * @param roomFactory * The factory class which will be used to create room instances. */ public OpenSecureRoomPresenter(final String type, final HablarEventBus eventBus, final XmppSession session, final ISecurityLabelManager securityLabelManager, final XmppSecurityLabelExtensionFactory securityLabelExtensionFactory, final EditSecureRoomDisplay display, final SecureRoomFactory roomFactory) { super(type, eventBus, securityLabelManager, securityLabelExtensionFactory, display); this.roomFactory = roomFactory; this.session = session; } /** * {@inheritDoc}. */ @Override protected void onAccept() { final XmppURI user = session.getCurrentUserURI(); final String inviteReason = display.getMessage().getText(); roomFactory.createSecureRoom(user, display.getRoomName().getValue(), getItems(), securityLabelChooserPresenter.getSecurityLabel(), inviteReason); } }
gpl-2.0
CoordCulturaDigital-Minc/culturadigital.br
wp-content/plugins/tubepress/classes/org/tubepress/video/feed/inspection/FeedInspectionService.class.php
1002
<?php /** * Copyright 2006 - 2010 Eric D. Hough (http://ehough.com) * * This file is part of TubePress (http://tubepress.org) * * TubePress 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. * * TubePress 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 TubePress. If not, see <http://www.gnu.org/licenses/>. * */ /** * Examines the feed results * */ interface org_tubepress_video_feed_inspection_FeedInspectionService { public function getTotalResultCount($rawFeed); public function getQueryResultCount($rawFeed); }
gpl-2.0
jurkov/j-algo-mod
src/org/jalgo/module/am0c0/model/AM0History.java
3938
/* * j-Algo - j-Algo is an algorithm visualization tool, especially useful for * students and lecturers of computer science. It is written in Java and platform * independent. j-Algo is developed with the help of Dresden University of * Technology. * * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 59 Temple * Place, Suite 330, Boston, MA 02111-1307 USA */ package org.jalgo.module.am0c0.model; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.jalgo.module.am0c0.model.am0.MachineConfiguration; import org.jalgo.module.am0c0.model.c0.ast.C0AST; /** * History to store already calculated elements like * {@link MachineConfiguration} or {@link C0AST}. * * @author Max Leuth&auml;user */ public class AM0History<T> implements Iterator<T> { private List<T> history; private int currentIndex; public AM0History() { history = new ArrayList<T>(); currentIndex = 0; } /** * @return true if there is one more element in the history, false * otherwise. * * @see java.util.Iterator#hasNext() */ @Override public boolean hasNext() { return currentIndex < history.size(); } /** * @return true if there is one more previous element in the history, false * otherwise. * */ public boolean hasPrevious() { return currentIndex > 0; } /** * @return the next element in the history if this exists, <b>null</b> * otherwise. * * @see java.util.Iterator#next() */ @Override public T next() { if (hasNext()) { currentIndex++; return history.get(currentIndex); } return null; } /** * @return the previous element in the history if this exists, <b>null</b> * otherwise. * */ public T previous() { if (hasPrevious()) { currentIndex--; return history.get(currentIndex); } return null; } @Override public void remove() { throw new AbstractMethodError( "Calling this method is not allowed for this class."); } /** * @return the current size of the history. */ public int getCount() { return history.size(); } /** * @return the current index. */ public int getCurrentIndex() { return currentIndex; } /** * Add an object of type T to the history. * * @param m * Element of type T which should be added. * @throws IllegalArgumentException */ public void add(T m) throws IllegalArgumentException { if (m != null) { currentIndex++; for (int killIndex = currentIndex; killIndex < history.size(); killIndex++) { history.remove(killIndex); } history.add(m); } else throw new IllegalArgumentException( "Null arguments are not allowed here!"); } /** * Deletes all entries in the history. */ public void clear() { history.clear(); } /** * @return The object which is the last one in this history. */ public T getLastElement() { return history.get(history.size() - 1); } /** * @param s * Step to check. * @return true if this step exists already in the history. */ public boolean stepExists(int s) { return history.size() > s; } /** * @param step * @return the object at this step in the history. */ public T getAtStep(int step) { return history.get(step); } }
gpl-2.0
nanasess/mediawiki
includes/Revision.php
51347
<?php /** * Representation of a page version. * * 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. * http://www.gnu.org/copyleft/gpl.html * * @file */ /** * @todo document */ class Revision implements IDBAccessObject { protected $mId; /** * @var int|null */ protected $mPage; protected $mUserText; protected $mOrigUserText; protected $mUser; protected $mMinorEdit; protected $mTimestamp; protected $mDeleted; protected $mSize; protected $mSha1; protected $mParentId; protected $mComment; protected $mText; protected $mTextId; /** * @var stdClass|null */ protected $mTextRow; /** * @var null|Title */ protected $mTitle; protected $mCurrent; protected $mContentModel; protected $mContentFormat; /** * @var Content|null|bool */ protected $mContent; /** * @var null|ContentHandler */ protected $mContentHandler; /** * @var int */ protected $mQueryFlags = 0; // Revision deletion constants const DELETED_TEXT = 1; const DELETED_COMMENT = 2; const DELETED_USER = 4; const DELETED_RESTRICTED = 8; const SUPPRESSED_USER = 12; // convenience // Audience options for accessors const FOR_PUBLIC = 1; const FOR_THIS_USER = 2; const RAW = 3; /** * Load a page revision from a given revision ID number. * Returns null if no such revision can be found. * * $flags include: * Revision::READ_LATEST : Select the data from the master * Revision::READ_LOCKING : Select & lock the data from the master * * @param int $id * @param int $flags (optional) * @return Revision|null */ public static function newFromId( $id, $flags = 0 ) { return self::newFromConds( array( 'rev_id' => intval( $id ) ), $flags ); } /** * Load either the current, or a specified, revision * that's attached to a given title. If not attached * to that title, will return null. * * $flags include: * Revision::READ_LATEST : Select the data from the master * Revision::READ_LOCKING : Select & lock the data from the master * * @param Title $title * @param int $id (optional) * @param int $flags Bitfield (optional) * @return Revision|null */ public static function newFromTitle( $title, $id = 0, $flags = 0 ) { $conds = array( 'page_namespace' => $title->getNamespace(), 'page_title' => $title->getDBkey() ); if ( $id ) { // Use the specified ID $conds['rev_id'] = $id; return self::newFromConds( $conds, $flags ); } else { // Use a join to get the latest revision $conds[] = 'rev_id=page_latest'; $db = wfGetDB( ( $flags & self::READ_LATEST ) ? DB_MASTER : DB_SLAVE ); return self::loadFromConds( $db, $conds, $flags ); } } /** * Load either the current, or a specified, revision * that's attached to a given page ID. * Returns null if no such revision can be found. * * $flags include: * Revision::READ_LATEST : Select the data from the master (since 1.20) * Revision::READ_LOCKING : Select & lock the data from the master * * @param int $pageId * @param int $revId (optional) * @param int $flags Bitfield (optional) * @return Revision|null */ public static function newFromPageId( $pageId, $revId = 0, $flags = 0 ) { $conds = array( 'page_id' => $pageId ); if ( $revId ) { $conds['rev_id'] = $revId; return self::newFromConds( $conds, $flags ); } else { // Use a join to get the latest revision $conds[] = 'rev_id = page_latest'; $db = wfGetDB( ( $flags & self::READ_LATEST ) ? DB_MASTER : DB_SLAVE ); return self::loadFromConds( $db, $conds, $flags ); } } /** * Make a fake revision object from an archive table row. This is queried * for permissions or even inserted (as in Special:Undelete) * @todo FIXME: Should be a subclass for RevisionDelete. [TS] * * @param object $row * @param array $overrides * * @throws MWException * @return Revision */ public static function newFromArchiveRow( $row, $overrides = array() ) { global $wgContentHandlerUseDB; $attribs = $overrides + array( 'page' => isset( $row->ar_page_id ) ? $row->ar_page_id : null, 'id' => isset( $row->ar_rev_id ) ? $row->ar_rev_id : null, 'comment' => $row->ar_comment, 'user' => $row->ar_user, 'user_text' => $row->ar_user_text, 'timestamp' => $row->ar_timestamp, 'minor_edit' => $row->ar_minor_edit, 'text_id' => isset( $row->ar_text_id ) ? $row->ar_text_id : null, 'deleted' => $row->ar_deleted, 'len' => $row->ar_len, 'sha1' => isset( $row->ar_sha1 ) ? $row->ar_sha1 : null, 'content_model' => isset( $row->ar_content_model ) ? $row->ar_content_model : null, 'content_format' => isset( $row->ar_content_format ) ? $row->ar_content_format : null, ); if ( !$wgContentHandlerUseDB ) { unset( $attribs['content_model'] ); unset( $attribs['content_format'] ); } if ( !isset( $attribs['title'] ) && isset( $row->ar_namespace ) && isset( $row->ar_title ) ) { $attribs['title'] = Title::makeTitle( $row->ar_namespace, $row->ar_title ); } if ( isset( $row->ar_text ) && !$row->ar_text_id ) { // Pre-1.5 ar_text row $attribs['text'] = self::getRevisionText( $row, 'ar_' ); if ( $attribs['text'] === false ) { throw new MWException( 'Unable to load text from archive row (possibly bug 22624)' ); } } return new self( $attribs ); } /** * @since 1.19 * * @param object $row * @return Revision */ public static function newFromRow( $row ) { return new self( $row ); } /** * Load a page revision from a given revision ID number. * Returns null if no such revision can be found. * * @param DatabaseBase $db * @param int $id * @return Revision|null */ public static function loadFromId( $db, $id ) { return self::loadFromConds( $db, array( 'rev_id' => intval( $id ) ) ); } /** * Load either the current, or a specified, revision * that's attached to a given page. If not attached * to that page, will return null. * * @param DatabaseBase $db * @param int $pageid * @param int $id * @return Revision|null */ public static function loadFromPageId( $db, $pageid, $id = 0 ) { $conds = array( 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) ); if ( $id ) { $conds['rev_id'] = intval( $id ); } else { $conds[] = 'rev_id=page_latest'; } return self::loadFromConds( $db, $conds ); } /** * Load either the current, or a specified, revision * that's attached to a given page. If not attached * to that page, will return null. * * @param DatabaseBase $db * @param Title $title * @param int $id * @return Revision|null */ public static function loadFromTitle( $db, $title, $id = 0 ) { if ( $id ) { $matchId = intval( $id ); } else { $matchId = 'page_latest'; } return self::loadFromConds( $db, array( "rev_id=$matchId", 'page_namespace' => $title->getNamespace(), 'page_title' => $title->getDBkey() ) ); } /** * Load the revision for the given title with the given timestamp. * WARNING: Timestamps may in some circumstances not be unique, * so this isn't the best key to use. * * @param DatabaseBase $db * @param Title $title * @param string $timestamp * @return Revision|null */ public static function loadFromTimestamp( $db, $title, $timestamp ) { return self::loadFromConds( $db, array( 'rev_timestamp' => $db->timestamp( $timestamp ), 'page_namespace' => $title->getNamespace(), 'page_title' => $title->getDBkey() ) ); } /** * Given a set of conditions, fetch a revision * * This method is used then a revision ID is qualified and * will incorporate some basic slave/master fallback logic * * @param array $conditions * @param int $flags (optional) * @return Revision|null */ private static function newFromConds( $conditions, $flags = 0 ) { $db = wfGetDB( ( $flags & self::READ_LATEST ) ? DB_MASTER : DB_SLAVE ); $rev = self::loadFromConds( $db, $conditions, $flags ); // Make sure new pending/committed revision are visibile later on // within web requests to certain avoid bugs like T93866 and T94407. if ( !$rev && !( $flags & self::READ_LATEST ) && wfGetLB()->getServerCount() > 1 && wfGetLB()->hasOrMadeRecentMasterChanges() ) { $flags = self::READ_LATEST; $db = wfGetDB( DB_MASTER ); $rev = self::loadFromConds( $db, $conditions, $flags ); } if ( $rev ) { $rev->mQueryFlags = $flags; } return $rev; } /** * Given a set of conditions, fetch a revision from * the given database connection. * * @param DatabaseBase $db * @param array $conditions * @param int $flags (optional) * @return Revision|null */ private static function loadFromConds( $db, $conditions, $flags = 0 ) { $res = self::fetchFromConds( $db, $conditions, $flags ); if ( $res ) { $row = $res->fetchObject(); if ( $row ) { $ret = new Revision( $row ); return $ret; } } $ret = null; return $ret; } /** * Return a wrapper for a series of database rows to * fetch all of a given page's revisions in turn. * Each row can be fed to the constructor to get objects. * * @param Title $title * @return ResultWrapper */ public static function fetchRevision( $title ) { return self::fetchFromConds( wfGetDB( DB_SLAVE ), array( 'rev_id=page_latest', 'page_namespace' => $title->getNamespace(), 'page_title' => $title->getDBkey() ) ); } /** * Given a set of conditions, return a ResultWrapper * which will return matching database rows with the * fields necessary to build Revision objects. * * @param DatabaseBase $db * @param array $conditions * @param int $flags (optional) * @return ResultWrapper */ private static function fetchFromConds( $db, $conditions, $flags = 0 ) { $fields = array_merge( self::selectFields(), self::selectPageFields(), self::selectUserFields() ); $options = array( 'LIMIT' => 1 ); if ( ( $flags & self::READ_LOCKING ) == self::READ_LOCKING ) { $options[] = 'FOR UPDATE'; } return $db->select( array( 'revision', 'page', 'user' ), $fields, $conditions, __METHOD__, $options, array( 'page' => self::pageJoinCond(), 'user' => self::userJoinCond() ) ); } /** * Return the value of a select() JOIN conds array for the user table. * This will get user table rows for logged-in users. * @since 1.19 * @return array */ public static function userJoinCond() { return array( 'LEFT JOIN', array( 'rev_user != 0', 'user_id = rev_user' ) ); } /** * Return the value of a select() page conds array for the page table. * This will assure that the revision(s) are not orphaned from live pages. * @since 1.19 * @return array */ public static function pageJoinCond() { return array( 'INNER JOIN', array( 'page_id = rev_page' ) ); } /** * Return the list of revision fields that should be selected to create * a new revision. * @return array */ public static function selectFields() { global $wgContentHandlerUseDB; $fields = array( 'rev_id', 'rev_page', 'rev_text_id', 'rev_timestamp', 'rev_comment', 'rev_user_text', 'rev_user', 'rev_minor_edit', 'rev_deleted', 'rev_len', 'rev_parent_id', 'rev_sha1', ); if ( $wgContentHandlerUseDB ) { $fields[] = 'rev_content_format'; $fields[] = 'rev_content_model'; } return $fields; } /** * Return the list of revision fields that should be selected to create * a new revision from an archive row. * @return array */ public static function selectArchiveFields() { global $wgContentHandlerUseDB; $fields = array( 'ar_id', 'ar_page_id', 'ar_rev_id', 'ar_text', 'ar_text_id', 'ar_timestamp', 'ar_comment', 'ar_user_text', 'ar_user', 'ar_minor_edit', 'ar_deleted', 'ar_len', 'ar_parent_id', 'ar_sha1', ); if ( $wgContentHandlerUseDB ) { $fields[] = 'ar_content_format'; $fields[] = 'ar_content_model'; } return $fields; } /** * Return the list of text fields that should be selected to read the * revision text * @return array */ public static function selectTextFields() { return array( 'old_text', 'old_flags' ); } /** * Return the list of page fields that should be selected from page table * @return array */ public static function selectPageFields() { return array( 'page_namespace', 'page_title', 'page_id', 'page_latest', 'page_is_redirect', 'page_len', ); } /** * Return the list of user fields that should be selected from user table * @return array */ public static function selectUserFields() { return array( 'user_name' ); } /** * Do a batched query to get the parent revision lengths * @param DatabaseBase $db * @param array $revIds * @return array */ public static function getParentLengths( $db, array $revIds ) { $revLens = array(); if ( !$revIds ) { return $revLens; // empty } $res = $db->select( 'revision', array( 'rev_id', 'rev_len' ), array( 'rev_id' => $revIds ), __METHOD__ ); foreach ( $res as $row ) { $revLens[$row->rev_id] = $row->rev_len; } return $revLens; } /** * Constructor * * @param object|array $row Either a database row or an array * @throws MWException * @access private */ function __construct( $row ) { if ( is_object( $row ) ) { $this->mId = intval( $row->rev_id ); $this->mPage = intval( $row->rev_page ); $this->mTextId = intval( $row->rev_text_id ); $this->mComment = $row->rev_comment; $this->mUser = intval( $row->rev_user ); $this->mMinorEdit = intval( $row->rev_minor_edit ); $this->mTimestamp = $row->rev_timestamp; $this->mDeleted = intval( $row->rev_deleted ); if ( !isset( $row->rev_parent_id ) ) { $this->mParentId = null; } else { $this->mParentId = intval( $row->rev_parent_id ); } if ( !isset( $row->rev_len ) ) { $this->mSize = null; } else { $this->mSize = intval( $row->rev_len ); } if ( !isset( $row->rev_sha1 ) ) { $this->mSha1 = null; } else { $this->mSha1 = $row->rev_sha1; } if ( isset( $row->page_latest ) ) { $this->mCurrent = ( $row->rev_id == $row->page_latest ); $this->mTitle = Title::newFromRow( $row ); } else { $this->mCurrent = false; $this->mTitle = null; } if ( !isset( $row->rev_content_model ) ) { $this->mContentModel = null; # determine on demand if needed } else { $this->mContentModel = strval( $row->rev_content_model ); } if ( !isset( $row->rev_content_format ) ) { $this->mContentFormat = null; # determine on demand if needed } else { $this->mContentFormat = strval( $row->rev_content_format ); } // Lazy extraction... $this->mText = null; if ( isset( $row->old_text ) ) { $this->mTextRow = $row; } else { // 'text' table row entry will be lazy-loaded $this->mTextRow = null; } // Use user_name for users and rev_user_text for IPs... $this->mUserText = null; // lazy load if left null if ( $this->mUser == 0 ) { $this->mUserText = $row->rev_user_text; // IP user } elseif ( isset( $row->user_name ) ) { $this->mUserText = $row->user_name; // logged-in user } $this->mOrigUserText = $row->rev_user_text; } elseif ( is_array( $row ) ) { // Build a new revision to be saved... global $wgUser; // ugh # if we have a content object, use it to set the model and type if ( !empty( $row['content'] ) ) { // @todo when is that set? test with external store setup! check out insertOn() [dk] if ( !empty( $row['text_id'] ) ) { throw new MWException( "Text already stored in external store (id {$row['text_id']}), " . "can't serialize content object" ); } $row['content_model'] = $row['content']->getModel(); # note: mContentFormat is initializes later accordingly # note: content is serialized later in this method! # also set text to null? } $this->mId = isset( $row['id'] ) ? intval( $row['id'] ) : null; $this->mPage = isset( $row['page'] ) ? intval( $row['page'] ) : null; $this->mTextId = isset( $row['text_id'] ) ? intval( $row['text_id'] ) : null; $this->mUserText = isset( $row['user_text'] ) ? strval( $row['user_text'] ) : $wgUser->getName(); $this->mUser = isset( $row['user'] ) ? intval( $row['user'] ) : $wgUser->getId(); $this->mMinorEdit = isset( $row['minor_edit'] ) ? intval( $row['minor_edit'] ) : 0; $this->mTimestamp = isset( $row['timestamp'] ) ? strval( $row['timestamp'] ) : wfTimestampNow(); $this->mDeleted = isset( $row['deleted'] ) ? intval( $row['deleted'] ) : 0; $this->mSize = isset( $row['len'] ) ? intval( $row['len'] ) : null; $this->mParentId = isset( $row['parent_id'] ) ? intval( $row['parent_id'] ) : null; $this->mSha1 = isset( $row['sha1'] ) ? strval( $row['sha1'] ) : null; $this->mContentModel = isset( $row['content_model'] ) ? strval( $row['content_model'] ) : null; $this->mContentFormat = isset( $row['content_format'] ) ? strval( $row['content_format'] ) : null; // Enforce spacing trimming on supplied text $this->mComment = isset( $row['comment'] ) ? trim( strval( $row['comment'] ) ) : null; $this->mText = isset( $row['text'] ) ? rtrim( strval( $row['text'] ) ) : null; $this->mTextRow = null; $this->mTitle = isset( $row['title'] ) ? $row['title'] : null; // if we have a Content object, override mText and mContentModel if ( !empty( $row['content'] ) ) { if ( !( $row['content'] instanceof Content ) ) { throw new MWException( '`content` field must contain a Content object.' ); } $handler = $this->getContentHandler(); $this->mContent = $row['content']; $this->mContentModel = $this->mContent->getModel(); $this->mContentHandler = null; $this->mText = $handler->serializeContent( $row['content'], $this->getContentFormat() ); } elseif ( $this->mText !== null ) { $handler = $this->getContentHandler(); $this->mContent = $handler->unserializeContent( $this->mText ); } // If we have a Title object, make sure it is consistent with mPage. if ( $this->mTitle && $this->mTitle->exists() ) { if ( $this->mPage === null ) { // if the page ID wasn't known, set it now $this->mPage = $this->mTitle->getArticleID(); } elseif ( $this->mTitle->getArticleID() !== $this->mPage ) { // Got different page IDs. This may be legit (e.g. during undeletion), // but it seems worth mentioning it in the log. wfDebug( "Page ID " . $this->mPage . " mismatches the ID " . $this->mTitle->getArticleID() . " provided by the Title object." ); } } $this->mCurrent = false; // If we still have no length, see it we have the text to figure it out if ( !$this->mSize && $this->mContent !== null ) { $this->mSize = $this->mContent->getSize(); } // Same for sha1 if ( $this->mSha1 === null ) { $this->mSha1 = $this->mText === null ? null : self::base36Sha1( $this->mText ); } // force lazy init $this->getContentModel(); $this->getContentFormat(); } else { throw new MWException( 'Revision constructor passed invalid row format.' ); } $this->mUnpatrolled = null; } /** * Get revision ID * * @return int|null */ public function getId() { return $this->mId; } /** * Set the revision ID * * @since 1.19 * @param int $id */ public function setId( $id ) { $this->mId = $id; } /** * Get text row ID * * @return int|null */ public function getTextId() { return $this->mTextId; } /** * Get parent revision ID (the original previous page revision) * * @return int|null */ public function getParentId() { return $this->mParentId; } /** * Returns the length of the text in this revision, or null if unknown. * * @return int|null */ public function getSize() { return $this->mSize; } /** * Returns the base36 sha1 of the text in this revision, or null if unknown. * * @return string|null */ public function getSha1() { return $this->mSha1; } /** * Returns the title of the page associated with this entry or null. * * Will do a query, when title is not set and id is given. * * @return Title|null */ public function getTitle() { if ( $this->mTitle !== null ) { return $this->mTitle; } //rev_id is defined as NOT NULL, but this revision may not yet have been inserted. if ( $this->mId !== null ) { $dbr = wfGetDB( DB_SLAVE ); $row = $dbr->selectRow( array( 'page', 'revision' ), self::selectPageFields(), array( 'page_id=rev_page', 'rev_id' => $this->mId ), __METHOD__ ); if ( $row ) { $this->mTitle = Title::newFromRow( $row ); } } if ( !$this->mTitle && $this->mPage !== null && $this->mPage > 0 ) { $this->mTitle = Title::newFromID( $this->mPage ); } return $this->mTitle; } /** * Set the title of the revision * * @param Title $title */ public function setTitle( $title ) { $this->mTitle = $title; } /** * Get the page ID * * @return int|null */ public function getPage() { return $this->mPage; } /** * Fetch revision's user id if it's available to the specified audience. * If the specified audience does not have access to it, zero will be * returned. * * @param int $audience One of: * Revision::FOR_PUBLIC to be displayed to all users * Revision::FOR_THIS_USER to be displayed to the given user * Revision::RAW get the ID regardless of permissions * @param User $user User object to check for, only if FOR_THIS_USER is passed * to the $audience parameter * @return int */ public function getUser( $audience = self::FOR_PUBLIC, User $user = null ) { if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) { return 0; } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $user ) ) { return 0; } else { return $this->mUser; } } /** * Fetch revision's user id without regard for the current user's permissions * * @return string * @deprecated since 1.25, use getUser( Revision::RAW ) */ public function getRawUser() { wfDeprecated( __METHOD__, '1.25' ); return $this->getUser( self::RAW ); } /** * Fetch revision's username if it's available to the specified audience. * If the specified audience does not have access to the username, an * empty string will be returned. * * @param int $audience One of: * Revision::FOR_PUBLIC to be displayed to all users * Revision::FOR_THIS_USER to be displayed to the given user * Revision::RAW get the text regardless of permissions * @param User $user User object to check for, only if FOR_THIS_USER is passed * to the $audience parameter * @return string */ public function getUserText( $audience = self::FOR_PUBLIC, User $user = null ) { if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) { return ''; } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $user ) ) { return ''; } else { if ( $this->mUserText === null ) { $this->mUserText = User::whoIs( $this->mUser ); // load on demand if ( $this->mUserText === false ) { # This shouldn't happen, but it can if the wiki was recovered # via importing revs and there is no user table entry yet. $this->mUserText = $this->mOrigUserText; } } return $this->mUserText; } } /** * Fetch revision's username without regard for view restrictions * * @return string * @deprecated since 1.25, use getUserText( Revision::RAW ) */ public function getRawUserText() { wfDeprecated( __METHOD__, '1.25' ); return $this->getUserText( self::RAW ); } /** * Fetch revision comment if it's available to the specified audience. * If the specified audience does not have access to the comment, an * empty string will be returned. * * @param int $audience One of: * Revision::FOR_PUBLIC to be displayed to all users * Revision::FOR_THIS_USER to be displayed to the given user * Revision::RAW get the text regardless of permissions * @param User $user User object to check for, only if FOR_THIS_USER is passed * to the $audience parameter * @return string */ function getComment( $audience = self::FOR_PUBLIC, User $user = null ) { if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) { return ''; } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_COMMENT, $user ) ) { return ''; } else { return $this->mComment; } } /** * Fetch revision comment without regard for the current user's permissions * * @return string * @deprecated since 1.25, use getComment( Revision::RAW ) */ public function getRawComment() { wfDeprecated( __METHOD__, '1.25' ); return $this->getComment( self::RAW ); } /** * @return bool */ public function isMinor() { return (bool)$this->mMinorEdit; } /** * @return int Rcid of the unpatrolled row, zero if there isn't one */ public function isUnpatrolled() { if ( $this->mUnpatrolled !== null ) { return $this->mUnpatrolled; } $rc = $this->getRecentChange(); if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == 0 ) { $this->mUnpatrolled = $rc->getAttribute( 'rc_id' ); } else { $this->mUnpatrolled = 0; } return $this->mUnpatrolled; } /** * Get the RC object belonging to the current revision, if there's one * * @since 1.22 * @return RecentChange|null */ public function getRecentChange() { $dbr = wfGetDB( DB_SLAVE ); return RecentChange::newFromConds( array( 'rc_user_text' => $this->getUserText( Revision::RAW ), 'rc_timestamp' => $dbr->timestamp( $this->getTimestamp() ), 'rc_this_oldid' => $this->getId() ), __METHOD__ ); } /** * @param int $field One of DELETED_* bitfield constants * * @return bool */ public function isDeleted( $field ) { return ( $this->mDeleted & $field ) == $field; } /** * Get the deletion bitfield of the revision * * @return int */ public function getVisibility() { return (int)$this->mDeleted; } /** * Fetch revision text if it's available to the specified audience. * If the specified audience does not have the ability to view this * revision, an empty string will be returned. * * @param int $audience One of: * Revision::FOR_PUBLIC to be displayed to all users * Revision::FOR_THIS_USER to be displayed to the given user * Revision::RAW get the text regardless of permissions * @param User $user User object to check for, only if FOR_THIS_USER is passed * to the $audience parameter * * @deprecated since 1.21, use getContent() instead * @todo Replace usage in core * @return string */ public function getText( $audience = self::FOR_PUBLIC, User $user = null ) { ContentHandler::deprecated( __METHOD__, '1.21' ); $content = $this->getContent( $audience, $user ); return ContentHandler::getContentText( $content ); # returns the raw content text, if applicable } /** * Fetch revision content if it's available to the specified audience. * If the specified audience does not have the ability to view this * revision, null will be returned. * * @param int $audience One of: * Revision::FOR_PUBLIC to be displayed to all users * Revision::FOR_THIS_USER to be displayed to $wgUser * Revision::RAW get the text regardless of permissions * @param User $user User object to check for, only if FOR_THIS_USER is passed * to the $audience parameter * @since 1.21 * @return Content|null */ public function getContent( $audience = self::FOR_PUBLIC, User $user = null ) { if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_TEXT ) ) { return null; } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_TEXT, $user ) ) { return null; } else { return $this->getContentInternal(); } } /** * Fetch revision text without regard for view restrictions * * @return string * * @deprecated since 1.21. Instead, use Revision::getContent( Revision::RAW ) * or Revision::getSerializedData() as appropriate. */ public function getRawText() { ContentHandler::deprecated( __METHOD__, "1.21" ); return $this->getText( self::RAW ); } /** * Fetch original serialized data without regard for view restrictions * * @since 1.21 * @return string */ public function getSerializedData() { if ( $this->mText === null ) { $this->mText = $this->loadText(); } return $this->mText; } /** * Gets the content object for the revision (or null on failure). * * Note that for mutable Content objects, each call to this method will return a * fresh clone. * * @since 1.21 * @return Content|null The Revision's content, or null on failure. */ protected function getContentInternal() { if ( $this->mContent === null ) { // Revision is immutable. Load on demand: if ( $this->mText === null ) { $this->mText = $this->loadText(); } if ( $this->mText !== null && $this->mText !== false ) { // Unserialize content $handler = $this->getContentHandler(); $format = $this->getContentFormat(); $this->mContent = $handler->unserializeContent( $this->mText, $format ); } } // NOTE: copy() will return $this for immutable content objects return $this->mContent ? $this->mContent->copy() : null; } /** * Returns the content model for this revision. * * If no content model was stored in the database, the default content model for the title is * used to determine the content model to use. If no title is know, CONTENT_MODEL_WIKITEXT * is used as a last resort. * * @return string The content model id associated with this revision, * see the CONTENT_MODEL_XXX constants. **/ public function getContentModel() { if ( !$this->mContentModel ) { $title = $this->getTitle(); if ( $title ) { $this->mContentModel = ContentHandler::getDefaultModelFor( $title ); } else { $this->mContentModel = CONTENT_MODEL_WIKITEXT; } assert( !empty( $this->mContentModel ) ); } return $this->mContentModel; } /** * Returns the content format for this revision. * * If no content format was stored in the database, the default format for this * revision's content model is returned. * * @return string The content format id associated with this revision, * see the CONTENT_FORMAT_XXX constants. **/ public function getContentFormat() { if ( !$this->mContentFormat ) { $handler = $this->getContentHandler(); $this->mContentFormat = $handler->getDefaultFormat(); assert( !empty( $this->mContentFormat ) ); } return $this->mContentFormat; } /** * Returns the content handler appropriate for this revision's content model. * * @throws MWException * @return ContentHandler */ public function getContentHandler() { if ( !$this->mContentHandler ) { $model = $this->getContentModel(); $this->mContentHandler = ContentHandler::getForModelID( $model ); $format = $this->getContentFormat(); if ( !$this->mContentHandler->isSupportedFormat( $format ) ) { throw new MWException( "Oops, the content format $format is not supported for " . "this content model, $model" ); } } return $this->mContentHandler; } /** * @return string */ public function getTimestamp() { return wfTimestamp( TS_MW, $this->mTimestamp ); } /** * @return bool */ public function isCurrent() { return $this->mCurrent; } /** * Get previous revision for this title * * @return Revision|null */ public function getPrevious() { if ( $this->getTitle() ) { $prev = $this->getTitle()->getPreviousRevisionID( $this->getId() ); if ( $prev ) { return self::newFromTitle( $this->getTitle(), $prev ); } } return null; } /** * Get next revision for this title * * @return Revision|null */ public function getNext() { if ( $this->getTitle() ) { $next = $this->getTitle()->getNextRevisionID( $this->getId() ); if ( $next ) { return self::newFromTitle( $this->getTitle(), $next ); } } return null; } /** * Get previous revision Id for this page_id * This is used to populate rev_parent_id on save * * @param DatabaseBase $db * @return int */ private function getPreviousRevisionId( $db ) { if ( $this->mPage === null ) { return 0; } # Use page_latest if ID is not given if ( !$this->mId ) { $prevId = $db->selectField( 'page', 'page_latest', array( 'page_id' => $this->mPage ), __METHOD__ ); } else { $prevId = $db->selectField( 'revision', 'rev_id', array( 'rev_page' => $this->mPage, 'rev_id < ' . $this->mId ), __METHOD__, array( 'ORDER BY' => 'rev_id DESC' ) ); } return intval( $prevId ); } /** * Get revision text associated with an old or archive row * $row is usually an object from wfFetchRow(), both the flags and the text * field must be included. * * @param stdClass $row The text data * @param string $prefix Table prefix (default 'old_') * @param string|bool $wiki The name of the wiki to load the revision text from * (same as the the wiki $row was loaded from) or false to indicate the local * wiki (this is the default). Otherwise, it must be a symbolic wiki database * identifier as understood by the LoadBalancer class. * @return string Text the text requested or false on failure */ public static function getRevisionText( $row, $prefix = 'old_', $wiki = false ) { # Get data $textField = $prefix . 'text'; $flagsField = $prefix . 'flags'; if ( isset( $row->$flagsField ) ) { $flags = explode( ',', $row->$flagsField ); } else { $flags = array(); } if ( isset( $row->$textField ) ) { $text = $row->$textField; } else { return false; } # Use external methods for external objects, text in table is URL-only then if ( in_array( 'external', $flags ) ) { $url = $text; $parts = explode( '://', $url, 2 ); if ( count( $parts ) == 1 || $parts[1] == '' ) { return false; } $text = ExternalStore::fetchFromURL( $url, array( 'wiki' => $wiki ) ); } // If the text was fetched without an error, convert it if ( $text !== false ) { $text = self::decompressRevisionText( $text, $flags ); } return $text; } /** * If $wgCompressRevisions is enabled, we will compress data. * The input string is modified in place. * Return value is the flags field: contains 'gzip' if the * data is compressed, and 'utf-8' if we're saving in UTF-8 * mode. * * @param mixed $text Reference to a text * @return string */ public static function compressRevisionText( &$text ) { global $wgCompressRevisions; $flags = array(); # Revisions not marked this way will be converted # on load if $wgLegacyCharset is set in the future. $flags[] = 'utf-8'; if ( $wgCompressRevisions ) { if ( function_exists( 'gzdeflate' ) ) { $deflated = gzdeflate( $text ); if ( $deflated === false ) { wfLogWarning( __METHOD__ . ': gzdeflate() failed' ); } else { $text = $deflated; $flags[] = 'gzip'; } } else { wfDebug( __METHOD__ . " -- no zlib support, not compressing\n" ); } } return implode( ',', $flags ); } /** * Re-converts revision text according to it's flags. * * @param mixed $text Reference to a text * @param array $flags Compression flags * @return string|bool Decompressed text, or false on failure */ public static function decompressRevisionText( $text, $flags ) { if ( in_array( 'gzip', $flags ) ) { # Deal with optional compression of archived pages. # This can be done periodically via maintenance/compressOld.php, and # as pages are saved if $wgCompressRevisions is set. $text = gzinflate( $text ); if ( $text === false ) { wfLogWarning( __METHOD__ . ': gzinflate() failed' ); return false; } } if ( in_array( 'object', $flags ) ) { # Generic compressed storage $obj = unserialize( $text ); if ( !is_object( $obj ) ) { // Invalid object return false; } $text = $obj->getText(); } global $wgLegacyEncoding; if ( $text !== false && $wgLegacyEncoding && !in_array( 'utf-8', $flags ) && !in_array( 'utf8', $flags ) ) { # Old revisions kept around in a legacy encoding? # Upconvert on demand. # ("utf8" checked for compatibility with some broken # conversion scripts 2008-12-30) global $wgContLang; $text = $wgContLang->iconv( $wgLegacyEncoding, 'UTF-8', $text ); } return $text; } /** * Insert a new revision into the database, returning the new revision ID * number on success and dies horribly on failure. * * @param DatabaseBase $dbw (master connection) * @throws MWException * @return int */ public function insertOn( $dbw ) { global $wgDefaultExternalStore, $wgContentHandlerUseDB; $this->checkContentModel(); $data = $this->mText; $flags = self::compressRevisionText( $data ); # Write to external storage if required if ( $wgDefaultExternalStore ) { // Store and get the URL $data = ExternalStore::insertToDefault( $data ); if ( !$data ) { throw new MWException( "Unable to store text to external storage" ); } if ( $flags ) { $flags .= ','; } $flags .= 'external'; } # Record the text (or external storage URL) to the text table if ( $this->mTextId === null ) { $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' ); $dbw->insert( 'text', array( 'old_id' => $old_id, 'old_text' => $data, 'old_flags' => $flags, ), __METHOD__ ); $this->mTextId = $dbw->insertId(); } if ( $this->mComment === null ) { $this->mComment = ""; } # Record the edit in revisions $rev_id = $this->mId !== null ? $this->mId : $dbw->nextSequenceValue( 'revision_rev_id_seq' ); $row = array( 'rev_id' => $rev_id, 'rev_page' => $this->mPage, 'rev_text_id' => $this->mTextId, 'rev_comment' => $this->mComment, 'rev_minor_edit' => $this->mMinorEdit ? 1 : 0, 'rev_user' => $this->mUser, 'rev_user_text' => $this->mUserText, 'rev_timestamp' => $dbw->timestamp( $this->mTimestamp ), 'rev_deleted' => $this->mDeleted, 'rev_len' => $this->mSize, 'rev_parent_id' => $this->mParentId === null ? $this->getPreviousRevisionId( $dbw ) : $this->mParentId, 'rev_sha1' => $this->mSha1 === null ? Revision::base36Sha1( $this->mText ) : $this->mSha1, ); if ( $wgContentHandlerUseDB ) { //NOTE: Store null for the default model and format, to save space. //XXX: Makes the DB sensitive to changed defaults. // Make this behavior optional? Only in miser mode? $model = $this->getContentModel(); $format = $this->getContentFormat(); $title = $this->getTitle(); if ( $title === null ) { throw new MWException( "Insufficient information to determine the title of the " . "revision's page!" ); } $defaultModel = ContentHandler::getDefaultModelFor( $title ); $defaultFormat = ContentHandler::getForModelID( $defaultModel )->getDefaultFormat(); $row['rev_content_model'] = ( $model === $defaultModel ) ? null : $model; $row['rev_content_format'] = ( $format === $defaultFormat ) ? null : $format; } $dbw->insert( 'revision', $row, __METHOD__ ); $this->mId = $rev_id !== null ? $rev_id : $dbw->insertId(); // Assertion to try to catch T92046 if ( (int)$this->mId === 0 ) { throw new UnexpectedValueException( 'After insert, Revision mId is ' . var_export( $this->mId, 1 ) . ': ' . var_export( $row, 1 ) ); } Hooks::run( 'RevisionInsertComplete', array( &$this, $data, $flags ) ); return $this->mId; } protected function checkContentModel() { global $wgContentHandlerUseDB; $title = $this->getTitle(); //note: may return null for revisions that have not yet been inserted. $model = $this->getContentModel(); $format = $this->getContentFormat(); $handler = $this->getContentHandler(); if ( !$handler->isSupportedFormat( $format ) ) { $t = $title->getPrefixedDBkey(); throw new MWException( "Can't use format $format with content model $model on $t" ); } if ( !$wgContentHandlerUseDB && $title ) { // if $wgContentHandlerUseDB is not set, // all revisions must use the default content model and format. $defaultModel = ContentHandler::getDefaultModelFor( $title ); $defaultHandler = ContentHandler::getForModelID( $defaultModel ); $defaultFormat = $defaultHandler->getDefaultFormat(); if ( $this->getContentModel() != $defaultModel ) { $t = $title->getPrefixedDBkey(); throw new MWException( "Can't save non-default content model with " . "\$wgContentHandlerUseDB disabled: model is $model, " . "default for $t is $defaultModel" ); } if ( $this->getContentFormat() != $defaultFormat ) { $t = $title->getPrefixedDBkey(); throw new MWException( "Can't use non-default content format with " . "\$wgContentHandlerUseDB disabled: format is $format, " . "default for $t is $defaultFormat" ); } } $content = $this->getContent( Revision::RAW ); if ( !$content || !$content->isValid() ) { $t = $title->getPrefixedDBkey(); throw new MWException( "Content of $t is not valid! Content model is $model" ); } } /** * Get the base 36 SHA-1 value for a string of text * @param string $text * @return string */ public static function base36Sha1( $text ) { return wfBaseConvert( sha1( $text ), 16, 36, 31 ); } /** * Lazy-load the revision's text. * Currently hardcoded to the 'text' table storage engine. * * @return string|bool The revision's text, or false on failure */ protected function loadText() { // Caching may be beneficial for massive use of external storage global $wgRevisionCacheExpiry, $wgMemc; $textId = $this->getTextId(); $key = wfMemcKey( 'revisiontext', 'textid', $textId ); if ( $wgRevisionCacheExpiry ) { $text = $wgMemc->get( $key ); if ( is_string( $text ) ) { wfDebug( __METHOD__ . ": got id $textId from cache\n" ); return $text; } } // If we kept data for lazy extraction, use it now... if ( $this->mTextRow !== null ) { $row = $this->mTextRow; $this->mTextRow = null; } else { $row = null; } if ( !$row ) { // Text data is immutable; check slaves first. $dbr = wfGetDB( DB_SLAVE ); $row = $dbr->selectRow( 'text', array( 'old_text', 'old_flags' ), array( 'old_id' => $textId ), __METHOD__ ); } // Fallback to the master in case of slave lag. Also use FOR UPDATE if it was // used to fetch this revision to avoid missing the row due to REPEATABLE-READ. $forUpdate = ( $this->mQueryFlags & self::READ_LOCKING == self::READ_LOCKING ); if ( !$row && ( $forUpdate || wfGetLB()->getServerCount() > 1 ) ) { $dbw = wfGetDB( DB_MASTER ); $row = $dbw->selectRow( 'text', array( 'old_text', 'old_flags' ), array( 'old_id' => $textId ), __METHOD__, $forUpdate ? array( 'FOR UPDATE' ) : array() ); } if ( !$row ) { wfDebugLog( 'Revision', "No text row with ID '$textId' (revision {$this->getId()})." ); } $text = self::getRevisionText( $row ); if ( $row && $text === false ) { wfDebugLog( 'Revision', "No blob for text row '$textId' (revision {$this->getId()})." ); } # No negative caching -- negative hits on text rows may be due to corrupted slave servers if ( $wgRevisionCacheExpiry && $text !== false ) { $wgMemc->set( $key, $text, $wgRevisionCacheExpiry ); } return $text; } /** * Create a new null-revision for insertion into a page's * history. This will not re-save the text, but simply refer * to the text from the previous version. * * Such revisions can for instance identify page rename * operations and other such meta-modifications. * * @param DatabaseBase $dbw * @param int $pageId ID number of the page to read from * @param string $summary Revision's summary * @param bool $minor Whether the revision should be considered as minor * @param User|null $user User object to use or null for $wgUser * @return Revision|null Revision or null on error */ public static function newNullRevision( $dbw, $pageId, $summary, $minor, $user = null ) { global $wgContentHandlerUseDB, $wgContLang; $fields = array( 'page_latest', 'page_namespace', 'page_title', 'rev_text_id', 'rev_len', 'rev_sha1' ); if ( $wgContentHandlerUseDB ) { $fields[] = 'rev_content_model'; $fields[] = 'rev_content_format'; } $current = $dbw->selectRow( array( 'page', 'revision' ), $fields, array( 'page_id' => $pageId, 'page_latest=rev_id', ), __METHOD__ ); if ( $current ) { if ( !$user ) { global $wgUser; $user = $wgUser; } // Truncate for whole multibyte characters $summary = $wgContLang->truncate( $summary, 255 ); $row = array( 'page' => $pageId, 'user_text' => $user->getName(), 'user' => $user->getId(), 'comment' => $summary, 'minor_edit' => $minor, 'text_id' => $current->rev_text_id, 'parent_id' => $current->page_latest, 'len' => $current->rev_len, 'sha1' => $current->rev_sha1 ); if ( $wgContentHandlerUseDB ) { $row['content_model'] = $current->rev_content_model; $row['content_format'] = $current->rev_content_format; } $revision = new Revision( $row ); $revision->setTitle( Title::makeTitle( $current->page_namespace, $current->page_title ) ); } else { $revision = null; } return $revision; } /** * Determine if the current user is allowed to view a particular * field of this revision, if it's marked as deleted. * * @param int $field One of self::DELETED_TEXT, * self::DELETED_COMMENT, * self::DELETED_USER * @param User|null $user User object to check, or null to use $wgUser * @return bool */ public function userCan( $field, User $user = null ) { return self::userCanBitfield( $this->mDeleted, $field, $user ); } /** * Determine if the current user is allowed to view a particular * field of this revision, if it's marked as deleted. This is used * by various classes to avoid duplication. * * @param int $bitfield Current field * @param int $field One of self::DELETED_TEXT = File::DELETED_FILE, * self::DELETED_COMMENT = File::DELETED_COMMENT, * self::DELETED_USER = File::DELETED_USER * @param User|null $user User object to check, or null to use $wgUser * @param Title|null $title A Title object to check for per-page restrictions on, * instead of just plain userrights * @return bool */ public static function userCanBitfield( $bitfield, $field, User $user = null, Title $title = null ) { if ( $bitfield & $field ) { // aspect is deleted if ( $user === null ) { global $wgUser; $user = $wgUser; } if ( $bitfield & self::DELETED_RESTRICTED ) { $permissions = array( 'suppressrevision', 'viewsuppressed' ); } elseif ( $field & self::DELETED_TEXT ) { $permissions = array( 'deletedtext' ); } else { $permissions = array( 'deletedhistory' ); } $permissionlist = implode( ', ', $permissions ); if ( $title === null ) { wfDebug( "Checking for $permissionlist due to $field match on $bitfield\n" ); return call_user_func_array( array( $user, 'isAllowedAny' ), $permissions ); } else { $text = $title->getPrefixedText(); wfDebug( "Checking for $permissionlist on $text due to $field match on $bitfield\n" ); foreach ( $permissions as $perm ) { if ( $title->userCan( $perm, $user ) ) { return true; } } return false; } } else { return true; } } /** * Get rev_timestamp from rev_id, without loading the rest of the row * * @param Title $title * @param int $id * @return string|bool False if not found */ static function getTimestampFromId( $title, $id, $flags = 0 ) { $db = ( $flags & self::READ_LATEST ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE ); // Casting fix for databases that can't take '' for rev_id if ( $id == '' ) { $id = 0; } $conds = array( 'rev_id' => $id ); $conds['rev_page'] = $title->getArticleID(); $timestamp = $db->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__ ); return ( $timestamp !== false ) ? wfTimestamp( TS_MW, $timestamp ) : false; } /** * Get count of revisions per page...not very efficient * * @param DatabaseBase $db * @param int $id Page id * @return int */ static function countByPageId( $db, $id ) { $row = $db->selectRow( 'revision', array( 'revCount' => 'COUNT(*)' ), array( 'rev_page' => $id ), __METHOD__ ); if ( $row ) { return $row->revCount; } return 0; } /** * Get count of revisions per page...not very efficient * * @param DatabaseBase $db * @param Title $title * @return int */ static function countByTitle( $db, $title ) { $id = $title->getArticleID(); if ( $id ) { return self::countByPageId( $db, $id ); } return 0; } /** * Check if no edits were made by other users since * the time a user started editing the page. Limit to * 50 revisions for the sake of performance. * * @since 1.20 * @deprecated since 1.24 * * @param DatabaseBase|int $db The Database to perform the check on. May be given as a * Database object or a database identifier usable with wfGetDB. * @param int $pageId The ID of the page in question * @param int $userId The ID of the user in question * @param string $since Look at edits since this time * * @return bool True if the given user was the only one to edit since the given timestamp */ public static function userWasLastToEdit( $db, $pageId, $userId, $since ) { if ( !$userId ) { return false; } if ( is_int( $db ) ) { $db = wfGetDB( $db ); } $res = $db->select( 'revision', 'rev_user', array( 'rev_page' => $pageId, 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) ) ), __METHOD__, array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) ); foreach ( $res as $row ) { if ( $row->rev_user != $userId ) { return false; } } return true; } }
gpl-2.0
lu1sd4/tcpacman
ClientePacman/WindowsFormsApplication1/Properties/AssemblyInfo.cs
1460
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WindowsFormsApplication1")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WindowsFormsApplication1")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f33a7fda-5d9d-4e7f-a611-8a06f58183d6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
gpl-2.0
egiggy/githubericgiguere
wp-content/themes/8Cells/templates/_vti_cnf/template-portfolio-2r.php
1518
vti_encoding:SR|utf8-nl vti_timelastmodified:TR|07 Nov 2011 16:42:00 -0000 vti_extenderversion:SR|12.0.0.0 vti_author:SR|Eric-PC\\Eric vti_modifiedby:SR|Eric-PC\\Eric vti_timecreated:TR|07 Nov 2011 16:42:00 -0000 vti_cacheddtm:TX|07 Nov 2011 16:42:00 -0000 vti_filesize:IR|12188 vti_cachedlinkinfo:VX|H|javascript:; H|javascript:; H|< S|< S|< H|< S|< S|< K|template-portfolio-2r.php S|< S|< S|http://www.youtube.com/v/< S|http://www.youtube.com/v/< K|template-portfolio-2r.php S|< S|< S|http://vimeo.com/moogaloop.swf S|http://vimeo.com/moogaloop.swf vti_cachedsvcrellinks:VX|SHUS|javascript:; SHUS|javascript:; DHUS|wp-content/themes/8Cells/templates/< DSUS|wp-content/themes/8Cells/templates/< DSUS|wp-content/themes/8Cells/templates/< DHUS|wp-content/themes/8Cells/templates/< DSUS|wp-content/themes/8Cells/templates/< DSUS|wp-content/themes/8Cells/templates/< FKUS|wp-content/themes/8Cells/templates/template-portfolio-2r.php DSUS|wp-content/themes/8Cells/templates/< DSUS|wp-content/themes/8Cells/templates/< NSHS|http://www.youtube.com/v/< NSHS|http://www.youtube.com/v/< FKUS|wp-content/themes/8Cells/templates/template-portfolio-2r.php DSUS|wp-content/themes/8Cells/templates/< DSUS|wp-content/themes/8Cells/templates/< NSHS|http://vimeo.com/moogaloop.swf NSHS|http://vimeo.com/moogaloop.swf vti_cachedneedsrewrite:BR|false vti_cachedhasbots:BR|false vti_cachedhastheme:BR|false vti_cachedhasborder:BR|false vti_charset:SR|utf-8 vti_backlinkinfo:VX|wp-content/themes/8Cells/templates/template-portfolio-2r.php
gpl-2.0
adamfisk/littleshoot-client
common/ice/src/main/java/org/lastbamboo/common/ice/candidate/IceCandidateGatherer.java
647
package org.lastbamboo.common.ice.candidate; import java.net.InetAddress; import java.util.Collection; /** * Interface for classes that gather ICE candidates. */ public interface IceCandidateGatherer { /** * Gathers ICE candidates. * * @return The {@link Collection} of gathered candidates. */ Collection<IceCandidate> gatherCandidates(); /** * Close any resources associated with the gatherer. */ void close(); /** * Accessor for the public address of the machine. * * @return The public address of the machine. */ InetAddress getPublicAddress(); }
gpl-2.0
misilot/vufind
module/VuFind/src/VuFind/Search/Summon/Params.php
13176
<?php /** * Summon Search Parameters * * PHP version 5 * * Copyright (C) Villanova University 2011. * * 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. * * 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 * * @category VuFind * @package Search_Summon * @author Demian Katz <demian.katz@villanova.edu> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org Main Page */ namespace VuFind\Search\Summon; use SerialsSolutions_Summon_Query as SummonQuery, VuFind\Solr\Utils as SolrUtils, VuFindSearch\ParamBag; /** * Summon Search Parameters * * @category VuFind * @package Search_Summon * @author Demian Katz <demian.katz@villanova.edu> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org Main Page */ class Params extends \VuFind\Search\Base\Params { /** * Settings for all the facets * * @var array */ protected $fullFacetSettings = []; /** * Settings for the date facet only * * @var array */ protected $dateFacetSettings = []; /** * Add a field to facet on. * * @param string $newField Field name * @param string $newAlias Optional on-screen display label * @param bool $ored Should we treat this as an ORed facet? * * @return void */ public function addFacet($newField, $newAlias = null, $ored = false) { // Save the full field name (which may include extra parameters); // we'll need these to do the proper search using the Summon class: if (strstr($newField, 'PublicationDate')) { // Special case -- we don't need to send this to the Summon API, // but we do need to set a flag so VuFind knows to display the // date facet control. $this->dateFacetSettings[] = 'PublicationDate'; } else { $this->fullFacetSettings[] = $newField; } // Field name may have parameters attached -- remove them: $parts = explode(',', $newField); return parent::addFacet($parts[0], $newAlias, $ored); } /** * Reset the current facet configuration. * * @return void */ public function resetFacetConfig() { parent::resetFacetConfig(); $this->dateFacetSettings = []; $this->fullFacetSettings = []; } /** * Get the full facet settings stored by addFacet -- these may include extra * parameters needed by the search results class. * * @return array */ public function getFullFacetSettings() { return $this->fullFacetSettings; } /** * Get the date facet settings stored by addFacet. * * @return array */ public function getDateFacetSettings() { return $this->dateFacetSettings; } /** * Get a user-friendly string to describe the provided facet field. * * @param string $field Facet field name. * @param string $value Facet value. * * @return string Human-readable description of field. * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function getFacetLabel($field, $value = null) { // The default use of "Other" for undefined facets doesn't work well with // checkbox facets -- we'll use field names as the default within the Summon // search object. return isset($this->facetConfig[$field]) ? $this->facetConfig[$field] : $field; } /** * Get information on the current state of the boolean checkbox facets. * * @return array */ public function getCheckboxFacets() { // Grab checkbox facet details using the standard method: $facets = parent::getCheckboxFacets(); // Special case -- if we have a "holdings only" or "expand query" facet, // we want this to always appear, even on the "no results" screen, since // setting this facet actually EXPANDS rather than reduces the result set. if (isset($facets['holdingsOnly'])) { $facets['holdingsOnly']['alwaysVisible'] = true; } if (isset($facets['queryExpansion'])) { $facets['queryExpansion']['alwaysVisible'] = true; } // Return modified list: return $facets; } /** * Create search backend parameters for advanced features. * * @return ParamBag */ public function getBackendParameters() { $backendParams = new ParamBag(); $options = $this->getOptions(); $sort = $this->getSort(); if ($sort) { // If we have an empty search with relevance sort, see if there is // an override configured: if ($sort == 'relevance' && $this->getQuery()->getAllTerms() == '' && ($relOv = $this->getOptions()->getEmptySearchRelevanceOverride()) ) { $sort = $relOv; } } // The "relevance" sort option is a VuFind reserved word; we need to make // this null in order to achieve the desired effect with Summon: $finalSort = ($sort == 'relevance') ? null : $sort; $backendParams->set('sort', $finalSort); $backendParams->set('didYouMean', $options->spellcheckEnabled()); // Get the language setting: $lang = $this->getServiceLocator()->get('VuFind\Translator')->getLocale(); $backendParams->set('language', substr($lang, 0, 2)); if ($options->highlightEnabled()) { $backendParams->set('highlight', true); $backendParams->set('highlightStart', '{{{{START_HILITE}}}}'); $backendParams->set('highlightEnd', '{{{{END_HILITE}}}}'); } if ($maxTopics = $options->getMaxTopicRecommendations()) { $backendParams->set('maxTopics', $maxTopics); } $backendParams->set('facets', $this->getBackendFacetParameters()); $this->createBackendFilterParameters($backendParams); return $backendParams; } /** * Set up facets based on VuFind settings. * * @return array */ protected function getBackendFacetParameters() { $config = $this->getServiceLocator()->get('VuFind\Config')->get('Summon'); $defaultFacetLimit = isset($config->Facet_Settings->facet_limit) ? $config->Facet_Settings->facet_limit : 30; $fieldSpecificLimits = isset($config->Facet_Settings->facet_limit_by_field) ? $config->Facet_Settings->facet_limit_by_field : null; $finalFacets = []; foreach ($this->getFullFacetSettings() as $facet) { // See if parameters are included as part of the facet name; // if not, override them with defaults. $parts = explode(',', $facet); $facetName = $parts[0]; $bestDefaultFacetLimit = isset($fieldSpecificLimits->$facetName) ? $fieldSpecificLimits->$facetName : $defaultFacetLimit; $defaultMode = ($this->getFacetOperator($facet) == 'OR') ? 'or' : 'and'; $facetMode = isset($parts[1]) ? $parts[1] : $defaultMode; $facetPage = isset($parts[2]) ? $parts[2] : 1; $facetLimit = isset($parts[3]) ? $parts[3] : $bestDefaultFacetLimit; $facetParams = "{$facetMode},{$facetPage},{$facetLimit}"; $finalFacets[] = "{$facetName},{$facetParams}"; } return $finalFacets; } /** * Set up filters based on VuFind settings. * * @param ParamBag $params Parameter collection to update * * @return void */ public function createBackendFilterParameters(ParamBag $params) { // Which filters should be applied to our query? $filterList = $this->getFilterList(); if (!empty($filterList)) { $orFacets = []; // Loop through all filters and add appropriate values to request: foreach ($filterList as $filterArray) { foreach ($filterArray as $filt) { $safeValue = SummonQuery::escapeParam($filt['value']); // Special case -- "holdings only" is a separate parameter from // other facets. if ($filt['field'] == 'holdingsOnly') { $params->set( 'holdings', strtolower(trim($safeValue)) == 'true' ); } else if ($filt['field'] == 'queryExpansion') { // Special case -- "query expansion" is a separate parameter // from other facets. $params->set( 'expand', strtolower(trim($safeValue)) == 'true' ); } else if ($filt['field'] == 'excludeNewspapers') { // Special case -- support a checkbox for excluding // newspapers: $params ->add('filters', "ContentType,Newspaper Article,true"); } else if ($range = SolrUtils::parseRange($filt['value'])) { // Special case -- range query (translate [x TO y] syntax): $from = SummonQuery::escapeParam($range['from']); $to = SummonQuery::escapeParam($range['to']); $params ->add('rangeFilters', "{$filt['field']},{$from}:{$to}"); } else if ($filt['operator'] == 'OR') { // Special case -- OR facets: $orFacets[$filt['field']] = isset($orFacets[$filt['field']]) ? $orFacets[$filt['field']] : []; $orFacets[$filt['field']][] = $safeValue; } else { // Standard case: $fq = "{$filt['field']},{$safeValue}"; if ($filt['operator'] == 'NOT') { $fq .= ',true'; } $params->add('filters', $fq); } } // Deal with OR facets: foreach ($orFacets as $field => $values) { $params->add( 'groupFilters', $field . ',or,' . implode(',', $values) ); } } } } /** * Format a single filter for use in getFilterList(). * * @param string $field Field name * @param string $value Field value * @param string $operator Operator (AND/OR/NOT) * @param bool $translate Should we translate the label? * * @return array */ protected function formatFilterListEntry($field, $value, $operator, $translate) { $filter = parent::formatFilterListEntry( $field, $value, $operator, $translate ); // Convert range queries to a language-non-specific format: $caseInsensitiveRegex = '/^\(\[(.*) TO (.*)\] OR \[(.*) TO (.*)\]\)$/'; if (preg_match('/^\[(.*) TO (.*)\]$/', $value, $matches)) { // Simple case: [X TO Y] $filter['displayText'] = $matches[1] . '-' . $matches[2]; } else if (preg_match($caseInsensitiveRegex, $value, $matches)) { // Case insensitive case: [x TO y] OR [X TO Y]; convert // only if values in both ranges match up! if (strtolower($matches[3]) == strtolower($matches[1]) && strtolower($matches[4]) == strtolower($matches[2]) ) { $filter['displayText'] = $matches[1] . '-' . $matches[2]; } } return $filter; } /** * Load all available facet settings. This is mainly useful for showing * appropriate labels when an existing search has multiple filters associated * with it. * * @param string $preferredSection Section to favor when loading settings; if * multiple sections contain the same facet, this section's description will * be favored. * * @return void */ public function activateAllFacets($preferredSection = false) { $this->initFacetList('Facets', 'Results_Settings', 'Summon'); $this->initFacetList('Advanced_Facets', 'Advanced_Facet_Settings', 'Summon'); $this->initCheckboxFacets('CheckboxFacets', 'Summon'); } }
gpl-2.0
uhager/toast
FakeServer.java
1229
// part of Toast // author: Ulrike Hager import java.io.*; import java.net.*; class ClientHandler extends Thread { protected Socket incoming; FileReader inFile; public ClientHandler(Socket incoming) { this.incoming = incoming; } public void run() { try { inFile = new FileReader("tracks.txt"); BufferedReader in = new BufferedReader(inFile); in.mark(4000); PrintWriter out = new PrintWriter(new OutputStreamWriter(incoming.getOutputStream())); String l; boolean connect = true; while(connect){ while ((l = in.readLine()) != null) { if (l.startsWith("#")) sleep(50); out.println(l); out.flush(); } in.reset(); } in.close(); out.close(); } catch (Exception e) { System.out.println("Error: " + e); } } } public class FakeServer { public static void main(String[] args) { // System.out.println("MultiEchoServer started."); try { ServerSocket s = new ServerSocket(4711); for (;;) { Socket incoming = s.accept(); new ClientHandler(incoming).start(); } } catch (Exception e) { System.out.println("Error: " + e); } // System.out.println("MultiEchoServer stopped."); } }
gpl-2.0
sguha-work/fiddletest
fiddles/Gauge/Trend-Point/Trend-points-with-markers-in-linear-gauge_207/url.js
186
http://jsfiddle.net/fusioncharts/49VxD/ http://jsfiddle.net/gh/get/jquery/1.9.1/sguha-work/fiddletest/tree/master/fiddles/Gauge/Trend-Point/Trend-points-with-markers-in-linear-gauge_207/
gpl-2.0
klst-com/metasfresh
de.metas.adempiere.adempiere/base/src/main/java/org/adempiere/context/ThreadLocalServerContext.java
3764
package org.adempiere.context; /* * #%L * de.metas.adempiere.adempiere.base * %% * Copyright (C) 2015 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ import java.util.Properties; import org.adempiere.util.AbstractPropertiesProxy; import org.adempiere.util.Check; import org.adempiere.util.lang.IAutoCloseable; import org.adempiere.util.lang.NullAutoCloseable; /* package */final class ThreadLocalServerContext extends AbstractPropertiesProxy { private static final long serialVersionUID = 794823850355755679L; private IContextProviderListener listener = NullContextProviderListener.instance; private final InheritableThreadLocal<Properties> threadLocalContext = new InheritableThreadLocal<Properties>() { /** @return an empty properties instance */ @Override protected Properties initialValue() { final Properties ctx = new Properties(); listener.onContextCreated(ctx); return ctx; } /** @Return a new properties instance, using the given <code>parentValue</code> for defaults */ @Override protected Properties childValue(final Properties ctx) { final Properties childCtx = new Properties(ctx); listener.onChildContextCreated(ctx, childCtx); return childCtx; } @Override public Properties get() { final Properties ctx = super.get(); listener.onContextCheckOut(ctx); return ctx; }; @Override public void set(final Properties ctx) { final Properties ctxOld = super.get(); super.set(ctx); listener.onContextCheckIn(ctx, ctxOld); }; }; @Override protected Properties getDelegate() { return threadLocalContext.get(); } public ThreadLocalServerContext() { super(); } /** * Temporarily switches the context in the current thread. * * @param ctx * @return */ public IAutoCloseable switchContext(final Properties ctx) { Check.assumeNotNull(ctx, "ctx not null"); // Avoid StackOverflowException caused by setting the same context if (ctx == this) { return NullAutoCloseable.instance; } final long threadIdOnSet = Thread.currentThread().getId(); final Properties ctxOld = threadLocalContext.get(); threadLocalContext.set(ctx); return new IAutoCloseable() { private boolean closed = false; @Override public void close() { // Do nothing if already closed if (closed) { return; } // Assert we are restoring the ctx in same thread. // Because else, we would set the context "back" in another thread which would lead to huge inconsistencies. if (Thread.currentThread().getId() != threadIdOnSet) { throw new IllegalStateException("Error: setting back the context shall be done in the same thread as it was set initially"); } threadLocalContext.set(ctxOld); closed = true; } }; } /** * Dispose the context from current thread */ public void dispose() { final Properties ctx = threadLocalContext.get(); ctx.clear(); threadLocalContext.remove(); } public void setListener(final IContextProviderListener listener) { Check.assumeNotNull(listener, "listener not null"); this.listener = listener; } }
gpl-2.0
muromec/qtopia-ezx
devices/i686fb/src/plugins/qtopiacore/kbddrivers/i686fb/i686fbkbddriverplugin.cpp
1532
/**************************************************************************** ** ** This file is part of the Qtopia Opensource Edition Package. ** ** Copyright (C) 2008 Trolltech ASA. ** ** Contact: Qt Extended Information (info@qtextended.org) ** ** This file may be used under the terms of the GNU General Public License ** versions 2.0 as published by the Free Software Foundation and appearing ** in the file LICENSE.GPL included in the packaging of this file. ** ** Please review the following information to ensure GNU General Public ** Licensing requirements will be met: ** http://www.fsf.org/licensing/licenses/info/GPLv2.html. ** ** ****************************************************************************/ #include "i686fbkbddriverplugin.h" #include "i686fbkbdhandler.h" #include <qtopiaglobal.h> I686fbKbdDriverPlugin::I686fbKbdDriverPlugin( QObject *parent ) : QKbdDriverPlugin( parent ) {} I686fbKbdDriverPlugin::~I686fbKbdDriverPlugin() {} QWSKeyboardHandler* I686fbKbdDriverPlugin::create(const QString& driver, const QString&) { qWarning("I686fbKbdDriverPlugin:create()"); return create( driver ); } QWSKeyboardHandler* I686fbKbdDriverPlugin::create( const QString& driver) { if( driver.toLower() == "i686fbkbdhandler" ) { qWarning("Before call I686fbKbdHandler()"); return new I686fbKbdHandler(); } return 0; } QStringList I686fbKbdDriverPlugin::keys() const { return QStringList() << "i686fbkbdhandler"; } QTOPIA_EXPORT_QT_PLUGIN(I686fbKbdDriverPlugin)
gpl-2.0
hockeyhurd/Project-Zed
com/projectzed/mod/registry/ItemRegistry.java
3612
/* This file is part of Project-Zed. Project-Zed 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. Project-Zed 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 Project-Zed. If not, see <http://www.gnu.org/licenses/> */ package com.projectzed.mod.registry; import com.hockeyhurd.hcorelib.api.item.IHItem; import com.hockeyhurd.hcorelib.api.util.interfaces.IForgeMod; import net.minecraft.item.Item; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; /** * Class used for initializing and containing all items that are registered for this mod. * * @author hockeyhurd * @version Oct 20, 2014 */ public final class ItemRegistry { private static Map<String, IHItem> items; private static Map<String, IHItem> itemOres; private static ItemRegistry reg = new ItemRegistry(); private ItemRegistry() { items = new HashMap<String, IHItem>(0x80, 2.0f / 3.0f); itemOres = new HashMap<String, IHItem>(0x80, 2.0f / 3.0f); } /** * Create new instance of this class and register all items with this registry. * @param mainClass = class containing all item objects. */ public void init(Class<? extends IForgeMod> mainClass) { Field[] fields = mainClass.getFields(); if (fields.length == 0) return; // if there are no objects declared, nothing to do. for (Field f : fields) { try { if (f.get(mainClass) instanceof Item) { Item item = (Item) f.get(mainClass); // cast object to a item. if (item instanceof IHItem) { items.put(((IHItem) item).getName(), (IHItem) item); // add block to list if not null. if (item.getUnlocalizedName().toLowerCase().contains("ingot") || item.getUnlocalizedName().toLowerCase().contains("dust") || item.getUnlocalizedName().toLowerCase().contains("nugget") || item.getUnlocalizedName().toLowerCase().contains("plate")) { itemOres.put(((IHItem) item).getName(), (IHItem) item); } } } } catch (Exception e) { e.printStackTrace(); break; } } } /** * Gets the instance of this class. * @return class instance. */ public static ItemRegistry instance() { return reg; } /** * Gets the list of registered items. * @return list of items registered in this current instance. */ public Map<String, IHItem> getItems() { return items; } /** * Gets the list for ore dictionary. * @return list of items to be registered in ore dictionary. */ public Map<String, IHItem> getItemOres() { return itemOres; } /** * Gets the item by name specified. * @param name = name of item to find. * @return item if found, else null. */ public Item getItemByName(String name) { if (name == null || name.isEmpty() || items.isEmpty()) return null; final IHItem result = items.get(name); return result != null ? result.getItem() : null; } /** * Returns the actual unlocalized name for said block. * @param i = block to get name for. * @return block's unlocalized name. */ public static String getBlockName(Item i) { return i.getUnlocalizedName().substring(5); } }
gpl-2.0
munglaub/silence
src/persistence/kjotsimporter.cpp
3951
/* * Silence * * Copyright (C) 2011 Manuel Unglaub * * This file is part of Silence. * * Silence is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version GPLv2 only of the License. * * Silence 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 Silence. If not, see <http://www.gnu.org/licenses/>. */ #include <QDomDocument> #include <QFile> #include <QTextStream> #include "src/controller.h" #include "src/data/node/booknodecontent.h" #include "src/data/node/node.h" #include "src/data/node/richtextnodecontent.h" #include "src/persistence/kjotsimporter.h" KjotsImporter::KjotsImporter(Node *node, QString fileName) { this->rootNode = node; this->fileName = fileName; } KjotsImporter::~KjotsImporter() { } void KjotsImporter::getBook(QDomElement element, Node *parentNode) { int index = parentNode->getChildCount(); parentNode->addChildren(index, 1); Node *node = parentNode->getChild(index); node->setId(new NodeId); node->setModificationDate(QDateTime::currentDateTime()); node->setCreationDate(QDateTime::currentDateTime()); node->setContent(new BookNodeContent); importedNodes << node; QDomNode n = element.firstChild(); while (!n.isNull()){ QDomElement e = n.toElement(); if (e.tagName().toLower() == "title"){ node->setCaption(e.text()); } if (e.tagName().toLower() == "kjotsbook"){ getBook(e, node); } if (e.tagName().toLower() == "kjotspage"){ getPage(e, node); } n = n.nextSibling(); } connect(node, SIGNAL(changed(Node*)), Controller::create()->getDataStore(), SLOT(saveNode(Node*))); } void KjotsImporter::getPage(QDomElement element, Node *parentNode) { int index = parentNode->getChildCount(); parentNode->addChildren(index, 1); Node *node = parentNode->getChild(index); node->setId(new NodeId()); node->setModificationDate(QDateTime::currentDateTime()); node->setCreationDate(QDateTime::currentDateTime()); RichTextNodeContent *content = new RichTextNodeContent; node->setContent(content); importedNodes << node; QDomNode n = element.firstChild(); while (!n.isNull()) { QDomElement e = n.toElement(); if (e.tagName().toLower() == "title"){ node->setCaption(e.text()); } else if (e.tagName().toLower() == "text"){ if (e.firstChild().isCDATASection()){ QString text = e.firstChild().toCDATASection().data(); content->setText(text); } } n = n.nextSibling(); } connect(node, SIGNAL(changed(Node*)), Controller::create()->getDataStore(), SLOT(saveNode(Node*))); } QString KjotsImporter::readFile(QFile & file) { QString xml = ""; QTextStream in(&file); while (!in.atEnd()) { QString line = in.readLine(); // repair broken kjots xml line.replace("<KjotsBook>", "<kjotsbook>"); line.replace("</KJotsBook>", "</kjotsbook>"); line.replace("<KjotsPage>", "<kjotspage>"); line.replace("</KJotsPage>", "</kjotspage>"); xml += line + "\n"; } return xml; } QList<Node*> KjotsImporter::import() { QDomDocument doc; QFile file(fileName); if (!file.open(QIODevice::ReadOnly)){ return this->importedNodes;; } doc.setContent(readFile(file)); file.close(); QDomElement xmlRoot = doc.documentElement(); if (xmlRoot.tagName().toLower() != "kjots"){ return this->importedNodes;; } // needs to be saved/updated this->importedNodes << rootNode; QDomNode n = xmlRoot.firstChild(); while (!n.isNull()) { QDomElement e = n.toElement(); if (e.tagName().toLower() == "kjotsbook"){ getBook(e, rootNode); } if (e.tagName().toLower() == "kjotspage"){ getPage(e, rootNode); } n = n.nextSibling(); } return this->importedNodes; }
gpl-2.0
aaahexing/cheer
puzzles/leetcode/71.cpp
1493
/**************************** Simplify Path: https://leetcode.com/problems/simplify-path/ Given an absolute path for a file (Unix-style), simplify it. For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c" Corner Cases: Did you consider the case where path = "/../"? In this case, you should return "/". Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". In this case, you should ignore redundant slashes and return "/home/foo". **/ //@time complexity: O(n) //@space complexity: O(n) string simplifyPath(string path) { int firstPos = 0; int secondPos; stack<string> sStr; while (firstPos != -1) { firstPos = path.find('/', firstPos); if (firstPos == -1) { break; } secondPos = path.find('/', firstPos + 1); string content; if (secondPos != -1) { content = path.substr(firstPos + 1, secondPos - firstPos - 1); } else { content = path.substr(firstPos + 1); } if (content == "..") { if (!sStr.empty()) { sStr.pop(); } } else if (content != "." && content != ""){ sStr.push(content); } firstPos = secondPos; } string ret; while(!sStr.empty()) { ret = "/" + sStr.top() + ret; sStr.pop(); } if (ret == "") { ret = "/"; } return ret; }
gpl-2.0
bramalingam/bioformats
components/formats-bsd/test/loci/formats/utests/GenericExcitationMapTest.java
5993
/* * #%L * Tests for OME Bio-Formats BSD-licensed readers and writers. * %% * Copyright (C) 2005 - 2016 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of any organization. * #L% */ package loci.formats.utests; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import ome.xml.model.Channel; import ome.xml.model.Image; import ome.xml.model.Instrument; import ome.xml.model.LightSourceSettings; import ome.xml.model.GenericExcitationSource; import ome.xml.model.MapPair; import ome.xml.model.OME; import ome.xml.model.OMEModel; import ome.xml.model.OMEModelImpl; import ome.xml.model.Pixels; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Test case for GenericExcitationSource Map values * * @author Andrew Patterson */ public class GenericExcitationMapTest { private OME ome = new OME(); @BeforeClass public void setUp() throws Exception { Instrument instrument = new Instrument(); instrument.setID("Instrument:0"); // Add a GenericExcitationSource with an Map GenericExcitationSource geSource = new GenericExcitationSource(); geSource.setID("LightSource:0"); List<MapPair> dataMap = new ArrayList<MapPair>(); dataMap.add(new MapPair("a", "1")); dataMap.add(new MapPair("d", "2")); dataMap.add(new MapPair("c", "3")); dataMap.add(new MapPair("b", "4")); dataMap.add(new MapPair("e", "5")); dataMap.add(new MapPair("c", "6")); assertEquals(6, dataMap.size()); geSource.setMap(dataMap); instrument.addLightSource(geSource); ome.addInstrument(instrument); // Add an Image/Pixels with a LightSourceSettings reference to the // GenericExcitationSource on one of its channels. Image image = new Image(); image.setID("Image:0"); Pixels pixels = new Pixels(); pixels.setID("Pixels:0"); Channel channel = new Channel(); channel.setID("Channel:0"); LightSourceSettings settings = new LightSourceSettings(); settings.setID("LightSource:0"); channel.setLightSourceSettings(settings); pixels.addChannel(channel); image.setPixels(pixels); ome.addImage(image); } @Test public void testGenericExcitationSourceValid() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document document = parser.newDocument(); // Produce a valid OME DOM element hierarchy Element root = ome.asXMLElement(document); SPWModelMock.postProcess(root, document, false); OMEModel model = new OMEModelImpl(); ome = new OME(document.getDocumentElement(), model); model.resolveReferences(); } @Test public void testGenericExcitationSourceMapContent() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document document = parser.newDocument(); // Produce a valid OME DOM element hierarchy Element root = ome.asXMLElement(document); SPWModelMock.postProcess(root, document, false); OMEModel model = new OMEModelImpl(); ome = new OME(document.getDocumentElement(), model); model.resolveReferences(); assertNotNull(ome); assertEquals(ome.getImage(0).getPixels().getChannel(0).getLightSourceSettings().getID(), "LightSource:0"); assertNotNull(ome.getInstrument(0).getLightSource(0)); GenericExcitationSource geSource = (GenericExcitationSource) ome.getInstrument(0).getLightSource(0); List<MapPair> dataMap = geSource.getMap(); assertEquals(6, dataMap.size()); assertPair(dataMap, 0, "a", "1"); assertPair(dataMap, 1, "d", "2"); assertPair(dataMap, 2, "c", "3"); assertPair(dataMap, 3, "b", "4"); assertPair(dataMap, 4, "e", "5"); assertPair(dataMap, 5, "c", "6"); } void assertPair(List<MapPair> dataMap, int idx, String name, String value) { assertEquals(name, dataMap.get(idx).getName()); assertEquals(value, dataMap.get(idx).getValue()); } }
gpl-2.0
aosm/gcc_42
gcc/testsuite/g++.apple/asm-block-23.C
385
/* APPLE LOCAL file CW asm blocks */ /* { dg-do assemble { target i?86*-*-darwin* } } */ /* { dg-options { -fasm-blocks -msse3 } } */ /* Radar 4248139 */ void foo() { asm { nop ; 1st insn nop ; 2nd insn nop // ; Don't die here nop ; 24 = 11000b nop ; # of cols nop ; ## of cols nop ;  of cols } int i = 1st 0; /* { dg-error "invalid suffix" } */ }
gpl-2.0
klst-com/metasfresh
de.metas.acct.base/src/main/java-legacy/org/adempiere/process/ClientAcctProcessor.java
6856
/********************************************************************** * This file is part of Adempiere ERP Bazaar * * http://www.adempiere.org * * * * Copyright (C) Carlos Ruiz - globalqss * * Copyright (C) Contributors * * * * 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. * * * * Contributors: * * - Carlos Ruiz - globalqss * * * * Sponsors: * * - Company (http://www.globalqss.com) * ***********************************************************************/ package org.adempiere.process; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.slf4j.Logger; import de.metas.logging.LogManager; import de.metas.process.ProcessInfoParameter; import de.metas.process.JavaProcess; import org.adempiere.acct.api.IDocFactory; import org.adempiere.acct.api.IDocMetaInfo; import org.adempiere.acct.api.IPostingService; import org.adempiere.exceptions.AdempiereException; import org.adempiere.util.Services; import org.compiere.acct.Doc; import org.compiere.model.MAcctSchema; import org.compiere.model.MClient; import org.compiere.model.MCost; import org.compiere.util.DB; import org.compiere.util.Trx; /** * Client Accounting Processor * * @author Carlos Ruiz */ public class ClientAcctProcessor extends JavaProcess { // services private final transient IPostingService postingService = Services.get(IPostingService.class); /* The Accounting Schema */ private int p_C_AcctSchema_ID; /* The Table */ private int p_AD_Table_ID; /** Last Summary */ private StringBuilder m_summary = new StringBuilder(); /** Client info */ private MClient m_client = null; /** Accounting Schema */ private MAcctSchema[] m_ass = null; /** * Prepare */ @Override protected void prepare() { ProcessInfoParameter[] para = getParametersAsArray(); for (int i = 0; i < para.length; i++) { String name = para[i].getParameterName(); if (para[i].getParameter() == null) ; else if (name.equals("C_AcctSchema_ID")) p_C_AcctSchema_ID = para[i].getParameterAsInt(); else if (name.equals("AD_Table_ID")) p_AD_Table_ID = para[i].getParameterAsInt(); else log.error("Unknown Parameter: " + name); } } // prepare /** * Process * * @return info * @throws Exception */ @Override protected String doIt() throws Exception { log.info("C_AcctSchema_ID=" + p_C_AcctSchema_ID + ", AD_Table_ID=" + p_AD_Table_ID); if (!postingService.isClientAccountingEnabled()) { throw new AdempiereException("@ClientAccountingNotEnabled@"); } m_client = MClient.get(getCtx(), getAD_Client_ID()); if (p_C_AcctSchema_ID == 0) m_ass = MAcctSchema.getClientAcctSchema(getCtx(), getAD_Client_ID()); else // only specific accounting schema m_ass = new MAcctSchema[] { new MAcctSchema(getCtx(), p_C_AcctSchema_ID, get_TrxName()) }; postSession(); MCost.create(m_client); addLog(m_summary.toString()); return "@OK@"; } // doIt /** * Post Session */ private void postSession() { final IDocFactory docFactory = Services.get(IDocFactory.class); for (final IDocMetaInfo docMetaInfo : docFactory.getDocMetaInfoList()) { final int AD_Table_ID = docMetaInfo.getAD_Table_ID(); final String TableName = docMetaInfo.getTableName(); // Post only special documents if (p_AD_Table_ID != 0 && p_AD_Table_ID != AD_Table_ID) { continue; } // SELECT * FROM table StringBuilder sql = new StringBuilder("SELECT * FROM ").append(TableName) .append(" WHERE AD_Client_ID=?") .append(" AND Processed='Y' AND Posted='N' AND IsActive='Y'") .append(" ORDER BY Created"); // int count = 0; int countError = 0; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql.toString(), get_TrxName()); pstmt.setInt(1, getAD_Client_ID()); rs = pstmt.executeQuery(); while (rs.next()) { count++; boolean ok = true; // Run every posting document in own transaction String innerTrxName = Trx.createTrxName("CAP"); Trx innerTrx = Trx.get(innerTrxName, true); try { Doc doc = docFactory.get(getCtx(), docMetaInfo, m_ass, rs, innerTrxName); if (doc == null) { log.error(getName() + ": No Doc for " + TableName); ok = false; } else { String error = doc.post(false, false); // post no force/repost ok = (error == null); } } catch (Exception e) { log.error(getName() + ": " + TableName + ": " + e.getLocalizedMessage(), e); // metas: improve error logging ok = false; } finally { if (ok) innerTrx.commit(); else innerTrx.rollback(); innerTrx.close(); innerTrx = null; } if (!ok) countError++; } } catch (Exception e) { log.error(sql.toString(), e); } finally { DB.close(rs, pstmt); } // if (count > 0) { m_summary.append(TableName).append("=").append(count); if (countError > 0) m_summary.append("(Errors=").append(countError).append(")"); m_summary.append(" - "); log.trace(getName() + ": " + m_summary.toString()); } else log.trace(getName() + ": " + TableName + " - no work"); } } // postSession } // ClientAcctProcessor
gpl-2.0
giahuy10/mokarafashion
libraries/regularlabs/helpers/field.php
568
<?php /** * @package Regular Labs Library * @version 17.5.14365 * * @author Peter van Westen <info@regularlabs.com> * @link http://www.regularlabs.com * @copyright Copyright © 2017 Regular Labs All Rights Reserved * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL */ /* @DEPRECATED */ defined('_JEXEC') or die; if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php')) { require_once JPATH_LIBRARIES . '/regularlabs/autoload.php'; } class RLFormField extends \RegularLabs\Library\Field { }
gpl-2.0
david-martyn-ford/ProjectAsylum
src/ProjectAsylum.Core/SearchProviders/ProviderType.cs
154
namespace ProjectAsylum.Core.SearchProviders { public enum ProviderType { Unknown = 0, Torrent = 1, Usernet = 2 } }
gpl-2.0
duganchen/dosbox
src/dos/dos_files.cpp
39298
/* * Copyright (C) 2002-2019 The DOSBox Team * * 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. */ #include <string.h> #include <stdlib.h> #include <time.h> #include <ctype.h> #include "dosbox.h" #include "bios.h" #include "mem.h" #include "regs.h" #include "dos_inc.h" #include "drives.h" #include "cross.h" #define DOS_FILESTART 4 #define FCB_SUCCESS 0 #define FCB_READ_NODATA 1 #define FCB_READ_PARTIAL 3 #define FCB_ERR_NODATA 1 #define FCB_ERR_EOF 3 #define FCB_ERR_WRITE 1 DOS_File * Files[DOS_FILES]; DOS_Drive * Drives[DOS_DRIVES]; Bit8u DOS_GetDefaultDrive(void) { // return DOS_SDA(DOS_SDA_SEG,DOS_SDA_OFS).GetDrive(); Bit8u d = DOS_SDA(DOS_SDA_SEG,DOS_SDA_OFS).GetDrive(); if( d != dos.current_drive ) LOG(LOG_DOSMISC,LOG_ERROR)("SDA drive %d not the same as dos.current_drive %d",d,dos.current_drive); return dos.current_drive; } void DOS_SetDefaultDrive(Bit8u drive) { // if (drive<=DOS_DRIVES && ((drive<2) || Drives[drive])) DOS_SDA(DOS_SDA_SEG,DOS_SDA_OFS).SetDrive(drive); if (drive<DOS_DRIVES && ((drive<2) || Drives[drive])) {dos.current_drive = drive; DOS_SDA(DOS_SDA_SEG,DOS_SDA_OFS).SetDrive(drive);} } bool DOS_MakeName(char const * const name,char * const fullname,Bit8u * drive) { if(!name || *name == 0 || *name == ' ') { /* Both \0 and space are seperators and * empty filenames report file not found */ DOS_SetError(DOSERR_FILE_NOT_FOUND); return false; } const char * name_int = name; char tempdir[DOS_PATHLENGTH]; char upname[DOS_PATHLENGTH]; Bitu r,w; Bit8u c; *drive = DOS_GetDefaultDrive(); /* First get the drive */ if (name_int[1]==':') { *drive=(name_int[0] | 0x20)-'a'; name_int+=2; } if (*drive>=DOS_DRIVES || !Drives[*drive]) { DOS_SetError(DOSERR_PATH_NOT_FOUND); return false; } r=0;w=0; while (name_int[r]!=0 && (r<DOS_PATHLENGTH)) { c=name_int[r++]; if ((c>='a') && (c<='z')) c-=32; else if (c==' ') continue; /* should be separator */ else if (c=='/') c='\\'; upname[w++]=c; } while (r>0 && name_int[r-1]==' ') r--; if (r>=DOS_PATHLENGTH) { DOS_SetError(DOSERR_PATH_NOT_FOUND);return false; } upname[w]=0; /* Now parse the new file name to make the final filename */ if (upname[0]!='\\') strcpy(fullname,Drives[*drive]->curdir); else fullname[0]=0; Bit32u lastdir=0;Bit32u t=0; while (fullname[t]!=0) { if ((fullname[t]=='\\') && (fullname[t+1]!=0)) lastdir=t; t++; }; r=0;w=0; tempdir[0]=0; bool stop=false; while (!stop) { if (upname[r]==0) stop=true; if ((upname[r]=='\\') || (upname[r]==0)){ tempdir[w]=0; if (tempdir[0]==0) { w=0;r++;continue;} if (strcmp(tempdir,".")==0) { tempdir[0]=0; w=0;r++; continue; } Bit32s iDown; bool dots = true; Bit32s templen=(Bit32s)strlen(tempdir); for(iDown=0;(iDown < templen) && dots;iDown++) if(tempdir[iDown] != '.') dots = false; // only dots? if (dots && (templen > 1)) { Bit32s cDots = templen - 1; for(iDown=(Bit32s)strlen(fullname)-1;iDown>=0;iDown--) { if(fullname[iDown]=='\\' || iDown==0) { lastdir = iDown; cDots--; if(cDots==0) break; } } fullname[lastdir]=0; t=0;lastdir=0; while (fullname[t]!=0) { if ((fullname[t]=='\\') && (fullname[t+1]!=0)) lastdir=t; t++; } tempdir[0]=0; w=0;r++; continue; } lastdir=(Bit32u)strlen(fullname); if (lastdir!=0) strcat(fullname,"\\"); char * ext=strchr(tempdir,'.'); if (ext) { if(strchr(ext+1,'.')) { //another dot in the extension =>file not found //Or path not found depending on wether //we are still in dir check stage or file stage if(stop) DOS_SetError(DOSERR_FILE_NOT_FOUND); else DOS_SetError(DOSERR_PATH_NOT_FOUND); return false; } ext[4] = 0; if((strlen(tempdir) - strlen(ext)) > 8) memmove(tempdir + 8, ext, 5); } else tempdir[8]=0; for (Bitu i=0;i<strlen(tempdir);i++) { c=tempdir[i]; if ((c>='A') && (c<='Z')) continue; if ((c>='0') && (c<='9')) continue; switch (c) { case '$': case '#': case '@': case '(': case ')': case '!': case '%': case '{': case '}': case '`': case '~': case '_': case '-': case '.': case '*': case '?': case '&': case '\'': case '+': case '^': case 246: case 255: case 0xa0: case 0xe5: case 0xbd: case 0x9d: break; default: LOG(LOG_FILES,LOG_NORMAL)("Makename encountered an illegal char %c hex:%X in %s!",c,c,name); DOS_SetError(DOSERR_PATH_NOT_FOUND);return false; break; } } if (strlen(fullname)+strlen(tempdir)>=DOS_PATHLENGTH) { DOS_SetError(DOSERR_PATH_NOT_FOUND);return false; } strcat(fullname,tempdir); tempdir[0]=0; w=0;r++; continue; } tempdir[w++]=upname[r++]; } return true; } bool DOS_GetCurrentDir(Bit8u drive,char * const buffer) { if (drive==0) drive=DOS_GetDefaultDrive(); else drive--; if ((drive>=DOS_DRIVES) || (!Drives[drive])) { DOS_SetError(DOSERR_INVALID_DRIVE); return false; } strcpy(buffer,Drives[drive]->curdir); return true; } bool DOS_ChangeDir(char const * const dir) { Bit8u drive;char fulldir[DOS_PATHLENGTH]; const char * testdir=dir; if (strlen(testdir) && testdir[1]==':') testdir+=2; size_t len=strlen(testdir); if (!len) { DOS_SetError(DOSERR_PATH_NOT_FOUND); return false; } if (!DOS_MakeName(dir,fulldir,&drive)) return false; if (strlen(fulldir) && testdir[len-1]=='\\') { DOS_SetError(DOSERR_PATH_NOT_FOUND); return false; } if (Drives[drive]->TestDir(fulldir)) { strcpy(Drives[drive]->curdir,fulldir); return true; } else { DOS_SetError(DOSERR_PATH_NOT_FOUND); } return false; } bool DOS_MakeDir(char const * const dir) { Bit8u drive;char fulldir[DOS_PATHLENGTH]; size_t len = strlen(dir); if(!len || dir[len-1] == '\\') { DOS_SetError(DOSERR_PATH_NOT_FOUND); return false; } if (!DOS_MakeName(dir,fulldir,&drive)) return false; if(Drives[drive]->MakeDir(fulldir)) return true; /* Determine reason for failing */ if(Drives[drive]->TestDir(fulldir)) DOS_SetError(DOSERR_ACCESS_DENIED); else DOS_SetError(DOSERR_PATH_NOT_FOUND); return false; } bool DOS_RemoveDir(char const * const dir) { /* We need to do the test before the removal as can not rely on * the host to forbid removal of the current directory. * We never change directory. Everything happens in the drives. */ Bit8u drive;char fulldir[DOS_PATHLENGTH]; if (!DOS_MakeName(dir,fulldir,&drive)) return false; /* Check if exists */ if(!Drives[drive]->TestDir(fulldir)) { DOS_SetError(DOSERR_PATH_NOT_FOUND); return false; } /* See if it's current directory */ char currdir[DOS_PATHLENGTH]= { 0 }; DOS_GetCurrentDir(drive + 1 ,currdir); if(strcmp(currdir,fulldir) == 0) { DOS_SetError(DOSERR_REMOVE_CURRENT_DIRECTORY); return false; } if(Drives[drive]->RemoveDir(fulldir)) return true; /* Failed. We know it exists and it's not the current dir */ /* Assume non empty */ DOS_SetError(DOSERR_ACCESS_DENIED); return false; } bool DOS_Rename(char const * const oldname,char const * const newname) { Bit8u driveold;char fullold[DOS_PATHLENGTH]; Bit8u drivenew;char fullnew[DOS_PATHLENGTH]; if (!DOS_MakeName(oldname,fullold,&driveold)) return false; if (!DOS_MakeName(newname,fullnew,&drivenew)) return false; /* No tricks with devices */ if ( (DOS_FindDevice(oldname) != DOS_DEVICES) || (DOS_FindDevice(newname) != DOS_DEVICES) ) { DOS_SetError(DOSERR_FILE_NOT_FOUND); return false; } /* Must be on the same drive */ if(driveold != drivenew) { DOS_SetError(DOSERR_NOT_SAME_DEVICE); return false; } /*Test if target exists => no access */ Bit16u attr; if(Drives[drivenew]->GetFileAttr(fullnew,&attr)) { DOS_SetError(DOSERR_ACCESS_DENIED); return false; } /* Source must exist, check for path ? */ if (!Drives[driveold]->GetFileAttr( fullold, &attr ) ) { DOS_SetError(DOSERR_FILE_NOT_FOUND); return false; } if (Drives[drivenew]->Rename(fullold,fullnew)) return true; /* If it still fails, which error should we give ? PATH NOT FOUND or EACCESS */ LOG(LOG_FILES,LOG_NORMAL)("Rename fails for %s to %s, no proper errorcode returned.",oldname,newname); DOS_SetError(DOSERR_FILE_NOT_FOUND); return false; } bool DOS_FindFirst(char * search,Bit16u attr,bool fcb_findfirst) { LOG(LOG_FILES,LOG_NORMAL)("file search attributes %X name %s",attr,search); DOS_DTA dta(dos.dta()); Bit8u drive;char fullsearch[DOS_PATHLENGTH]; char dir[DOS_PATHLENGTH];char pattern[DOS_PATHLENGTH]; size_t len = strlen(search); if(len && search[len - 1] == '\\' && !( (len > 2) && (search[len - 2] == ':') && (attr == DOS_ATTR_VOLUME) )) { //Dark Forces installer, but c:\ is allright for volume labels(exclusively set) DOS_SetError(DOSERR_NO_MORE_FILES); return false; } if (!DOS_MakeName(search,fullsearch,&drive)) return false; //Check for devices. FindDevice checks for leading subdir as well bool device = (DOS_FindDevice(search) != DOS_DEVICES); /* Split the search in dir and pattern */ char * find_last; find_last=strrchr(fullsearch,'\\'); if (!find_last) { /*No dir */ strcpy(pattern,fullsearch); dir[0]=0; } else { *find_last=0; strcpy(pattern,find_last+1); strcpy(dir,fullsearch); } dta.SetupSearch(drive,(Bit8u)attr,pattern); if(device) { find_last = strrchr(pattern,'.'); if(find_last) *find_last = 0; //TODO use current date and time dta.SetResult(pattern,0,0,0,DOS_ATTR_DEVICE); LOG(LOG_DOSMISC,LOG_WARN)("finding device %s",pattern); return true; } if (Drives[drive]->FindFirst(dir,dta,fcb_findfirst)) return true; return false; } bool DOS_FindNext(void) { DOS_DTA dta(dos.dta()); Bit8u i = dta.GetSearchDrive(); if(i >= DOS_DRIVES || !Drives[i]) { /* Corrupt search. */ LOG(LOG_FILES,LOG_ERROR)("Corrupt search!!!!"); DOS_SetError(DOSERR_NO_MORE_FILES); return false; } if (Drives[i]->FindNext(dta)) return true; return false; } bool DOS_ReadFile(Bit16u entry,Bit8u * data,Bit16u * amount,bool fcb) { Bit32u handle = fcb?entry:RealHandle(entry); if (handle>=DOS_FILES) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; if (!Files[handle] || !Files[handle]->IsOpen()) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; /* if ((Files[handle]->flags & 0x0f) == OPEN_WRITE)) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; } */ Bit16u toread=*amount; bool ret=Files[handle]->Read(data,&toread); *amount=toread; return ret; } bool DOS_WriteFile(Bit16u entry,Bit8u * data,Bit16u * amount,bool fcb) { Bit32u handle = fcb?entry:RealHandle(entry); if (handle>=DOS_FILES) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; if (!Files[handle] || !Files[handle]->IsOpen()) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; /* if ((Files[handle]->flags & 0x0f) == OPEN_READ)) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; } */ Bit16u towrite=*amount; bool ret=Files[handle]->Write(data,&towrite); *amount=towrite; return ret; } bool DOS_SeekFile(Bit16u entry,Bit32u * pos,Bit32u type,bool fcb) { Bit32u handle = fcb?entry:RealHandle(entry); if (handle>=DOS_FILES) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; if (!Files[handle] || !Files[handle]->IsOpen()) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; return Files[handle]->Seek(pos,type); } bool DOS_CloseFile(Bit16u entry, bool fcb) { Bit32u handle = fcb?entry:RealHandle(entry); if (handle>=DOS_FILES) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; if (!Files[handle]) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; if (Files[handle]->IsOpen()) { Files[handle]->Close(); } DOS_PSP psp(dos.psp()); if (!fcb) psp.SetFileHandle(entry,0xff); if (Files[handle]->RemoveRef()<=0) { delete Files[handle]; Files[handle]=0; } return true; } bool DOS_FlushFile(Bit16u entry) { Bit32u handle=RealHandle(entry); if (handle>=DOS_FILES) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; if (!Files[handle] || !Files[handle]->IsOpen()) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; LOG(LOG_DOSMISC,LOG_NORMAL)("FFlush used."); return true; } static bool PathExists(char const * const name) { const char* leading = strrchr(name,'\\'); if(!leading) return true; char temp[CROSS_LEN]; strcpy(temp,name); char * lead = strrchr(temp,'\\'); if (lead == temp) return true; *lead = 0; Bit8u drive;char fulldir[DOS_PATHLENGTH]; if (!DOS_MakeName(temp,fulldir,&drive)) return false; if(!Drives[drive]->TestDir(fulldir)) return false; return true; } bool DOS_CreateFile(char const * name,Bit16u attributes,Bit16u * entry,bool fcb) { // Creation of a device is the same as opening it // Tc201 installer if (DOS_FindDevice(name) != DOS_DEVICES) return DOS_OpenFile(name, OPEN_READ, entry, fcb); LOG(LOG_FILES,LOG_NORMAL)("file create attributes %X file %s",attributes,name); char fullname[DOS_PATHLENGTH];Bit8u drive; DOS_PSP psp(dos.psp()); if (!DOS_MakeName(name,fullname,&drive)) return false; /* Check for a free file handle */ Bit8u handle=DOS_FILES;Bit8u i; for (i=0;i<DOS_FILES;i++) { if (!Files[i]) { handle=i; break; } } if (handle==DOS_FILES) { DOS_SetError(DOSERR_TOO_MANY_OPEN_FILES); return false; } /* We have a position in the main table now find one in the psp table */ *entry = fcb?handle:psp.FindFreeFileEntry(); if (*entry==0xff) { DOS_SetError(DOSERR_TOO_MANY_OPEN_FILES); return false; } /* Don't allow directories to be created */ if (attributes&DOS_ATTR_DIRECTORY) { DOS_SetError(DOSERR_ACCESS_DENIED); return false; } bool foundit=Drives[drive]->FileCreate(&Files[handle],fullname,attributes); if (foundit) { Files[handle]->SetDrive(drive); Files[handle]->AddRef(); if (!fcb) psp.SetFileHandle(*entry,handle); return true; } else { if(!PathExists(name)) DOS_SetError(DOSERR_PATH_NOT_FOUND); else DOS_SetError(DOSERR_FILE_NOT_FOUND); return false; } } bool DOS_OpenFile(char const * name,Bit8u flags,Bit16u * entry,bool fcb) { /* First check for devices */ if (flags>2) LOG(LOG_FILES,LOG_ERROR)("Special file open command %X file %s",flags,name); else LOG(LOG_FILES,LOG_NORMAL)("file open command %X file %s",flags,name); DOS_PSP psp(dos.psp()); Bit16u attr = 0; Bit8u devnum = DOS_FindDevice(name); bool device = (devnum != DOS_DEVICES); if(!device && DOS_GetFileAttr(name,&attr)) { //DON'T ALLOW directories to be openened.(skip test if file is device). if((attr & DOS_ATTR_DIRECTORY) || (attr & DOS_ATTR_VOLUME)){ DOS_SetError(DOSERR_ACCESS_DENIED); return false; } } char fullname[DOS_PATHLENGTH];Bit8u drive;Bit8u i; /* First check if the name is correct */ if (!DOS_MakeName(name,fullname,&drive)) return false; Bit8u handle=255; /* Check for a free file handle */ for (i=0;i<DOS_FILES;i++) { if (!Files[i]) { handle=i; break; } } if (handle==255) { DOS_SetError(DOSERR_TOO_MANY_OPEN_FILES); return false; } /* We have a position in the main table now find one in the psp table */ *entry = fcb?handle:psp.FindFreeFileEntry(); if (*entry==0xff) { DOS_SetError(DOSERR_TOO_MANY_OPEN_FILES); return false; } bool exists=false; if (device) { Files[handle]=new DOS_Device(*Devices[devnum]); } else { exists=Drives[drive]->FileOpen(&Files[handle],fullname,flags); if (exists) Files[handle]->SetDrive(drive); } if (exists || device ) { Files[handle]->AddRef(); if (!fcb) psp.SetFileHandle(*entry,handle); return true; } else { //Test if file exists, but opened in read-write mode (and writeprotected) if(((flags&3) != OPEN_READ) && Drives[drive]->FileExists(fullname)) DOS_SetError(DOSERR_ACCESS_DENIED); else { if(!PathExists(name)) DOS_SetError(DOSERR_PATH_NOT_FOUND); else DOS_SetError(DOSERR_FILE_NOT_FOUND); } return false; } } bool DOS_OpenFileExtended(char const * name, Bit16u flags, Bit16u createAttr, Bit16u action, Bit16u *entry, Bit16u* status) { // FIXME: Not yet supported : Bit 13 of flags (int 0x24 on critical error) Bit16u result = 0; if (action==0) { // always fail setting DOS_SetError(DOSERR_FUNCTION_NUMBER_INVALID); return false; } else { if (((action & 0x0f)>2) || ((action & 0xf0)>0x10)) { // invalid action parameter DOS_SetError(DOSERR_FUNCTION_NUMBER_INVALID); return false; } } if (DOS_OpenFile(name, (Bit8u)(flags&0xff), entry)) { // File already exists switch (action & 0x0f) { case 0x00: // failed DOS_SetError(DOSERR_FILE_ALREADY_EXISTS); return false; case 0x01: // file open (already done) result = 1; break; case 0x02: // replace DOS_CloseFile(*entry); if (!DOS_CreateFile(name, createAttr, entry)) return false; result = 3; break; default: DOS_SetError(DOSERR_FUNCTION_NUMBER_INVALID); E_Exit("DOS: OpenFileExtended: Unknown action."); break; } } else { // File doesn't exist if ((action & 0xf0)==0) { // uses error code from failed open return false; } // Create File if (!DOS_CreateFile(name, createAttr, entry)) { // uses error code from failed create return false; } result = 2; } // success *status = result; return true; } bool DOS_UnlinkFile(char const * const name) { char fullname[DOS_PATHLENGTH];Bit8u drive; // An existing device returns an access denied error if (DOS_FindDevice(name) != DOS_DEVICES) { DOS_SetError(DOSERR_ACCESS_DENIED); return false; } if (!DOS_MakeName(name,fullname,&drive)) return false; if(Drives[drive]->FileUnlink(fullname)){ return true; } else { DOS_SetError(DOSERR_FILE_NOT_FOUND); return false; } } bool DOS_GetFileAttr(char const * const name,Bit16u * attr) { char fullname[DOS_PATHLENGTH];Bit8u drive; if (!DOS_MakeName(name,fullname,&drive)) return false; if (Drives[drive]->GetFileAttr(fullname,attr)) { return true; } else { DOS_SetError(DOSERR_FILE_NOT_FOUND); return false; } } bool DOS_SetFileAttr(char const * const name,Bit16u /*attr*/) // this function does not change the file attributs // it just does some tests if file is available // returns false when using on cdrom (stonekeep) { Bit16u attrTemp; char fullname[DOS_PATHLENGTH];Bit8u drive; if (!DOS_MakeName(name,fullname,&drive)) return false; if (strncmp(Drives[drive]->GetInfo(),"CDRom ",6)==0 || strncmp(Drives[drive]->GetInfo(),"isoDrive ",9)==0) { DOS_SetError(DOSERR_ACCESS_DENIED); return false; } return Drives[drive]->GetFileAttr(fullname,&attrTemp); } bool DOS_Canonicalize(char const * const name,char * const big) { //TODO Add Better support for devices and shit but will it be needed i doubt it :) Bit8u drive; char fullname[DOS_PATHLENGTH]; if (!DOS_MakeName(name,fullname,&drive)) return false; big[0]=drive+'A'; big[1]=':'; big[2]='\\'; strcpy(&big[3],fullname); return true; } bool DOS_GetFreeDiskSpace(Bit8u drive,Bit16u * bytes,Bit8u * sectors,Bit16u * clusters,Bit16u * free) { if (drive==0) drive=DOS_GetDefaultDrive(); else drive--; if ((drive>=DOS_DRIVES) || (!Drives[drive])) { DOS_SetError(DOSERR_INVALID_DRIVE); return false; } return Drives[drive]->AllocationInfo(bytes,sectors,clusters,free); } bool DOS_DuplicateEntry(Bit16u entry,Bit16u * newentry) { // Dont duplicate console handles /* if (entry<=STDPRN) { *newentry = entry; return true; }; */ Bit8u handle=RealHandle(entry); if (handle>=DOS_FILES) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; if (!Files[handle] || !Files[handle]->IsOpen()) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; DOS_PSP psp(dos.psp()); *newentry = psp.FindFreeFileEntry(); if (*newentry==0xff) { DOS_SetError(DOSERR_TOO_MANY_OPEN_FILES); return false; } Files[handle]->AddRef(); psp.SetFileHandle(*newentry,handle); return true; } bool DOS_ForceDuplicateEntry(Bit16u entry,Bit16u newentry) { if(entry == newentry) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; } Bit8u orig = RealHandle(entry); if (orig >= DOS_FILES) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; if (!Files[orig] || !Files[orig]->IsOpen()) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; Bit8u newone = RealHandle(newentry); if (newone < DOS_FILES && Files[newone]) { DOS_CloseFile(newentry); } DOS_PSP psp(dos.psp()); Files[orig]->AddRef(); psp.SetFileHandle(newentry,orig); return true; } bool DOS_CreateTempFile(char * const name,Bit16u * entry) { size_t namelen=strlen(name); char * tempname=name+namelen; if (namelen==0) { // temp file created in root directory tempname[0]='\\'; tempname++; } else { if ((name[namelen-1]!='\\') && (name[namelen-1]!='/')) { tempname[0]='\\'; tempname++; } } dos.errorcode=0; /* add random crap to the end of the name and try to open */ do { Bit32u i; for (i=0;i<8;i++) { tempname[i]=(rand()%26)+'A'; } tempname[8]=0; } while ((!DOS_CreateFile(name,0,entry)) && (dos.errorcode==DOSERR_FILE_ALREADY_EXISTS)); if (dos.errorcode) return false; return true; } char DOS_ToUpper(char c) { unsigned char uc = *reinterpret_cast<unsigned char*>(&c); if (uc > 0x60 && uc < 0x7B) uc -= 0x20; else if (uc > 0x7F && uc < 0xA5) { const unsigned char t[0x25] = { 0x00, 0x9a, 0x45, 0x41, 0x8E, 0x41, 0x8F, 0x80, 0x45, 0x45, 0x45, 0x49, 0x49, 0x49, 0x00, 0x00, 0x00, 0x92, 0x00, 0x4F, 0x99, 0x4F, 0x55, 0x55, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x41, 0x49, 0x4F, 0x55, 0xA5}; if (t[uc - 0x80]) uc = t[uc-0x80]; } char sc = *reinterpret_cast<char*>(&uc); return sc; } #define FCB_SEP ":;,=+" #define ILLEGAL ":.;,=+ \t/\"[]<>|" static bool isvalid(const char in){ const char ill[]=ILLEGAL; return (Bit8u(in)>0x1F) && (!strchr(ill,in)); } #define PARSE_SEP_STOP 0x01 #define PARSE_DFLT_DRIVE 0x02 #define PARSE_BLNK_FNAME 0x04 #define PARSE_BLNK_FEXT 0x08 #define PARSE_RET_NOWILD 0 #define PARSE_RET_WILD 1 #define PARSE_RET_BADDRIVE 0xff Bit8u FCB_Parsename(Bit16u seg,Bit16u offset,Bit8u parser ,char *string, Bit8u *change) { char * string_begin=string; Bit8u ret=0; if (!(parser & PARSE_DFLT_DRIVE)) { // default drive forced, this intentionally invalidates an extended FCB mem_writeb(PhysMake(seg,offset),0); } DOS_FCB fcb(seg,offset,false); // always a non-extended FCB bool hasdrive,hasname,hasext,finished; hasdrive=hasname=hasext=finished=false; Bitu index=0; Bit8u fill=' '; /* First get the old data from the fcb */ #ifdef _MSC_VER #pragma pack (1) #endif union { struct { char drive[2]; char name[9]; char ext[4]; } GCC_ATTRIBUTE (packed) part; char full[DOS_FCBNAME]; } fcb_name; #ifdef _MSC_VER #pragma pack() #endif /* Get the old information from the previous fcb */ fcb.GetName(fcb_name.full); fcb_name.part.drive[0]-='A'-1;fcb_name.part.drive[1]=0; fcb_name.part.name[8]=0;fcb_name.part.ext[3]=0; /* strip leading spaces */ while((*string==' ')||(*string=='\t')) string++; /* Strip of the leading separator */ if((parser & PARSE_SEP_STOP) && *string) { char sep[] = FCB_SEP;char a[2]; a[0] = *string;a[1] = '\0'; if (strcspn(a,sep) == 0) string++; } /* Skip following spaces as well */ while((*string==' ')||(*string=='\t')) string++; /* Check for a drive */ if (string[1]==':') { unsigned char d = *reinterpret_cast<unsigned char*>(&string[0]); if (!isvalid(toupper(d))) {string += 2; goto savefcb;} //TODO check (for ret value) fcb_name.part.drive[0]=0; hasdrive=true; if (isalpha(d) && Drives[toupper(d)-'A']) { //Floppies under dos always exist, but don't bother with that at this level ; //THIS* was here } else ret=0xff; fcb_name.part.drive[0]=DOS_ToUpper(string[0])-'A'+1; //Always do THIS* and continue parsing, just return the right code string+=2; } /* Check for extension only file names */ if (string[0] == '.') {string++;goto checkext;} /* do nothing if not a valid name */ if(!isvalid(string[0])) goto savefcb; hasname=true;finished=false;fill=' ';index=0; /* Copy the name */ while (true) { unsigned char nc = *reinterpret_cast<unsigned char*>(&string[0]); char ncs = (char)toupper(nc); //Should use DOS_ToUpper, but then more calls need to be changed. if (ncs == '*') { //Handle * fill = '?'; ncs = '?'; } if (ncs == '?' && !ret && index < 8) ret = 1; //Don't override bad drive if (!isvalid(ncs)) { //Fill up the name. while(index < 8) fcb_name.part.name[index++] = fill; break; } if (index < 8) { fcb_name.part.name[index++] = (fill == '?')?fill:ncs; } string++; } if (!(string[0]=='.')) goto savefcb; string++; checkext: /* Copy the extension */ hasext=true;finished=false;fill=' ';index=0; while (true) { unsigned char nc = *reinterpret_cast<unsigned char*>(&string[0]); char ncs = (char)toupper(nc); if (ncs == '*') { //Handle * fill = '?'; ncs = '?'; } if (ncs == '?' && !ret && index < 3) ret = 1; if (!isvalid(ncs)) { //Fill up the name. while(index < 3) fcb_name.part.ext[index++] = fill; break; } if (index < 3) { fcb_name.part.ext[index++] = (fill=='?')?fill:ncs; } string++; } savefcb: if (!hasdrive & !(parser & PARSE_DFLT_DRIVE)) fcb_name.part.drive[0] = 0; if (!hasname & !(parser & PARSE_BLNK_FNAME)) strcpy(fcb_name.part.name," "); if (!hasext & !(parser & PARSE_BLNK_FEXT)) strcpy(fcb_name.part.ext," "); fcb.SetName(fcb_name.part.drive[0],fcb_name.part.name,fcb_name.part.ext); fcb.ClearBlockRecsize(); //Undocumented bonus work. *change=(Bit8u)(string-string_begin); return ret; } static void DTAExtendName(char * const name,char * const filename,char * const ext) { char * find=strchr(name,'.'); if (find && find!=name) { strcpy(ext,find+1); *find=0; } else ext[0]=0; strcpy(filename,name); size_t i; for (i=strlen(name);i<8;i++) filename[i]=' '; filename[8]=0; for (i=strlen(ext);i<3;i++) ext[i]=' '; ext[3]=0; } static void SaveFindResult(DOS_FCB & find_fcb) { DOS_DTA find_dta(dos.tables.tempdta); char name[DOS_NAMELENGTH_ASCII];Bit32u size;Bit16u date;Bit16u time;Bit8u attr;Bit8u drive; char file_name[9];char ext[4]; find_dta.GetResult(name,size,date,time,attr); drive=find_fcb.GetDrive()+1; Bit8u find_attr = DOS_ATTR_ARCHIVE; find_fcb.GetAttr(find_attr); /* Gets search attributes if extended */ /* Create a correct file and extention */ DTAExtendName(name,file_name,ext); DOS_FCB fcb(RealSeg(dos.dta()),RealOff(dos.dta()));//TODO fcb.Create(find_fcb.Extended()); fcb.SetName(drive,file_name,ext); fcb.SetAttr(find_attr); /* Only adds attribute if fcb is extended */ fcb.SetResult(size,date,time,attr); } bool DOS_FCBCreate(Bit16u seg,Bit16u offset) { DOS_FCB fcb(seg,offset); char shortname[DOS_FCBNAME];Bit16u handle; fcb.GetName(shortname); Bit8u attr = DOS_ATTR_ARCHIVE; fcb.GetAttr(attr); if (!attr) attr = DOS_ATTR_ARCHIVE; //Better safe than sorry if (!DOS_CreateFile(shortname,attr,&handle,true)) return false; fcb.FileOpen((Bit8u)handle); return true; } bool DOS_FCBOpen(Bit16u seg,Bit16u offset) { DOS_FCB fcb(seg,offset); char shortname[DOS_FCBNAME];Bit16u handle; fcb.GetName(shortname); /* Search for file if name has wildcards */ if (strpbrk(shortname,"*?")) { LOG(LOG_FCB,LOG_WARN)("Wildcards in filename"); if (!DOS_FCBFindFirst(seg,offset)) return false; DOS_DTA find_dta(dos.tables.tempdta); DOS_FCB find_fcb(RealSeg(dos.tables.tempdta),RealOff(dos.tables.tempdta)); char name[DOS_NAMELENGTH_ASCII],file_name[9],ext[4]; Bit32u size;Bit16u date,time;Bit8u attr; find_dta.GetResult(name,size,date,time,attr); DTAExtendName(name,file_name,ext); find_fcb.SetName(fcb.GetDrive()+1,file_name,ext); find_fcb.GetName(shortname); } /* First check if the name is correct */ Bit8u drive; char fullname[DOS_PATHLENGTH]; if (!DOS_MakeName(shortname,fullname,&drive)) return false; /* Check, if file is already opened */ for (Bit8u i = 0;i < DOS_FILES;i++) { if (Files[i] && Files[i]->IsOpen() && Files[i]->IsName(fullname)) { Files[i]->AddRef(); fcb.FileOpen(i); return true; } } if (!DOS_OpenFile(shortname,OPEN_READWRITE,&handle,true)) return false; fcb.FileOpen((Bit8u)handle); return true; } bool DOS_FCBClose(Bit16u seg,Bit16u offset) { DOS_FCB fcb(seg,offset); if(!fcb.Valid()) return false; Bit8u fhandle; fcb.FileClose(fhandle); DOS_CloseFile(fhandle,true); return true; } bool DOS_FCBFindFirst(Bit16u seg,Bit16u offset) { DOS_FCB fcb(seg,offset); RealPt old_dta=dos.dta();dos.dta(dos.tables.tempdta); char name[DOS_FCBNAME];fcb.GetName(name); Bit8u attr = DOS_ATTR_ARCHIVE; fcb.GetAttr(attr); /* Gets search attributes if extended */ bool ret=DOS_FindFirst(name,attr,true); dos.dta(old_dta); if (ret) SaveFindResult(fcb); return ret; } bool DOS_FCBFindNext(Bit16u seg,Bit16u offset) { DOS_FCB fcb(seg,offset); RealPt old_dta=dos.dta();dos.dta(dos.tables.tempdta); bool ret=DOS_FindNext(); dos.dta(old_dta); if (ret) SaveFindResult(fcb); return ret; } Bit8u DOS_FCBRead(Bit16u seg,Bit16u offset,Bit16u recno) { DOS_FCB fcb(seg,offset); Bit8u fhandle,cur_rec;Bit16u cur_block,rec_size; fcb.GetSeqData(fhandle,rec_size); if (fhandle==0xff && rec_size!=0) { if (!DOS_FCBOpen(seg,offset)) return FCB_READ_NODATA; LOG(LOG_FCB,LOG_WARN)("Reopened closed FCB"); fcb.GetSeqData(fhandle,rec_size); } if (rec_size == 0) { rec_size = 128; fcb.SetSeqData(fhandle,rec_size); } fcb.GetRecord(cur_block,cur_rec); Bit32u pos=((cur_block*128)+cur_rec)*rec_size; if (!DOS_SeekFile(fhandle,&pos,DOS_SEEK_SET,true)) return FCB_READ_NODATA; Bit16u toread=rec_size; if (!DOS_ReadFile(fhandle,dos_copybuf,&toread,true)) return FCB_READ_NODATA; if (toread==0) return FCB_READ_NODATA; if (toread < rec_size) { //Zero pad copybuffer to rec_size Bitu i = toread; while(i < rec_size) dos_copybuf[i++] = 0; } MEM_BlockWrite(Real2Phys(dos.dta())+recno*rec_size,dos_copybuf,rec_size); if (++cur_rec>127) { cur_block++;cur_rec=0; } fcb.SetRecord(cur_block,cur_rec); if (toread==rec_size) return FCB_SUCCESS; if (toread==0) return FCB_READ_NODATA; return FCB_READ_PARTIAL; } Bit8u DOS_FCBWrite(Bit16u seg,Bit16u offset,Bit16u recno) { DOS_FCB fcb(seg,offset); Bit8u fhandle,cur_rec;Bit16u cur_block,rec_size; fcb.GetSeqData(fhandle,rec_size); if (fhandle==0xff && rec_size!=0) { if (!DOS_FCBOpen(seg,offset)) return FCB_READ_NODATA; LOG(LOG_FCB,LOG_WARN)("Reopened closed FCB"); fcb.GetSeqData(fhandle,rec_size); } if (rec_size == 0) { rec_size = 128; fcb.SetSeqData(fhandle,rec_size); } fcb.GetRecord(cur_block,cur_rec); Bit32u pos=((cur_block*128)+cur_rec)*rec_size; if (!DOS_SeekFile(fhandle,&pos,DOS_SEEK_SET,true)) return FCB_ERR_WRITE; MEM_BlockRead(Real2Phys(dos.dta())+recno*rec_size,dos_copybuf,rec_size); Bit16u towrite=rec_size; if (!DOS_WriteFile(fhandle,dos_copybuf,&towrite,true)) return FCB_ERR_WRITE; Bit32u size;Bit16u date,time; fcb.GetSizeDateTime(size,date,time); if (pos+towrite>size) size=pos+towrite; //time doesn't keep track of endofday date = DOS_PackDate(dos.date.year,dos.date.month,dos.date.day); Bit32u ticks = mem_readd(BIOS_TIMER); Bit32u seconds = (ticks*10)/182; Bit16u hour = (Bit16u)(seconds/3600); Bit16u min = (Bit16u)((seconds % 3600)/60); Bit16u sec = (Bit16u)(seconds % 60); time = DOS_PackTime(hour,min,sec); Files[fhandle]->time = time; Files[fhandle]->date = date; fcb.SetSizeDateTime(size,date,time); if (++cur_rec>127) { cur_block++;cur_rec=0; } fcb.SetRecord(cur_block,cur_rec); return FCB_SUCCESS; } Bit8u DOS_FCBIncreaseSize(Bit16u seg,Bit16u offset) { DOS_FCB fcb(seg,offset); Bit8u fhandle,cur_rec;Bit16u cur_block,rec_size; fcb.GetSeqData(fhandle,rec_size); fcb.GetRecord(cur_block,cur_rec); Bit32u pos=((cur_block*128)+cur_rec)*rec_size; if (!DOS_SeekFile(fhandle,&pos,DOS_SEEK_SET,true)) return FCB_ERR_WRITE; Bit16u towrite=0; if (!DOS_WriteFile(fhandle,dos_copybuf,&towrite,true)) return FCB_ERR_WRITE; Bit32u size;Bit16u date,time; fcb.GetSizeDateTime(size,date,time); if (pos+towrite>size) size=pos+towrite; //time doesn't keep track of endofday date = DOS_PackDate(dos.date.year,dos.date.month,dos.date.day); Bit32u ticks = mem_readd(BIOS_TIMER); Bit32u seconds = (ticks*10)/182; Bit16u hour = (Bit16u)(seconds/3600); Bit16u min = (Bit16u)((seconds % 3600)/60); Bit16u sec = (Bit16u)(seconds % 60); time = DOS_PackTime(hour,min,sec); Files[fhandle]->time = time; Files[fhandle]->date = date; fcb.SetSizeDateTime(size,date,time); fcb.SetRecord(cur_block,cur_rec); return FCB_SUCCESS; } Bit8u DOS_FCBRandomRead(Bit16u seg,Bit16u offset,Bit16u * numRec,bool restore) { /* if restore is true :random read else random blok read. * random read updates old block and old record to reflect the random data * before the read!!!!!!!!! and the random data is not updated! (user must do this) * Random block read updates these fields to reflect the state after the read! */ DOS_FCB fcb(seg,offset); Bit32u random; Bit16u old_block=0; Bit8u old_rec=0; Bit8u error=0; Bit16u count; /* Set the correct record from the random data */ fcb.GetRandom(random); fcb.SetRecord((Bit16u)(random / 128),(Bit8u)(random & 127)); if (restore) fcb.GetRecord(old_block,old_rec);//store this for after the read. // Read records for (count=0; count<*numRec; count++) { error = DOS_FCBRead(seg,offset,count); if (error!=FCB_SUCCESS) break; } if (error==FCB_READ_PARTIAL) count++; //partial read counts *numRec=count; Bit16u new_block;Bit8u new_rec; fcb.GetRecord(new_block,new_rec); if (restore) fcb.SetRecord(old_block,old_rec); /* Update the random record pointer with new position only when restore is false*/ if(!restore) fcb.SetRandom(new_block*128+new_rec); return error; } Bit8u DOS_FCBRandomWrite(Bit16u seg,Bit16u offset,Bit16u * numRec,bool restore) { /* see FCB_RandomRead */ DOS_FCB fcb(seg,offset); Bit32u random; Bit16u old_block=0; Bit8u old_rec=0; Bit8u error=0; Bit16u count; /* Set the correct record from the random data */ fcb.GetRandom(random); fcb.SetRecord((Bit16u)(random / 128),(Bit8u)(random & 127)); if (restore) fcb.GetRecord(old_block,old_rec); if (*numRec > 0) { /* Write records */ for (count=0; count<*numRec; count++) { error = DOS_FCBWrite(seg,offset,count);// dos_fcbwrite return 0 false when true... if (error!=FCB_SUCCESS) break; } *numRec=count; } else { DOS_FCBIncreaseSize(seg,offset); } Bit16u new_block;Bit8u new_rec; fcb.GetRecord(new_block,new_rec); if (restore) fcb.SetRecord(old_block,old_rec); /* Update the random record pointer with new position only when restore is false */ if (!restore) fcb.SetRandom(new_block*128+new_rec); return error; } bool DOS_FCBGetFileSize(Bit16u seg,Bit16u offset) { char shortname[DOS_PATHLENGTH];Bit16u entry; DOS_FCB fcb(seg,offset); fcb.GetName(shortname); if (!DOS_OpenFile(shortname,OPEN_READ,&entry,true)) return false; Bit32u size = 0; Files[entry]->Seek(&size,DOS_SEEK_END); DOS_CloseFile(entry,true); Bit8u handle; Bit16u rec_size; fcb.GetSeqData(handle,rec_size); if (rec_size == 0) rec_size = 128; //Use default if missing. Bit32u random=(size/rec_size); if (size % rec_size) random++; fcb.SetRandom(random); return true; } bool DOS_FCBDeleteFile(Bit16u seg,Bit16u offset){ /* FCB DELETE honours wildcards. it will return true if one or more * files get deleted. * To get this: the dta is set to temporary dta in which found files are * stored. This can not be the tempdta as that one is used by fcbfindfirst */ RealPt old_dta=dos.dta();dos.dta(dos.tables.tempdta_fcbdelete); RealPt new_dta=dos.dta(); bool nextfile = false; bool return_value = false; nextfile = DOS_FCBFindFirst(seg,offset); DOS_FCB fcb(RealSeg(new_dta),RealOff(new_dta)); while(nextfile) { char shortname[DOS_FCBNAME] = { 0 }; fcb.GetName(shortname); bool res=DOS_UnlinkFile(shortname); if(!return_value && res) return_value = true; //at least one file deleted nextfile = DOS_FCBFindNext(seg,offset); } dos.dta(old_dta); /*Restore dta */ return return_value; } bool DOS_FCBRenameFile(Bit16u seg, Bit16u offset){ DOS_FCB fcbold(seg,offset); DOS_FCB fcbnew(seg,offset+16); if(!fcbold.Valid()) return false; char oldname[DOS_FCBNAME]; char newname[DOS_FCBNAME]; fcbold.GetName(oldname);fcbnew.GetName(newname); /* Check, if sourcefile is still open. This was possible in DOS, but modern oses don't like this */ Bit8u drive; char fullname[DOS_PATHLENGTH]; if (!DOS_MakeName(oldname,fullname,&drive)) return false; DOS_PSP psp(dos.psp()); for (Bit8u i=0;i<DOS_FILES;i++) { if (Files[i] && Files[i]->IsOpen() && Files[i]->IsName(fullname)) { Bit16u handle = psp.FindEntryByHandle(i); //(more than once maybe) if (handle == 0xFF) { DOS_CloseFile(i,true); } else { DOS_CloseFile(handle); } } } /* Rename the file */ return DOS_Rename(oldname,newname); } void DOS_FCBSetRandomRecord(Bit16u seg, Bit16u offset) { DOS_FCB fcb(seg,offset); Bit16u block;Bit8u rec; fcb.GetRecord(block,rec); fcb.SetRandom(block*128+rec); } bool DOS_FileExists(char const * const name) { char fullname[DOS_PATHLENGTH];Bit8u drive; if (!DOS_MakeName(name,fullname,&drive)) return false; return Drives[drive]->FileExists(fullname); } bool DOS_GetAllocationInfo(Bit8u drive,Bit16u * _bytes_sector,Bit8u * _sectors_cluster,Bit16u * _total_clusters) { if (!drive) drive = DOS_GetDefaultDrive(); else drive--; if (drive >= DOS_DRIVES || !Drives[drive]) { DOS_SetError(DOSERR_INVALID_DRIVE); return false; } Bit16u _free_clusters; Drives[drive]->AllocationInfo(_bytes_sector,_sectors_cluster,_total_clusters,&_free_clusters); SegSet16(ds,RealSeg(dos.tables.mediaid)); reg_bx=RealOff(dos.tables.mediaid+drive*9); return true; } bool DOS_SetDrive(Bit8u drive) { if (Drives[drive]) { DOS_SetDefaultDrive(drive); return true; } else { return false; } } bool DOS_GetFileDate(Bit16u entry, Bit16u* otime, Bit16u* odate) { Bit32u handle=RealHandle(entry); if (handle>=DOS_FILES) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; if (!Files[handle] || !Files[handle]->IsOpen()) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; if (!Files[handle]->UpdateDateTimeFromHost()) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; } *otime = Files[handle]->time; *odate = Files[handle]->date; return true; } void DOS_SetupFiles (void) { /* Setup the File Handles */ Bit32u i; for (i=0;i<DOS_FILES;i++) { Files[i]=0; } /* Setup the Virtual Disk System */ for (i=0;i<DOS_DRIVES;i++) { Drives[i]=0; } Drives[25]=new Virtual_Drive(); }
gpl-2.0
hoelzl/argos2
common/control_interface/neural_networks/ci_rnctn_controller.cpp
11226
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /** * @file <common/control_interface/ci_ctrnn_multilayer_controller.cpp> * * @brief This file provides the definition of the CTRNN multilayer * neural network controller * * @author Vito Trianni - <vito.trianni@istc.cnr.it> */ #include "ci_rnctn_controller.h" #include <argos2/common/utility/string_utilities.h> using namespace argos; const string CONFIGURATION_RNCTN_NUMHIDDEN = "num_hidden"; const string CONFIGURATION_RNCTN_TIMESTEP = "integration_step"; const string CONFIGURATION_RNCTN_WEIGHTS = "weight_range"; const string CONFIGURATION_RNCTN_BIASES = "bias_range"; const string CONFIGURATION_RNCTN_TAUS = "tau_range"; CCI_RnctnController::CCI_RnctnController() : CCI_NeuralNetworkController() { m_pfInput2HiddenWeights = NULL; m_pfCTN2CTNWeights = NULL; m_pfCTNBiases = NULL; m_pfCTNTaus = NULL; m_pfCTNDeltaStates = NULL; m_pfCTNStates = NULL; m_unNumCTNs = 0; m_unNumHidden = 0; m_fTimeStep = 0.1; m_fWeightsBounds[0] = -4.0; m_fWeightsBounds[1] = 4.0; m_fBiasesBounds[0] = -4.0; m_fBiasesBounds[1] = 4.0; m_fTausBounds[0] = -1.0; m_fTausBounds[1] = 3.0; } /****************************************/ /****************************************/ CCI_RnctnController::~CCI_RnctnController() { } /****************************************/ /****************************************/ int CCI_RnctnController::Init( const TConfigurationTree t_configuration_tree ) { //////////////////////////////////////////////////////////////////////////////// // First perform common initialisation from base class //////////////////////////////////////////////////////////////////////////////// if( CCI_NeuralNetworkController::Init( t_configuration_tree ) != 0 ) return -1; //////////////////////////////////////////////////////////////////////////////// // Load number of hidden nodes //////////////////////////////////////////////////////////////////////////////// string s_num_hidden = CExperimentConfiguration::GetNodeValue( t_configuration_tree, CONFIGURATION_RNCTN_NUMHIDDEN ); if( s_num_hidden == "" ) { CSwarmanoidLogger::LogErr( ) << "[FATAL] Missing required tag <" << CONFIGURATION_RNCTN_NUMHIDDEN << ">" << " for RNCTN multi-layer initialisation" << endl; return -1; } if( StringToUnsignedInt( s_num_hidden, m_unNumHidden ) != 0 ) { CSwarmanoidLogger::LogErr( ) << "[FATAL] Could not convert tag <" << CONFIGURATION_RNCTN_NUMHIDDEN << ">" << s_num_hidden << " to a valid number" << endl; return -1; } // compute the number of continuous time neurons as the sum of // hidden and output neurons m_unNumCTNs = m_unNumHidden + m_unNumberOfOutputs; //////////////////////////////////////////////////////////////////////////////// // integration step //////////////////////////////////////////////////////////////////////////////// string s_step_size = CExperimentConfiguration::GetNodeValue( t_configuration_tree, CONFIGURATION_RNCTN_TIMESTEP ); if( (s_step_size != "") && (StringToDouble( s_step_size, m_fTimeStep ) != 0) ) { CSwarmanoidLogger::LogErr( ) << "[FATAL] Could not convert tag <" << CONFIGURATION_RNCTN_TIMESTEP << ">" << s_step_size << " to a valid number" << endl; return -1; } //////////////////////////////////////////////////////////////////////////////// // Load upper and lower bounds for weigths, biases and taus //////////////////////////////////////////////////////////////////////////////// string s_weights_bounds = CExperimentConfiguration::GetNodeValue( t_configuration_tree, CONFIGURATION_RNCTN_WEIGHTS ); if( (s_weights_bounds != "") && (CExperimentConfiguration::GetNReals( s_weights_bounds, m_fWeightsBounds, 2 ) != 0) ) { CSwarmanoidLogger::LogErr( ) << "[FATAL] Could not convert tag <" << CONFIGURATION_RNCTN_WEIGHTS << ">" << s_weights_bounds << " to valid numbers" << endl; return -1; } string s_biases_bounds = CExperimentConfiguration::GetNodeValue( t_configuration_tree, CONFIGURATION_RNCTN_BIASES ); if( (s_biases_bounds != "") && (CExperimentConfiguration::GetNReals( s_biases_bounds, m_fBiasesBounds, 2 ) != 0) ) { CSwarmanoidLogger::LogErr( ) << "[FATAL] Could not convert tag <" << CONFIGURATION_RNCTN_BIASES << ">" << s_biases_bounds << " to valid numbers" << endl; return -1; } string s_taus_bounds = CExperimentConfiguration::GetNodeValue( t_configuration_tree, CONFIGURATION_RNCTN_TAUS ); if( (s_taus_bounds != "") && (CExperimentConfiguration::GetNReals( s_taus_bounds, m_fTausBounds, 2 ) != 0) ) { CSwarmanoidLogger::LogErr( ) << "[FATAL] Could not convert tag <" << CONFIGURATION_RNCTN_TAUS << ">" << s_taus_bounds << " to valid numbers" << endl; return -1; } //////////////////////////////////////////////////////////////////////////////// // check and load parameters from file //////////////////////////////////////////////////////////////////////////////// if( (m_sParamterFile != "") && (LoadNetworkParamters( m_sParamterFile ) != 0) ) return -1; return CCI_Controller::RETURN_OK; } /****************************************/ /****************************************/ void CCI_RnctnController::Destroy() { if( m_pfInput2HiddenWeights ) delete[] m_pfInput2HiddenWeights; if( m_pfCTN2CTNWeights ) delete[] m_pfCTN2CTNWeights; if( m_pfCTNBiases ) delete[] m_pfCTNBiases; if( m_pfCTNTaus ) delete[] m_pfCTNTaus; if( m_pfCTNDeltaStates ) delete[] m_pfCTNDeltaStates; if( m_pfCTNStates ) delete[] m_pfCTNStates; } /****************************************/ /****************************************/ int CCI_RnctnController::LoadNetworkParamters( const string filename ) { // open the input file ifstream in( filename.c_str(), ios::in ); if( !in ) { CSwarmanoidLogger::LogErr() << "[FATAL] Cannot open file '" << filename << "' for reading" << endl; return -1; } // first parameter is the number of real-valued weights unsigned int un_length = 0; if( !(in >> un_length) ) { CSwarmanoidLogger::LogErr() << "[FATAL] Cannot read data from file '" << filename << "'" << endl; return -1; } // create weights vector and load it from file Real* pfGenes = new Real[un_length]; for( unsigned int i = 0; i < un_length; i++ ) { if( !(in >> pfGenes[i]) ) { CSwarmanoidLogger::LogErr() << "[FATAL] Cannot read data from file '" << filename << "'" << endl; delete [] pfGenes; return -1; } } // load parameters in the appropriate structures if( LoadNetworkParamters( un_length, pfGenes ) != 0 ) { delete [] pfGenes; return -1; } delete [] pfGenes; return 0; } /****************************************/ /****************************************/ int CCI_RnctnController::LoadNetworkParamters( const unsigned int un_num_params, const Real* params ) { // check consistency between paramter file and xml declaration unsigned int un_num_parameters = m_unNumberOfInputs * m_unNumHidden + // weights of the input -> hidden layer m_unNumCTNs * m_unNumCTNs + // wigths of the fully recurrent layer m_unNumCTNs * 2; // recurrent layer taus and biases if( un_num_params != un_num_parameters ) { CSwarmanoidLogger::LogErr() << "[FATAL] Number of paramter mismatch: '" << "passed " << un_num_params << " paramters, while " << un_num_parameters << " were expected from the xml configuration file" << endl; return -1; } if( m_pfInput2HiddenWeights ) delete[] m_pfInput2HiddenWeights; if( m_pfCTN2CTNWeights ) delete[] m_pfCTN2CTNWeights; if( m_pfCTNBiases ) delete[] m_pfCTNBiases; if( m_pfCTNTaus ) delete[] m_pfCTNTaus; if( m_pfCTNDeltaStates ) delete[] m_pfCTNDeltaStates; if( m_pfCTNStates ) delete[] m_pfCTNStates; unsigned int unChromosomePosition = 0; m_pfInput2HiddenWeights = new Real[m_unNumberOfInputs * m_unNumHidden]; for( unsigned int i = 0; i < m_unNumberOfInputs * m_unNumHidden; i++ ) { m_pfInput2HiddenWeights[i] = params[unChromosomePosition++]*(m_fWeightsBounds[1] - m_fWeightsBounds[0]) + m_fWeightsBounds[0]; } m_pfCTN2CTNWeights = new Real[m_unNumCTNs * m_unNumCTNs]; for( unsigned int i = 0; i < m_unNumCTNs * m_unNumCTNs; i++ ) { m_pfCTN2CTNWeights[i] = params[unChromosomePosition++]*(m_fWeightsBounds[1] - m_fWeightsBounds[0]) + m_fWeightsBounds[0]; } m_pfCTNBiases = new Real[m_unNumCTNs]; for( unsigned int i = 0; i < m_unNumCTNs; i++ ) { m_pfCTNBiases[i] = params[unChromosomePosition++]*(m_fBiasesBounds[1] - m_fBiasesBounds[0]) + m_fBiasesBounds[0]; } m_pfCTNTaus = new Real[m_unNumCTNs]; for( unsigned int i = 0; i < m_unNumCTNs; i++ ) { m_pfCTNTaus[i] = pow(10, (m_fTausBounds[0] + ((m_fTausBounds[1] - m_fTausBounds[0]) * (params[unChromosomePosition++]))) ); } m_pfCTNDeltaStates = new Real[m_unNumCTNs]; m_pfCTNStates = new Real[m_unNumCTNs]; for( unsigned int i = 0; i < m_unNumCTNs; i++ ) { m_pfCTNDeltaStates[i] = 0.0; m_pfCTNStates[i] = 0.0; } return 0; } /****************************************/ /****************************************/ void CCI_RnctnController::ComputeOutputs( void ) { // Update delta state of hidden layer from inputs: for( unsigned int i = 0; i < m_unNumCTNs; i++ ) { m_pfCTNDeltaStates[i] = -m_pfCTNStates[i]; for( unsigned int j = 0; ((i < m_unNumHidden) && (j < m_unNumberOfInputs)); j++ ) { // weight * sigmoid(state) m_pfCTNDeltaStates[i] += m_pfInput2HiddenWeights[i * m_unNumberOfInputs + j] * m_pfInputs[j]; } // Update delta state from hidden layer, self-recurrent connections: for( unsigned int j = 0; j < m_unNumCTNs; j++ ) { Real z = (Real(1.0)/(exp(-( m_pfCTNStates[j] + m_pfCTNBiases[j])) + 1.0)); m_pfCTNDeltaStates[i] += m_pfCTN2CTNWeights[i * m_unNumCTNs + j] * z; } } // once all delta state are computed, get the new activation for the // hidden unit amd compute the output for( unsigned int i = 0; i < m_unNumCTNs; i++ ) { m_pfCTNStates[i] += m_pfCTNDeltaStates[i] * m_fTimeStep/m_pfCTNTaus[i]; if( i >= m_unNumHidden ) { m_pfOutputs[i-m_unNumHidden] = (Real(1.0)/( exp(-( m_pfCTNStates[i] + m_pfCTNBiases[i])) + 1.0 )); } } }
gpl-2.0
inspircd/inspircd.github.com
api/3.0/search/all_6.js
20871
var searchData= [ ['generate_329',['Generate',['../class_z_line_factory.html#a9075b6653fee8c7a6584e24cd5724c6b',1,'ZLineFactory::Generate()'],['../class_q_line_factory.html#ab1fec79ee00c32c513280081804a49bf',1,'QLineFactory::Generate()'],['../class_k_line_factory.html#ac8b6593062c2d930ad70270dac4b653f',1,'KLineFactory::Generate()'],['../class_x_line_factory.html#a68c58492f743a1abad223c2fc8d94cb2',1,'XLineFactory::Generate()'],['../class_g_line_factory.html#ac1bb1583bf37c451cc8cbcd710354335',1,'GLineFactory::Generate()'],['../class_e_line_factory.html#aaa6e67f5b2e1d43fa0f9ce51d9440b22',1,'ELineFactory::Generate()']]], ['generatesid_330',['GenerateSID',['../class_u_i_d_generator.html#ac5fb06206223c1c0307eb955774fd96a',1,'UIDGenerator']]], ['genericbuilder_331',['GenericBuilder',['../class_numeric_1_1_generic_builder.html',1,'Numeric']]], ['genericbuilder_3c_20sep_2c_20sendempty_2c_20writenumericsink_20_3e_332',['GenericBuilder&lt; Sep, SendEmpty, WriteNumericSink &gt;',['../class_numeric_1_1_generic_builder.html',1,'Numeric']]], ['genericparambuilder_333',['GenericParamBuilder',['../class_numeric_1_1_generic_param_builder.html',1,'Numeric']]], ['genericparambuilder_3c_20numstaticparams_2c_20sendempty_2c_20writenumericsink_20_3e_334',['GenericParamBuilder&lt; NumStaticParams, SendEmpty, WriteNumericSink &gt;',['../class_numeric_1_1_generic_param_builder.html',1,'Numeric']]], ['genrandom_335',['GenRandom',['../class_insp_i_r_cd.html#a5bd98021cc35f4006b2384533d8d201e',1,'InspIRCd']]], ['genrandomint_336',['GenRandomInt',['../class_insp_i_r_cd.html#a3278cb8a5d92237c8ca04bfbe62820ff',1,'InspIRCd']]], ['genrandomstr_337',['GenRandomStr',['../class_insp_i_r_cd.html#a553c13c9dd344306ff2c787161e426c3',1,'InspIRCd']]], ['get_338',['Get',['../class_message_target.html#a3fc3b3898a6694cc0766d744097a51b2',1,'MessageTarget']]], ['get_5fraw_339',['get_raw',['../class_extension_item.html#a4e47911ae07ff31f997150e78e088c7a',1,'ExtensionItem']]], ['getall_340',['GetAll',['../class_x_line_manager.html#a47436e3e86a6ee04a8fb90f9c61ca7c8',1,'XLineManager']]], ['getallprefixchars_341',['GetAllPrefixChars',['../class_membership.html#a3b7d11d8d8039595f82db2bc44a48383',1,'Membership']]], ['getalltypes_342',['GetAllTypes',['../class_x_line_manager.html#add5f01a8a847a82d88c8bc2d570f8418',1,'XLineManager']]], ['getbandwidth_343',['GetBandwidth',['../class_socket_engine_1_1_statistics.html#a2b0b7eaf2ae3b60eb4e0fe3f5c7b5bd8',1,'SocketEngine::Statistics']]], ['getbanident_344',['GetBanIdent',['../class_user.html#a88e1e8c9fd82381dd73fe2d29e378b5f',1,'User']]], ['getbeginiterator_345',['GetBeginIterator',['../class_client_protocol_1_1_messages_1_1_mode.html#ae7234ebe57c8df3a50fd1c3c90ed9ef0',1,'ClientProtocol::Messages::Mode']]], ['getbool_346',['getBool',['../class_config_tag.html#a709cbc347214f1f2f44e0d5050224614',1,'ConfigTag']]], ['getchans_347',['GetChans',['../class_insp_i_r_cd.html#a9dac67bc44f273d9300b4dc8a71b1e96',1,'InspIRCd']]], ['getchantarget_348',['GetChanTarget',['../class_client_protocol_1_1_messages_1_1_mode.html#a924336d3463cc000bfcbbeab48392fd3',1,'ClientProtocol::Messages::Mode']]], ['getchildren_349',['GetChildren',['../class_serializable_1_1_data.html#a39b24d2dcfa41aed6f9c5ba6ad5e597b',1,'Serializable::Data']]], ['getcidrmask_350',['GetCIDRMask',['../class_user.html#a54a48058fd59033a8e606492339d5d41',1,'User']]], ['getclass_351',['GetClass',['../class_local_user.html#a1889973979a1d8ea2a10efacc48d5458',1,'LocalUser']]], ['getclonecounts_352',['GetCloneCounts',['../class_user_manager.html#a96df9db4804f1f0306f677605ba84576',1,'UserManager']]], ['getclonemap_353',['GetCloneMap',['../class_user_manager.html#a199f89342dc486838f27aeec6a08d2dc',1,'UserManager']]], ['getcommand_354',['GetCommand',['../class_client_protocol_1_1_message.html#ab631f6f68051e3af6d864061e665ee84',1,'ClientProtocol::Message']]], ['getcommands_355',['GetCommands',['../class_command_parser.html#aec74ed89ee42c6c3ccfa77d49a1e10d3',1,'CommandParser']]], ['getconfig_356',['getConfig',['../class_oper_info.html#a81090190b049f304ff1c348f6340c93e',1,'OperInfo']]], ['getdesc_357',['GetDesc',['../class_server.html#ab6112e6551fcf12109ff7fdc70295707',1,'Server']]], ['getdescription_358',['GetDescription',['../class_snomask.html#a859c3a0b82b301668bba29fcf3d03ac0',1,'Snomask']]], ['getdisplayedhost_359',['GetDisplayedHost',['../class_user.html#ad20fc47e074577d98c22ffac4e140ce6',1,'User']]], ['getduration_360',['getDuration',['../class_config_tag.html#a09f2951f8b6ce98cf2a14b1e28c760a6',1,'ConfigTag']]], ['getenditerator_361',['GetEndIterator',['../class_client_protocol_1_1_messages_1_1_mode.html#a82feb9508c0c5c97f4a46a5caac93bf4',1,'ClientProtocol::Messages::Mode']]], ['getentries_362',['GetEntries',['../class_serializable_1_1_data.html#a07365fc69a7efb90a5844b70f8afb5c6',1,'Serializable::Data']]], ['geterror_363',['GetError',['../class_socket_engine.html#a001731d22a14e12cfd90144094676dc6',1,'SocketEngine']]], ['geterror_364',['getError',['../class_stream_socket.html#af04fdf06a02ad2eff7db8994375e8b0c',1,'StreamSocket']]], ['getexitflag_365',['GetExitFlag',['../class_thread.html#aee887ff1653b6c2912dd97ec07d2fd16',1,'Thread']]], ['getextbanstatus_366',['GetExtBanStatus',['../class_channel.html#ac13eec9f30fa9b59c8d105e6e9a81a46',1,'Channel']]], ['getextlist_367',['GetExtList',['../class_extensible.html#a04cab0b329ab81c275553347fd124b03',1,'Extensible']]], ['getexts_368',['GetExts',['../class_extension_manager.html#ad2bcb29323ee49c5158d743b7633f641',1,'ExtensionManager']]], ['getfactory_369',['GetFactory',['../class_x_line_manager.html#a1c86965fcb78804f24c0087feb6434c7',1,'XLineManager']]], ['getfd_370',['GetFd',['../class_event_handler.html#a703b8952d8f83b5d2c3b9bec2802109d',1,'EventHandler']]], ['getfilelist_371',['GetFileList',['../class_file_system.html#a74add4d1c46ab42bf43bd40b19eaa91b',1,'FileSystem']]], ['getfilename_372',['GetFileName',['../class_file_system.html#a7da4e8135ab91b5b9c6ef8b69cf11bc6',1,'FileSystem']]], ['getfloat_373',['getFloat',['../class_config_tag.html#a3f8c3c4656829704f0b937143ea638ac',1,'ConfigTag']]], ['getfullhost_374',['GetFullHost',['../class_user.html#a242725aae6836377706ed4e202c5893e',1,'User::GetFullHost()'],['../class_fake_user.html#a25d640886cf10c55d146cee889a206b6',1,'FakeUser::GetFullHost()']]], ['getfullrealhost_375',['GetFullRealHost',['../class_user.html#a1e57732a6d19e587c89e2b733796858c',1,'User::GetFullRealHost()'],['../class_fake_user.html#a7b472599a7864e55acdc659b0df0b537',1,'FakeUser::GetFullRealHost()']]], ['gethandler_376',['GetHandler',['../class_command_parser.html#af7c230220609e9ba68025dd90a8de8db',1,'CommandParser']]], ['gethost_377',['GetHost',['../class_connect_class.html#ae3f3cf92ea61e15026d538eb4fbbc796',1,'ConnectClass::GetHost()'],['../class_user.html#a7869627f60d7069d251b4b0f4ed5b84e',1,'User::GetHost()']]], ['gethosts_378',['GetHosts',['../class_connect_class.html#a4f362a368c818e66b64d6eeab2ed19ea',1,'ConnectClass']]], ['getid_379',['GetId',['../class_server.html#a6ab579bce9af7eb4f724931ce50483f7',1,'Server::GetId()'],['../class_mode_handler.html#ab87637aa898d813c58c911943c451baa',1,'ModeHandler::GetId()']]], ['getint_380',['getInt',['../class_config_tag.html#acd85775a471cac4fb1343bf5569b3abc',1,'ConfigTag']]], ['getinterval_381',['GetInterval',['../class_timer.html#a055790095a91c665adf3332151521fb5',1,'Timer']]], ['getipstring_382',['GetIPString',['../class_user.html#af887098b2253e32dccf592b3578ec58f',1,'User']]], ['getlastchangelist_383',['GetLastChangeList',['../class_mode_parser.html#a2cd0e5fc28292f90ff982973ebd13622',1,'ModeParser']]], ['getlasthook_384',['GetLastHook',['../class_stream_socket.html#a7799dced5fc937f62be573d155efcda6',1,'StreamSocket']]], ['getlevelrequired_385',['GetLevelRequired',['../class_mode_handler.html#ad3037b23b9152f8d54a1d8efb523995e',1,'ModeHandler']]], ['getlimit_386',['GetLimit',['../class_list_mode_base.html#ac04736f35a96f8a4766052eef18f1680',1,'ListModeBase']]], ['getlines_387',['GetLines',['../class_i_support_manager.html#a0833fc13516375d9b0304ea5e8ef66f2',1,'ISupportManager']]], ['getlist_388',['GetList',['../class_list_mode_base.html#a2954f5f704121e602cab00f5d1fc17ef',1,'ListModeBase']]], ['getlist_389',['getlist',['../class_modes_1_1_change_list.html#ab3a7b88c5fe34abdb7aaaf65b9d9a88a',1,'Modes::ChangeList::getlist() const'],['../class_modes_1_1_change_list.html#ae075a5ad925ab4a505b982a1cf82277e',1,'Modes::ChangeList::getlist()']]], ['getlistmodes_390',['GetListModes',['../class_mode_parser.html#a84cd9aa20814fb9b33ac3ac6b9d0e5d3',1,'ModeParser']]], ['getlocalusers_391',['GetLocalUsers',['../class_user_manager.html#a2dc6f6ac6c1aa577aca694ad1a5ad9ba',1,'UserManager']]], ['getlowerlimit_392',['GetLowerLimit',['../class_list_mode_base.html#abd2be6fa55b80365e3d0e49ae452e1fb',1,'ListModeBase']]], ['getmaxfds_393',['GetMaxFds',['../class_socket_engine.html#a71ae58dc2e8e5e31233d948c8e90fc95',1,'SocketEngine']]], ['getmaxglobal_394',['GetMaxGlobal',['../class_connect_class.html#aaef4980b9736a2286ee963ee4d4ddca0',1,'ConnectClass']]], ['getmaxlocal_395',['GetMaxLocal',['../class_connect_class.html#a386011513b4985d65db40318b5331f72',1,'ConnectClass']]], ['getmaxmask_396',['GetMaxMask',['../class_server_limits.html#a363b8e053fef1e904662bd45618f6577',1,'ServerLimits']]], ['getmember_397',['GetMember',['../class_client_protocol_1_1_messages_1_1_join.html#a007bfbd516a6a84d521356fd21f9d78d',1,'ClientProtocol::Messages::Join']]], ['getmessage_398',['GetMessage',['../classirc_1_1tokenstream.html#aa607a533b8977d9a127a97681a04d022',1,'irc::tokenstream']]], ['getmessagesforuser_399',['GetMessagesForUser',['../class_client_protocol_1_1_event.html#a8e4dd25470dc57de175586f2fdb3c73d',1,'ClientProtocol::Event']]], ['getmiddle_400',['GetMiddle',['../classirc_1_1tokenstream.html#aecf3e0462bc8f13f604da3b7ba809b7a',1,'irc::tokenstream']]], ['getmodechar_401',['GetModeChar',['../class_mode_handler.html#a2cb515e37977ba08e2e350b46e01c49a',1,'ModeHandler']]], ['getmodeletters_402',['GetModeLetters',['../class_user.html#a26800686fb1245473bd6254a4e4b2de1',1,'User']]], ['getmodename_403',['GetModeName',['../class_mode_watcher.html#a7b10a9eeab90e847bc0b48c8ab3ca357',1,'ModeWatcher']]], ['getmodeparameter_404',['GetModeParameter',['../class_channel.html#a10041cad3be895b9e2d2165bb6551e3e',1,'Channel']]], ['getmodes_405',['GetModes',['../class_mode_parser.html#ab868818e889589a3d4aa151e35d97677',1,'ModeParser']]], ['getmodetype_406',['GetModeType',['../class_mode_watcher.html#ab7f95db96d5d5256daadd5726f3751b6',1,'ModeWatcher::GetModeType()'],['../class_mode_handler.html#ad4e333c0fce3ee407088576b5563354b',1,'ModeHandler::GetModeType()']]], ['getmodhook_407',['GetModHook',['../class_stream_socket.html#a8f749127a9c6202fd3d302709d8a931c',1,'StreamSocket']]], ['getmodule_408',['GetModule',['../class_events_1_1_module_event_provider.html#aa2cc15122a844910ecfcdfd86af90581',1,'Events::ModuleEventProvider::GetModule()'],['../class_events_1_1_module_event_listener.html#a9929493211400f2ea306feab406ec9cf',1,'Events::ModuleEventListener::GetModule()']]], ['getmodules_409',['GetModules',['../class_module_manager.html#a63b95165f3e5463ea4f2551664af3bc6',1,'ModuleManager']]], ['getname_410',['GetName',['../class_message_target.html#abaaf29eb4d550f59becf5a9eab1ec4c4',1,'MessageTarget::GetName()'],['../class_server.html#a41941e9ce5ad7c0f2bab03f1c8dea955',1,'Server::GetName()'],['../class_connect_class.html#a6ce1ba14e75531d3a4b8c755c34127ba',1,'ConnectClass::GetName()']]], ['getnexthook_411',['GetNextHook',['../class_i_o_hook_middle.html#aca79f3e2f5e9046aad569ade4130cf36',1,'IOHookMiddle']]], ['getnextline_412',['GetNextLine',['../class_stream_socket.html#a30b5e5636e1122aa6b3a88728ba408fa',1,'StreamSocket']]], ['getnumeric_413',['GetNumeric',['../class_numeric_1_1_numeric.html#aed7fa51e7a7e7341d645019415530b3d',1,'Numeric::Numeric']]], ['getnumerictoken_414',['GetNumericToken',['../classirc_1_1sepstream.html#a5c176497dfb42dda6321ecbdfc917af5',1,'irc::sepstream']]], ['getparams_415',['GetParams',['../class_client_protocol_1_1_message.html#ad9639b6d8bd719606b00d4fb55e2809c',1,'ClientProtocol::Message::GetParams()'],['../class_numeric_1_1_numeric.html#a6560dc95f54b8fe3ee235dd82be08ab8',1,'Numeric::Numeric::GetParams() const'],['../class_numeric_1_1_numeric.html#aafdd782234fd5a96caa05183c0898735',1,'Numeric::Numeric::GetParams()']]], ['getpenaltythreshold_416',['GetPenaltyThreshold',['../class_connect_class.html#a81a56dc19d76506cc8fb515de56fe433',1,'ConnectClass']]], ['getpingtime_417',['GetPingTime',['../class_connect_class.html#a9b930b4d940d965d8ed110ea1783b3e2',1,'ConnectClass']]], ['getprefix_418',['GetPrefix',['../class_prefix_mode.html#a10c4dbd2e0896f1ba63d9ab556730215',1,'PrefixMode']]], ['getprefixchar_419',['GetPrefixChar',['../class_membership.html#a4c3c5604fd2b455bf61c8a656845ab9c',1,'Membership']]], ['getprefixmodes_420',['GetPrefixModes',['../class_mode_parser.html#a3adc4e9fe7b0aa4b6618f016f140ff1b',1,'ModeParser']]], ['getprefixrank_421',['GetPrefixRank',['../class_prefix_mode.html#a1f1c535a5e08f08b571564b879d54a10',1,'PrefixMode']]], ['getprefixvalue_422',['GetPrefixValue',['../class_channel.html#ae14d9dbe1700bec3b9e40265f67cdd77',1,'Channel']]], ['getpriority_423',['GetPriority',['../class_events_1_1_module_event_listener.html#abf13224c9dc157e849f2c2f13ceaff97',1,'Events::ModuleEventListener']]], ['getpublicname_424',['GetPublicName',['../class_server.html#a429aa5ba64aff85955bbfba64ace10ec',1,'Server']]], ['getrank_425',['getRank',['../class_membership.html#a24734a53c5ae159dc9c6b18a35a9602b',1,'Membership']]], ['getrealhost_426',['GetRealHost',['../class_user.html#a29a28538032a736db7e069439c042285',1,'User']]], ['getrealname_427',['GetRealName',['../class_user.html#aef175c05a963e6a647bf9081d0c92d95',1,'User']]], ['getreason_428',['GetReason',['../class_core_exception.html#aa4bb72c1e839437afc8e147c9cac51c1',1,'CoreException']]], ['getrecvq_429',['GetRecvQ',['../class_i_o_hook_middle.html#abb279016ba7a4b11f4a99dd624770228',1,'IOHookMiddle']]], ['getrecvqmax_430',['GetRecvqMax',['../class_connect_class.html#ae07c7939cb47337ce6c6a8f81730353e',1,'ConnectClass']]], ['getref_431',['GetRef',['../class_socket_engine.html#ae4201f4df3e79dd116de0cf3215a9cea',1,'SocketEngine']]], ['getregtimeout_432',['GetRegTimeout',['../class_connect_class.html#aafbb7ac1ab5114a7869d62690b7fd1a8',1,'ConnectClass']]], ['getremaining_433',['GetRemaining',['../classirc_1_1sepstream.html#a89d896cf3dd13852ea6955634792bb20',1,'irc::sepstream']]], ['getrepeat_434',['GetRepeat',['../class_timer.html#a01603180a6bf6b7d71924d43714afcc9',1,'Timer']]], ['getsendq_435',['GetSendQ',['../class_i_o_hook_middle.html#a5ef3597c0bb7cbf9caa102563d06911d',1,'IOHookMiddle::GetSendQ()'],['../class_i_o_hook_middle.html#aa76434f444c2436201f8ca9d3fe264aa',1,'IOHookMiddle::GetSendQ() const']]], ['getsendqhardmax_436',['GetSendqHardMax',['../class_connect_class.html#a218314cac5165d2dabc419c23c547091',1,'ConnectClass']]], ['getsendqsize_437',['getSendQSize',['../class_stream_socket.html#afbeb66c28eee58c7890496e970443f95',1,'StreamSocket']]], ['getsendqsoftmax_438',['GetSendqSoftMax',['../class_connect_class.html#a179ec32b10052d659dae5656c7717847',1,'ConnectClass']]], ['getserialized_439',['GetSerialized',['../class_client_protocol_1_1_message.html#ad684fc7d881738315cc038fc74c2d8f3',1,'ClientProtocol::Message']]], ['getserver_440',['GetServer',['../class_numeric_1_1_numeric.html#a091a94948852c943f85d5b92852e531d',1,'Numeric::Numeric']]], ['getserverdesc_441',['GetServerDesc',['../class_server_config.html#a2727fe3a893f8da1e7ded204381e3895',1,'ServerConfig']]], ['getserverlist_442',['GetServerList',['../class_protocol_interface.html#a10cc1a09026166e440fdc1ae29d40923',1,'ProtocolInterface']]], ['getservername_443',['GetServerName',['../class_server_config.html#afb756f82617eb11a5e62892dbcbb05c4',1,'ServerConfig']]], ['getsid_444',['GetSID',['../class_server_config.html#a3c655ca0f930b9aff7652884e076b054',1,'ServerConfig']]], ['getsource_445',['GetSource',['../class_core_exception.html#afc92ae1078032ff3ab1d0a81ad108161',1,'CoreException::GetSource()'],['../class_client_protocol_1_1_message_source.html#a24ffe25957892cbe4a1df711e2a7f205',1,'ClientProtocol::MessageSource::GetSource() const']]], ['getsourceuser_446',['GetSourceUser',['../class_client_protocol_1_1_message_source.html#a8425389d46c81d6683a966ec9bf5bdc7',1,'ClientProtocol::MessageSource']]], ['getstats_447',['GetStats',['../class_socket_engine.html#acbfcda6323b93f2b5f0368087c8d66b9',1,'SocketEngine']]], ['getstring_448',['getString',['../class_config_tag.html#a2da89f0be9356bb0d4e44271c5d7377b',1,'ConfigTag::getString(const std::string &amp;key, const std::string &amp;def, const std::tr1 ::function&lt; bool(const std::string &amp;)&gt; &amp;validator)'],['../class_config_tag.html#a1524a328f97b53741539e3356d9cd8a1',1,'ConfigTag::getString(const std::string &amp;key, const std::string &amp;def=&quot;&quot;, size_t minlen=0, size_t maxlen=UINT32_MAX)']]], ['getstring_449',['GetString',['../class_file_reader.html#a45d48a0096cb3a396a70ac1883fa7a85',1,'FileReader']]], ['getstrtarget_450',['GetStrTarget',['../class_client_protocol_1_1_messages_1_1_mode.html#af2eaece618e62fc63356233b9a946389',1,'ClientProtocol::Messages::Mode']]], ['getsubscribers_451',['GetSubscribers',['../class_events_1_1_module_event_provider.html#a951141176ff6c0d4540f91affc475963',1,'Events::ModuleEventProvider']]], ['getsymbol_452',['GetSymbol',['../class_d_l_l_manager.html#aace5601c1be30e3dc987cb920a3fa4f7',1,'DLLManager::GetSymbol(const char *name) const'],['../class_d_l_l_manager.html#a38dda70584162e945cf4e9a371cfeed2',1,'DLLManager::GetSymbol(const char *name) const']]], ['getsyntax_453',['GetSyntax',['../class_mode_handler.html#a39b2afb14c91126ff300fab2a8e45013',1,'ModeHandler']]], ['gettags_454',['GetTags',['../class_client_protocol_1_1_message.html#a41b704a1373514ac2ffb4ebfbb7d8843',1,'ClientProtocol::Message::GetTags()'],['../class_command_base_1_1_params.html#a1906509d89d82a488b50b882596ecfa1',1,'CommandBase::Params::GetTags()']]], ['gettoken_455',['GetToken',['../classirc_1_1sepstream.html#a9614205d9360120abc772e7ceb191c0b',1,'irc::sepstream::GetToken()'],['../classirc_1_1portparser.html#af5581bda92d07705c3d0c74eca1581f3',1,'irc::portparser::GetToken()']]], ['gettrailing_456',['GetTrailing',['../classirc_1_1tokenstream.html#a9796f72465f24f99808cb54ab5ca7bec',1,'irc::tokenstream']]], ['gettrigger_457',['GetTrigger',['../class_timer.html#a6951dfb9cfe51e3a08b1d291d77cdbad',1,'Timer']]], ['gettype_458',['GetType',['../class_x_line_factory.html#ae87005f4c4e7a86f13b1c9dbc8e4f20b',1,'XLineFactory']]], ['gettypestring_459',['GetTypeString',['../class_service_provider.html#a89bf645cadb13d1f3ac64fed93c879bd',1,'ServiceProvider']]], ['getuid_460',['GetUID',['../class_u_i_d_generator.html#a61b620fddb7d5c71ddad03801738aa3d',1,'UIDGenerator']]], ['getuint_461',['getUInt',['../class_config_tag.html#ad1af8eb76451c8fc14e0e93907cc1d6e',1,'ConfigTag']]], ['getusedfds_462',['GetUsedFds',['../class_socket_engine.html#ac24613fdd02880ac0433814c0a69a554',1,'SocketEngine']]], ['getusercounter_463',['GetUserCounter',['../class_channel.html#a2919d22432a7ba27cad822be5eef8676',1,'Channel']]], ['getuserparameter_464',['GetUserParameter',['../class_mode_handler.html#a764d23e605cdaf0a83b5227fb3dd5ecc',1,'ModeHandler']]], ['getusers_465',['GetUsers',['../class_channel.html#a44854fe076aa17616bec710b96c945d5',1,'Channel::GetUsers()'],['../class_user_manager.html#a14f1eee7e149eb8f7a79332b6659c11c',1,'UserManager::GetUsers()']]], ['getusertarget_466',['GetUserTarget',['../class_client_protocol_1_1_messages_1_1_mode.html#a3576a46d23efad59c5a9f0233f47d0b3',1,'ClientProtocol::Messages::Mode']]], ['getvector_467',['GetVector',['../class_file_reader.html#aed5380871543c120fcbbc4df4940aa3e',1,'FileReader']]], ['getversion_468',['GetVersion',['../class_d_l_l_manager.html#a2ece6589ed0561d554fd1f031c5a1cbb',1,'DLLManager::GetVersion()'],['../class_module.html#ace1cba59ac54d26b4649858b2cfc6aa8',1,'Module::GetVersion()']]], ['getversionstring_469',['GetVersionString',['../class_insp_i_r_cd.html#a0f0713742ab5754617b9589e810163fd',1,'InspIRCd']]], ['givemodelist_470',['GiveModeList',['../class_mode_parser.html#a7c68d35d3eb9496196fe59cefe8f711d',1,'ModeParser']]], ['gline_471',['GLine',['../class_g_line.html#a6b6fdc363fcc511d66e9f87918ffdb49',1,'GLine::GLine()'],['../class_g_line.html',1,'GLine']]], ['glinefactory_472',['GLineFactory',['../class_g_line_factory.html',1,'']]], ['globalculls_473',['GlobalCulls',['../class_insp_i_r_cd.html#a1d3ac9bd74bb30dede15bf2718dd6abb',1,'InspIRCd']]] ];
gpl-2.0
jpcaruana/jsynthlib
src/main/java/org/jsynthlib/editorbuilder/widgets/RootPanelWidget.java
644
package org.jsynthlib.editorbuilder.widgets; import org.jsynthlib.utils.XMLWriter; import org.xml.sax.SAXException; public class RootPanelWidget extends PanelWidget { public RootPanelWidget() { this(100,100); } public RootPanelWidget(int w, int h) { this("", w, h); } public RootPanelWidget(String title, int w, int h) { this("root", title, w, h); } public RootPanelWidget(String name, String title, int w, int h) { super(name, title, w, h); setBordered(false); } protected void writePosition(XMLWriter xml) throws SAXException { // do nothing } }
gpl-2.0
raimov/broneering
administrator/components/com_fabrik/views/element/tmpl/edit_access.php
836
<?php /** * Admin Element Edit:access Tmpl * * @package Joomla.Administrator * @subpackage Fabrik * @copyright Copyright (C) 2005-2013 fabrikar.com - All rights reserved. * @license GNU/GPL http://www.gnu.org/copyleft/gpl.html * @since 3.0 */ // No direct access defined('_JEXEC') or die('Restricted access'); echo JHtml::_('tabs.panel', JText::_('COM_FABRIK_GROUP_LABEL_RULES_DETAILS'), 'element-access');?> <fieldset class="adminform"> <ul class="adminformlist"> <?php foreach ($this->form->getFieldset('access') as $field) :?> <li> <?php echo $field->label; echo $field->input;?> </li> <?php endforeach; ?> <?php foreach ($this->form->getFieldset('access2') as $field) :?> <li> <?php echo $field->label; echo $field->input; ?> </li> <?php endforeach; ?> </ul> </fieldset>
gpl-2.0
StefanCristian/7kaa
src/OR_RANK.cpp
13618
/* * Seven Kingdoms: Ancient Adversaries * * Copyright 1997,1998 Enlight Software Ltd. * * 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/>. * */ //Filename : OR_RANK.CPP //Description : Ranking report #include <ODATE.h> #include <OFONT.h> #include <OGAME.h> #include <OCONFIG.h> #include <OVBROWIF.h> #include <ONATION.h> #include <OINFO.h> #include <vga_util.h> #include "gettext.h" //------------- Define coordinations -----------// enum { NATION_BROWSE_X1 = ZOOM_X1+6, NATION_BROWSE_Y1 = ZOOM_Y1+6, NATION_BROWSE_X2 = ZOOM_X2-6, NATION_BROWSE_Y2 = NATION_BROWSE_Y1+220, }; enum { NATION_SCORE_X1 = ZOOM_X1+6, NATION_SCORE_Y1 = NATION_BROWSE_Y2+6, NATION_SCORE_X2 = ZOOM_X2-6, NATION_SCORE_Y2 = NATION_SCORE_Y1+150, }; enum { NATION_GOAL_X1 = ZOOM_X1+6, NATION_GOAL_Y1 = NATION_SCORE_Y2+6, NATION_GOAL_X2 = ZOOM_X2-6, NATION_GOAL_Y2 = NATION_GOAL_Y1+110, }; enum { PLAY_TIME_X1 = ZOOM_X1+6, PLAY_TIME_X2 = ZOOM_X2-6, }; //----------- Define static variables ----------// static VBrowseIF browse_nation; static int nation_rank_data_array[MAX_RANK_TYPE][MAX_NATION]; //----------- Define static functions ----------// static void put_nation_rec(int recNo, int x, int y, int refreshFlag); static int nation_filter(int recNo=0); static void disp_score(); static void disp_goal(); static void disp_play_time(int y1); //--------- Begin of function Info::disp_rank ---------// // void Info::disp_rank(int refreshFlag) { set_rank_data(1); // 1-only set those nations that have contact with us int x=NATION_BROWSE_X1+9; int y=NATION_BROWSE_Y1+3; vga_back.d3_panel_up(NATION_BROWSE_X1, NATION_BROWSE_Y1, NATION_BROWSE_X2, NATION_BROWSE_Y1+32 ); font_san.put( x , y+7, _("Kingdom") ); font_san.put( x+180, y+7, _("Population") ); font_san.put( x+264, y+7, _("Military") ); font_san.put( x+332, y+7, _("Economy") ); font_san.put( x+406, y+7, _("Reputation") ); // TRANSLATORS: Part of "Fryhtan Battling" font_san.put( x+484, y , _("Fryhtan") ); // TRANSLATORS: Part of "Fryhtan Battling" font_san.put( x+484, y+13, _("Battling") ); if( refreshFlag == INFO_REPAINT ) { browse_nation.init( NATION_BROWSE_X1, NATION_BROWSE_Y1+34, NATION_BROWSE_X2, NATION_BROWSE_Y2, 0, 22, nation_filter(), put_nation_rec, 1 ); browse_nation.open(browse_nation_recno); } else { browse_nation.paint(); browse_nation.open(browse_nation_recno, nation_filter()); } //----- display score -------// disp_score(); //------ display goal -------// if( !game.game_has_ended ) // if the ending screen has already appeared once, don't display the goal { disp_goal(); y = NATION_GOAL_Y2+6; } else { y = NATION_GOAL_Y1; } //----- display total playing time -----// disp_play_time(y); } //----------- End of function Info::disp_rank -----------// //--------- Begin of static function disp_score ---------// // static void disp_score() { int x=NATION_SCORE_X1+6, y=NATION_SCORE_Y1+6; static const char* rankStrArray[] = { N_("Population Score"), N_("Military Score"), N_("Economic Score"), N_("Reputation Score"), N_("Fryhtan Battling Score") }; vga_util.d3_panel_down( NATION_SCORE_X1, NATION_SCORE_Y1, NATION_SCORE_X2, NATION_SCORE_Y2 ); //------ display individual scores ---------// int rankScore, totalScore=0; int viewNationRecno = nation_filter(browse_nation.recno()); for( int i=0 ; i<MAX_RANK_TYPE ; i++, y+=16 ) { rankScore = info.get_rank_score(i+1, viewNationRecno); totalScore += rankScore; font_san.put( x , y, _(rankStrArray[i]) ); font_san.put( x+300, y, rankScore, 1 ); } vga_back.bar( x, y, x+340, y+1, V_BLACK ); y+=4; //-------- display thte total score --------// font_san.put( x , y+2, _("Total Score") ); font_san.put( x+300, y+2, totalScore, 1 ); y+=20; vga_back.bar( x, y, x+340, y+1, V_BLACK ); y+=4; //-------- display the final score ---------// int difficultyRating = config.difficulty_rating; int finalScore = totalScore * difficultyRating / 100; String str; // TRANSLATORS: Final Score: <Number> X snprintf( str, MAX_STR_LEN+1, _("Final Score: %s X "), misc.format(totalScore) ); int x2 = font_san.put( x, y+12, str ) + 5; // TRANSLATORS: <Number> (Difficulty Rating) snprintf( str, MAX_STR_LEN+1, _("%s (Difficulty Rating)"), misc.format(difficultyRating) ); font_san.center_put( x2, y+1, x2+156, y+15, str ); vga_back.bar( x2 , y+16, x2+156, y+17, V_BLACK ); font_san.put( x2+65, y+19, 100 ); //------- if the player has cheated -------// if( nation_array[viewNationRecno]->cheat_enabled_flag ) { str = _("X 0 (Cheated) = 0"); } else { str = "= "; str += finalScore; } font_san.put( x2+170, y+12, str); y+=36; } //----------- End of static function disp_score -----------// //--------- Begin of static function disp_goal ---------// // static void disp_goal() { //----- if the ending screen has already appeared once -----// if( game.game_has_ended ) return; //------------------------------------// int x=NATION_GOAL_X1+6, y=NATION_GOAL_Y1+6; int goalCount = 1 + config.goal_destroy_monster + config.goal_population_flag + config.goal_economic_score_flag + config.goal_total_score_flag; vga_util.d3_panel_down( NATION_GOAL_X1, NATION_GOAL_Y1, NATION_GOAL_X2, NATION_GOAL_Y2 ); //------------------------------------// String str; if( goalCount > 1 ) { if( config.goal_year_limit_flag ) { // TRANSLATORS: GOAL: Achieve One of the Following Before <Date>: snprintf( str, MAX_STR_LEN+1, _("GOAL: Achieve One of the Following Before %s:"), date.date_str(info.goal_deadline) ); } else { str = _("GOAL: Achieve One of the Following:"); } } else { if( config.goal_year_limit_flag ) { // TRANSLATORS: GOAL: Defeat All Other Kingdoms Before <Date>. snprintf( str, MAX_STR_LEN+1, _("GOAL: Defeat All Other Kingdoms Before %s."), date.date_str( info.goal_deadline ) ); } else { str = _("GOAL: Defeat All Other Kingdoms."); } } //--------------------------------------// font_san.put( x, y, str ); y+=18; if( goalCount==1 ) return; //-----------------------------------// str = _("Defeat All Other Kingdoms."); font_san.put( x, y, str ); y+=16; //-----------------------------------// if( config.goal_destroy_monster ) { str = _("Destroy All Fryhtans."); font_san.put( x, y, str ); y+=16; } //-----------------------------------// if( config.goal_population_flag ) { // TRANSLATORS: Achieve a Population of <Number>. snprintf( str, MAX_STR_LEN+1, _("Achieve a Population of %s."), misc.format(config.goal_population) ); font_san.put( x, y, str ); y+=16; } //-----------------------------------// if( config.goal_economic_score_flag ) { // TRANSLATORS: Achieve an Economic Score of <Number>. snprintf( str, MAX_STR_LEN+1, _("Achieve an Economic Score of %s."), misc.format(config.goal_economic_score) ); font_san.put( x, y, str ); y+=16; } //-----------------------------------// if( config.goal_total_score_flag ) { // TRANSLATORS: Achieve a Total Score of <Number>. snprintf( str, MAX_STR_LEN+1, _("Achieve a Total Score of %s."), misc.format(config.goal_total_score) ); font_san.put( x, y, str ); y+=16; } } //----------- End of static function disp_goal -----------// //--------- Begin of static function disp_play_time ---------// // static void disp_play_time(int y1) { vga_util.d3_panel_down( PLAY_TIME_X1, y1, PLAY_TIME_X2, y1+24 ); String str; // TRANSLATORS: Total Playing Time: <Time duration> snprintf( str, MAX_STR_LEN+1, _("Total Playing Time: %s"), info.play_time_str() ); font_san.put( PLAY_TIME_X1+6, y1+6, str ); } //----------- End of static function disp_play_time -----------// //--------- Begin of function Info::detect_rank ---------// // void Info::detect_rank() { //------- detect nation browser ------// if( browse_nation.detect() ) { browse_nation_recno = browse_nation.recno(); return; } } //----------- End of function Info::detect_rank -----------// //-------- Begin of static function nation_filter --------// // // This function has dual purpose : // // 1. when <int> recNo is not given : // - return the total no. of nations of this nation // // 2. when <int> recNo is given : // - return the nation recno in nation_array of the given recno. // static int nation_filter(int recNo) { int i, nationCount=0; Nation* viewingNation = NULL; if( nation_array.player_recno ) viewingNation = nation_array[info.viewing_nation_recno]; for( i=1 ; i<=nation_array.size() ; i++ ) { if( nation_array.is_deleted(i) ) continue; if( i==info.viewing_nation_recno || !viewingNation || viewingNation->get_relation(i)->has_contact ) { nationCount++; } if( recNo && nationCount==recNo ) return i; } err_when( recNo ); // the recNo is not found, it is out of range return nationCount; } //----------- End of static function nation_filter -----------// //-------- Begin of static function put_nation_rec --------// // static void put_nation_rec(int recNo, int x, int y, int refreshFlag) { int nationRecno = nation_filter(recNo); Nation* nationPtr = nation_array[nationRecno]; x+=3; y+=5; nationPtr->disp_nation_color(x, y+4); font_san.put( x+20, y, nationPtr->nation_name() ); font_san.put( x+210, y, info.get_rank_pos_str(1, nationRecno) ); font_san.put( x+270, y, info.get_rank_pos_str(2, nationRecno) ); font_san.put( x+352, y, info.get_rank_pos_str(3, nationRecno) ); font_san.put( x+435, y, info.get_rank_pos_str(4, nationRecno) ); font_san.put( x+500, y, info.get_rank_pos_str(5, nationRecno) ); } //----------- End of static function put_nation_rec -----------// //-------- Begin of function Info::set_rank_data --------// // // <int> onlyHasContact - if this is 1, then only nations // that have contact with the viewing // nation is counted. Otherwise all nations // are counted. // void Info::set_rank_data(int onlyHasContact) { Nation* viewingNation = NULL; Nation* nationPtr; int rankPos=0; if( nation_array.player_recno && !nation_array.is_deleted(info.viewing_nation_recno) ) viewingNation = nation_array[info.viewing_nation_recno]; memset( nation_rank_data_array, 0, sizeof(nation_rank_data_array) ); for( int i=1 ; i<=nation_array.size() ; i++ ) { if( nation_array.is_deleted(i) ) continue; if( onlyHasContact ) { if( viewingNation && !viewingNation->get_relation(i)->has_contact ) continue; } nationPtr = nation_array[i]; nation_rank_data_array[0][i-1] = nationPtr->population_rating; nation_rank_data_array[1][i-1] = nationPtr->military_rating; nation_rank_data_array[2][i-1] = nationPtr->economic_rating; nation_rank_data_array[3][i-1] = (int) nationPtr->reputation; nation_rank_data_array[4][i-1] = (int) nationPtr->kill_monster_score; } } //----------- End of static function Info::set_rank_data -----------// //-------- Begin of function Info::get_rank_pos_str --------// // char* Info::get_rank_pos_str(int rankType, int nationRecno) { Nation* viewingNation = NULL; int curNationRankData = nation_rank_data_array[rankType-1][nationRecno-1]; int rankPos=1; if( nation_array.player_recno && !nation_array.is_deleted(info.viewing_nation_recno) ) viewingNation = nation_array[info.viewing_nation_recno]; for( int i=1 ; i<=nation_array.size() ; i++ ) { if( nation_array.is_deleted(i) || i == nationRecno ) continue; if( viewingNation && !viewingNation->get_relation(i)->has_contact ) continue; if( nation_rank_data_array[rankType-1][i-1] > curNationRankData ) // if another nation's value is higher than the given nation's value rankPos++; } return misc.num_th(rankPos); } //----------- End of function Info::get_rank_pos_str -----------// //-------- Begin of function Info::get_rank_score --------// // // Get the score of the given nation in the given ranking type. // int Info::get_rank_score(int rankType, int nationRecno) { int maxValue; switch( rankType ) { case 1: // population maxValue = 100; break; case 2: // military strength maxValue = 200; break; case 3: // economic strength maxValue = 6000; break; case 4: // reputation maxValue = 100; // so the maximum score of the reputation portion is 50 only break; case 5: // monsters slain score maxValue = 1000; break; } int rankScore = 100 * nation_rank_data_array[rankType-1][nationRecno-1] / maxValue; return MAX(0, rankScore); } //----------- End of function Info::get_rank_score -----------// //-------- Begin of function Info::get_total_score --------// // // Get the score of the given nation. // int Info::get_total_score(int nationRecno) { int totalScore=0; for( int i=0 ; i<MAX_RANK_TYPE ; i++ ) { totalScore += get_rank_score(i+1, nationRecno); } return totalScore; } //----------- End of function Info::get_total_score -----------//
gpl-2.0
azumimuo/family-xbmc-addon
plugin.video.genesisreborn/resources/lib/sources/threemovies.py
5378
# -*- coding: utf-8 -*- ''' 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/>. ''' import re,urllib,urlparse,random,urlresolver from resources.lib.modules import cleantitle from resources.lib.modules import client from resources.lib.modules import control debridstatus = control.setting('debridsources') from BeautifulSoup import BeautifulSoup from resources.lib.modules.common import random_agent, quality_tag import requests from schism_commons import quality_tag, google_tag, parseDOM, replaceHTMLCodes ,cleantitle_get, cleantitle_get_2, cleantitle_query, get_size, cleantitle_get_full class source: def __init__(self): self.domains = ['300movies.co'] self.base_link = 'http://300mbmovies4u.net' self.search_link = '/?s=%s+%s' def movie(self, imdb, title, year): self.genesisreborn_url = [] try: if not debridstatus == 'true': raise Exception() self.genesisreborn_url = [] headers = {'Accept-Language': 'en-US,en;q=0.5', 'User-Agent': random_agent()} cleanmovie = cleantitle.get(title) title = cleantitle.getsearch(title) titlecheck = cleanmovie+year query = self.search_link % (urllib.quote_plus(title),year) query = urlparse.urljoin(self.base_link, query) html = BeautifulSoup(requests.get(query, headers=headers, timeout=10).content) containers = html.findAll('div', attrs={'class': 'cover'}) for result in containers: r_title = result.findAll('a')[0]["title"] r_href = result.findAll('a')[0]["href"] r_href = r_href.encode('utf-8') r_title = r_title.encode('utf-8') c_title = cleantitle_get_2(r_title) if titlecheck in c_title: self.genesisreborn_url.append([r_href,r_title]) print("THREEMOVIES PASSED", self.genesisreborn_url) return self.genesisreborn_url except: return def tvshow(self, imdb, tvdb, tvshowtitle, year): try: url = {'tvshowtitle': tvshowtitle, 'year': year} url = urllib.urlencode(url) return url except: return def episode(self, url, imdb, tvdb, title, premiered, season, episode): try: if not debridstatus == 'true': raise Exception() self.genesisreborn_url = [] headers = {'Accept-Language': 'en-US,en;q=0.5', 'User-Agent': random_agent()} data = urlparse.parse_qs(url) data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data]) title = data['tvshowtitle'] if 'tvshowtitle' in data else data['title'] cleanmovie = cleantitle.get(title) data['season'], data['episode'] = season, episode ep_search = 'S%02dE%02d' % (int(data['season']), int(data['episode'])) episodecheck = str(ep_search).lower() titlecheck = cleanmovie+episodecheck query = self.search_link % (urllib.quote_plus(title), ep_search) query = urlparse.urljoin(self.base_link, query) print("HEVC query", query) html = BeautifulSoup(requests.get(query, headers=headers, timeout=10).content) containers = html.findAll('div', attrs={'class': 'cover'}) for result in containers: print("HEVC containers", result) r_title = result.findAll('a')[0]["title"] r_href = result.findAll('a')[0]["href"] r_href = r_href.encode('utf-8') r_title = r_title.encode('utf-8') c_title = cleantitle.get(r_title) if titlecheck in c_title: self.genesisreborn_url.append([r_href,r_title]) print("THREEMOVIES PASSED SHOW ", r_title, r_href) return self.url except: return def sources(self, url, hostDict, hostprDict): try: sources = [] headers = {'Accept-Language': 'en-US,en;q=0.5', 'User-Agent': random_agent()} for movielink,title in self.genesisreborn_url: quality = quality_tag(title) html = BeautifulSoup(requests.get(movielink, headers=headers, timeout=10).content) containers = html.findAll('div', attrs={'class': 'txt-block'}) for result in containers: print("THREEMOVIES LINKS ",result) links = result.findAll('a') for r_href in links: url = r_href['href'] myurl = str(url) if any (value in myurl for value in hostprDict): try:host = re.findall('([\w]+[.][\w]+)$', urlparse.urlparse(url.strip().lower()).netloc)[0] except: host = 'Threemovies' url = client.replaceHTMLCodes(url) url = url.encode('utf-8') host = client.replaceHTMLCodes(host) host = host.encode('utf-8') sources.append({'source': host, 'quality': quality, 'provider': 'Threemovies', 'url': url, 'direct': False, 'debridonly': True}) return sources except: return sources def resolve(self, url): return url
gpl-2.0
dans-lweb/immunoconcept
wp-content/plugins/responsive-menu/src/config/routing.php
1755
<?php if(is_admin()): add_action('admin_menu', function() use($container) { if(isset($_POST['responsive_menu_submit'])): $method = 'update'; elseif(isset($_POST['responsive_menu_reset'])): $method = 'reset'; elseif(isset($_POST['responsive_menu_export'])): $controller = $container['admin_controller']; $controller->export(); elseif(isset($_POST['responsive_menu_import'])): $method = 'import'; else: $method = 'index'; endif; add_menu_page( 'Responsive Menu', 'Responsive Menu', 'manage_options', 'responsive-menu', function() use ($method, $container) { $controller = $container['admin_controller']; switch ($method) : case 'update': $controller->$method($container['default_options'], $_POST['menu']); break; case 'reset': $controller->$method($container['default_options']); break; case 'import': $file = $_FILES['responsive_menu_import_file']; $file_options = isset($file['tmp_name']) ? (array) json_decode(file_get_contents($file['tmp_name'])) : null; $controller->$method($container['default_options'], $file_options); break; default: $controller->$method(); break; endswitch; }, 'dashicons-menu'); }); else: if(isset($_GET['responsive-menu-preview']) && isset($_POST['menu'])): add_action('template_redirect', function() use($container) { $container['front_controller']->preview(); }); else: add_action('template_redirect', function() use($container) { $container['front_controller']->index(); }); endif; endif;
gpl-2.0
Costin11/lim-db
src/executables/unit-test/unit-test.cpp
182
#include <stdio.h> #include "unit-test\bitmap-test.hpp" #include "unit-test\sector-manager-test.hpp" int main () { BitmapTest::check(); //SectorManagerTest::check(); return 0; }
gpl-2.0
pattop/wt
src/Wt/Auth/AuthWidget.C
12145
/* * Copyright (C) 2011 Emweb bvba, Kessel-Lo, Belgium. * * See the LICENSE file for terms of use. */ #include "Wt/Auth/AbstractUserDatabase" #include "Wt/Auth/AuthModel" #include "Wt/Auth/AuthService" #include "Wt/Auth/LostPasswordWidget" #include "Wt/Auth/PasswordPromptDialog" #include "Wt/Auth/RegistrationWidget" #include "Wt/Auth/UpdatePasswordWidget" #include "Wt/Auth/OAuthService" #include "Wt/WApplication" #include "Wt/WAnchor" #include "Wt/WCheckBox" #include "Wt/WContainerWidget" #include "Wt/WDialog" #include "Wt/WEnvironment" #include "Wt/WImage" #include "Wt/WLineEdit" #include "Wt/WMessageBox" #include "Wt/WPushButton" #include "Wt/WText" #include "Wt/WTheme" #include "Login" #include "AuthWidget" #include "web/WebUtils.h" #include <memory> namespace Wt { LOGGER("Auth.AuthWidget"); namespace Auth { AuthWidget::AuthWidget(const AuthService& baseAuth, AbstractUserDatabase& users, Login& login, WContainerWidget *parent) : WTemplateFormView(WString::Empty, parent), model_(new AuthModel(baseAuth, users, this)), login_(login) { init(); } AuthWidget::AuthWidget(Login& login, WContainerWidget *parent) : WTemplateFormView(WString::Empty, parent), model_(0), login_(login) { init(); } void AuthWidget::init() { registrationModel_ = 0; registrationEnabled_ = false; created_ = false; dialog_ = 0; messageBox_ = 0; WApplication *app = WApplication::instance(); app->internalPathChanged().connect(this, &AuthWidget::onPathChange); app->theme()->apply(this, this, AuthWidgets); } void AuthWidget::setModel(AuthModel *model) { delete model_; model_ = model; } void AuthWidget::setRegistrationEnabled(bool enabled) { registrationEnabled_ = enabled; } void AuthWidget::setInternalBasePath(const std::string& basePath) { basePath_ = Utils::append(Utils::prepend(basePath, '/'), '/');; } void AuthWidget::onPathChange(const std::string& path) { handleRegistrationPath(path); } bool AuthWidget::handleRegistrationPath(const std::string& path) { if (!basePath_.empty()) { WApplication *app = WApplication::instance(); if (app->internalPathMatches(basePath_)) { std::string ap = app->internalSubPath(basePath_); if (ap == "register") { registerNewUser(); return true; } } } return false; } void AuthWidget::registerNewUser() { registerNewUser(Identity::Invalid); } void AuthWidget::registerNewUser(const Identity& oauth) { showDialog(tr("Wt.Auth.registration"), createRegistrationView(oauth)); } WDialog *AuthWidget::showDialog(const WString& title, WWidget *contents) { delete dialog_; dialog_ = 0; if (contents) { dialog_ = new WDialog(title); dialog_->contents()->addWidget(contents); dialog_->contents()->childrenChanged() .connect(this, &AuthWidget::closeDialog); dialog_->footer()->hide(); if (!WApplication::instance()->environment().ajax()) { /* * try to center it better, we need to set the half width and * height as negative margins. */ dialog_->setMargin(WLength("-21em"), Left); // .Wt-form width dialog_->setMargin(WLength("-200px"), Top); // ??? } dialog_->show(); } return dialog_; } void AuthWidget::closeDialog() { if (dialog_) { delete dialog_; dialog_ = 0; } else { delete messageBox_; messageBox_ = 0; } } RegistrationModel *AuthWidget::registrationModel() { if (!registrationModel_) { registrationModel_ = createRegistrationModel(); if (model_->passwordAuth()) registrationModel_->addPasswordAuth(model_->passwordAuth()); registrationModel_->addOAuth(model_->oAuth()); } else registrationModel_->reset(); return registrationModel_; } RegistrationModel *AuthWidget::createRegistrationModel() { RegistrationModel *result = new RegistrationModel(*model_->baseAuth(), model_->users(), login_, this); if (model_->passwordAuth()) result->addPasswordAuth(model_->passwordAuth()); result->addOAuth(model_->oAuth()); return result; } WWidget *AuthWidget::createRegistrationView(const Identity& id) { RegistrationModel *model = registrationModel(); if (id.isValid()) model->registerIdentified(id); RegistrationWidget *w = new RegistrationWidget(this); w->setModel(model); return w; } void AuthWidget::handleLostPassword() { showDialog(tr("Wt.Auth.lostpassword"), createLostPasswordView()); } WWidget *AuthWidget::createLostPasswordView() { return new LostPasswordWidget(model_->users(), *model_->baseAuth()); } void AuthWidget::letUpdatePassword(const User& user, bool promptPassword) { showDialog(tr("Wt.Auth.updatepassword"), createUpdatePasswordView(user, promptPassword)); } WWidget *AuthWidget::createUpdatePasswordView(const User& user, bool promptPassword) { return new UpdatePasswordWidget(user, registrationModel(), promptPassword ? model_ : 0); } WDialog *AuthWidget::createPasswordPromptDialog(Login& login) { return new PasswordPromptDialog(login, model_); } void AuthWidget::logout() { model_->logout(login_); } void AuthWidget::displayError(const WString& m) { delete messageBox_; WMessageBox *box = new WMessageBox(tr("Wt.Auth.error"), m, NoIcon, Ok); box->buttonClicked().connect(this, &AuthWidget::closeDialog); box->show(); messageBox_ = box; } void AuthWidget::displayInfo(const WString& m) { delete messageBox_; WMessageBox *box = new WMessageBox(tr("Wt.Auth.notice"), m, NoIcon, Ok); box->buttonClicked().connect(this, &AuthWidget::closeDialog); box->show(); messageBox_ = box; } void AuthWidget::render(WFlags<RenderFlag> flags) { if (!created_) { create(); created_ = true; } WTemplateFormView::render(flags); } void AuthWidget::create() { if (created_) return; login_.changed().connect(this, &AuthWidget::onLoginChange); onLoginChange(); created_ = true; } void AuthWidget::onLoginChange() { clear(); if (login_.loggedIn()) { #ifndef WT_TARGET_JAVA if (created_) // do not do this if onLoginChange() is called from create() WApplication::instance()->changeSessionId(); #endif // WT_TARGET_JAVA createLoggedInView(); } else { if (login_.state() != DisabledLogin) { if (model_->baseAuth()->authTokensEnabled()) { WApplication::instance()->removeCookie (model_->baseAuth()->authTokenCookieName()); } model_->reset(); createLoginView(); } } } void AuthWidget::createLoginView() { setTemplateText(tr("Wt.Auth.template.login")); createPasswordLoginView(); createOAuthLoginView(); } void AuthWidget::createPasswordLoginView() { updatePasswordLoginView(); } WFormWidget *AuthWidget::createFormWidget(WFormModel::Field field) { WFormWidget *result = 0; if (field == AuthModel::LoginNameField) { result = new WLineEdit(); result->setFocus(true); } else if (field == AuthModel::PasswordField) { WLineEdit *p = new WLineEdit(); p->enterPressed().connect(this, &AuthWidget::attemptPasswordLogin); p->setEchoMode(WLineEdit::Password); result = p; } else if (field == AuthModel::RememberMeField) { result = new WCheckBox(); } return result; } void AuthWidget::updatePasswordLoginView() { if (model_->passwordAuth()) { setCondition("if:passwords", true); updateView(model_); WInteractWidget *login = resolve<WInteractWidget *>("login"); if (!login) { login = new WPushButton(tr("Wt.Auth.login")); login->clicked().connect(this, &AuthWidget::attemptPasswordLogin); bindWidget("login", login); model_->configureThrottling(login); if (model_->baseAuth()->emailVerificationEnabled()) { WText *text = new WText(tr("Wt.Auth.lost-password")); text->clicked().connect(this, &AuthWidget::handleLostPassword); bindWidget("lost-password", text); } else bindEmpty("lost-password"); if (registrationEnabled_) { WInteractWidget *w; if (!basePath_.empty()) { w = new WAnchor (WLink(WLink::InternalPath, basePath_ + "register"), tr("Wt.Auth.register")); } else { w = new WText(tr("Wt.Auth.register")); w->clicked().connect(this, &AuthWidget::registerNewUser); } bindWidget("register", w); } else bindEmpty("register"); if (model_->baseAuth()->emailVerificationEnabled() && registrationEnabled_) bindString("sep", " | "); else bindEmpty("sep"); } model_->updateThrottling(login); } else { bindEmpty("lost-password"); bindEmpty("sep"); bindEmpty("register"); bindEmpty("login"); } } void AuthWidget::createOAuthLoginView() { if (!model_->oAuth().empty()) { setCondition("if:oauth", true); WContainerWidget *icons = new WContainerWidget(); icons->setInline(isInline()); for (unsigned i = 0; i < model_->oAuth().size(); ++i) { const OAuthService *auth = model_->oAuth()[i]; WImage *w = new WImage("css/oauth-" + auth->name() + ".png", icons); w->setToolTip(auth->description()); w->setStyleClass("Wt-auth-icon"); w->setVerticalAlignment(AlignMiddle); OAuthProcess *const process = auth->createProcess(auth->authenticationScope()); #ifndef WT_TARGET_JAVA w->clicked().connect(process, &OAuthProcess::startAuthenticate); #else process->connectStartAuthenticate(w->clicked()); #endif process->authenticated().connect (boost::bind(&AuthWidget::oAuthDone, this, process, _1)); WObject::addChild(process); } bindWidget("icons", icons); } } void AuthWidget::oAuthDone(OAuthProcess *oauth, const Identity& identity) { /* * FIXME: perhaps consider moving this to the model with signals or * by passing the Login object ? */ if (identity.isValid()) { LOG_SECURE(oauth->service().name() << ": identified: as " << identity.id() << ", " << identity.name() << ", " << identity.email()); std::auto_ptr<AbstractUserDatabase::Transaction> t(model_->users().startTransaction()); User user = model_->baseAuth()->identifyUser(identity, model_->users()); if (user.isValid()) model_->loginUser(login_, user); else registerNewUser(identity); if (t.get()) t->commit(); } else { LOG_SECURE(oauth->service().name() << ": error: " << oauth->error()); displayError(oauth->error()); } } void AuthWidget::attemptPasswordLogin() { updateModel(model_); if (model_->validate()) { if (!model_->login(login_)) updatePasswordLoginView(); } else updatePasswordLoginView(); } void AuthWidget::createLoggedInView() { setTemplateText(tr("Wt.Auth.template.logged-in")); bindString("user-name", login_.user().identity(Identity::LoginName)); WPushButton *logout = new WPushButton(tr("Wt.Auth.logout")); logout->clicked().connect(this, &AuthWidget::logout); bindWidget("logout", logout); } void AuthWidget::processEnvironment() { const WEnvironment& env = WApplication::instance()->environment(); if (registrationEnabled_) if (handleRegistrationPath(env.internalPath())) return; std::string emailToken = model_->baseAuth()->parseEmailToken(env.internalPath()); if (!emailToken.empty()) { EmailTokenResult result = model_->processEmailToken(emailToken); switch (result.result()) { case EmailTokenResult::Invalid: displayError(tr("Wt.Auth.error-invalid-token")); break; case EmailTokenResult::Expired: displayError(tr("Wt.Auth.error-token-expired")); break; case EmailTokenResult::UpdatePassword: letUpdatePassword(result.user(), false); break; case EmailTokenResult::EmailConfirmed: displayInfo(tr("Wt.Auth.info-email-confirmed")); User user = result.user(); model_->loginUser(login_, user); } /* * In progressive bootstrap mode, this would cause a redirect w/o * session ID, losing the dialog. */ if (WApplication::instance()->environment().ajax()) WApplication::instance()->setInternalPath("/"); return; } User user = model_->processAuthToken(); model_->loginUser(login_, user, WeakLogin); } } }
gpl-2.0
ZeroK-RTS/Zero-K
scripts/vehaa.lua
5966
--linear constant 163840 include "constants.lua" local base, rockbase, body, turret, firepoint, rwheel1, rwheel2, lwheel1, lwheel2, gs1r, gs2r, gs1l, gs2l = piece('base', 'rockbase', 'body', 'turret', 'firepoint', 'rwheel1', 'rwheel2', 'lwheel1', 'lwheel2', 'gs1r', 'gs2r', 'gs1l', 'gs2l') local spGetGroundHeight = Spring.GetGroundHeight local spGetUnitVelocity = Spring.GetUnitVelocity local spGetUnitPosition = Spring.GetUnitPosition local spGetUnitPiecePosDir = Spring.GetUnitPiecePosDir local MAX_STEER = math.rad(25) local STEER_MULT = 3.5 local STEER_RATE_MAX = math.rad(235) local SUSPENSION_BOUND = 7 local WHEEL_TURN_MULT = 1.2 local ANIM_PERIOD = 50 local smokePiece = {turret, body} local moving, wheelTurnSpeed local lastHeading = 0 local turnTilt = 0 local lastSteer = 0 local steerRate = 0 local steer = 0 local OKP_DAMAGE = tonumber(UnitDefs[unitDefID].customParams.okp_damage) local SETTLE_PERIODS = 15 local settleTimer = 0 local function GetWheelHeight(piece) local x,y,z = spGetUnitPiecePosDir(unitID, piece) local height = spGetGroundHeight(x,z) - y if height < -SUSPENSION_BOUND then height = -SUSPENSION_BOUND end if height > SUSPENSION_BOUND then height = SUSPENSION_BOUND end return height end local function Roll() Sleep(500) if not moving then StopSpin(rwheel1, x_axis) StopSpin(rwheel2, x_axis) StopSpin(lwheel1, x_axis) StopSpin(lwheel2, x_axis) end end function StopMoving() moving = false StartThread(Roll) end function StartMoving() moving = true local x,y,z = spGetUnitVelocity(unitID) wheelTurnSpeed = math.sqrt(x*x+y*y+z*z)*WHEEL_TURN_MULT Spin(rwheel1, x_axis, wheelTurnSpeed) Spin(rwheel2, x_axis, wheelTurnSpeed) Spin(lwheel1, x_axis, wheelTurnSpeed) Spin(lwheel2, x_axis, wheelTurnSpeed) end local function UpdateAnimControl() local currHeading, diffHeading, turnAngle --pivot currHeading = GetUnitValue(COB.HEADING)*GG.Script.headingToRad diffHeading = (currHeading - lastHeading) -- Fix wrap location if diffHeading > math.pi then diffHeading = diffHeading - 2*math.pi end if diffHeading < -math.pi then diffHeading = diffHeading + 2*math.pi end steer = STEER_MULT * diffHeading steer = math.min(MAX_STEER, math.max(-MAX_STEER, steer)) steerRate = STEER_RATE_MAX if math.abs(steer) > math.abs(lastSteer) then steerRate = STEER_RATE_MAX / 2 end -- Bound maximun pivot turnAngle = diffHeading turnTilt = -turnAngle*0.007 lastHeading = currHeading lastSteer = steer end function Suspension() -- local xtilt, xtiltv = 0, 0 local ztilt, ztiltv = 0, 0 local yp, yv = 0, 0 lastHeading = GetUnitValue(COB.HEADING)*GG.Script.headingToRad while true do local _, _, _, speed = spGetUnitVelocity(unitID) wheelTurnSpeed = speed*WHEEL_TURN_MULT if moving then if speed <= 0.05 then StopMoving() end else if speed > 0.05 then StartMoving() end end if speed > 0.05 then settleTimer = 0 elseif settleTimer < SETTLE_PERIODS then settleTimer = settleTimer + 1 end UpdateAnimControl() if speed > 0.05 or (settleTimer < SETTLE_PERIODS) then local x,y,z = spGetUnitPosition(unitID) local height = spGetGroundHeight(x,z) if y - height < 1 then -- If I am on the ground local s1r = GetWheelHeight(gs1r) local s2r = GetWheelHeight(gs2r) local s1l = GetWheelHeight(gs1l) local s2l = GetWheelHeight(gs2l) --local xtilta = (s3r + s3l - s1l - s1r)/6000 --xtiltv = xtiltv*0.99 + xtilta --xtilt = xtilt*0.98 + xtiltv local ztilta = (s1r + s2r - s1l - s2l)/10000 + turnTilt ztiltv = ztiltv*0.99 + ztilta ztilt = ztilt*0.98 + ztiltv local ya = (s1r + s2r + s1l + s2l)/1000 yv = yv*0.99 + ya yp = yp*0.98 + yv Turn(rwheel1, y_axis, steer, steerRate) Turn(lwheel1, y_axis, steer, steerRate) Move(rockbase, y_axis, yp, 9000) --Turn(rockbase, x_axis, xtilt, math.rad(9000)) Turn(rockbase, z_axis, -ztilt, math.rad(9000)) Move(rwheel1, y_axis, s1r, 20) Move(rwheel2, y_axis, s2r, 20) Move(lwheel1, y_axis, s1l, 20) Move(lwheel2, y_axis, s2l, 20) Spin(rwheel1, x_axis, wheelTurnSpeed) Spin(rwheel2, x_axis, wheelTurnSpeed) Spin(lwheel1, x_axis, wheelTurnSpeed) Spin(lwheel2, x_axis, wheelTurnSpeed) end end Sleep(ANIM_PERIOD) end end function script.Create() moving = false StartThread(Suspension) StartThread(GG.Script.SmokeUnit, unitID, smokePiece) end -- Weapons function script.AimFromWeapon() return firepoint end function script.QueryWeapon() return firepoint end function script.BlockShot(num, targetID) return GG.Script.OverkillPreventionCheck(unitID, targetID, OKP_DAMAGE, 730, 30, 0.05, true) end function script.AimWeapon() return true end function script.Killed(recentDamage, maxHealth) local severity = recentDamage / maxHealth if severity <= 0.25 then Explode(rwheel2, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT) Explode(turret, SFX.NONE) Explode(body, SFX.NONE) return 1 elseif severity <= 0.50 then Explode(lwheel1, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT) Explode(lwheel2, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT) Explode(turret, SFX.SHATTER) Explode(body, SFX.NONE) return 1 elseif severity <= 0.99 then Explode(rwheel1, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT) Explode(lwheel2, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT) Explode(lwheel1, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT) Explode(turret, SFX.SHATTER) Explode(body, SFX.NONE) return 2 end Explode(rwheel1, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT) Explode(rwheel2, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT) Explode(lwheel1, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT) Explode(lwheel2, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT) Explode(turret, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT) Explode(body, SFX.SHATTER) return 2 end
gpl-2.0
daz3d/vanilla
applications/dashboard/controllers/class.entrycontroller.php
66700
<?php if (!defined('APPLICATION')) exit(); /* Copyright 2008, 2009 Vanilla Forums Inc. This file is part of Garden. Garden 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. Garden 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 Garden. If not, see <http://www.gnu.org/licenses/>. Contact Vanilla Forums Inc. at support [at] vanillaforums [dot] com */ /** * Entry Controller * * @package Dashboard */ /** * Manages users manually authenticating (signing in). * * @since 2.0.0 * @package Dashboard */ class EntryController extends Gdn_Controller { /** * Models to include. * * @since 2.0.0 * @access public * @var array */ public $Uses = array('Database', 'Form', 'UserModel'); /** * @var Gdn_Form */ public $Form; /** * * @var UserModel */ public $UserModel; /** * Resuable username requirement error message. * * @since 2.0.17 * @access public * @var string */ public $UsernameError = ''; /** * Place to store DeliveryType. * * @since 2.0.0 * @access protected * @var string */ protected $_RealDeliveryType; /** * Setup error message & override MasterView for popups. * * @since 2.0.0 * @access public */ public function __construct() { parent::__construct(); // Set error message here so it can run thru T() $this->UsernameError = T('UsernameError', 'Username can only contain letters, numbers, underscores, and must be between 3 and 20 characters long.'); switch (isset($_GET['display'])) { case 'popup': $this->MasterView = 'popup'; break; } } /** * Include JS and CSS used by all methods. * * Always called by dispatcher before controller's requested method. * * @since 2.0.0 * @access public */ public function Initialize() { $this->Head = new HeadModule($this); $this->Head->AddTag('meta', array('name' => 'robots', 'content' => 'noindex')); $this->AddJsFile('jquery.js'); $this->AddJsFile('jquery.livequery.js'); $this->AddJsFile('jquery.form.js'); $this->AddJsFile('jquery.popup.js'); $this->AddJsFile('jquery.gardenhandleajaxform.js'); $this->AddJsFile('global.js'); $this->AddCssFile('style.css'); parent::Initialize(); Gdn_Theme::Section('Entry'); } /** * Authenticate the user attempting to sign in. * * Events: BeforeAuth * * @since 2.0.0 * @access public * * @param string $AuthenticationSchemeAlias Type of authentication we're attempting. */ public function Auth($AuthenticationSchemeAlias = 'default') { Gdn::Session()->EnsureTransientKey(); $this->EventArguments['AuthenticationSchemeAlias'] = $AuthenticationSchemeAlias; $this->FireEvent('BeforeAuth'); // Allow hijacking auth type $AuthenticationSchemeAlias = $this->EventArguments['AuthenticationSchemeAlias']; // Attempt to set Authenticator with requested method or fallback to default try { $Authenticator = Gdn::Authenticator()->AuthenticateWith($AuthenticationSchemeAlias); } catch (Exception $e) { $Authenticator = Gdn::Authenticator()->AuthenticateWith('default'); } // Set up controller $this->View = 'auth/'.$Authenticator->GetAuthenticationSchemeAlias(); $this->Form->SetModel($this->UserModel); $this->Form->AddHidden('ClientHour', date('Y-m-d H:00')); // Use the server's current hour as a default. $Target = $this->Target(); $this->Form->AddHidden('Target', $Target); // Import authenticator data source switch ($Authenticator->DataSourceType()) { case Gdn_Authenticator::DATA_FORM: $Authenticator->FetchData($this->Form); break; case Gdn_Authenticator::DATA_REQUEST: case Gdn_Authenticator::DATA_COOKIE: $Authenticator->FetchData(Gdn::Request()); break; } // By default, just render the view $Reaction = Gdn_Authenticator::REACT_RENDER; // Where are we in the process? Still need to gather (render view) or are we validating? $AuthenticationStep = $Authenticator->CurrentStep(); switch ($AuthenticationStep) { // User is already logged in case Gdn_Authenticator::MODE_REPEAT: $Reaction = $Authenticator->RepeatResponse(); break; // Not enough information to perform authentication, render input form case Gdn_Authenticator::MODE_GATHER: $this->AddJsFile('entry.js'); $Reaction = $Authenticator->LoginResponse(); if ($this->Form->IsPostBack()) $this->Form->AddError('ErrorCredentials'); break; // All information is present, authenticate case Gdn_Authenticator::MODE_VALIDATE: // Attempt to authenticate. try { if (!$this->Request->IsAuthenticatedPostBack()) { $this->Form->AddError('Please try again.'); $Reaction = $Authenticator->FailedResponse(); } else { $AuthenticationResponse = $Authenticator->Authenticate(); $UserInfo = array(); $UserEventData = array_merge(array( 'UserID' => Gdn::Session()->UserID, 'Payload' => GetValue('HandshakeResponse', $Authenticator, FALSE) ),$UserInfo); Gdn::Authenticator()->Trigger($AuthenticationResponse, $UserEventData); switch ($AuthenticationResponse) { case Gdn_Authenticator::AUTH_PERMISSION: $this->Form->AddError('ErrorPermission'); $Reaction = $Authenticator->FailedResponse(); break; case Gdn_Authenticator::AUTH_DENIED: $this->Form->AddError('ErrorCredentials'); $Reaction = $Authenticator->FailedResponse(); break; case Gdn_Authenticator::AUTH_INSUFFICIENT: // Unable to comply with auth request, more information is needed from user. $this->Form->AddError('ErrorInsufficient'); $Reaction = $Authenticator->FailedResponse(); break; case Gdn_Authenticator::AUTH_PARTIAL: // Partial auth completed. $Reaction = $Authenticator->PartialResponse(); break; case Gdn_Authenticator::AUTH_SUCCESS: default: // Full auth completed. if ($AuthenticationResponse == Gdn_Authenticator::AUTH_SUCCESS) $UserID = Gdn::Session()->UserID; else $UserID = $AuthenticationResponse; header("X-Vanilla-Authenticated: yes"); header("X-Vanilla-TransientKey: ".Gdn::Session()->TransientKey()); $Reaction = $Authenticator->SuccessResponse(); } } } catch (Exception $Ex) { $this->Form->AddError($Ex); } break; case Gdn_Authenticator::MODE_NOAUTH: $Reaction = Gdn_Authenticator::REACT_REDIRECT; break; } switch ($Reaction) { case Gdn_Authenticator::REACT_RENDER: // Do nothing (render the view) break; case Gdn_Authenticator::REACT_EXIT: exit(); break; case Gdn_Authenticator::REACT_REMOTE: // Let the authenticator handle generating output, using a blank slate $this->_DeliveryType= DELIVERY_TYPE_VIEW; exit; break; case Gdn_Authenticator::REACT_REDIRECT: default: if (is_string($Reaction)) $Route = $Reaction; else $Route = $this->RedirectTo(); if ($this->_RealDeliveryType != DELIVERY_TYPE_ALL && $this->_DeliveryType != DELIVERY_TYPE_ALL) { $this->RedirectUrl = Url($Route); } else { if ($Route !== FALSE) { Redirect($Route); } else { Redirect(Gdn::Router()->GetDestination('DefaultController')); } } break; } $this->SetData('SendWhere', "/entry/auth/{$AuthenticationSchemeAlias}"); $this->Render(); } /** * Connect the user with an external source. * * This controller method is meant to be used with plugins that set its data array to work. * Events: ConnectData * * @since 2.0.0 * @access public * * @param string $Method Used to register multiple providers on ConnectData event. */ public function Connect($Method) { $this->AddJsFile('entry.js'); $this->View = 'connect'; $IsPostBack = $this->Form->IsPostBack() && $this->Form->GetFormValue('Connect', NULL) !== NULL; if (!$IsPostBack) { // Here are the initial data array values. that can be set by a plugin. $Data = array('Provider' => '', 'ProviderName' => '', 'UniqueID' => '', 'FullName' => '', 'Name' => '', 'Email' => '', 'Photo' => '', 'Target' => $this->Target()); $this->Form->SetData($Data); $this->Form->AddHidden('Target', $this->Request->Get('Target', '/')); } // The different providers can check to see if they are being used and modify the data array accordingly. $this->EventArguments = array($Method); // Fire ConnectData event & error handling. $currentData = $this->Form->formValues(); // Filter the form data for users here. SSO plugins must reset validated data each postback. $filteredData = Gdn::userModel()->filterForm($currentData, true); $filteredData = array_replace($filteredData, arrayTranslate($currentData, array('TransientKey', 'hpt'))); unset($filteredData['Roles'], $filteredData['RoleID']); $this->Form->formValues($filteredData); try { $this->EventArguments['Form'] = $this->Form; $this->FireEvent('ConnectData'); } catch (Gdn_UserException $Ex) { $this->Form->AddError($Ex); return $this->Render('ConnectError'); } catch (Exception $Ex) { if (Debug()) $this->Form->AddError($Ex); else $this->Form->AddError('There was an error fetching the connection data.'); return $this->Render('ConnectError'); } if (!UserModel::NoEmail()) { if (!$this->Form->GetFormValue('Email') || $this->Form->GetFormValue('EmailVisible')) { $this->Form->SetFormValue('EmailVisible', TRUE); $this->Form->AddHidden('EmailVisible', TRUE); if ($IsPostBack) { $this->Form->SetFormValue('Email', GetValue('Email', $currentData)); } } } $FormData = $this->Form->FormValues(); // debug // Make sure the minimum required data has been provided to the connect. if (!$this->Form->GetFormValue('Provider')) $this->Form->AddError('ValidateRequired', T('Provider')); if (!$this->Form->GetFormValue('UniqueID')) $this->Form->AddError('ValidateRequired', T('UniqueID')); if (!$this->Data('Verified')) { // Whatever event handler catches this must Set the data 'Verified' to true to prevent a random site from connecting without credentials. // This must be done EVERY postback and is VERY important. $this->Form->AddError('The connection data has not been verified.'); } if ($this->Form->ErrorCount() > 0) return $this->Render(); $UserModel = Gdn::UserModel(); // Check to see if there is an existing user associated with the information above. $Auth = $UserModel->GetAuthentication($this->Form->GetFormValue('UniqueID'), $this->Form->GetFormValue('Provider')); $UserID = GetValue('UserID', $Auth); // Check to synchronise roles upon connecting. if (($this->Data('Trusted') || C('Garden.SSO.SynchRoles')) && $this->Form->GetFormValue('Roles', NULL) !== NULL) { $SaveRoles = TRUE; // Translate the role names to IDs. $Roles = $this->Form->GetFormValue('Roles', NULL); $Roles = RoleModel::GetByName($Roles); $RoleIDs = array_keys($Roles); // only these roles can be changed via SSO $ChangeRoles = array( 34, // Platinum Club 35, // Published Artist 46, // _Member - Publishing - Publishing Builds 47, // _Member - Publishing - Active PA 50, // Season Pass ); $CurrentRoles = array( ); foreach ($this->UserModel->GetRoles($UserID) as $CurrentRole) { $CurrentRoles[] = $CurrentRole['RoleID']; } $NonChangeableRoles = array_diff($CurrentRoles, $ChangeRoles); $RoleIDs = array_intersect($RoleIDs, $ChangeRoles); $RoleIDs = array_merge($RoleIDs, $NonChangeableRoles); // add "Member" to new users if ( ! $Auth) { $RoleIDs[] = 8; } if (empty($RoleIDs)) { // The user must have at least one role. This protects that. $RoleIDs = $this->UserModel->NewUserRoleIDs(); } $this->Form->SetFormValue('RoleID', $RoleIDs); } else { $SaveRoles = FALSE; } if ($UserID) { // The user is already connected. $this->Form->SetFormValue('UserID', $UserID); if (C('Garden.Registration.ConnectSynchronize', TRUE)) { $User = Gdn::UserModel()->GetID($UserID, DATASET_TYPE_ARRAY); $Data = $this->Form->FormValues(); // Don't overwrite the user photo if the user uploaded a new one. $Photo = GetValue('Photo', $User); if (!GetValue('Photo', $Data) || ($Photo && !StringBeginsWith($Photo, 'http'))) { unset($Data['Photo']); } // DAZ 2015-07-08 ---- // Check the database for duplicate names and emails and change those // because this name and/or email needs to go through, Magento is the master database $db = Gdn::Database(); $id = $db->QuoteExpression($UserID); $name = $db->QuoteExpression($Data['Name']); $others = Gdn::SQL()->Query(" SELECT `UserID` , `Name` FROM `{$db->DatabasePrefix}User` WHERE `Name` LIKE {$name} AND `UserID` <> {$id} "); foreach ($others as $other) { Gdn::UserModel()->Update(array('Name' => $other->Name.'_'.$other->UserID), array('UserID' => $other->UserID)); } $email = $db->QuoteExpression($Data['Email']); $others = Gdn::SQL()->Query(" SELECT `UserID` , `Email` FROM `{$db->DatabasePrefix}User` WHERE `Email` LIKE {$email} AND `UserID` <> {$id} "); foreach ($others as $other) { Gdn::UserModel()->Update(array('Email' => $other->Email .'.'. $other->UserID .'.disabled'), array('UserID' => $other->UserID)); } // make sure verified is set, so it doesn't get cleared in the next step if ( ! array_key_exists('Verified', $Data)) { $Data['Verified'] = $User['Verified']; } // DAZ ---- // Synchronize the user's data. $UserModel->Save($Data, array('NoConfirmEmail' => TRUE, 'FixUnique' => TRUE, 'SaveRoles' => $SaveRoles)); } // Always save the attributes because they may contain authorization information. if ($Attributes = $this->Form->GetFormValue('Attributes')) { $UserModel->SaveAttribute($UserID, $Attributes); } // Sign the user in. Gdn::Session()->Start($UserID, TRUE, TRUE); Gdn::UserModel()->FireEvent('AfterSignIn'); // $this->_SetRedirect(TRUE); $this->_SetRedirect($this->Request->Get('display') == 'popup'); } elseif ($this->Form->GetFormValue('Name') || $this->Form->GetFormValue('Email')) { $NameUnique = C('Garden.Registration.NameUnique', TRUE); $EmailUnique = C('Garden.Registration.EmailUnique', TRUE); $AutoConnect = C('Garden.Registration.AutoConnect'); // Get the existing users that match the name or email of the connection. $Search = FALSE; if ($this->Form->GetFormValue('Name') && $NameUnique) { $UserModel->SQL->OrWhere('Name', $this->Form->GetFormValue('Name')); $Search = TRUE; } if ($this->Form->GetFormValue('Email') && ($EmailUnique || $AutoConnect)) { $UserModel->SQL->OrWhere('Email', $this->Form->GetFormValue('Email')); $Search = TRUE; } if ($Search) $ExistingUsers = $UserModel->GetWhere()->ResultArray(); else $ExistingUsers = array(); // Check to automatically link the user. if ($AutoConnect && count($ExistingUsers) > 0) { foreach ($ExistingUsers as $Row) { if ($this->Form->GetFormValue('Email') == $Row['Email']) { $UserID = $Row['UserID']; $this->Form->SetFormValue('UserID', $UserID); $Data = $this->Form->FormValues(); if (C('Garden.Registration.ConnectSynchronize', TRUE)) { // Don't overwrite a photo if the user has already uploaded one. $Photo = GetValue('Photo', $Row); if (!GetValue('Photo', $Data) || ($Photo && !StringBeginsWith($Photo, 'http'))) { unset($Data['Photo']); } $UserModel->Save($Data, array('NoConfirmEmail' => TRUE, 'FixUnique' => TRUE, 'SaveRoles' => $SaveRoles)); } if ($Attributes = $this->Form->GetFormValue('Attributes')) { $UserModel->SaveAttribute($UserID, $Attributes); } // Save the userauthentication link. $UserModel->SaveAuthentication(array( 'UserID' => $UserID, 'Provider' => $this->Form->GetFormValue('Provider'), 'UniqueID' => $this->Form->GetFormValue('UniqueID'))); // Sign the user in. Gdn::Session()->Start($UserID, TRUE, TRUE); Gdn::UserModel()->FireEvent('AfterSignIn'); // $this->_SetRedirect(TRUE); $this->_SetRedirect($this->Request->Get('display') == 'popup'); $this->Render(); return; } } } $CurrentUserID = Gdn::Session()->UserID; // Massage the existing users. foreach ($ExistingUsers as $Index => $UserRow) { if ($EmailUnique && $UserRow['Email'] == $this->Form->GetFormValue('Email')) { $EmailFound = $UserRow; break; } if ($UserRow['Name'] == $this->Form->GetFormValue('Name')) { $NameFound = $UserRow; } if ($CurrentUserID > 0 && $UserRow['UserID'] == $CurrentUserID) { unset($ExistingUsers[$Index]); $CurrentUserFound = TRUE; } } if (isset($EmailFound)) { // The email address was found and can be the only user option. $ExistingUsers = array($UserRow); $this->SetData('NoConnectName', TRUE); } elseif (isset($CurrentUserFound)) { $ExistingUsers = array_merge( array('UserID' => 'current', 'Name' => sprintf(T('%s (Current)'), Gdn::Session()->User->Name)), $ExistingUsers); } if (!isset($NameFound) && !$IsPostBack) { $this->Form->SetFormValue('ConnectName', $this->Form->GetFormValue('Name')); } $this->SetData('ExistingUsers', $ExistingUsers); if (UserModel::NoEmail()) $EmailValid = TRUE; else $EmailValid = ValidateRequired($this->Form->GetFormValue('Email')); if ($this->Form->GetFormValue('Name') && $EmailValid && (!is_array($ExistingUsers) || count($ExistingUsers) == 0)) { // There is no existing user with the suggested name so we can just create the user. $User = $this->Form->FormValues(); $User['Password'] = RandomString(50); // some password is required $User['HashMethod'] = 'Random'; $User['Source'] = $this->Form->GetFormValue('Provider'); $User['SourceID'] = $this->Form->GetFormValue('UniqueID'); $User['Attributes'] = $this->Form->GetFormValue('Attributes', NULL); $User['Email'] = $this->Form->GetFormValue('ConnectEmail', $this->Form->GetFormValue('Email', NULL)); // $UserID = $UserModel->InsertForBasic($User, FALSE, array('ValidateEmail' => FALSE, 'NoConfirmEmail' => TRUE, 'SaveRoles' => $SaveRoles)); $UserID = $UserModel->Register($User, array('CheckCaptcha' => FALSE, 'ValidateEmail' => FALSE, 'NoConfirmEmail' => TRUE, 'SaveRoles' => $SaveRoles)); $User['UserID'] = $UserID; $this->Form->SetValidationResults($UserModel->ValidationResults()); if ($UserID) { $UserModel->SaveAuthentication(array( 'UserID' => $UserID, 'Provider' => $this->Form->GetFormValue('Provider'), 'UniqueID' => $this->Form->GetFormValue('UniqueID'))); $this->Form->SetFormValue('UserID', $UserID); Gdn::Session()->Start($UserID, TRUE, TRUE); Gdn::UserModel()->FireEvent('AfterSignIn'); // Send the welcome email. if (C('Garden.Registration.SendConnectEmail', FALSE)) { try { $UserModel->SendWelcomeEmail($UserID, '', 'Connect', array('ProviderName' => $this->Form->GetFormValue('ProviderName', $this->Form->GetFormValue('Provider', 'Unknown')))); } catch (Exception $Ex) { // Do nothing if emailing doesn't work. } } $this->_SetRedirect(TRUE); } } } // Save the user's choice. if ($IsPostBack) { // The user has made their decision. $PasswordHash = new Gdn_PasswordHash(); $UserSelect = $this->Form->GetFormValue('UserSelect'); if (!$UserSelect || $UserSelect == 'other') { // The user entered a username. $ConnectNameEntered = TRUE; if ($this->Form->ValidateRule('ConnectName', 'ValidateRequired')) { $ConnectName = $this->Form->GetFormValue('ConnectName'); $User = FALSE; if (C('Garden.Registration.NameUnique')) { // Check to see if there is already a user with the given name. $User = $UserModel->GetWhere(array('Name' => $ConnectName))->FirstRow(DATASET_TYPE_ARRAY); } if (!$User) { $this->Form->ValidateRule('ConnectName', 'ValidateUsername'); } } } else { // The user selected an existing user. $ConnectNameEntered = FALSE; if ($UserSelect == 'current') { if (Gdn::Session()->UserID == 0) { // This shouldn't happen, but a use could sign out in another browser and click submit on this form. $this->Form->AddError('@You were unexpectedly signed out.'); } else { $UserSelect = Gdn::Session()->UserID; } } $User = $UserModel->GetID($UserSelect, DATASET_TYPE_ARRAY); } if (isset($User) && $User) { // Make sure the user authenticates. if (!$User['UserID'] == Gdn::Session()->UserID) { if ($this->Form->ValidateRule('ConnectPassword', 'ValidateRequired', sprintf(T('ValidateRequired'), T('Password')))) { try { if (!$PasswordHash->CheckPassword($this->Form->GetFormValue('ConnectPassword'), $User['Password'], $User['HashMethod'], $this->Form->GetFormValue('ConnectName'))) { if ($ConnectNameEntered) { $this->Form->AddError('The username you entered has already been taken.'); } else { $this->Form->AddError('The password you entered is incorrect.'); } } } catch (Gdn_UserException $Ex) { $this->Form->AddError($Ex); } } } } elseif ($this->Form->ErrorCount() == 0) { // The user doesn't exist so we need to add another user. $User = $this->Form->FormValues(); $User['Name'] = $User['ConnectName']; $User['Password'] = RandomString(50); // some password is required $User['HashMethod'] = 'Random'; $UserID = $UserModel->Register($User, array('CheckCaptcha' => FALSE, 'NoConfirmEmail' => TRUE, 'SaveRoles' => $SaveRoles)); $User['UserID'] = $UserID; $this->Form->SetValidationResults($UserModel->ValidationResults()); if ($UserID) { // // Add the user to the default roles. // $UserModel->SaveRoles($UserID, C('Garden.Registration.DefaultRoles')); // Send the welcome email. $UserModel->SendWelcomeEmail($UserID, '', 'Connect', array('ProviderName' => $this->Form->GetFormValue('ProviderName', $this->Form->GetFormValue('Provider', 'Unknown')))); } } if ($this->Form->ErrorCount() == 0) { // Save the authentication. if (isset($User) && GetValue('UserID', $User)) { $UserModel->SaveAuthentication(array( 'UserID' => $User['UserID'], 'Provider' => $this->Form->GetFormValue('Provider'), 'UniqueID' => $this->Form->GetFormValue('UniqueID'))); $this->Form->SetFormValue('UserID', $User['UserID']); } // Sign the appropriate user in. Gdn::Session()->Start($this->Form->GetFormValue('UserID', TRUE, TRUE)); Gdn::UserModel()->FireEvent('AfterSignIn'); $this->_SetRedirect(TRUE); } } $this->Render(); } /** * After sign in, send them along. * * @since 2.0.0 * @access protected * * @param bool $CheckPopup */ protected function _SetRedirect($CheckPopup = FALSE) { $Url = Url($this->RedirectTo(), TRUE); $this->RedirectUrl = $Url; $this->MasterView = 'popup'; $this->View = 'redirect'; if ($this->_RealDeliveryType != DELIVERY_TYPE_ALL && $this->DeliveryType() != DELIVERY_TYPE_ALL) { $this->DeliveryMethod(DELIVERY_METHOD_JSON); $this->SetHeader('Content-Type', 'application/json'); } elseif ($CheckPopup) { $this->AddDefinition('CheckPopup', $CheckPopup); } else { Redirect(Url($this->RedirectUrl)); } } /** * Default to SignIn(). * * @access public * @since 2.0.0 */ public function Index() { $this->View = 'SignIn'; $this->SignIn(); } /** * Auth via password. * * @access public * @since 2.0.0 */ public function Password() { $this->Auth('password'); } /** * Auth via default method. Simpler, old version of SignIn(). * * Events: SignIn * * @access public * @return void */ public function SignIn2() { $this->FireEvent("SignIn"); $this->Auth('default'); } /** * Good afternoon, good evening, and goodnight. * * Events: SignOut * * @access public * @since 2.0.0 * * @param string $TransientKey (default: "") */ public function SignOut($TransientKey = "") { if (Gdn::Session()->ValidateTransientKey($TransientKey) || $this->Form->IsPostBack()) { $User = Gdn::Session()->User; $this->EventArguments['SignoutUser'] = $User; $this->FireEvent("BeforeSignOut"); // Sign the user right out. Gdn::Session()->End(); $this->SetData('SignedOut', TRUE); $this->EventArguments['SignoutUser'] = $User; $this->FireEvent("SignOut"); $this->_SetRedirect(); } elseif (!Gdn::Session()->IsValid()) $this->_SetRedirect(); $this->SetData('Target', $this->Target()); $this->Leaving = FALSE; $this->Render(); } /** * Signin process that multiple authentication methods. * * @access public * @since 2.0.0 * @author Tim Gunter * * @param string $Method * @param array $Arg1 * @return string Rendered XHTML template. */ public function SignIn($Method = FALSE, $Arg1 = FALSE) { // DAZ-- this should be overridden by the JSConnect plugin, but seems not to be // so it's hard-coded here $provider = JsConnectPlugin::GetProvider(1044711398); if ( ! empty($provider)) { // modify the sign in URL to have the proper referer hash $sign_in_url = $provider['SignInUrl']; $ref_pos = strpos($sign_in_url, 'referer/'); if ( ! $ref_pos) { if (strrpos('/', $sign_in_url) !== (strlen($sign_in_url) - 1)) { $sign_in_url .= '/'; } $sign_in_url .= 'referer/'; } else { $sign_in_url = substr($sign_in_url, 0, strpos($sign_in_url, 'referer/') + strlen('referer/')); } $referer = urldecode(ArrayValue('Target', $_GET, '')); $referer = preg_replace('%^/'.Gdn::Request()->WebRoot().'/%i', '', $referer); $referer = Gdn::Request()->Url($referer, TRUE); $referer = strtr(base64_encode($referer), '+/=', '-_,'); header('Location: ' . $sign_in_url . $referer); exit; } Gdn::Session()->EnsureTransientKey(); $this->AddJsFile('entry.js'); $this->SetData('Title', T('Sign In')); $this->Form->AddHidden('Target', $this->Target()); $this->Form->AddHidden('ClientHour', date('Y-m-d H:00')); // Use the server's current hour as a default. // Additional signin methods are set up with plugins. $Methods = array(); $this->SetData('Methods', $Methods); $this->SetData('FormUrl', Url('entry/signin')); $this->FireEvent('SignIn'); if ($this->Form->IsPostBack()) { $this->Form->ValidateRule('Email', 'ValidateRequired', sprintf(T('%s is required.'), T(UserModel::SigninLabelCode()))); $this->Form->ValidateRule('Password', 'ValidateRequired'); if (!$this->Request->IsAuthenticatedPostBack()) { $this->Form->AddError('Please try again.'); } // Check the user. if ($this->Form->ErrorCount() == 0) { $Email = $this->Form->GetFormValue('Email'); $User = Gdn::UserModel()->GetByEmail($Email); if (!$User) $User = Gdn::UserModel()->GetByUsername($Email); if (!$User) { $this->Form->AddError('@'.sprintf(T('User not found.'), strtolower(T(UserModel::SigninLabelCode())))); } else { // Check the password. $PasswordHash = new Gdn_PasswordHash(); $Password = $this->Form->GetFormValue('Password'); try { $PasswordChecked = $PasswordHash->CheckPassword($Password, GetValue('Password', $User), GetValue('HashMethod', $User)); // Rate limiting Gdn::UserModel()->RateLimit($User, $PasswordChecked); if ($PasswordChecked) { // Update weak passwords $HashMethod = GetValue('HashMethod', $User); if ($PasswordHash->Weak || ($HashMethod && strcasecmp($HashMethod, 'Vanilla') != 0)) { $Pw = $PasswordHash->HashPassword($Password); Gdn::UserModel()->SetField(GetValue('UserID', $User), array('Password' => $Pw, 'HashMethod' => 'Vanilla')); } Gdn::Session()->Start(GetValue('UserID', $User), TRUE, (bool)$this->Form->GetFormValue('RememberMe')); if (!Gdn::Session()->CheckPermission('Garden.SignIn.Allow')) { $this->Form->AddError('ErrorPermission'); Gdn::Session()->End(); } else { $ClientHour = $this->Form->GetFormValue('ClientHour'); $HourOffset = Gdn::Session()->User->HourOffset; if (is_numeric($ClientHour) && $ClientHour >= 0 && $ClientHour < 24) { $HourOffset = $ClientHour - date('G', time()); } if ($HourOffset != Gdn::Session()->User->HourOffset) { Gdn::UserModel()->SetProperty(Gdn::Session()->UserID, 'HourOffset', $HourOffset); } Gdn::UserModel()->FireEvent('AfterSignIn'); $this->_SetRedirect(); } } else { $this->Form->AddError('Invalid password.'); } } catch (Gdn_UserException $Ex) { $this->Form->AddError($Ex); } } } } else { if ($Target = $this->Request->Get('Target')) $this->Form->AddHidden('Target', $Target); $this->Form->SetValue('RememberMe', TRUE); } return $this->Render(); } /** * Create secure handshake with remote authenticator. * * @access public * @since 2.0.? * @author Tim Gunter * * @param string $AuthenticationSchemeAlias (default: 'default') */ public function Handshake($AuthenticationSchemeAlias = 'default') { try { // Don't show anything if handshaking not turned on by an authenticator if (!Gdn::Authenticator()->CanHandshake()) throw new Exception(); // Try to load the authenticator $Authenticator = Gdn::Authenticator()->AuthenticateWith($AuthenticationSchemeAlias); // Try to grab the authenticator data $Payload = $Authenticator->GetHandshake(); if ($Payload === FALSE) { Gdn::Request()->WithURI('dashboard/entry/auth/password'); return Gdn::Dispatcher()->Dispatch(); } } catch (Exception $e) { Gdn::Request()->WithURI('/entry/signin'); return Gdn::Dispatcher()->Dispatch(); } $UserInfo = array( 'UserKey' => $Authenticator->GetUserKeyFromHandshake($Payload), 'ConsumerKey' => $Authenticator->GetProviderKeyFromHandshake($Payload), 'TokenKey' => $Authenticator->GetTokenKeyFromHandshake($Payload), 'UserName' => $Authenticator->GetUserNameFromHandshake($Payload), 'UserEmail' => $Authenticator->GetUserEmailFromHandshake($Payload) ); if (method_exists($Authenticator, 'GetRolesFromHandshake')) { $RemoteRoles = $Authenticator->GetRolesFromHandshake($Payload); if (!empty($RemoteRoles)) $UserInfo['Roles'] = $RemoteRoles; } // Manual user sync is disabled. No hand holding will occur for users. $SyncScreen = C('Garden.Authenticator.SyncScreen', 'on'); switch ($SyncScreen) { case 'on': // Authenticator events fired inside $this->SyncScreen($Authenticator, $UserInfo, $Payload); break; case 'off': case 'smart': $UserID = $this->UserModel->Synchronize($UserInfo['UserKey'], array( 'Name' => $UserInfo['UserName'], 'Email' => $UserInfo['UserEmail'], 'Roles' => GetValue('Roles', $UserInfo) )); if ($UserID > 0) { // Account created successfully. // Finalize the link between the forum user and the foreign userkey $Authenticator->Finalize($UserInfo['UserKey'], $UserID, $UserInfo['ConsumerKey'], $UserInfo['TokenKey'], $Payload); $UserEventData = array_merge(array( 'UserID' => $UserID, 'Payload' => $Payload ),$UserInfo); Gdn::Authenticator()->Trigger(Gdn_Authenticator::AUTH_CREATED, $UserEventData); /// ... and redirect them appropriately $Route = $this->RedirectTo(); if ($Route !== FALSE) Redirect($Route); else Redirect('/'); } else { // Account not created. if ($SyncScreen == 'smart') { $this->InformMessage(T('There is already an account in this forum using your email address. Please create a new account, or enter the credentials for the existing account.')); $this->SyncScreen($Authenticator, $UserInfo, $Payload); } else { // Set the memory cookie to allow signinloopback to shortcircuit remote query. $CookiePayload = array( 'Sync' => 'Failed' ); $SerializedCookiePayload = Gdn_Format::Serialize($CookiePayload); $Authenticator->Remember($UserInfo['ConsumerKey'], $SerializedCookiePayload); // This resets vanilla's internal "where am I" to the homepage. Needed. Gdn::Request()->WithRoute('DefaultController'); $this->SelfUrl = Url('');//Gdn::Request()->Path(); $this->View = 'syncfailed'; $this->ProviderSite = $Authenticator->GetProviderUrl(); $this->Render(); } } break; } } /** * Attempt to syncronize user data from remote system into Dashboard. * * @access public * @since 2.0.? * @author Tim Gunter * * @param object $Authenticator * @param array $UserInfo * @param array $Payload */ public function SyncScreen($Authenticator, $UserInfo, $Payload) { $this->AddJsFile('entry.js'); $this->View = 'handshake'; $this->HandshakeScheme = $Authenticator->GetAuthenticationSchemeAlias(); $this->Form->SetModel($this->UserModel); $this->Form->AddHidden('ClientHour', date('Y-m-d H:00')); // Use the server's current hour as a default $this->Form->AddHidden('Target', $this->Target()); $PreservedKeys = array( 'UserKey', 'Token', 'Consumer', 'Email', 'Name', 'Gender', 'HourOffset' ); $UserID = 0; $Target = $this->Target(); if ($this->Form->IsPostBack() === TRUE) { $FormValues = $this->Form->FormValues(); if (ArrayValue('StopLinking', $FormValues)) { $AuthResponse = Gdn_Authenticator::AUTH_ABORTED; $UserEventData = array_merge(array( 'UserID' => $UserID, 'Payload' => $Payload ),$UserInfo); Gdn::Authenticator()->Trigger($AuthResponse, $UserEventData); $Authenticator->DeleteCookie(); Gdn::Request()->WithRoute('DefaultController'); return Gdn::Dispatcher()->Dispatch(); } elseif (ArrayValue('NewAccount', $FormValues)) { $AuthResponse = Gdn_Authenticator::AUTH_CREATED; // Try and synchronize the user with the new username/email. $FormValues['Name'] = $FormValues['NewName']; $FormValues['Email'] = $FormValues['NewEmail']; $UserID = $this->UserModel->Synchronize($UserInfo['UserKey'], $FormValues); $this->Form->SetValidationResults($this->UserModel->ValidationResults()); } else { $AuthResponse = Gdn_Authenticator::AUTH_SUCCESS; // Try and sign the user in. $PasswordAuthenticator = Gdn::Authenticator()->AuthenticateWith('password'); $PasswordAuthenticator->HookDataField('Email', 'SignInEmail'); $PasswordAuthenticator->HookDataField('Password', 'SignInPassword'); $PasswordAuthenticator->FetchData($this->Form); $UserID = $PasswordAuthenticator->Authenticate(); if ($UserID < 0) { $this->Form->AddError('ErrorPermission'); } else if ($UserID == 0) { $this->Form->AddError('ErrorCredentials'); } if ($UserID > 0) { $Data = $FormValues; $Data['UserID'] = $UserID; $Data['Email'] = ArrayValue('SignInEmail', $FormValues, ''); $UserID = $this->UserModel->Synchronize($UserInfo['UserKey'], $Data); } } if ($UserID > 0) { // The user has been created successfully, so sign in now // Finalize the link between the forum user and the foreign userkey $Authenticator->Finalize($UserInfo['UserKey'], $UserID, $UserInfo['ConsumerKey'], $UserInfo['TokenKey'], $Payload); $UserEventData = array_merge(array( 'UserID' => $UserID, 'Payload' => $Payload ),$UserInfo); Gdn::Authenticator()->Trigger($AuthResponse, $UserEventData); /// ... and redirect them appropriately $Route = $this->RedirectTo(); if ($Route !== FALSE) Redirect($Route); } else { // Add the hidden inputs back into the form. foreach($FormValues as $Key => $Value) { if (in_array($Key, $PreservedKeys)) $this->Form->AddHidden($Key, $Value); } } } else { $Id = Gdn::Authenticator()->GetIdentity(TRUE); if ($Id > 0) { // The user is signed in so we can just go back to the homepage. Redirect($Target); } $Name = $UserInfo['UserName']; $Email = $UserInfo['UserEmail']; // Set the defaults for a new user. $this->Form->SetFormValue('NewName', $Name); $this->Form->SetFormValue('NewEmail', $Email); // Set the default for the login. $this->Form->SetFormValue('SignInEmail', $Email); $this->Form->SetFormValue('Handshake', 'NEW'); // Add the handshake data as hidden fields. $this->Form->AddHidden('Name', $Name); $this->Form->AddHidden('Email', $Email); $this->Form->AddHidden('UserKey', $UserInfo['UserKey']); $this->Form->AddHidden('Token', $UserInfo['TokenKey']); $this->Form->AddHidden('Consumer', $UserInfo['ConsumerKey']); /* $this->Form->AddHidden('Payload', serialize($Payload)); $this->Form->AddHidden('UserInfo', serialize($UserInfo)); */ } $this->SetData('Name', ArrayValue('Name', $this->Form->HiddenInputs)); $this->SetData('Email', ArrayValue('Email', $this->Form->HiddenInputs)); $this->Render(); } /** * Calls the appropriate registration method based on the configuration setting. * * Events: Register * * @access public * @since 2.0.0 * * @param string $InvitationCode Unique code given to invited user. */ public function Register($InvitationCode = '') { // DAZ-- this should be overridden by the JSConnect plugin, but seems not to be // so it's hard-coded here $provider = JsConnectPlugin::GetProvider(1044711398); if ($provider) { header('Location: ' . $provider['RegisterUrl']); exit; } $this->FireEvent("Register"); $this->Form->SetModel($this->UserModel); // Define gender dropdown options $this->GenderOptions = array( 'u' => T('Unspecified'), 'm' => T('Male'), 'f' => T('Female') ); // Make sure that the hour offset for new users gets defined when their account is created $this->AddJsFile('entry.js'); $this->Form->AddHidden('ClientHour', date('Y-m-d H:00')); // Use the server's current hour as a default $this->Form->AddHidden('Target', $this->Target()); $this->SetData('NoEmail', UserModel::NoEmail()); $RegistrationMethod = $this->_RegistrationView(); $this->View = $RegistrationMethod; $this->$RegistrationMethod($InvitationCode); } /** * Select view/method to be used for registration (from config). * * @access protected * @since 2.0.0 * * @return string Method name. */ protected function _RegistrationView() { $RegistrationMethod = Gdn::Config('Garden.Registration.Method'); if (!in_array($RegistrationMethod, array('Closed', 'Basic','Captcha','Approval','Invitation','Connect'))) $RegistrationMethod = 'Basic'; return 'Register'.$RegistrationMethod; } /** * Registration that requires approval. * * Events: RegistrationPending * * @access private * @since 2.0.0 */ private function RegisterApproval() { Gdn::UserModel()->AddPasswordStrength($this); // If the form has been posted back... if ($this->Form->IsPostBack()) { // Add validation rules that are not enforced by the model $this->UserModel->DefineSchema(); $this->UserModel->Validation->ApplyRule('Name', 'Username', $this->UsernameError); $this->UserModel->Validation->ApplyRule('TermsOfService', 'Required', T('You must agree to the terms of service.')); $this->UserModel->Validation->ApplyRule('Password', 'Required'); $this->UserModel->Validation->ApplyRule('Password', 'Strength'); $this->UserModel->Validation->ApplyRule('Password', 'Match'); $this->UserModel->Validation->ApplyRule('DiscoveryText', 'Required', 'Tell us why you want to join!'); // $this->UserModel->Validation->ApplyRule('DateOfBirth', 'MinimumAge'); $this->FireEvent('RegisterValidation'); try { $Values = $this->Form->FormValues(); $Values = $this->UserModel->FilterForm($Values, TRUE); unset($Values['Roles']); $AuthUserID = $this->UserModel->Register($Values); if (!$AuthUserID) { $this->Form->SetValidationResults($this->UserModel->ValidationResults()); } else { // The user has been created successfully, so sign in now. Gdn::Session()->Start($AuthUserID); if ($this->Form->GetFormValue('RememberMe')) Gdn::Authenticator()->SetIdentity($AuthUserID, TRUE); // Notification text $Label = T('NewApplicantEmail', 'New applicant:'); $Story = Anchor(Gdn_Format::Text($Label.' '.$Values['Name']), ExternalUrl('dashboard/user/applicants')); $this->EventArguments['AuthUserID'] = $AuthUserID; $this->EventArguments['Story'] = &$Story; $this->FireEvent('RegistrationPending'); $this->View = "RegisterThanks"; // Tell the user their application will be reviewed by an administrator. // Grab all of the users that need to be notified. $Data = Gdn::Database()->SQL()->GetWhere('UserMeta', array('Name' => 'Preferences.Email.Applicant'))->ResultArray(); $ActivityModel = new ActivityModel(); foreach ($Data as $Row) { $ActivityModel->Add($AuthUserID, 'Applicant', $Story, $Row['UserID'], '', '/dashboard/user/applicants', 'Only'); } } } catch (Exception $Ex) { $this->Form->AddError($Ex); } } $this->Render(); } /** * Basic/simple registration. Allows immediate access. * * Events: RegistrationSuccessful * * @access private * @since 2.0.0 */ private function RegisterBasic() { Gdn::UserModel()->AddPasswordStrength($this); if ($this->Form->IsPostBack() === TRUE) { // Add validation rules that are not enforced by the model $this->UserModel->DefineSchema(); $this->UserModel->Validation->ApplyRule('Name', 'Username', $this->UsernameError); $this->UserModel->Validation->ApplyRule('TermsOfService', 'Required', T('You must agree to the terms of service.')); $this->UserModel->Validation->ApplyRule('Password', 'Required'); $this->UserModel->Validation->ApplyRule('Password', 'Strength'); $this->UserModel->Validation->ApplyRule('Password', 'Match'); // $this->UserModel->Validation->ApplyRule('DateOfBirth', 'MinimumAge'); $this->FireEvent('RegisterValidation'); try { $Values = $this->Form->FormValues(); $Values = $this->UserModel->FilterForm($Values, TRUE); unset($Values['Roles']); $AuthUserID = $this->UserModel->Register($Values); if ($AuthUserID == UserModel::REDIRECT_APPROVE) { $this->Form->SetFormValue('Target', '/entry/registerthanks'); $this->_SetRedirect(); return; } elseif (!$AuthUserID) { $this->Form->SetValidationResults($this->UserModel->ValidationResults()); } else { // The user has been created successfully, so sign in now. Gdn::Session()->Start($AuthUserID); if ($this->Form->GetFormValue('RememberMe')) Gdn::Authenticator()->SetIdentity($AuthUserID, TRUE); try { $this->UserModel->SendWelcomeEmail($AuthUserID, '', 'Register'); } catch (Exception $Ex) { } $this->FireEvent('RegistrationSuccessful'); // ... and redirect them appropriately $Route = $this->RedirectTo(); if ($this->_DeliveryType != DELIVERY_TYPE_ALL) { $this->RedirectUrl = Url($Route); } else { if ($Route !== FALSE) Redirect($Route); } } } catch (Exception $Ex) { $this->Form->AddError($Ex); } } $this->Render(); } /** * Deprecated since 2.0.18. */ private function RegisterConnect() { throw NotFoundException(); } /** * Captcha-authenticated registration. Used by default. * * Events: RegistrationSuccessful * * @access private * @since 2.0.0 */ private function RegisterCaptcha() { Gdn::UserModel()->AddPasswordStrength($this); include(CombinePaths(array(PATH_LIBRARY, 'vendors/recaptcha', 'functions.recaptchalib.php'))); if ($this->Form->IsPostBack() === TRUE) { // Add validation rules that are not enforced by the model $this->UserModel->DefineSchema(); $this->UserModel->Validation->ApplyRule('Name', 'Username', $this->UsernameError); $this->UserModel->Validation->ApplyRule('TermsOfService', 'Required', T('You must agree to the terms of service.')); $this->UserModel->Validation->ApplyRule('Password', 'Required'); $this->UserModel->Validation->ApplyRule('Password', 'Strength'); $this->UserModel->Validation->ApplyRule('Password', 'Match'); // $this->UserModel->Validation->ApplyRule('DateOfBirth', 'MinimumAge'); $this->FireEvent('RegisterValidation'); try { $Values = $this->Form->FormValues(); $Values = $this->UserModel->FilterForm($Values, TRUE); unset($Values['Roles']); $AuthUserID = $this->UserModel->Register($Values); if ($AuthUserID == UserModel::REDIRECT_APPROVE) { $this->Form->SetFormValue('Target', '/entry/registerthanks'); $this->_SetRedirect(); return; } elseif (!$AuthUserID) { $this->Form->SetValidationResults($this->UserModel->ValidationResults()); if ($this->_DeliveryType != DELIVERY_TYPE_ALL) $this->_DeliveryType = DELIVERY_TYPE_MESSAGE; } else { // The user has been created successfully, so sign in now. if (!Gdn::Session()->IsValid()) Gdn::Session()->Start($AuthUserID, TRUE, (bool)$this->Form->GetFormValue('RememberMe')); try { $this->UserModel->SendWelcomeEmail($AuthUserID, '', 'Register'); } catch (Exception $Ex) { } $this->FireEvent('RegistrationSuccessful'); // ... and redirect them appropriately $Route = $this->RedirectTo(); if ($this->_DeliveryType != DELIVERY_TYPE_ALL) { $this->RedirectUrl = Url($Route); } else { if ($Route !== FALSE) Redirect($Route); } } } catch (Exception $Ex) { $this->Form->AddError($Ex); } } $this->Render(); } /** * Registration not allowed. * * @access private * @since 2.0.0 */ private function RegisterClosed() { $this->Render(); } /** * Invitation-only registration. Requires code. * * Events: RegistrationSuccessful * * @access private * @since 2.0.0 */ private function RegisterInvitation($InvitationCode) { Gdn::UserModel()->AddPasswordStrength($this); if ($this->Form->IsPostBack() === TRUE) { $this->InvitationCode = $this->Form->GetValue('InvitationCode'); // Add validation rules that are not enforced by the model $this->UserModel->DefineSchema(); $this->UserModel->Validation->ApplyRule('Name', 'Username', $this->UsernameError); $this->UserModel->Validation->ApplyRule('TermsOfService', 'Required', T('You must agree to the terms of service.')); $this->UserModel->Validation->ApplyRule('Password', 'Required'); $this->UserModel->Validation->ApplyRule('Password', 'Strength'); $this->UserModel->Validation->ApplyRule('Password', 'Match'); // $this->UserModel->Validation->ApplyRule('DateOfBirth', 'MinimumAge'); $this->FireEvent('RegisterValidation'); try { $Values = $this->Form->FormValues(); $Values = $this->UserModel->FilterForm($Values, TRUE); unset($Values['Roles']); $AuthUserID = $this->UserModel->Register($Values); if (!$AuthUserID) { $this->Form->SetValidationResults($this->UserModel->ValidationResults()); } else { // The user has been created successfully, so sign in now. Gdn::Session()->Start($AuthUserID); if ($this->Form->GetFormValue('RememberMe')) Gdn::Authenticator()->SetIdentity($AuthUserID, TRUE); $this->FireEvent('RegistrationSuccessful'); // ... and redirect them appropriately $Route = $this->RedirectTo(); if ($this->_DeliveryType != DELIVERY_TYPE_ALL) { $this->RedirectUrl = Url($Route); } else { if ($Route !== FALSE) Redirect($Route); } } } catch (Exception $Ex) { $this->Form->AddError($Ex); } } else { $this->InvitationCode = $InvitationCode; } $this->Render(); } /** * @since 2.1 */ public function RegisterThanks() { $this->CssClass = 'SplashMessage NoPanel'; $this->SetData('_NoMessages', TRUE); $this->SetData('Title', T('Thank You!')); $this->Render(); } /** * Request password reset. * * @access public * @since 2.0.0 */ public function PasswordRequest() { Gdn::Locale()->SetTranslation('Email', T(UserModel::SigninLabelCode())); if ($this->Form->IsPostBack() === TRUE) { $this->Form->ValidateRule('Email', 'ValidateRequired'); if ($this->Form->ErrorCount() == 0) { try { $Email = $this->Form->GetFormValue('Email'); if (!$this->UserModel->PasswordRequest($Email)) { $this->Form->SetValidationResults($this->UserModel->ValidationResults()); } } catch (Exception $ex) { $this->Form->AddError($ex->getMessage()); } if ($this->Form->ErrorCount() == 0) { $this->Form->AddError('Success!'); $this->View = 'passwordrequestsent'; } } else { if ($this->Form->ErrorCount() == 0) $this->Form->AddError("Couldn't find an account associated with that email/username."); } } $this->Render(); } /** * Do password reset. * * @access public * @since 2.0.0 * * @param int $UserID Unique. * @param string $PasswordResetKey Authenticate with unique, 1-time code sent via email. */ public function PasswordReset($UserID = '', $PasswordResetKey = '') { $PasswordResetKey = trim($PasswordResetKey); if (!is_numeric($UserID) || $PasswordResetKey == '' || $this->UserModel->GetAttribute($UserID, 'PasswordResetKey', '') != $PasswordResetKey ) { $this->Form->AddError('Failed to authenticate your password reset request. Try using the reset request form again.'); } $Expires = $this->UserModel->GetAttribute($UserID, 'PasswordResetExpires'); if ($this->Form->ErrorCount() === 0 && $Expires < time()) { $this->Form->AddError('@'.T('Your password reset token has expired.', 'Your password reset token has expired. Try using the reset request form again.')); } if ($this->Form->ErrorCount() == 0) { $User = $this->UserModel->GetID($UserID, DATASET_TYPE_ARRAY); if ($User) { $User = ArrayTranslate($User, array('UserID', 'Name', 'Email')); $this->SetData('User', $User); } } else { $this->SetData('Fatal', TRUE); } if ($this->Form->ErrorCount() == 0 && $this->Form->IsPostBack() === TRUE ) { $Password = $this->Form->GetFormValue('Password', ''); $Confirm = $this->Form->GetFormValue('Confirm', ''); if ($Password == '') $this->Form->AddError('Your new password is invalid'); else if ($Password != $Confirm) $this->Form->AddError('Your passwords did not match.'); if ($this->Form->ErrorCount() == 0) { $User = $this->UserModel->PasswordReset($UserID, $Password); Gdn::Session()->Start($User->UserID, TRUE); // $Authenticator = Gdn::Authenticator()->AuthenticateWith('password'); // $Authenticator->FetchData($Authenticator, array('Email' => $User->Email, 'Password' => $Password, 'RememberMe' => FALSE)); // $AuthUserID = $Authenticator->Authenticate(); Redirect('/'); } } $this->Render(); } /** * Confirm email address is valid via sent code. * * @access public * @since 2.0.0 * * @param int $UserID * @param string $EmailKey Authenticate with unique, 1-time code sent via email. */ public function EmailConfirm($UserID, $EmailKey = '') { $User = $this->UserModel->GetID($UserID); if (!$User) throw NotFoundException('User'); $EmailConfirmed = $this->UserModel->ConfirmEmail($User, $EmailKey); $this->Form->SetValidationResults($this->UserModel->ValidationResults()); if ($EmailConfirmed) { $UserID = GetValue('UserID', $User); Gdn::Session()->Start($UserID); } $this->SetData('EmailConfirmed', $EmailConfirmed); $this->SetData('Email', $User->Email); $this->Render(); } /** * Send email confirmation message to user. * * @access public * @since 2.0.? * * @param int $UserID */ public function EmailConfirmRequest($UserID = '') { if ($UserID && !Gdn::Session()->CheckPermission('Garden.Users.Edit')) $UserID = ''; try { $this->UserModel->SendEmailConfirmationEmail($UserID); } catch (Exception $Ex) {} $this->Form->SetValidationResults($this->UserModel->ValidationResults()); $this->Render(); } /** * Does actual de-authentication of a user. Used by SignOut(). * * @access public * @since 2.0.0 * * @param string $AuthenticationSchemeAlias * @param string $TransientKey Unique value to prove intent. */ public function Leave($AuthenticationSchemeAlias = 'default', $TransientKey = '') { Deprecated(__FUNCTION__); $this->EventArguments['AuthenticationSchemeAlias'] = $AuthenticationSchemeAlias; $this->FireEvent('BeforeLeave'); // Allow hijacking deauth type $AuthenticationSchemeAlias = $this->EventArguments['AuthenticationSchemeAlias']; try { $Authenticator = Gdn::Authenticator()->AuthenticateWith($AuthenticationSchemeAlias); } catch (Exception $e) { $Authenticator = Gdn::Authenticator()->AuthenticateWith('default'); } // Only sign the user out if this is an authenticated postback! Start off pessimistic $this->Leaving = FALSE; $Result = Gdn_Authenticator::REACT_RENDER; // Build these before doing anything desctructive as they are supposed to have user context $LogoutResponse = $Authenticator->LogoutResponse(); $LoginResponse = $Authenticator->LoginResponse(); $AuthenticatedPostbackRequired = $Authenticator->RequireLogoutTransientKey(); if (!$AuthenticatedPostbackRequired || Gdn::Session()->ValidateTransientKey($TransientKey)) { $Result = $Authenticator->DeAuthenticate(); $this->Leaving = TRUE; } if ($Result == Gdn_Authenticator::AUTH_SUCCESS) { $this->View = 'leave'; $Reaction = $LogoutResponse; } else { $this->View = 'auth/'.$Authenticator->GetAuthenticationSchemeAlias(); $Reaction = $LoginResponse; } switch ($Reaction) { case Gdn_Authenticator::REACT_RENDER: break; case Gdn_Authenticator::REACT_EXIT: exit(); break; case Gdn_Authenticator::REACT_REMOTE: // Render the view, but set the delivery type to VIEW $this->_DeliveryType= DELIVERY_TYPE_VIEW; break; case Gdn_Authenticator::REACT_REDIRECT: default: // If we're just told to redirect, but not where... try to figure out somewhere that makes sense. if ($Reaction == Gdn_Authenticator::REACT_REDIRECT) { $Route = '/'; $Target = $this->Target(); if (!is_null($Target)) $Route = $Target; } else { $Route = $Reaction; } if ($this->_DeliveryType != DELIVERY_TYPE_ALL) { $this->RedirectUrl = Url($Route); } else { if ($Route !== FALSE) { Redirect($Route); } else { Redirect(Gdn::Router()->GetDestination('DefaultController')); } } break; } $this->Render(); } /** * Go to requested Target() or the default controller if none was set. * * @access public * @since 2.0.0 * * @return string URL. */ public function RedirectTo() { $Target = $this->Target(); return $Target == '' ? Gdn::Router()->GetDestination('DefaultController') : $Target; } /** * Set where to go after signin. * * @access public * @since 2.0.0 * * @param string $Target Where we're requested to go to. * @return string URL to actually go to (validated & safe). */ public function Target($Target = FALSE) { if ($Target === FALSE) { $Target = $this->Form->GetFormValue('Target', FALSE); if (!$Target) $Target = $this->Request->Get('Target', '/'); } // Make sure that the target is a valid url. if (!preg_match('`(^https?://)`', $Target)) { $Target = '/'.ltrim($Target, '/'); } else { $MyHostname = parse_url(Gdn::Request()->Domain(),PHP_URL_HOST); $TargetHostname = parse_url($Target, PHP_URL_HOST); // Only allow external redirects to trusted domains. $TrustedDomains = C('Garden.TrustedDomains', TRUE); if (is_array($TrustedDomains)) { // Add this domain to the trusted hosts. $TrustedDomains[] = $MyHostname; $Sender->EventArguments['TrustedDomains'] = &$TrustedDomains; $this->FireEvent('BeforeTargetReturn'); } if ($TrustedDomains === TRUE) { return $Target; } elseif (count($TrustedDomains) == 0) { // Only allow http redirects if they are to the same host name. if ($MyHostname != $TargetHostname) $Target = ''; } else { // Loop the trusted domains looking for a match $Match = FALSE; foreach ($TrustedDomains as $TrustedDomain) { if (StringEndsWith($TargetHostname, $TrustedDomain, TRUE)) $Match = TRUE; } if (!$Match) $Target = ''; } } return $Target; } }
gpl-2.0
zhenyue007/Decrypt-The-Stranger
src/com/zgsc/jmmsr/activity/NewFriendsMsgActivity.java
5477
/** * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved. * * 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. */ package com.zgsc.jmmsr.activity; import java.util.List; import android.app.Activity; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import com.easemob.chat.EMChatManager; import com.easemob.chat.EMGroupManager; import com.zgsc.jmmsr.R; import com.zgsc.jmmsr.Constant; import com.zgsc.jmmsr.DemoApplication; import com.zgsc.jmmsr.adapter.NewFriendsMsgAdapter; import com.zgsc.jmmsr.db.InviteMessgeDao; import com.zgsc.jmmsr.domain.InviteMessage; import com.zgsc.jmmsr.domain.InviteMessage.InviteMesageStatus; /** * 申请与通知 * */ public class NewFriendsMsgActivity extends BaseActivity { private ListView listView; private InviteMessgeDao messgeDao; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_friends_msg); messgeDao = new InviteMessgeDao(this); listView = (ListView) findViewById(R.id.list); InviteMessgeDao dao = new InviteMessgeDao(this); List<InviteMessage> msgs = dao.getMessagesList(); // 设置adapter NewFriendsMsgAdapter adapter = new NewFriendsMsgAdapter(this, 1, msgs); listView.setAdapter(adapter); DemoApplication.getInstance().getContactList() .get(Constant.NEW_FRIENDS_USERNAME).setUnreadMsgCount(0); } /* * 处理解密结果 */ public void onActivityResult(int requestCode, int resultCode, Intent intent) { // 当requestCode、resultCode同时为0,也就是处理特定的结果 if (requestCode == 122 && resultCode == 122) { Bundle res = intent.getExtras(); // 取出Bundle中的数据 String s = res.getString("challengeResult"); // 修改city文本框的内容 if (s.equals("finish")) { Toast.makeText(this, "挑战失败:(", Toast.LENGTH_SHORT).show(); refuseInvitation((InviteMessage) res.getSerializable("userMsg")); } else if (s.equals("exit")) { refuseInvitation((InviteMessage) res.getSerializable("userMsg")); } else if (s.equals("addFriend")) { Intent i = getIntent(); acceptInvitation((InviteMessage) res.getSerializable("userMsg")); } } } private void acceptInvitation(final InviteMessage msg) { final ProgressDialog pd = new ProgressDialog(this); pd.setMessage("正在同意..."); pd.setCanceledOnTouchOutside(false); pd.show(); new Thread(new Runnable() { public void run() { // 调用sdk的同意方法 try { if(msg.getGroupId() == null) //同意好友请求 EMChatManager.getInstance().acceptInvitation(msg.getFrom()); else //同意加群申请 EMGroupManager.getInstance().acceptApplication(msg.getFrom(), msg.getGroupId()); NewFriendsMsgActivity.this.runOnUiThread(new Runnable() { @Override public void run() { pd.dismiss(); msg.setStatus(InviteMesageStatus.AGREED); // 更新db ContentValues values = new ContentValues(); values.put(InviteMessgeDao.COLUMN_NAME_STATUS, msg.getStatus().ordinal()); messgeDao.updateMessage(msg.getId(), values); } }); } catch (final Exception e) { NewFriendsMsgActivity.this.runOnUiThread(new Runnable() { @Override public void run() { pd.dismiss(); Toast.makeText(NewFriendsMsgActivity.this, "同意失败: " + e.getMessage(), 1).show(); } }); } } }).start(); } private void refuseInvitation(final InviteMessage msg) { final ProgressDialog pd = new ProgressDialog(this); pd.setMessage("正在同意..."); pd.setCanceledOnTouchOutside(false); pd.show(); new Thread(new Runnable() { public void run() { // 调用sdk的同意方法 try { if(msg.getGroupId() == null) //拒绝好友请求 EMChatManager.getInstance().refuseInvitation(msg.getFrom()); else //同意加群申请 EMGroupManager.getInstance().acceptApplication(msg.getFrom(), msg.getGroupId()); NewFriendsMsgActivity.this.runOnUiThread(new Runnable() { @Override public void run() { pd.dismiss(); msg.setStatus(InviteMesageStatus.AGREED); // 更新db ContentValues values = new ContentValues(); values.put(InviteMessgeDao.COLUMN_NAME_STATUS, msg.getStatus().ordinal()); messgeDao.deleteMessage(msg.getFrom()); messgeDao.updateMessage(msg.getId(), values); } }); } catch (final Exception e) { NewFriendsMsgActivity.this.runOnUiThread(new Runnable() { @Override public void run() { pd.dismiss(); Toast.makeText(NewFriendsMsgActivity.this, "同意失败: " + e.getMessage(), 1).show(); } }); } } }).start(); } public void back(View view) { finish(); } }
gpl-2.0
denis-pahomov/skefi
wp-includes/js/tinymce/plugins/iespell/langs/en.js
261
// UK lang variables tinyMCE.addToLang('',{ iespell_desc : 'Запустить проверку орфографии', iespell_download : "ieSpell не обнаружен. Нажмите OK чтобы перейти к странице загрузки." });
gpl-2.0
mcgrath81/wordpress
wp-config.php
3160
<?php /** * The base configurations of the WordPress. * * This file has the following configurations: MySQL settings, Table Prefix, * Secret Keys, WordPress Language, and ABSPATH. You can find more information * by visiting {@link http://codex.wordpress.org/Editing_wp-config.php Editing * wp-config.php} Codex page. You can get the MySQL settings from your web host. * * This file is used by the wp-config.php creation script during the * installation. You don't have to use the web site, you can just copy this file * to "wp-config.php" and fill in the values. * * @package WordPress */ // ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define('DB_NAME', 'template'); /** MySQL database username */ define('DB_USER', 'root'); /** MySQL database password */ define('DB_PASSWORD', 'shearer9'); /** MySQL hostname */ define('DB_HOST', 'localhost'); /** Database Charset to use in creating database tables. */ define('DB_CHARSET', 'utf8'); /** The Database Collate type. Don't change this if in doubt. */ define('DB_COLLATE', ''); /**#@+ * Authentication Unique Keys and Salts. * * Change these to different unique phrases! * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service} * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again. * * @since 2.6.0 */ define('AUTH_KEY', 'put your unique phrase here'); define('SECURE_AUTH_KEY', 'put your unique phrase here'); define('LOGGED_IN_KEY', 'put your unique phrase here'); define('NONCE_KEY', 'put your unique phrase here'); define('AUTH_SALT', 'put your unique phrase here'); define('SECURE_AUTH_SALT', 'put your unique phrase here'); define('LOGGED_IN_SALT', 'put your unique phrase here'); define('NONCE_SALT', 'put your unique phrase here'); /**#@-*/ /** * WordPress Database Table prefix. * * You can have multiple installations in one database if you give each a unique * prefix. Only numbers, letters, and underscores please! */ $table_prefix = 'wp_'; /** * WordPress Localized Language, defaults to English. * * Change this to localize WordPress. A corresponding MO file for the chosen * language must be installed to wp-content/languages. For example, install * de_DE.mo to wp-content/languages and set WPLANG to 'de_DE' to enable German * language support. */ define('WPLANG', ''); /** * For developers: WordPress debugging mode. * * Change this to true to enable the display of notices during development. * It is strongly recommended that plugin and theme developers use WP_DEBUG * in their development environments. */ define('WP_DEBUG', false); /* That's all, stop editing! Happy blogging. */ /** Absolute path to the WordPress directory. */ if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); /** Sets up WordPress vars and included files. */ require_once(ABSPATH . 'wp-settings.php'); define('WP_HOME','http://localhost/template'); define('WP_SITEURL','http://localhost/template');
gpl-2.0