repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
bclementcsp/wiki
lib/plugin/PopUp.php
3229
<?php /** * Copyright 2004 Nicolas Noble <[email protected]> * Copyright 2009 Marc-Etienne Vargenau, Alcatel-Lucent * * This file is part of PhpWiki. * * PhpWiki 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. * * PhpWiki 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 PhpWiki; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /** * Display a page in a clickable popup link. * * Usage: * <<PopUp * link="HomePage" * title="PopUpped HomePage" * text="Click here to popup the HomePage" * width=300 * height=200 * resizable=no * scrollbars=no * toolbar=no * location=no * directories=no * status=no * menubar=no * copyhistory=no * >> * <<PopUp close=yes >> */ class WikiPlugin_PopUp extends WikiPlugin { function getDescription() { return _("Create a clickable popup link."); } function getDefaultArguments() { return array('link' => "HomePage", 'title' => "", 'text' => "", 'width' => "500", 'height' => "400", 'resizable' => "no", 'scrollbars' => "no", 'toolbar' => "no", 'location' => "no", 'directories' => "no", 'status' => "no", 'menubar' => "no", 'copyhistory' => "no", 'close' => "no", ); } /** * @param WikiDB $dbi * @param string $argstr * @param WikiRequest $request * @param string $basepage * @return mixed */ function run($dbi, $argstr, &$request, $basepage) { extract($this->getArgs($argstr, $request)); return HTML::a(array('href' => WikiURL($link), 'target' => "_blank", 'onclick' => ($close == "yes" ? "window.close()" : ("window.open('" . WikiURL($link) . "', '" . ($title == "" ? ($text == "" ? $link : $text) : $title) . "', '" . "width=$width," . "height=$height," . "resizable=$resizable," . "scrollbars=$scrollbars," . "toolbar=$toolbar," . "location=$location," . "directories=$directories," . "status=$status," . "menubar=$menubar," . "copyhistory=$copyhistory')" )) . ";return false;" ), ($text == "" ? ($close == "yes" ? "Close window" : $link) : $text) ); } } // Local Variables: // mode: php // tab-width: 8 // c-basic-offset: 4 // c-hanging-comment-ender-p: nil // indent-tabs-mode: nil // End:
gpl-2.0
sunenielsen/tribaltrouble
common/classes/com/oddlabs/matchmaking/MatchmakingServerLoginInterface.java
443
package com.oddlabs.matchmaking; import java.net.InetAddress; import java.security.SignedObject; public strictfp interface MatchmakingServerLoginInterface { public void setLocalRemoteAddress(InetAddress local_remote_address); public void login(Login login, SignedObject reg_key, int revision); public void loginAsGuest(int revision); public void createUser(Login login, LoginDetails login_details, SignedObject reg_key, int revision); }
gpl-2.0
dmmb/Instantcms-dev
core/lib_tags.php
8676
<?php /******************************************************************************/ // // // InstantCMS v1.8 // // http://www.instantcms.ru/ // // // // written by InstantCMS Team, 2007-2010 // // produced by InstantSoft, (www.instantsoft.ru) // // // // LICENSED BY GNU/GPL v2 // // // /******************************************************************************/ if(!defined('VALID_CMS')) { die('ACCESS DENIED'); } function cmsInsertTags($tagstr, $target, $item_id){ $inDB = cmsDatabase::getInstance(); $inDB->query("DELETE FROM cms_tags WHERE target='$target' AND item_id = $item_id"); if ($tagstr){ $tagstr = str_replace(', ', ',', $tagstr); $tagstr = str_replace(' ,', ',', $tagstr); $tags = explode(',', $tagstr); foreach ($tags as $key=>$tag){ if(strlen($tag)>1){ if (strlen($tag>15) && !(strstr($tag, ' ') || strstr($tag, '-'))) { $tag = substr($tag, 0, 15); } $tag = str_replace("\\", '', $tag); $tag = str_replace('"', '', $tag); $tag = str_replace("'", '', $tag); $tag = str_replace("&", '', $tag); $tag = strtolower($tag); $sql = "INSERT INTO cms_tags (tag, target, item_id) VALUES ('$tag', '$target', $item_id)"; $inDB->query($sql); } } } return; } function cmsClearTags($target, $item_id){ $inDB = cmsDatabase::getInstance(); $inDB->query("DELETE FROM cms_tags WHERE target='$target' AND item_id = $item_id"); return; } function cmsTagLine($target, $item_id, $links=true, $selected=''){ $inDB = cmsDatabase::getInstance(); $sql = "SELECT tag FROM cms_tags WHERE target='$target' AND item_id=$item_id ORDER BY tag DESC"; $rs = $inDB->query($sql) or die('Error while building tagline'); $html = ''; $tags = $inDB->num_rows($rs); if ($tags){ $t = 1; while ($tag=$inDB->fetch_assoc($rs)){ if ($links){ if ($selected==$tag['tag']){ $html .= '<a href="/search/tag/'.urlencode($tag['tag']).'" style="font-weight:bold;text-decoration:underline">'.$tag['tag'].'</a>'; } else { $html .= '<a href="/search/tag/'.urlencode($tag['tag']).'">'.$tag['tag'].'</a>'; } } else { $html .= $tag['tag']; } if ($t < $tags) { $html .= ', '; $t++; } } } else { $html = ''; } return $html; } function cmsTagBar($target, $item_id, $selected=''){ $inDB = cmsDatabase::getInstance(); if ($tagline = cmsTagLine($target, $item_id, true, $selected)){ return '<div class="taglinebar"><span class="label">Òåãè: </span><span class="tags">'.$tagline.'</span></div>'; } else { return ''; } } function cmsTagItemLink($target, $item_id){ $inDB = cmsDatabase::getInstance(); switch ($target){ case 'content': $sql = "SELECT i.title as title, c.title as cat, i.seolink as seolink, c.seolink as cat_seolink FROM cms_content i LEFT JOIN cms_category c ON c.id = i.category_id WHERE i.id = '$item_id' AND i.published = 1"; $rs = $inDB->query($sql) ; if ($inDB->num_rows($rs)){ $item = $inDB->fetch_assoc($rs); $link = '<a href="/'.$item['cat_seolink'].'" class="tag_searchcat">'.$item['cat'].'</a> &rarr; '; $link .= '<a href="/'.$item['seolink'].'.html" class="tag_searchitem">'.$item['title'].'</a>'; } break; case 'blogpost': $sql = "SELECT i.title as title, i.id as item_id, c.title as cat, c.id as cat_id, c.owner as owner, c.user_id user_id, i.seolink as seolink, c.seolink as bloglink FROM cms_blog_posts i LEFT JOIN cms_blogs c ON c.id = i.blog_id WHERE i.id = '$item_id'"; $rs = $inDB->query($sql) ; if ($inDB->num_rows($rs)){ $item = $inDB->fetch_assoc($rs); if ($item['owner'] == 'club') { $item['cat'] = dbGetField('cms_clubs','id='.$item['user_id'],'title'); } $link = '<a href="/blogs/'.$item['bloglink'].'" class="tag_searchcat">'.$item['cat'].'</a> &rarr; '; $link .= '<a href="/blogs/'.$item['bloglink'].'/'.$item['seolink'].'.html" class="tag_searchitem">'.$item['title'].'</a>'; } break; case 'photo': $sql = "SELECT i.title as title, i.id as item_id, c.title as cat, c.id as cat_id FROM cms_photo_files i LEFT JOIN cms_photo_albums c ON c.id = i.album_id WHERE i.id = '$item_id'"; $rs = $inDB->query($sql) ; if ($inDB->num_rows($rs)){ $item = $inDB->fetch_assoc($rs); $link = '<a href="/photos/'.$item['cat_id'].'" class="tag_searchcat">'.$item['cat'].'</a> &rarr; '; $link .= '<a href="/photos/photo'.$item['item_id'].'.html" class="tag_searchitem">'.$item['title'].'</a>'; } break; case 'userphoto': $sql = "SELECT i.title as title, i.id as item_id, c.nickname as cat, c.id as cat_id, c.login as login FROM cms_user_photos i LEFT JOIN cms_users c ON c.id = i.user_id WHERE i.id = '$item_id'"; $rs = $inDB->query($sql) ; if ($inDB->num_rows($rs)){ $item = $inDB->fetch_assoc($rs); $link = '<a href="'.cmsUser::getProfileURL($item['login']).'" class="tag_searchcat">'.$item['cat'].'</a> &rarr; '; $link .= '<a href="/users/'.$item['cat_id'].'/photo'.$item['item_id'].'.html" class="tag_searchitem">'.$item['title'].'</a>'; } break; case 'catalog': $sql = "SELECT i.title as title, i.id as item_id, c.title as cat, c.id as cat_id FROM cms_uc_items i LEFT JOIN cms_uc_cats c ON c.id = i.category_id WHERE i.id = '$item_id'"; $rs = $inDB->query($sql) ; if ($inDB->num_rows($rs)){ $item = $inDB->fetch_assoc($rs); $link = '<a href="/catalog/'.$item['cat_id'].'" class="tag_searchcat">'.$item['cat'].'</a> &rarr; '; $link .= '<a href="/catalog/item'.$item['item_id'].'.html" class="tag_searchitem">'.$item['title'].'</a>'; } break; case 'video': $sql = "SELECT i.title as title, i.id as item_id, c.title as cat, c.id as cat_id FROM cms_video_movie i LEFT JOIN cms_video_category c ON c.id = i.cat_id WHERE i.id = '$item_id'"; $rs = $inDB->query($sql) ; if ($inDB->num_rows($rs)){ $item = $inDB->fetch_assoc($rs); $link = '<a href="/video/'.$item['cat_id'].'" class="tag_searchcat">'.$item['cat'].'</a> &rarr; '; $link .= '<a href="/video/movie'.$item['item_id'].'.html" class="tag_searchitem">'.$item['title'].'</a>'; } break; case 'shop': $sql = "SELECT i.title as title, i.seolink as seolink, c.title as cat, c.seolink as cat_seolink FROM cms_shop_items i LEFT JOIN cms_shop_cats c ON c.id = i.category_id WHERE i.id = '$item_id'"; $rs = $inDB->query($sql) ; if ($inDB->num_rows($rs)){ $item = $inDB->fetch_assoc($rs); $link = '<a href="/shop/'.$item['cat_seolink'].'" class="tag_searchcat">'.$item['cat'].'</a> &rarr; '; $link .= '<a href="/shop/'.$item['seolink'].'.html" class="tag_searchitem">'.$item['title'].'</a>'; } break; case 'maps': $sql = "SELECT i.title as title, i.seolink as seolink, c.title as cat, c.seolink as cat_seolink FROM cms_maps_items i LEFT JOIN cms_maps_cats c ON c.id = i.category_id WHERE i.id = '$item_id'"; $rs = $inDB->query($sql) ; if ($inDB->num_rows($rs)){ $item = $inDB->fetch_assoc($rs); $link = '<a href="/maps/'.$item['cat_seolink'].'" class="tag_searchcat">'.$item['cat'].'</a> &rarr; '; $link .= '<a href="/maps/'.$item['seolink'].'.html" class="tag_searchitem">'.$item['title'].'</a>'; } break; } return $link; } function cmsTagsList(){ $inDB = cmsDatabase::getInstance(); $html = ''; $sql = "SELECT t.tag, COUNT(t.tag) as num FROM cms_tags t GROUP BY t.tag ORDER BY t.tag"; $result = $inDB->query($sql) ; if ($inDB->num_rows($result)>0){ while($tag = $inDB->fetch_assoc($result)){ if ($tag['tag']){ $html .= '<a href="/search/tag/'.urlencode($tag['tag']).'">'.$tag['tag'].'</a> ('.$tag['num'].') '; } } } return $html; } ?>
gpl-2.0
wirecard/shopware-wcs
Frontend/QentaCheckoutSeamless/Components/QentaCEE/QMore/Exception/ExceptionInterface.php
1717
<?php /** * Shop System Plugins - Terms of Use * * The plugins offered are provided free of charge by Qenta Payment CEE GmbH * (abbreviated to Qenta CEE) and are explicitly not part of the Qenta CEE range of * products and services. * * They have been tested and approved for full functionality in the standard configuration * (status on delivery) of the corresponding shop system. They are under General Public * License Version 2 (GPLv2) and can be used, developed and passed on to third parties under * the same terms. * * However, Qenta CEE does not provide any guarantee or accept any liability for any errors * occurring when used in an enhanced, customized shop system configuration. * * Operation in an enhanced, customized configuration is at your own risk and requires a * comprehensive test phase by the user of the plugin. * * Customers use the plugins at their own risk. Qenta CEE does not guarantee their full * functionality neither does Qenta CEE assume liability for any disadvantages related to * the use of the plugins. Additionally, Qenta CEE does not guarantee the full functionality * for customized shop systems or installed plugins of other vendors of plugins within the same * shop system. * * Customers are responsible for testing the plugin's functionality before starting productive * operation. * * By installing the plugin into the shop system the customer agrees to these terms of use. * Please do not use the plugin if you do not agree to these terms of use! */ /** * @name QentaCEE_QMore_Exception_ExceptionInterface * @category QentaCEE * @package QentaCEE_QMore * @subpackage Exception */ interface QentaCEE_QMore_Exception_ExceptionInterface { }
gpl-2.0
cyberpython/java-gnome
generated/bindings/org/gnome/atk/AtkTextRectangle.java
5269
/* * java-gnome, a UI library for writing GTK and GNOME programs from Java! * * Copyright © 2006-2011 Operational Dynamics Consulting, Pty Ltd and Others * * The code in this file, and the program it is a part of, is made available * to you by its authors as open source software: you can redistribute it * and/or modify it under the terms of the GNU General Public License version * 2 ("GPL") 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 GPL for more details. * * You should have received a copy of the GPL along with this program. If not, * see http://www.gnu.org/licenses/. The authors of this program may be * contacted through http://java-gnome.sourceforge.net/. * * Linking this library statically or dynamically with other modules is making * a combined work based on this library. Thus, the terms and conditions of * the GPL cover the whole combination. As a special exception (the * "Claspath Exception"), the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent modules, * and to copy and distribute the resulting executable under terms of your * choice, provided that you also meet, for each linked independent module, * the terms and conditions of the license of that module. An independent * module is a module which is not derived from or based on this library. If * you modify this library, you may extend the Classpath Exception to your * version of the library, but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. */ package org.gnome.atk; /* * THIS FILE IS GENERATED CODE! * * To modify its contents or behaviour, either update the generation program, * change the information in the source defs file, or implement an override for * this class. */ import org.gnome.atk.Plumbing; final class AtkTextRectangle extends Plumbing { private AtkTextRectangle() {} static final int getX(TextRectangle self) { int result; if (self == null) { throw new IllegalArgumentException("self can't be null"); } synchronized (lock) { result = atk_text_rectangle_get_x(pointerOf(self)); return result; } } private static native final int atk_text_rectangle_get_x(long self); static final void setX(TextRectangle self, int x) { if (self == null) { throw new IllegalArgumentException("self can't be null"); } synchronized (lock) { atk_text_rectangle_set_x(pointerOf(self), x); } } private static native final void atk_text_rectangle_set_x(long self, int x); static final int getY(TextRectangle self) { int result; if (self == null) { throw new IllegalArgumentException("self can't be null"); } synchronized (lock) { result = atk_text_rectangle_get_y(pointerOf(self)); return result; } } private static native final int atk_text_rectangle_get_y(long self); static final void setY(TextRectangle self, int y) { if (self == null) { throw new IllegalArgumentException("self can't be null"); } synchronized (lock) { atk_text_rectangle_set_y(pointerOf(self), y); } } private static native final void atk_text_rectangle_set_y(long self, int y); static final int getWidth(TextRectangle self) { int result; if (self == null) { throw new IllegalArgumentException("self can't be null"); } synchronized (lock) { result = atk_text_rectangle_get_width(pointerOf(self)); return result; } } private static native final int atk_text_rectangle_get_width(long self); static final void setWidth(TextRectangle self, int width) { if (self == null) { throw new IllegalArgumentException("self can't be null"); } synchronized (lock) { atk_text_rectangle_set_width(pointerOf(self), width); } } private static native final void atk_text_rectangle_set_width(long self, int width); static final int getHeight(TextRectangle self) { int result; if (self == null) { throw new IllegalArgumentException("self can't be null"); } synchronized (lock) { result = atk_text_rectangle_get_height(pointerOf(self)); return result; } } private static native final int atk_text_rectangle_get_height(long self); static final void setHeight(TextRectangle self, int height) { if (self == null) { throw new IllegalArgumentException("self can't be null"); } synchronized (lock) { atk_text_rectangle_set_height(pointerOf(self), height); } } private static native final void atk_text_rectangle_set_height(long self, int height); }
gpl-2.0
mekku93/sxl-interpreter-repl
src/com/miguel/sxl/ASTEqualTo.java
658
/* Generated By:JJTree: Do not edit this line. ASTEqualTo.java Version 4.3 */ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=true,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ package com.miguel.sxl; public class ASTEqualTo extends SXLNode { public ASTEqualTo(int id) { super(id); } public ASTEqualTo(SXLParser p, int id) { super(p, id); } /** Accept the visitor. **/ public Object jjtAccept(SXLParserVisitor visitor, Object data) { return visitor.visit(this, data); } } /* JavaCC - OriginalChecksum=cd9bd6b0b4e69a40687a0ec70546edee (do not edit this line) */
gpl-2.0
centreon/centreon-engine
test/commands/result_compare.cc
2106
/* ** Copyright 2011-2013 Merethis ** ** This file is part of Centreon Engine. ** ** Centreon Engine 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. ** ** Centreon Engine 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 Centreon Engine. If not, see ** <http://www.gnu.org/licenses/>. */ #include <cstdlib> #include <exception> #include "com/centreon/engine/commands/result.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/process.hh" #include "com/centreon/timestamp.hh" #include "test/unittest.hh" using namespace com::centreon; using namespace com::centreon::engine; using namespace com::centreon::engine::commands; #define DEFAULT_ID 42 #define DEFAULT_OUTPUT "output string test" #define DEFAULT_RETURN 0 #define DEFAULT_STATUS process::normal /** * Check the comparison operator. * * @param[in] argc Argument count. * @param[in] argv Argument values. * * @return EXIT_SUCCESS on success. */ int main_test(int argc, char** argv) { (void)argc; (void)argv; // Prepare. timestamp now(timestamp::now()); result res; res.command_id = DEFAULT_ID; res.output = DEFAULT_OUTPUT; res.start_time = now; res.end_time = now; res.exit_code = DEFAULT_RETURN; res.exit_status = DEFAULT_STATUS; // Tests. if (!(res == res)) throw(engine_error() << "error: operator== failed"); if (res != res) throw(engine_error() << "error: operator!= failed"); return (EXIT_SUCCESS); } /** * Init unit test. * * @param[in] argc Argument count. * @param[in] argv Argument values. * * @return Return value of main_test(). * * @see main_test */ int main(int argc, char* argv[]) { unittest utest(argc, argv, &main_test); return (utest.run()); }
gpl-2.0
timofeev-denis/trans-mobil
modules/mod_superfish_menu/js/superfish.js
7135
/* * jQuery Superfish Menu Plugin - v1.7.4 * Copyright (c) 2013 Joel Birch * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ ;(function ($) { "use strict"; var methods = (function () { // private properties and methods go here var c = { bcClass: 'sf-breadcrumb', menuClass: 'sf-js-enabled', anchorClass: 'sf-with-ul', menuArrowClass: 'sf-arrows' }, ios = (function () { var ios = /iPhone|iPad|iPod/i.test(navigator.userAgent); if (ios) { // iOS clicks only bubble as far as body children $(window).load(function () { $('body').children().on('click', $.noop); }); } return ios; })(), wp7 = (function () { var style = document.documentElement.style; return ('behavior' in style && 'fill' in style && /iemobile/i.test(navigator.userAgent)); })(), toggleMenuClasses = function ($menu, o) { var classes = c.menuClass; if (o.cssArrows) { classes += ' ' + c.menuArrowClass; } $menu.toggleClass(classes); }, setPathToCurrent = function ($menu, o) { return $menu.find('li.' + o.pathClass).slice(0, o.pathLevels) .addClass(o.hoverClass + ' ' + c.bcClass) .filter(function () { return ($(this).children('.sfHolder').children(o.popUpSelector).hide().show().length); }).removeClass(o.pathClass); }, toggleAnchorClass = function ($li) { $li.children('.sfHolder').children('a').toggleClass(c.anchorClass); }, toggleTouchAction = function ($menu) { var touchAction = $menu.css('ms-touch-action'); touchAction = (touchAction === 'pan-y') ? 'auto' : 'pan-y'; $menu.css('ms-touch-action', touchAction); }, applyHandlers = function ($menu, o) { var targets = 'li:has(' + o.popUpSelector + ')'; if ($.fn.hoverIntent && !o.disableHI) { $menu.hoverIntent(over, out, targets); } else { $menu .on('mouseenter.superfish', targets, over) .on('mouseleave.superfish', targets, out); } var touchevent = 'MSPointerDown.superfish'; if (!ios) { touchevent += ' touchend.superfish'; } if (wp7) { touchevent += ' mousedown.superfish'; } $menu .on('focusin.superfish', 'li', over) .on('focusout.superfish', 'li', out) .on(touchevent, 'a', o, touchHandler); }, touchHandler = function (e) { var $this = $(this), $ul = $this.siblings(e.data.popUpSelector); if ($ul.length > 0 && $ul.is(':hidden')) { $this.one('click.superfish', false); if (e.type === 'MSPointerDown') { $this.trigger('focus'); } else { $.proxy(over, $this.parent('li'))(); } } }, over = function () { var $this = $(this), o = getOptions($this); clearTimeout(o.sfTimer); $this.siblings().superfish('hide').end().superfish('show'); }, out = function () { var $this = $(this), o = getOptions($this); if (ios) { $.proxy(close, $this, o)(); } else { clearTimeout(o.sfTimer); o.sfTimer = setTimeout($.proxy(close, $this, o), o.delay); } }, close = function (o) { o.retainPath = ($.inArray(this[0], o.$path) > -1); this.superfish('hide'); if (!this.parents('.' + o.hoverClass).length) { o.onIdle.call(getMenu(this)); if (o.$path.length) { $.proxy(over, o.$path)(); } } }, getMenu = function ($el) { return $el.closest('.' + c.menuClass); }, getOptions = function ($el) { return getMenu($el).data('sf-options'); }; return { // public methods hide: function (instant) { if (this.length) { var $this = this, o = getOptions($this); if (!o) { return this; } var not = (o.retainPath === true) ? o.$path : '', $ul = $this.find('li.' + o.hoverClass).add(this).not(not).removeClass(o.hoverClass).children('.sfHolder').children(o.popUpSelector), speed = o.speedOut; if (instant) { $ul.show(); speed = 0; } o.retainPath = false; o.onBeforeHide.call($ul); $ul.stop(true, true).animate(o.animationOut, speed, function () { var $this = $(this); o.onHide.call($this); }); } return this; }, show: function () { var o = getOptions(this); if (!o) { return this; } var $this = this.addClass(o.hoverClass), $ul = $this.children('.sfHolder').children(o.popUpSelector); o.onBeforeShow.call($ul); $ul.stop(true, true).animate(o.animation, o.speed, function () { o.onShow.call($ul); }); return this; }, destroy: function () { return this.each(function () { var $this = $(this), o = $this.data('sf-options'), $hasPopUp; if (!o) { return false; } $hasPopUp = $this.find(o.popUpSelector).parent('.sfHolder').parent('li'); clearTimeout(o.sfTimer); toggleMenuClasses($this, o); toggleAnchorClass($hasPopUp); toggleTouchAction($this); // remove event handlers $this.off('.superfish').off('.hoverIntent'); // clear animation's inline display style $hasPopUp.children('.sfHolder').children(o.popUpSelector).attr('style', function (i, style) { return style.replace(/display[^;]+;?/g, ''); }); // reset 'current' path classes o.$path.removeClass(o.hoverClass + ' ' + c.bcClass).addClass(o.pathClass); $this.find('.' + o.hoverClass).removeClass(o.hoverClass); o.onDestroy.call($this); $this.removeData('sf-options'); }); }, init: function (op) { return this.each(function () { var $this = $(this); if ($this.data('sf-options')) { return false; } var o = $.extend({}, $.fn.superfish.defaults, op), $hasPopUp = $this.find(o.popUpSelector).parent('.sfHolder').parent('li'); o.$path = setPathToCurrent($this, o); $this.data('sf-options', o); toggleMenuClasses($this, o); toggleAnchorClass($hasPopUp); toggleTouchAction($this); applyHandlers($this, o); $hasPopUp.not('.' + c.bcClass).superfish('hide', true); o.onInit.call(this); }); } }; })(); $.fn.superfish = function (method, args) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || ! method) { return methods.init.apply(this, arguments); } else { return $.error('Method ' + method + ' does not exist on jQuery.fn.superfish'); } }; $.fn.superfish.defaults = { popUpSelector: 'ul,.sf-mega', // within menu context hoverClass: 'sfHover', pathClass: 'overrideThisToUse', pathLevels: 1, delay: 800, animation: {opacity: 'show'}, animationOut: {opacity: 'hide'}, speed: 'normal', speedOut: 'fast', cssArrows: true, disableHI: false, onInit: $.noop, onBeforeShow: $.noop, onShow: $.noop, onBeforeHide: $.noop, onHide: $.noop, onIdle: $.noop, onDestroy: $.noop }; // soon to be deprecated $.fn.extend({ hideSuperfishUl: methods.hide, showSuperfishUl: methods.show }); })(jQuery);
gpl-2.0
cpesch/MetaMusic
retrieval-tools/src/main/java/slash/metamusic/freedb/CDDBEntry.java
5901
/* You may freely copy, distribute, modify and use this class as long as the original author attribution remains intact. See message below. Copyright (C) 2004 Christian Pesch. All Rights Reserved. */ /* * --------------------------------------------------------- * Antelmann.com Java Framework by Holger Antelmann * Copyright (c) 2002 Holger Antelmann <[email protected]> * For details, see also http://www.antelmann.com/developer/ * --------------------------------------------------------- */ package slash.metamusic.freedb; import slash.metamusic.discid.DiscId; import slash.metamusic.mp3.ID3Genre; import java.io.IOException; import java.text.ParseException; /** * CDDBEntry represents an entry for a CD in a CDDB database * that contains all known properties about the associated CD. * <p/> * CDDBEntry also contains methods to generate Artist and Composition * objects to bridge from a CDDB database to a more sophisticated internal * CD database. * * @author Christian Pesch based on work from Holger Antelmann * @version $Id: CDDBEntry.java 714 2005-08-22 18:40:22Z cpesch $ * @see CDDBXmcdParser, CDDBRecord */ public class CDDBEntry { private CDDBXmcdParser parser; private CDDBRecord record; /** * The fileContent must be in xmcd format specified by CDDB and must contain * the disc id from the record. * * @throws ParseException if the fileContent is not in valid xmcd format * or inconsistent with the given record */ public CDDBEntry(CDDBRecord record, String fileContent) throws ParseException { this.record = record; parser = new CDDBXmcdParser(fileContent); String[] ids = parser.readDiscIds(); for (int i = 0; i < ids.length; i++) { if (ids[i].equals(record.getDiscId())) return; } throw new ParseException("disc id in record not found in file content", -1); } CDDBXmcdParser getParser() { return parser; } String getXmcdContent() { return parser.getContent(); } public CDDBRecord getCDDBRecord() { return record; } /** * From the given set of entries, find the most specific entry. * This is an entry, which is not part of the misc category. * If the only entry is of the misc category, it is returned. * * @param entries the set of entries to find the most specific one * @return the most specific entry, i.e. that is an entry, which * is not part of the misc category. */ public static CDDBEntry findMostSpecificEntry(CDDBEntry[] entries) { int categoryIndex = 0; for (int i = 0; i < entries.length; i++) { CDDBEntry entry = entries[i]; if (entry != null) { String category = entry.getCDDBRecord().getCategory(); if (!"misc".equals(category) && !"data".equals(category)) categoryIndex = i; } } return entries[categoryIndex]; } /** * Create <code>CDDBEntry</code>s from the given <code>DiscId</code> * by querying the FreeDB data base * * @param discId the <code>DiscId</code> to query the FreeDB data base * @return the queried <code>CDDBEntry</code>s * @throws IOException if an access error occurs * and the request cannot be processed */ public static CDDBEntry[] fetchCDDBEntries(DiscId discId) throws IOException { FreeDBClient client = new FreeDBClient(); CDDBRecord[] records = client.queryDiscId(discId); FreeDBClient.log.info("Found " + records.length + " matches for disc id " + discId); CDDBEntry[] entries = new CDDBEntry[records.length]; for (int i = 0; i < records.length; i++) { try { entries[i] = client.readCDInfo(records[i]); } catch (IOException e) { FreeDBClient.log.severe("Cannot read CD info for record " + records[i] + ": " + e.getMessage()); } } return entries; } public String getArtist() { return parser.readCDArtist(); } public String getAlbum() { return parser.readCDAlbum(); } public int getYear() { int year = parser.readYear(); if (year == -1) year = parser.readExtdYear(); return year; } /** * Read the genre from an ID3G extension or from the DGENRE attribute. * * @return the genre from an ID3G extension or from the DGENRE attribute */ public ID3Genre getID3Genre() { int genreId = parser.readExtdGenre(); if (genreId == -1) { Integer id = ID3Genre.getGenreId(parser.readGenre()); if (id == null) id = ID3Genre.getGenreId(record.getCategory()); if (id != null) genreId = id; } return new ID3Genre(genreId); } public int getTrackCount() { return parser.readNumberOfTracks(); } public String getTrackArtist(int trackNumber) { return parser.readTrackArtist(trackNumber); } public String getTrackAlbum(int trackNumber) { return parser.readTrackAlbum(trackNumber); } public String getSubmitter() { return parser.readSubmitter(); } public int[] getOffsets() { return parser.readOffsets(); } public int getLength() { return parser.readLength(); } public long getBitRate() { return 144000 * 8; } public long getSampleFrequency() { return 44100; } public String toString() { return super.toString() + "[" + "record=" + getCDDBRecord() + ", parser=" + getParser() + ", content=" + getXmcdContent() + "]"; } }
gpl-2.0
adamfisk/littleshoot-client
common/bencode/src/test/java/org/lastbamboo/common/bencode/BDecoderTest.java
2864
package org.lastbamboo.common.bencode; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import org.junit.Test; import org.lastbamboo.common.bencode.composite.DictionaryValue; import org.lastbamboo.common.bencode.composite.EntryValue; import org.lastbamboo.common.bencode.composite.ListValue; import org.lastbamboo.common.bencode.primitive.IntegerValue; import org.lastbamboo.common.bencode.primitive.StringValue; public class BDecoderTest { @Test public void testFailedTorrent() throws Exception { } @Test public void testBDecoder() throws Exception { final Parser parser = new Parser(); final ByteArrayInputStream is = new ByteArrayInputStream( "ld5:Helloi5e5:World7:Testing4:Fivei4ee10:Test Valueli123ei456ei7890eee" .getBytes()); final ListValue root = (ListValue) parser.parse(is); for (final Value<?> value : root) { if (value instanceof DictionaryValue) { final DictionaryValue dict = (DictionaryValue) value; System.out.println('{'); for (EntryValue pair : dict) { System.out.print(" \"" + new String(pair.getKey().resolve()) + "\" -> "); if (pair.getValue() instanceof IntegerValue) { System.out.println(pair.getValue().resolve().toString()); } else if (pair.getValue() instanceof StringValue) { System.out.println('"' + new String( ((StringValue) pair.getValue()) .resolve()) + '"'); } else { fail("Unrecognized type"); } } System.out.println('}'); } else if (value instanceof StringValue) { System.out.println(new String(((StringValue) value) .resolve())); } else if (value instanceof ListValue) { System.out.println("["); for (Value<?> subValue : (ListValue) value) { System.out.println(" " + subValue.resolve().toString()); } System.out.println("]"); } else { fail("Unrecognized type"); } } } }
gpl-2.0
smartwifi/stores-rd
rd/app/view/nas/frmNasBasic.js
16967
Ext.define('Rd.view.nas.frmNasBasic', { extend: 'Ext.form.Panel', alias : 'widget.frmNasBasic', border: false, layout: 'fit', autoScroll:true, fieldDefaults: { msgTarget: 'under', labelClsExtra: 'lblRd', labelAlign: 'left', labelSeparator: '', labelWidth: 200, margin: 15 }, buttons: [ { itemId : 'save', text : i18n('sOK'), scale : 'large', iconCls : 'b-btn_ok', glyph: Rd.config.icnYes, formBind: true, margin : '0 20 40 0' } ], defaultType: 'textfield', marginSize: 5, initComponent: function() { var monitor_types = Ext.create('Ext.data.Store', { fields: ['id', 'text'], data : [ {"id":"off", "text": i18n("sOff")}, {"id":"ping", "text": i18n("sPing")}, {"id":"heartbeat", "text": i18n("sHeartbeat")} ] }); // Create the combo box, attached to the states data store var cmbMt = Ext.create('Ext.form.ComboBox', { fieldLabel : i18n('sMonitor_method'), store : monitor_types , itemId : 'monitorType', name : 'monitor', queryMode : 'local', displayField : 'text', valueField : 'id' }); var me = this; me.items = [ { xtype : 'tabpanel', layout : 'fit', xtype : 'tabpanel', margins : '0 0 0 0', plain : true, tabPosition: 'bottom', border : true, items : [ { 'title' : i18n('sRequired_info'), 'layout' : 'anchor', defaults : { anchor : '100%' }, items: [ { itemId : 'nasname', xtype : 'textfield', fieldLabel : i18n('sIP_Address'), name : "nasname", allowBlank : false, blankText : i18n("sSupply_a_value"), labelClsExtra: 'lblRdReq' }, { xtype : 'textfield', fieldLabel : i18n('sName'), name : "shortname", allowBlank : false, blankText : i18n('sSupply_a_value'), labelClsExtra: 'lblRdReq' }, { xtype : 'textfield', fieldLabel : i18n('sSecret'), name : "secret", allowBlank : false, blankText : i18n('sSupply_a_value'), labelClsExtra: 'lblRdReq' } ] }, { 'title' : i18n('sOptional_Info'), 'layout' : 'anchor', defaults : { anchor : '100%' }, items: [ { itemId : 'type', xtype : 'textfield', fieldLabel : i18n('sType'), name : "type", labelClsExtra: 'lblRd' }, { xtype : 'textfield', fieldLabel : i18n('sPorts'), name : "ports", labelClsExtra: 'lblRd' }, { xtype : 'textfield', fieldLabel : i18n('sCommunity'), name : "community", labelClsExtra: 'lblRd' }, { xtype : 'textfield', fieldLabel : i18n('sServer'), name : "server", labelClsExtra: 'lblRd' }, { xtype : 'textareafield', grow : true, name : 'description', fieldLabel : i18n('sDescription'), anchor : '100%', labelClsExtra: 'lblRd' } ] }, { 'title' : i18n('sMonitor_settings'), 'layout' : 'anchor', defaults : { anchor : '100%' }, items: [ cmbMt, { xtype: 'numberfield', anchor: '100%', name: 'heartbeat_dead_after', itemId: 'heartbeat_dead_after', fieldLabel: i18n('sHeartbeat_is_dead_after'), value: 300, maxValue: 21600, minValue: 300, hidden: true }, { xtype: 'numberfield', anchor: '100%', name: 'ping_interval', itemId: 'ping_interval', fieldLabel: i18n('sPing_interval'), value: 300, maxValue: 21600, minValue: 300, hidden: true } ] }, { 'title' : i18n('sMaps_info'), 'layout' : 'anchor', defaults : { anchor : '100%' }, items: [ { xtype : 'textfield', fieldLabel : i18n('sLongitude'), name : "lon", labelClsExtra: 'lblRd' }, { xtype : 'textfield', fieldLabel : i18n('sLatitude'), name : "lat", labelClsExtra: 'lblRd' }, { xtype : 'checkbox', boxLabel : i18n('sDispaly_on_public_maps'), name : 'on_public_maps', inputValue : 'on_public_maps', checked : false, boxLabelCls : 'lblRdCheck', margin: me.marginSize } ] }, { 'title' : i18n('sEnhancements'), 'layout' : 'anchor', defaults : { anchor : '100%' }, items: [ { xtype : 'checkbox', boxLabel : i18n('sRecord_authentication_requests'), name : 'record_auth', inputValue : 'record_auth', checked : false, boxLabelCls : 'lblRdCheck', margin: me.marginSize }, { xtype : 'checkbox', boxLabel : i18n('sAuto_close_stale_sessions'), name : 'session_auto_close', inputValue : 'session_auto_close', checked : false, boxLabelCls : 'lblRdCheck', margin: me.marginSize }, { xtype: 'numberfield', anchor: '100%', name: 'session_dead_time', fieldLabel: i18n('sAuto_close_activation_time'), value: 300, maxValue: 21600, minValue: 300, hidden: false } ] } ] } ]; /* { xtype:'fieldset', title: i18n('sRequired_info'), collapsible: false, border: true, collapsed: false, margin: me.marginSize, defaults: { anchor: '100%' }, items: [ { itemId : 'nasname', xtype : 'textfield', fieldLabel : i18n('sIP_Address'), name : "nasname", allowBlank : false, blankText : i18n("sSupply_a_value"), labelClsExtra: 'lblRdReq' }, { xtype : 'textfield', fieldLabel : i18n('sName'), name : "shortname", allowBlank : false, blankText : i18n('sSupply_a_value'), labelClsExtra: 'lblRdReq' }, { xtype : 'textfield', fieldLabel : i18n('sSecret'), name : "secret", allowBlank : false, blankText : i18n('sSupply_a_value'), labelClsExtra: 'lblRdReq' } ] }, { xtype:'fieldset', title: i18n('sOptional_Info'), collapsible: false, border: true, margin: me.marginSize, collapsed: false, defaults: { anchor: '100%' }, items: [ { itemId : 'type', xtype : 'textfield', fieldLabel : i18n('sType'), name : "type", labelClsExtra: 'lblRd' }, { xtype : 'textfield', fieldLabel : i18n('sPorts'), name : "ports", labelClsExtra: 'lblRd' }, { xtype : 'textfield', fieldLabel : i18n('sCommunity'), name : "community", labelClsExtra: 'lblRd' }, { xtype : 'textfield', fieldLabel : i18n('sServer'), name : "server", labelClsExtra: 'lblRd' }, { xtype : 'textareafield', grow : true, name : 'description', fieldLabel : i18n('sDescription'), anchor : '100%', labelClsExtra: 'lblRd' } ] }, { xtype:'fieldset', title: i18n('sMonitor_settings'), collapsible: false, border: true, margin: me.marginSize, collapsed: false, defaults: { anchor: '100%' }, items: [ cmbMt, { xtype: 'numberfield', anchor: '100%', name: 'heartbeat_dead_after', itemId: 'heartbeat_dead_after', fieldLabel: i18n('sHeartbeat_is_dead_after'), value: 300, maxValue: 21600, minValue: 300, hidden: true }, { xtype: 'numberfield', anchor: '100%', name: 'ping_interval', itemId: 'ping_interval', fieldLabel: i18n('sPing_interval'), value: 300, maxValue: 21600, minValue: 300, hidden: true } ] }, { xtype:'fieldset', title: i18n('sMaps_info'), collapsible: false, border: true, margin: me.marginSize, collapsed: false, defaults: { anchor: '100%' }, items: [ { xtype : 'textfield', fieldLabel : i18n('sLongitude'), name : "lon", labelClsExtra: 'lblRd' }, { xtype : 'textfield', fieldLabel : i18n('sLatitude'), name : "lat", labelClsExtra: 'lblRd' }, { xtype : 'checkbox', boxLabel : i18n('sDispaly_on_public_maps'), name : 'on_public_maps', inputValue : 'on_public_maps', checked : false, boxLabelCls : 'lblRd', margin: me.marginSize } ] }, { xtype:'fieldset', title: i18n('sEnhancements'), collapsible: false, border: true, margin: me.marginSize, collapsed: false, defaults: { anchor: '100%' }, items: [ { xtype : 'checkbox', boxLabel : i18n('sRecord_authentication_requests'), name : 'record_auth', inputValue : 'record_auth', checked : false, boxLabelCls : 'lblRd', margin: me.marginSize, }, { xtype : 'checkbox', boxLabel : i18n('sAuto_close_stale_sessions'), name : 'session_auto_close', inputValue : 'session_auto_close', checked : false, boxLabelCls : 'lblRd', margin: me.marginSize, }, { xtype: 'numberfield', anchor: '100%', name: 'session_dead_time', fieldLabel: i18n('sAuto_close_activation_time'), value: 300, maxValue: 21600, minValue: 300, hidden: false } ] } ]; */ this.callParent(arguments); } });
gpl-2.0
george5613/libertv
libtorrent.svn/src/http_connection.cpp
10218
/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include "libtorrent/http_connection.hpp" #include <boost/bind.hpp> #include <boost/lexical_cast.hpp> #include <asio/ip/tcp.hpp> #include <string> using boost::bind; namespace libtorrent { void http_connection::get(std::string const& url, time_duration timeout , bool handle_redirect) { m_redirect = handle_redirect; std::string protocol; std::string auth; std::string hostname; std::string path; int port; boost::tie(protocol, auth, hostname, port, path) = parse_url_components(url); std::stringstream headers; headers << "GET " << path << " HTTP/1.0\r\n" "Host:" << hostname << "\r\nConnection: close\r\n"; if (!auth.empty()) headers << "Authorization: Basic " << base64encode(auth) << "\r\n"; headers << "\r\n"; sendbuffer = headers.str(); start(hostname, boost::lexical_cast<std::string>(port), timeout); } void http_connection::start(std::string const& hostname, std::string const& port , time_duration timeout, bool handle_redirect) { m_redirect = handle_redirect; m_timeout = timeout; m_timer.expires_from_now(m_timeout); m_timer.async_wait(bind(&http_connection::on_timeout , boost::weak_ptr<http_connection>(shared_from_this()), _1)); m_called = false; if (m_sock.is_open() && m_hostname == hostname && m_port == port) { m_parser.reset(); asio::async_write(m_sock, asio::buffer(sendbuffer) , bind(&http_connection::on_write, shared_from_this(), _1)); } else { m_sock.close(); tcp::resolver::query query(hostname, port); m_resolver.async_resolve(query, bind(&http_connection::on_resolve , shared_from_this(), _1, _2)); m_hostname = hostname; m_port = port; } } void http_connection::on_connect_timeout() { if (m_connection_ticket > -1) m_cc.done(m_connection_ticket); m_connection_ticket = -1; if (m_bottled && m_called) return; m_called = true; m_handler(asio::error::timed_out, m_parser, 0, 0); close(); } void http_connection::on_timeout(boost::weak_ptr<http_connection> p , asio::error_code const& e) { boost::shared_ptr<http_connection> c = p.lock(); if (!c) return; if (c->m_connection_ticket > -1) c->m_cc.done(c->m_connection_ticket); c->m_connection_ticket = -1; if (e == asio::error::operation_aborted) return; if (c->m_bottled && c->m_called) return; if (c->m_last_receive + c->m_timeout < time_now()) { c->m_called = true; c->m_handler(asio::error::timed_out, c->m_parser, 0, 0); return; } c->m_timer.expires_at(c->m_last_receive + c->m_timeout); c->m_timer.async_wait(bind(&http_connection::on_timeout, p, _1)); } void http_connection::close() { m_timer.cancel(); m_limiter_timer.cancel(); m_sock.close(); m_hostname.clear(); m_port.clear(); if (m_connection_ticket > -1) m_cc.done(m_connection_ticket); m_connection_ticket = -1; } void http_connection::on_resolve(asio::error_code const& e , tcp::resolver::iterator i) { if (e) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); return; } assert(i != tcp::resolver::iterator()); m_cc.enqueue(bind(&http_connection::connect, shared_from_this(), _1, *i) , bind(&http_connection::on_connect_timeout, shared_from_this()) , m_timeout); } void http_connection::connect(int ticket, tcp::endpoint target_address) { m_connection_ticket = ticket; m_sock.async_connect(target_address, boost::bind(&http_connection::on_connect , shared_from_this(), _1/*, ++i*/)); } void http_connection::on_connect(asio::error_code const& e /*, tcp::resolver::iterator i*/) { if (!e) { m_last_receive = time_now(); asio::async_write(m_sock, asio::buffer(sendbuffer) , bind(&http_connection::on_write, shared_from_this(), _1)); } /* else if (i != tcp::resolver::iterator()) { // The connection failed. Try the next endpoint in the list. m_sock.close(); m_cc.enqueue(bind(&http_connection::connect, shared_from_this(), _1, *i) , bind(&http_connection::on_connect_timeout, shared_from_this()) , m_timeout); } */ else { close(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); } } void http_connection::on_write(asio::error_code const& e) { if (e) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); return; } std::string().swap(sendbuffer); m_recvbuffer.resize(4096); int amount_to_read = m_recvbuffer.size() - m_read_pos; if (m_rate_limit > 0 && amount_to_read > m_download_quota) { amount_to_read = m_download_quota; if (m_download_quota == 0) { if (!m_limiter_timer_active) on_assign_bandwidth(asio::error_code()); return; } } m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos , amount_to_read) , bind(&http_connection::on_read , shared_from_this(), _1, _2)); } void http_connection::on_read(asio::error_code const& e , std::size_t bytes_transferred) { if (m_rate_limit) { m_download_quota -= bytes_transferred; assert(m_download_quota >= 0); } if (e == asio::error::eof) { close(); if (m_bottled && m_called) return; m_called = true; char const* data = 0; std::size_t size = 0; if (m_bottled) { data = m_parser.get_body().begin; size = m_parser.get_body().left(); } m_handler(e, m_parser, data, size); return; } if (e) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); return; } m_read_pos += bytes_transferred; assert(m_read_pos <= int(m_recvbuffer.size())); // having a nonempty path means we should handle redirects if (m_redirect && m_parser.header_finished()) { int code = m_parser.status_code(); if (code >= 300 && code < 400) { // attempt a redirect std::string url = m_parser.header<std::string>("location"); if (url.empty()) { // missing location header if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); return; } m_limiter_timer_active = false; close(); get(url, m_timeout); return; } m_redirect = false; } if (m_bottled || !m_parser.header_finished()) { libtorrent::buffer::const_interval rcv_buf(&m_recvbuffer[0] , &m_recvbuffer[0] + m_read_pos); m_parser.incoming(rcv_buf); if (!m_bottled && m_parser.header_finished()) { if (m_read_pos > m_parser.body_start()) m_handler(e, m_parser, &m_recvbuffer[0] + m_parser.body_start() , m_read_pos - m_parser.body_start()); m_read_pos = 0; m_last_receive = time_now(); } else if (m_bottled && m_parser.finished()) { m_timer.cancel(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, m_parser.get_body().begin, m_parser.get_body().left()); } } else { assert(!m_bottled); m_handler(e, m_parser, &m_recvbuffer[0], m_read_pos); m_read_pos = 0; m_last_receive = time_now(); } if (int(m_recvbuffer.size()) == m_read_pos) m_recvbuffer.resize((std::min)(m_read_pos + 2048, 1024*500)); if (m_read_pos == 1024 * 500) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(asio::error::eof, m_parser, 0, 0); return; } int amount_to_read = m_recvbuffer.size() - m_read_pos; if (m_rate_limit > 0 && amount_to_read > m_download_quota) { amount_to_read = m_download_quota; if (m_download_quota == 0) { if (!m_limiter_timer_active) on_assign_bandwidth(asio::error_code()); return; } } m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos , amount_to_read) , bind(&http_connection::on_read , shared_from_this(), _1, _2)); } void http_connection::on_assign_bandwidth(asio::error_code const& e) { if ((e == asio::error::operation_aborted && m_limiter_timer_active) || !m_sock.is_open()) { if (!m_bottled || !m_called) m_handler(e, m_parser, 0, 0); return; } m_limiter_timer_active = false; if (e) return; if (m_download_quota > 0) return; m_download_quota = m_rate_limit / 4; int amount_to_read = m_recvbuffer.size() - m_read_pos; if (amount_to_read > m_download_quota) amount_to_read = m_download_quota; m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos , amount_to_read) , bind(&http_connection::on_read , shared_from_this(), _1, _2)); m_limiter_timer_active = true; m_limiter_timer.expires_from_now(milliseconds(250)); m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth , shared_from_this(), _1)); } void http_connection::rate_limit(int limit) { if (!m_limiter_timer_active) { m_limiter_timer_active = true; m_limiter_timer.expires_from_now(milliseconds(250)); m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth , shared_from_this(), _1)); } m_rate_limit = limit; } }
gpl-2.0
jeffcox111/LaunchLater
LaunchLater_LaunchPad/LaunchPadMainForm.Designer.cs
1603
namespace LaunchLater_LaunchPad { partial class LaunchPadMainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.SuspendLayout(); // // LaunchPadMainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 262); this.Name = "Form1"; this.Opacity = 0D; this.ShowInTaskbar = false; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); } #endregion } }
gpl-2.0
BeWelcome/rox
src/Command/GeonamesUpdateFullCommand.php
13515
<?php namespace App\Command; use App\Entity\Location; use Doctrine\DBAL\Connection; use Doctrine\ORM\EntityManagerInterface; use Doctrine\Persistence\ObjectRepository; use Exception; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\Filesystem\Filesystem; use Symfony\Contracts\HttpClient\HttpClientInterface; use ZipArchive; /** * @SuppressWarnings(PHPMD) */ class GeonamesUpdateFullCommand extends Command { private HttpClientInterface $httpClient; private Connection $connection; private ObjectRepository $repository; private EntityManagerInterface $entityManager; private OutputInterface $output; private InputInterface $input; public function __construct(HttpClientInterface $httpClient, EntityManagerInterface $entityManager) { parent::__construct('geonames:update:full'); $this->httpClient = $httpClient; $this->entityManager = $entityManager; $this->connection = $entityManager->getConnection(); $this->repository = $entityManager->getRepository(Location::class); } protected function configure() { $this ->setDescription('Downloads geonames and/or alternatenames data dump and imports it') ->addOption( 'geonames', null, InputOption::VALUE_NONE, '' ) ->addOption( 'alternate', null, InputOption::VALUE_NONE, 'Will drop the database if one already exist. Needs to be used with --force.' ) ->addOption( 'no-downloads', null, InputOption::VALUE_NONE, 'Will not download the latest files but use the ones already there.' ) ->setHelp('Downloads geonames and/or alternatenames data dump and imports it') ; } protected function execute(InputInterface $input, OutputInterface $output): int { $this->input = $input; $this->output = $output; $io = new SymfonyStyle($input, $output); $returnCode = 0; $noDownloads = $input->getOption('no-downloads'); $downloadFiles = (null === $noDownloads) || !(true === $noDownloads); if ($input->getOption('geonames')) { $returnCode = $this->updateGeonames($io, $downloadFiles); } if ($input->getOption('alternate')) { if (0 === $returnCode || $input->getOption('continue-on-errors')) { $returnCode = $this->updateAlternatenames($io, $downloadFiles); } } gc_disable(); return $returnCode; } protected function updateGeonames(SymfonyStyle $io, bool $download): int { $io->note('Updating the geonames database'); $dir = sys_get_temp_dir() . '/allcountries'; if ($download) { $filename = $this->downloadFile( $io, 'https://download.geonames.org/export/dump/allCountries.zip' ); if (null === $filename) { return -1; } $zip = new ZipArchive(); if (true === $zip->open($filename)) { $zip->extractTo($dir); $zip->close(); } else { $io->error('Couldn\'t extract geoname database.'); return -1; } } $lines = $this->getLines($dir . '/allCountries.txt'); $progressbar = $io->createProgressBar(); $progressbar->start($lines); $handle = fopen($dir . '/allCountries.txt', 'r'); $rows = []; while (($row = fgetcsv($handle, 0, "\t")) !== false) { if (is_numeric($row[0]) && ('A' === $row[6] || 'P' === $row[6])) { $rows[] = $row; if (10000 === \count($rows)) { $this->updateGeonamesInDatabase($rows); unset($rows); $rows = []; gc_collect_cycles(); } } $progressbar->advance(); } // Also write the remaining entries to the database $this->updateGeonamesInDatabase($rows); fclose($handle); $progressbar->finish(); $filesystem = new Filesystem(); $filesystem->remove([ $dir . '/allCountries.txt', $dir, ]); $io->success('Updated the geonames databases to current state.'); return 0; } protected function updateAlternatenames(SymfonyStyle $io, bool $download): int { $io->title('Updating the alternate names database.'); $dir = sys_get_temp_dir() . '/alternatenames'; if ($download) { $io->writeln('Downloading necessary file.'); $filename = $this->downloadFile( $io, 'https://download.geonames.org/export/dump/alternateNamesV2.zip' ); if (null === $filename) { return -1; } $io->writeln('Extracting downlaoded file.'); $zip = new ZipArchive(); if (true === $zip->open($filename)) { $zip->extractTo($dir); $zip->close(); } else { $io->error('Couldn\'t extract geoname alternate name database.'); return -1; } $io->writeln('Import alternate names into database'); } $statement = $this->connection->executeQuery( 'SELECT geonameId from geonames' ); $geonameIds = []; while (false !== ($geonameId = $statement->fetchOne())) { $geonameIds[] = $geonameId; } $io->writeln('Getting number of rows to import'); $lines = $this->getLines($dir . '/alternateNamesV2.txt'); $io->newLine(); $progressbar = $io->createProgressBar(); $progressbar->minSecondsBetweenRedraws(1); $progressbar->start($lines); $i = 0; $handle = fopen($dir . '/alternateNamesV2.txt', 'r'); while (($row = fgetcsv($handle, 0, "\t")) !== false) { if (\in_array($row[0], $geonameIds, true)) { $this->updateAlternatenamesRow($row); } $progressbar->advance(); ++$i; if (0 === ($i % 100000)) { gc_collect_cycles(); } } fclose($handle); $progressbar->finish(); $io->writeln('Removing temporary files'); $filesystem = new Filesystem(); $filesystem->remove([ $dir . '/alternateNamesV2.txt', $dir . '/isoLanguages.txt', $dir, ]); $io->success('Updated the alternate names database to current state.'); return 0; } private function downloadFile(SymfonyStyle $io, string $url): ?string { $filesystem = new Filesystem(); $filename = $filesystem->tempnam('.', 'rox-geonames'); $progressbar = null; $response = $this->httpClient->request('GET', $url, [ 'on_progress' => function (int $dlNow, int $dlSize, array $info) use ($io, &$progressbar): void { // $dlNow is the number of bytes downloaded so far // $dlSize is the total size to be downloaded or -1 if it is unknown // $info is what $response->getInfo() would return at this very time if ($dlSize > 0 && null === $progressbar) { $progressbar = $io->createProgressBar($dlSize); $progressbar->start(); } if (null !== $progressbar) { if ($dlSize === $dlNow) { $progressbar->finish(); return; } $progressbar->setProgress($dlNow); } }, ]); if (200 !== $response->getStatusCode()) { $io->error('Couldn\'t download and extract geoname database.'); return null; } $fileHandler = fopen($filename, 'w'); foreach ($this->httpClient->stream($response) as $chunk) { fwrite($fileHandler, $chunk->getContent()); } fclose($fileHandler); return $filename; } private function updateGeonamesInDatabase(array $rows): int { /* geonameid : integer id of record in geonames database name : name of geographical point (utf8) varchar(200) asciiname : name of geographical point in plain ascii characters, varchar(200) alternatenames : ignored latitude : latitude in decimal degrees (wgs84) longitude : longitude in decimal degrees (wgs84) feature class : see http://www.geonames.org/export/codes.html, char(1) feature code : see http://www.geonames.org/export/codes.html, varchar(10) country code : ISO-3166 2-letter country code, 2 characters cc2 : ignored admin1 code : ignored admin2 code : ignored admin3 code : code for third level administrative division, varchar(20) admin4 code : code for fourth level administrative division, varchar(20) population : bigint (8 byte int) elevation : in meters, integer dem : ignored timezone : the iana timezone id (see file timeZone.txt) varchar(40) modification date : date of last modification in yyyy-MM-dd format */ // Write rows into a file and call external command to import // Otherwise we hit memory limites $handle = fopen('geonames_rows.csv', 'w'); foreach ($rows as $row) { fputcsv($handle, $row); } fclose($handle); $io = new SymfonyStyle($this->input, $this->output); $io->block('Running external command'); /** @var Command $command */ $command = $this->getApplication()->find('geonames:import:file'); $arguments = [ 'file' => 'geonames_rows.csv', ]; $import = new ArrayInput($arguments); $returnCode = $command->run($import, $this->output); return $returnCode; } private function updateAlternatenamesRow(array $row): void { /* alternateNameId : the id of this alternate name, int geonameid : geonameId referring to id in table 'geoname', int isolanguage : iso 639 language code 2- or 3-characters (ignored otherwise) alternate name : alternate name or name variant, varchar(400) isPreferredName : '1', if this alternate name is an official/preferred name isShortName : '1', if this is a short name like 'California' for 'State of California' isColloquial : skipped if '1' isHistoric : skipped if '1' from : ignored to : ignored */ if (is_numeric($row[0]) && \strlen($row[2]) <= 3 && '1' !== $row[6] && '1' !== $row[7]) { try { $statement = $this->connection->executeQuery( ' REPLACE INTO `geonamesalternatenames` SET alternateNameId = :alternateNameId, geonameId = :geonameId, isolanguage = :isoLanguage, alternateName = :alternateName, ispreferred = :isPreferred, isshort = :isShort, iscolloquial = :isColloquial, isHistoric = :isHistoric ', [ 'alternateNameId' => $row[0], 'geonameId' => $row[1], 'isoLanguage' => $row[2], 'alternateName' => $row[3], 'isPreferred' => $row[4], 'isShort' => $row[5], 'isColloquial' => $row[6], 'isHistoric' => $row[7], ] ); } catch (Exception $e) { // do nothing likely a foreign key constraint. } finally { $statement = null; unset($statement); } // Check if statement was executed successfully } } private function getLines($file): int { $f = fopen($file, 'r'); $lines = 0; while (!feof($f)) { $lines += substr_count(fread($f, 8192), "\n"); } fclose($f); return $lines; } }
gpl-2.0
113Ideas/westfieldbank
sites/all/themes/evolve/templates/views-view-fields--agency-banking-view--page.tpl.php
1762
<div id="agency-container"> <div class="section-white"> <div class="container"> <div class="row"> <div class="region region-section_1_banking-advisory col-xs-12 col-sm-12 col-md-12 col-lg-12"> <?php print $fields["field_section_1_banking"]->content; ?> </div> </div> </div> <div class="row"> <div class="region region-head-advisory col-xs-12 col-sm-12 col-md-12 col-lg-12"> <?php print $fields["field_header_agency"]->content; ?> </div> </div> </div> <div class="section-blue"> <div class="container"> <div class="row"> <div class="region region-section_2_banking-advisory col-xs-12 col-sm-12 col-md-12 col-lg-12"> <?php print $fields["field_section_2_banking"]->content; ?> </div> </div> </div> </div> <div class="section-white"> <div class="container"> <div class="row"> <div class="region region-body-advisory col-xs-12 col-sm-12 col-md-12 col-lg-12"> <?php print $fields["body"]->content; ?> </div> </div> </div> </div> <div class="section-blue"> <div class="container"> <div class="row"> <div class="region region-section_3_banking-advisory col-xs-12 col-sm-12 col-md-12 col-lg-12"> <?php print $fields["field_section_3_banking"]->content; ?> </div> </div> </div> </div> </div>
gpl-2.0
janich/SiteOp
fields/siteopinfo.php
1748
<?php /** * @package Joomla.Plugin * @subpackage System.SiteOp * * @copyright Copyright (C) 2016 CGOnline.dk, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ defined('_JEXEC') or die; jimport('joomla.form.helper'); class JFormFieldSiteopinfo extends JFormField { protected $type = 'siteopinfo'; public function getInput() { JFactory::getDocument()->addStyleDeclaration(' .siteopinfo-container { margin-left: 0px !important; } .siteopinfo { box-sizing: border-box; padding: 20px 50px; display: inline-block; box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.8); } .siteopinfo img { float: left; max-width: 200px; margin: 25px 50px 0px 0px; } .siteopinfo dl { float: left; width: 310px; } .siteopinfo dt { float: left; clear: left; width: 100px; } .siteopinfo dd { float: left; width: 200px; } '); JFactory::getDocument()->addScriptDeclaration(' jQuery(document).ready(function (){ jQuery(".siteopinfo").parent().addClass("siteopinfo-container"); }); '); return ' <div class="siteopinfo"> <img src="../plugins/system/siteop/fields/logo.jpg" /> <dl> <dt>Name</dt> <dd>Site Optimisation</dd> <dt>Version</dt> <dd>1.0.0</dd> <dt>Author</dt> <dd>CGOnline.dk</dd> <dt>Website</dt> <dd><a href="http://www.cgonline.dk" target="_blank">http://www.cgonline.dk</a> </dd> <dt>Contact</dt> <dd><a href="mailto:[email protected]">[email protected]</a> </dd> </dl> </div> '; } }
gpl-2.0
ifunam/salva
app/controllers/jobpositions_controller.rb
104
class JobpositionsController < UserResourcesController defaults :resource_class_scope => :at_unam end
gpl-2.0
mobile-event-processing/Asper
source/src/com/asper/sources/sun/reflect/UnsafeQualifiedBooleanFieldAccessorImpl.java
4708
/* * Copyright (c) 2004, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.asper.sources.sun.reflect; import java.lang.reflect.Field; class UnsafeQualifiedBooleanFieldAccessorImpl extends UnsafeQualifiedFieldAccessorImpl { UnsafeQualifiedBooleanFieldAccessorImpl(Field field, boolean isReadOnly) { super(field, isReadOnly); } public Object get(Object obj) throws IllegalArgumentException { return new Boolean(getBoolean(obj)); } public boolean getBoolean(Object obj) throws IllegalArgumentException { ensureObj(obj); return unsafe.getBooleanVolatile(obj, fieldOffset); } public byte getByte(Object obj) throws IllegalArgumentException { throw newGetByteIllegalArgumentException(); } public char getChar(Object obj) throws IllegalArgumentException { throw newGetCharIllegalArgumentException(); } public short getShort(Object obj) throws IllegalArgumentException { throw newGetShortIllegalArgumentException(); } public int getInt(Object obj) throws IllegalArgumentException { throw newGetIntIllegalArgumentException(); } public long getLong(Object obj) throws IllegalArgumentException { throw newGetLongIllegalArgumentException(); } public float getFloat(Object obj) throws IllegalArgumentException { throw newGetFloatIllegalArgumentException(); } public double getDouble(Object obj) throws IllegalArgumentException { throw newGetDoubleIllegalArgumentException(); } public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isReadOnly) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Boolean) { unsafe.putBooleanVolatile(obj, fieldOffset, ((Boolean) value).booleanValue()); return; } throwSetIllegalArgumentException(value); } public void setBoolean(Object obj, boolean z) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isReadOnly) { throwFinalFieldIllegalAccessException(z); } unsafe.putBooleanVolatile(obj, fieldOffset, z); } public void setByte(Object obj, byte b) throws IllegalArgumentException, IllegalAccessException { throwSetIllegalArgumentException(b); } public void setChar(Object obj, char c) throws IllegalArgumentException, IllegalAccessException { throwSetIllegalArgumentException(c); } public void setShort(Object obj, short s) throws IllegalArgumentException, IllegalAccessException { throwSetIllegalArgumentException(s); } public void setInt(Object obj, int i) throws IllegalArgumentException, IllegalAccessException { throwSetIllegalArgumentException(i); } public void setLong(Object obj, long l) throws IllegalArgumentException, IllegalAccessException { throwSetIllegalArgumentException(l); } public void setFloat(Object obj, float f) throws IllegalArgumentException, IllegalAccessException { throwSetIllegalArgumentException(f); } public void setDouble(Object obj, double d) throws IllegalArgumentException, IllegalAccessException { throwSetIllegalArgumentException(d); } }
gpl-2.0
IMA-WorldHealth/bhima
client/src/modules/fiscal/fiscal.closingBalance.js
6391
angular.module('bhima.controllers') .controller('FiscalClosingBalanceController', FiscalClosingBalanceController); FiscalClosingBalanceController.$inject = [ '$state', 'AccountService', 'FiscalService', 'NotifyService', 'SessionService', 'uiGridConstants', 'bhConstants', 'TreeService', 'GridExportService', ]; /** * @function FiscalClosingBalanceController * * @description * This controller is responsible for handling the closing balance of a fiscal year. */ function FiscalClosingBalanceController( $state, Accounts, Fiscal, Notify, Session, uiGridConstants, bhConstants, Tree, GridExport ) { const vm = this; const fiscalYearId = $state.params.id; vm.currency_id = Session.enterprise.currency_id; // expose to the view vm.showAccountFilter = false; vm.toggleAccountFilter = toggleAccountFilter; // grid options vm.indentTitleSpace = 15; vm.gridApi = {}; const columns = [{ field : 'number', displayName : 'ACCOUNT.LABEL', cellClass : 'text-right', headerCellFilter : 'translate', width : 100, }, { field : 'label', displayName : 'FORM.LABELS.ACCOUNT', cellTemplate : '/modules/accounts/templates/grid.labelCell.tmpl.html', headerCellFilter : 'translate', enableFiltering : true, }, { field : 'debit', displayName : 'FORM.LABELS.DEBIT', headerCellClass : 'text-center', headerCellFilter : 'translate', cellTemplate : '/modules/fiscal/templates/debit.tmpl.html', aggregationType : customAggregationFn, footerCellClass : 'text-right', footerCellFilter : 'currency:'.concat(Session.enterprise.currency_id), width : 200, enableFiltering : false, }, { field : 'credit', displayName : 'FORM.LABELS.CREDIT', headerCellClass : 'text-center', headerCellFilter : 'translate', cellTemplate : '/modules/fiscal/templates/credit.tmpl.html', aggregationType : customAggregationFn, footerCellClass : 'text-right', footerCellFilter : 'currency:'.concat(Session.enterprise.currency_id), width : 200, enableFiltering : false, }]; vm.gridOptions = { appScopeProvider : vm, fastWatch : true, flatEntityAccess : true, enableSorting : false, showColumnFooter : true, enableColumnMenus : false, enableFiltering : vm.showAccountFilter, columnDefs : columns, onRegisterApi, }; const exporter = new GridExport(vm.gridOptions, 'all', 'visible'); function exportRowsFormatter(rows) { return rows .filter(account => !account.isTitleAccount) .map(account => { const row = [account.number, account.label, account.debit, account.credit]; return row.map(value => ({ value })); }); } vm.export = () => { const fname = `${vm.fiscal.label}`; return exporter.exportToCsv(fname, exporter.defaultColumnFormatter, exportRowsFormatter); }; function customAggregationFn(columnDefs, column) { if (vm.AccountTree) { const root = vm.AccountTree.getRootNode(); return (root[column.field] || 0); } return 0; } // API register function function onRegisterApi(gridApi) { vm.gridApi = gridApi; } // get fiscal year Fiscal.read(fiscalYearId) .then((fy) => { vm.fiscal = fy; $state.params.label = vm.fiscal.label; return fy.previous_fiscal_year_id; }) .then(loadFinalBalance) .catch(Notify.handleError); /** * @function pruneUntilSettled * * @description * Tree shaking algorithm that prunes the tree until only accounts with * children remain in the tree. Highly inefficient! But this operation * doesn't happen that frequently. * * In practice, the prune function is called 0 - 5 times, depending on how * many title accounts are missing children. */ function pruneUntilSettled(tree) { const pruneFn = node => node.isTitleAccount && node.children.length === 0; let settled = tree.prune(pruneFn); while (settled > 0) { settled = tree.prune(pruneFn); } } const debitSumFn = Tree.common.sumOnProperty('debit'); const creditSumFn = Tree.common.sumOnProperty('credit'); /** * @function onBalanceChange * * @description * This function tells the ui-grid to sum the values of the debit/credit * columns in the footer. */ function onBalanceChange() { vm.AccountTree.walk((node, parent) => { parent.debit = 0; parent.credit = 0; }); vm.AccountTree.walk((childNode, parentNode) => { debitSumFn(childNode, parentNode); creditSumFn(childNode, parentNode); }, false); vm.gridApi.core.notifyDataChange(uiGridConstants.dataChange.COLUMN); } /** * @function hasBalancedAccount * * @description * Checks if the debits and credits balance */ function hasBalancedAccount() { const { debit, credit } = vm.AccountTree.getRootNode(); return debit === credit; } /** * @method loadFinalBalance * * @description * Load the balance until a given period. */ function loadFinalBalance(showHiddenAccounts) { vm.loading = true; vm.hasError = false; Fiscal.getClosingBalance(fiscalYearId) .then(data => { let accounts = data; if (!showHiddenAccounts) { accounts = accounts.filter(account => account.hidden !== 1); } vm.AccountTree = new Tree(accounts); // compute properties for rendering pretty indented templates vm.AccountTree.walk((child, parent) => { child.isTitleAccount = child.type_id === bhConstants.accounts.TITLE; child.$$treeLevel = (parent.$$treeLevel || 0) + 1; }); // prune all title accounts with empty children pruneUntilSettled(vm.AccountTree); // compute balances vm.balanced = hasBalancedAccount(); onBalanceChange(); vm.gridOptions.data = vm.AccountTree.data; }) .catch(err => { vm.hasError = true; Notify.handleError(err); }) .finally(() => { vm.loading = false; }); } /** * @function toggleAccountFilter * @description show a filter for finding an account */ function toggleAccountFilter() { vm.showAccountFilter = !vm.showAccountFilter; vm.gridOptions.enableFiltering = vm.showAccountFilter; vm.gridApi.core.notifyDataChange(uiGridConstants.dataChange.ALL); } }
gpl-2.0
ndtrung81/lammps
unittest/formats/test_file_operations.cpp
17776
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator https://www.lammps.org/, Sandia National Laboratories Steve Plimpton, [email protected] Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #include "../testing/core.h" #include "../testing/utils.h" #include "atom.h" #include "domain.h" #include "error.h" #include "info.h" #include "input.h" #include "lammps.h" #include "update.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include <cstdio> #include <mpi.h> #include <string> using namespace LAMMPS_NS; using testing::MatchesRegex; using testing::StrEq; using utils::read_lines_from_file; using utils::sfgets; using utils::sfread; using utils::split_words; // whether to print verbose output (i.e. not capturing LAMMPS screen output). bool verbose = false; class FileOperationsTest : public LAMMPSTest { protected: void SetUp() override { testbinary = "FileOperationsTest"; LAMMPSTest::SetUp(); ASSERT_NE(lmp, nullptr); std::ofstream out("safe_file_read_test.txt", std::ios_base::out | std::ios_base::binary); ASSERT_TRUE(out.good()); out << "one line\ntwo_lines\n\nno newline"; out.close(); out.open("file_with_long_lines_test.txt", std::ios_base::out | std::ios_base::binary); ASSERT_TRUE(out.good()); out << "zero ##########################################################" "##################################################################" "##################################################################" "############################################################\n"; out << "one line\ntwo_lines\n\n"; for (int i = 0; i < 100; ++i) out << "one two "; out << "\nthree\nfour five #"; for (int i = 0; i < 1000; ++i) out << '#'; out.close(); } void TearDown() override { LAMMPSTest::TearDown(); remove("safe_file_read_test.txt"); remove("file_with_long_lines_test.txt"); } }; #define MAX_BUF_SIZE 128 TEST_F(FileOperationsTest, safe_fgets) { char buf[MAX_BUF_SIZE]; FILE *fp = fopen("safe_file_read_test.txt", "rb"); ASSERT_NE(fp, nullptr); memset(buf, 0, MAX_BUF_SIZE); utils::sfgets(FLERR, buf, MAX_BUF_SIZE, fp, "safe_file_read_test.txt", lmp->error); ASSERT_THAT(buf, StrEq("one line\n")); memset(buf, 0, MAX_BUF_SIZE); utils::sfgets(FLERR, buf, MAX_BUF_SIZE, fp, "safe_file_read_test.txt", lmp->error); ASSERT_THAT(buf, StrEq("two_lines\n")); memset(buf, 0, MAX_BUF_SIZE); utils::sfgets(FLERR, buf, MAX_BUF_SIZE, fp, "safe_file_read_test.txt", lmp->error); ASSERT_THAT(buf, StrEq("\n")); memset(buf, 0, MAX_BUF_SIZE); utils::sfgets(FLERR, buf, 4, fp, "safe_file_read_test.txt", lmp->error); ASSERT_THAT(buf, StrEq("no ")); memset(buf, 0, MAX_BUF_SIZE); utils::sfgets(FLERR, buf, MAX_BUF_SIZE, fp, "safe_file_read_test.txt", lmp->error); ASSERT_THAT(buf, StrEq("newline")); memset(buf, 0, MAX_BUF_SIZE); TEST_FAILURE( ".*ERROR on proc 0: Unexpected end of file while " "reading file 'safe_file_read_test.txt'.*", utils::sfgets(FLERR, buf, MAX_BUF_SIZE, fp, "safe_file_read_test.txt", lmp->error);); fclose(fp); } #define MAX_BUF_SIZE 128 TEST_F(FileOperationsTest, fgets_trunc) { char buf[MAX_BUF_SIZE]; char *ptr; FILE *fp = fopen("safe_file_read_test.txt", "rb"); ASSERT_NE(fp, nullptr); memset(buf, 0, MAX_BUF_SIZE); ptr = utils::fgets_trunc(buf, MAX_BUF_SIZE, fp); ASSERT_THAT(buf, StrEq("one line\n")); ASSERT_NE(ptr,nullptr); memset(buf, 0, MAX_BUF_SIZE); ptr = utils::fgets_trunc(buf, MAX_BUF_SIZE, fp); ASSERT_THAT(buf, StrEq("two_lines\n")); ASSERT_NE(ptr,nullptr); memset(buf, 0, MAX_BUF_SIZE); ptr = utils::fgets_trunc(buf, MAX_BUF_SIZE, fp); ASSERT_THAT(buf, StrEq("\n")); ASSERT_NE(ptr,nullptr); memset(buf, 0, MAX_BUF_SIZE); ptr = utils::fgets_trunc(buf, 4, fp); ASSERT_THAT(buf, StrEq("no\n")); ASSERT_NE(ptr,nullptr); ptr = utils::fgets_trunc(buf, MAX_BUF_SIZE, fp); ASSERT_EQ(ptr,nullptr); fclose(fp); fp = fopen("file_with_long_lines_test.txt", "r"); ASSERT_NE(fp,nullptr); memset(buf, 0, MAX_BUF_SIZE); ptr = utils::fgets_trunc(buf, MAX_BUF_SIZE, fp); ASSERT_NE(ptr,nullptr); ASSERT_THAT(buf, StrEq("zero ##########################################################" "###############################################################\n")); ptr = utils::fgets_trunc(buf, MAX_BUF_SIZE, fp); ASSERT_THAT(buf, StrEq("one line\n")); ASSERT_NE(ptr,nullptr); ptr = utils::fgets_trunc(buf, MAX_BUF_SIZE, fp); ASSERT_THAT(buf, StrEq("two_lines\n")); ASSERT_NE(ptr,nullptr); ptr = utils::fgets_trunc(buf, MAX_BUF_SIZE, fp); ASSERT_THAT(buf, StrEq("\n")); ASSERT_NE(ptr,nullptr); ptr = utils::fgets_trunc(buf, MAX_BUF_SIZE, fp); ASSERT_NE(ptr,nullptr); ASSERT_THAT(buf, StrEq("one two one two one two one two one two one two one two one two " "one two one two one two one two one two one two one two one tw\n")); fclose(fp); } #define MAX_BUF_SIZE 128 TEST_F(FileOperationsTest, safe_fread) { char buf[MAX_BUF_SIZE]; FILE *fp = fopen("safe_file_read_test.txt", "rb"); ASSERT_NE(fp, nullptr); memset(buf, 0, MAX_BUF_SIZE); utils::sfread(FLERR, buf, 1, 9, fp, "safe_file_read_test.txt", lmp->error); ASSERT_THAT(buf, StrEq("one line\n")); memset(buf, 0, MAX_BUF_SIZE); utils::sfread(FLERR, buf, 1, 10, fp, "safe_file_read_test.txt", nullptr); ASSERT_THAT(buf, StrEq("two_lines\n")); TEST_FAILURE(".*ERROR on proc 0: Unexpected end of file while " "reading file 'safe_file_read_test.txt'.*", utils::sfread(FLERR, buf, 1, 100, fp, "safe_file_read_test.txt", lmp->error);); // short read but no error triggered due to passing a NULL pointer memset(buf, 0, MAX_BUF_SIZE); clearerr(fp); rewind(fp); utils::sfread(FLERR, buf, 1, 100, fp, "safe_file_read_test.txt", nullptr); ASSERT_THAT(buf, StrEq("one line\ntwo_lines\n\nno newline")); fclose(fp); } TEST_F(FileOperationsTest, read_lines_from_file) { char *buf = new char[MAX_BUF_SIZE]; FILE *fp = nullptr; MPI_Comm world = MPI_COMM_WORLD; int me, rv; memset(buf, 0, MAX_BUF_SIZE); MPI_Comm_rank(world, &me); rv = utils::read_lines_from_file(nullptr, 1, MAX_BUF_SIZE, buf, me, world); ASSERT_EQ(rv, 1); if (me == 0) { fp = fopen("safe_file_read_test.txt", "r"); ASSERT_NE(fp, nullptr); } else ASSERT_EQ(fp, nullptr); rv = utils::read_lines_from_file(fp, 2, MAX_BUF_SIZE / 2, buf, me, world); ASSERT_EQ(rv, 0); ASSERT_THAT(buf, StrEq("one line\ntwo_lines\n")); rv = utils::read_lines_from_file(fp, 2, MAX_BUF_SIZE / 2, buf, me, world); ASSERT_EQ(rv, 0); ASSERT_THAT(buf, StrEq("\nno newline\n")); rv = utils::read_lines_from_file(fp, 2, MAX_BUF_SIZE / 2, buf, me, world); ASSERT_EQ(rv, 1); delete[] buf; } TEST_F(FileOperationsTest, logmesg) { char buf[64]; BEGIN_HIDE_OUTPUT(); command("echo none"); END_HIDE_OUTPUT(); BEGIN_CAPTURE_OUTPUT(); utils::logmesg(lmp, "one\n"); command("log test_logmesg.log"); utils::logmesg(lmp, "two\n"); utils::logmesg(lmp, "three={}\n", 3); utils::logmesg(lmp, "four {}\n"); utils::logmesg(lmp, "five\n", 5); command("log none"); std::string out = END_CAPTURE_OUTPUT(); memset(buf, 0, 64); FILE *fp = fopen("test_logmesg.log", "r"); fread(buf, 1, 64, fp); fclose(fp); ASSERT_THAT(out, StrEq("one\ntwo\nthree=3\nargument not found\nfive\n")); ASSERT_THAT(buf, StrEq("two\nthree=3\nargument not found\nfive\n")); remove("test_logmesg.log"); } TEST_F(FileOperationsTest, error_message_warn) { char buf[64]; BEGIN_HIDE_OUTPUT(); command("echo none"); command("log test_error_warn.log"); END_HIDE_OUTPUT(); BEGIN_CAPTURE_OUTPUT(); lmp->error->message("testme.cpp", 10, "message me"); lmp->error->warning("testme.cpp", 100, "warn me"); command("log none"); std::string out = END_CAPTURE_OUTPUT(); memset(buf, 0, 64); FILE *fp = fopen("test_error_warn.log", "r"); fread(buf, 1, 64, fp); fclose(fp); auto msg = StrEq("message me (testme.cpp:10)\n" "WARNING: warn me (testme.cpp:100)\n"); ASSERT_THAT(out, msg); ASSERT_THAT(buf, msg); remove("test_error_warn.log"); } TEST_F(FileOperationsTest, error_all_one) { BEGIN_HIDE_OUTPUT(); command("echo none"); command("log none"); END_HIDE_OUTPUT(); TEST_FAILURE(".*ERROR: exit \\(testme.cpp:10\\).*", lmp->error->all("testme.cpp", 10, "exit");); TEST_FAILURE(".*ERROR: exit too \\(testme.cpp:10\\).*", lmp->error->all("testme.cpp", 10, "exit {}", "too");); TEST_FAILURE(".*ERROR: argument not found \\(testme.cpp:10\\).*", lmp->error->all("testme.cpp", 10, "exit {} {}", "too");); TEST_FAILURE(".*ERROR on proc 0: exit \\(testme.cpp:10\\).*", lmp->error->one("testme.cpp", 10, "exit");); TEST_FAILURE(".*ERROR on proc 0: exit too \\(testme.cpp:10\\).*", lmp->error->one("testme.cpp", 10, "exit {}", "too");); TEST_FAILURE(".*ERROR on proc 0: argument not found \\(testme.cpp:10\\).*", lmp->error->one("testme.cpp", 10, "exit {} {}", "too");); } TEST_F(FileOperationsTest, write_restart) { BEGIN_HIDE_OUTPUT(); command("echo none"); END_HIDE_OUTPUT(); TEST_FAILURE(".*ERROR: Write_restart command before simulation box is defined.*", command("write_restart test.restart");); BEGIN_HIDE_OUTPUT(); command("region box block -2 2 -2 2 -2 2"); command("create_box 1 box"); command("create_atoms 1 single 0.0 0.0 0.0"); command("mass 1 1.0"); command("reset_timestep 333"); command("comm_modify cutoff 0.2"); command("write_restart noinit.restart noinit"); command("run 0 post no"); command("write_restart test.restart"); command("write_restart step*.restart"); command("write_restart multi-%.restart"); command("write_restart multi2-%.restart fileper 2"); command("write_restart multi3-%.restart nfile 1"); if (info->has_package("MPIIO")) command("write_restart test.restart.mpiio"); END_HIDE_OUTPUT(); ASSERT_FILE_EXISTS("noinit.restart"); ASSERT_FILE_EXISTS("test.restart"); ASSERT_FILE_EXISTS("step333.restart"); ASSERT_FILE_EXISTS("multi-base.restart"); ASSERT_FILE_EXISTS("multi-0.restart"); ASSERT_FILE_EXISTS("multi2-base.restart"); ASSERT_FILE_EXISTS("multi2-0.restart"); ASSERT_FILE_EXISTS("multi3-base.restart"); ASSERT_FILE_EXISTS("multi3-0.restart"); if (info->has_package("MPIIO")) ASSERT_FILE_EXISTS("test.restart.mpiio"); if (!info->has_package("MPIIO")) { TEST_FAILURE(".*ERROR: Writing to MPI-IO filename when MPIIO package is not inst.*", command("write_restart test.restart.mpiio");); } else { TEST_FAILURE(".*ERROR: Restart file MPI-IO output not allowed with % in filename.*", command("write_restart test.restart-%.mpiio");); } TEST_FAILURE(".*ERROR: Illegal write_restart command.*", command("write_restart");); TEST_FAILURE(".*ERROR: Illegal write_restart command.*", command("write_restart test.restart xxxx");); TEST_FAILURE(".*ERROR on proc 0: Cannot open restart file some_crazy_dir/test.restart:" " No such file or directory.*", command("write_restart some_crazy_dir/test.restart");); BEGIN_HIDE_OUTPUT(); command("clear"); END_HIDE_OUTPUT(); ASSERT_EQ(lmp->atom->natoms, 0); ASSERT_EQ(lmp->update->ntimestep, 0); ASSERT_EQ(lmp->domain->triclinic, 0); TEST_FAILURE( ".*ERROR on proc 0: Cannot open restart file noexist.restart: No such file or directory.*", command("read_restart noexist.restart");); BEGIN_HIDE_OUTPUT(); command("read_restart step333.restart"); command("change_box all triclinic"); command("write_restart triclinic.restart"); END_HIDE_OUTPUT(); ASSERT_EQ(lmp->atom->natoms, 1); ASSERT_EQ(lmp->update->ntimestep, 333); ASSERT_EQ(lmp->domain->triclinic, 1); BEGIN_HIDE_OUTPUT(); command("clear"); END_HIDE_OUTPUT(); ASSERT_EQ(lmp->atom->natoms, 0); ASSERT_EQ(lmp->update->ntimestep, 0); ASSERT_EQ(lmp->domain->triclinic, 0); BEGIN_HIDE_OUTPUT(); command("read_restart triclinic.restart"); END_HIDE_OUTPUT(); ASSERT_EQ(lmp->atom->natoms, 1); ASSERT_EQ(lmp->update->ntimestep, 333); ASSERT_EQ(lmp->domain->triclinic, 1); // clean up delete_file("noinit.restart"); delete_file("test.restart"); delete_file("step333.restart"); delete_file("multi-base.restart"); delete_file("multi-0.restart"); delete_file("multi2-base.restart"); delete_file("multi2-0.restart"); delete_file("multi3-base.restart"); delete_file("multi3-0.restart"); delete_file("triclinic.restart"); if (info->has_package("MPIIO")) delete_file("test.restart.mpiio"); } TEST_F(FileOperationsTest, write_data) { BEGIN_HIDE_OUTPUT(); command("echo none"); END_HIDE_OUTPUT(); TEST_FAILURE(".*ERROR: Write_data command before simulation box is defined.*", command("write_data test.data");); BEGIN_HIDE_OUTPUT(); command("region box block -2 2 -2 2 -2 2"); command("create_box 2 box"); command("create_atoms 1 single 0.5 0.0 0.0"); command("pair_style zero 1.0"); command("pair_coeff * *"); command("mass * 1.0"); command("reset_timestep 333"); command("write_data noinit.data noinit"); command("write_data nocoeff.data nocoeff"); command("run 0 post no"); command("write_data test.data"); command("write_data step*.data pair ij"); command("fix q all property/atom q"); command("set type 1 charge -0.5"); command("write_data charge.data"); command("write_data nofix.data nofix"); END_HIDE_OUTPUT(); ASSERT_FILE_EXISTS("noinit.data"); ASSERT_EQ(count_lines("noinit.data"), 26); ASSERT_FILE_EXISTS("test.data"); ASSERT_EQ(count_lines("test.data"), 26); ASSERT_FILE_EXISTS("step333.data"); ASSERT_EQ(count_lines("step333.data"), 27); ASSERT_FILE_EXISTS("nocoeff.data"); ASSERT_EQ(count_lines("nocoeff.data"), 21); ASSERT_FILE_EXISTS("nofix.data"); ASSERT_EQ(count_lines("nofix.data"), 26); ASSERT_FILE_EXISTS("charge.data"); ASSERT_EQ(count_lines("charge.data"), 30); TEST_FAILURE(".*ERROR: Illegal write_data command.*", command("write_data");); TEST_FAILURE(".*ERROR: Illegal write_data command.*", command("write_data test.data xxxx");); TEST_FAILURE(".*ERROR: Illegal write_data command.*", command("write_data test.data pair xx");); TEST_FAILURE(".*ERROR on proc 0: Cannot open data file some_crazy_dir/test.data:" " No such file or directory.*", command("write_data some_crazy_dir/test.data");); BEGIN_HIDE_OUTPUT(); command("clear"); END_HIDE_OUTPUT(); ASSERT_EQ(lmp->domain->box_exist, 0); ASSERT_EQ(lmp->atom->natoms, 0); ASSERT_EQ(lmp->update->ntimestep, 0); ASSERT_EQ(lmp->domain->triclinic, 0); TEST_FAILURE(".*ERROR: Cannot open file noexist.data: No such file or directory.*", command("read_data noexist.data");); BEGIN_HIDE_OUTPUT(); command("pair_style zero 1.0"); command("read_data step333.data"); command("change_box all triclinic"); command("write_data triclinic.data"); END_HIDE_OUTPUT(); ASSERT_EQ(lmp->atom->natoms, 1); ASSERT_EQ(lmp->update->ntimestep, 0); ASSERT_EQ(lmp->domain->triclinic, 1); BEGIN_HIDE_OUTPUT(); command("clear"); END_HIDE_OUTPUT(); ASSERT_EQ(lmp->atom->natoms, 0); ASSERT_EQ(lmp->domain->triclinic, 0); BEGIN_HIDE_OUTPUT(); command("pair_style zero 1.0"); command("read_data triclinic.data"); END_HIDE_OUTPUT(); ASSERT_EQ(lmp->atom->natoms, 1); ASSERT_EQ(lmp->domain->triclinic, 1); // clean up delete_file("charge.data"); delete_file("nocoeff.data"); delete_file("noinit.data"); delete_file("nofix.data"); delete_file("test.data"); delete_file("step333.data"); delete_file("triclinic.data"); } int main(int argc, char **argv) { MPI_Init(&argc, &argv); ::testing::InitGoogleMock(&argc, argv); if (Info::get_mpi_vendor() == "Open MPI" && !LAMMPS_NS::Info::has_exceptions()) std::cout << "Warning: using OpenMPI without exceptions. " "Death tests will be skipped\n"; // handle arguments passed via environment variable if (const char *var = getenv("TEST_ARGS")) { std::vector<std::string> env = split_words(var); for (auto arg : env) { if (arg == "-v") { verbose = true; } } } if ((argc > 1) && (strcmp(argv[1], "-v") == 0)) verbose = true; int rv = RUN_ALL_TESTS(); MPI_Finalize(); return rv; }
gpl-2.0
Remper/TwitchParser
src/main/java/org/fbk/cit/hlt/parsers/twitchtv/StreamConfiguration.java
3564
package org.fbk.cit.hlt.parsers.twitchtv; import org.apache.commons.cli.CommandLine; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import java.net.MalformedURLException; import java.net.URL; /** * Class that manages configuration along with stream-config.properties */ public class StreamConfiguration { public static final String CONFIG_FILENAME = "/stream-config.properties"; public static final String ROOT_NAMESPACE = "twitchtv"; public static final String PARAM_WILDCARD = "wildcard"; public static final String PARAM_WHITELIST = "whitelist"; public static final String PARAM_TOKEN = "token"; public static final String PARAM_USER = "user"; protected int wildcard; protected String[] whitelist; protected String token; protected String user; public StreamConfiguration() throws ConfigurationException { load(CorpusRecorder.class.getResource(CONFIG_FILENAME)); } public StreamConfiguration(String corpusDir) throws ConfigurationException { try { load(new URL("file://" + corpusDir + CONFIG_FILENAME)); } catch (MalformedURLException e) { throw new ConfigurationException("Malformed corpus directory"); } } private void load(URL filename) throws ConfigurationException{ Configuration config = new PropertiesConfiguration(filename); try { wildcard = config.getInt(getParamName(PARAM_WILDCARD)); whitelist = config.getStringArray(getParamName(PARAM_WHITELIST)); if (config.containsKey(getParamName(PARAM_TOKEN))) { token = config.getString(getParamName(PARAM_TOKEN)); } if (config.containsKey(getParamName(PARAM_USER))) { user = config.getString(getParamName(PARAM_USER)); } } catch(Exception e) { throw new ConfigurationException("Parameter parsing failed: "+e.getClass().getSimpleName()+" "+e.getMessage()); } } public void replaceWithCommandLine(CommandLine line) throws ConfigurationException { if (line.hasOption(PARAM_WHITELIST)) { String[] channels = line.getOptionValue(PARAM_WHITELIST).split(","); if (channels.length > 0) { this.whitelist = channels; } } if (line.hasOption(PARAM_WILDCARD)) { wildcard = Integer.parseInt(line.getOptionValue(PARAM_WILDCARD)); } if (!line.hasOption(PARAM_USER) || !line.hasOption(PARAM_TOKEN)) { throw new ConfigurationException("Required parameters missing"); } token = line.getOptionValue(PARAM_TOKEN); user = line.getOptionValue(PARAM_USER); } private String getParamName(String param) { return ROOT_NAMESPACE + "." + param; } public String[] getWhitelist() { return whitelist; } public int getWildcard() { return wildcard; } public String getUser() { return user; } public String getToken() { return token; } public void setWildcard(int wildcard) { this.wildcard = wildcard; } public void setWhitelist(String[] whitelist) { this.whitelist = whitelist; } public void setUser(String user) { this.user = user; } public void setToken(String token) { this.token = token; } }
gpl-2.0
rudaoshi/mate
src/se/lth/cs/srl/ml/liblinear/WeightVector.java
7663
package se.lth.cs.srl.ml.liblinear; import java.io.BufferedReader; import java.io.IOException; import java.io.Serializable; import java.util.Collection; import java.util.HashMap; public abstract class WeightVector implements Serializable { private static final long serialVersionUID = 1L; protected double bias; protected int features; protected int classes; public WeightVector(double bias,int features,int classes){ this.bias=bias; this.classes=classes; this.features=features; } /** * Used to parse the weights and return the proper weightvector * @param in the inputstream, assuming header is parsed and weights are next * @param features number of features * @param classes number of classes * @param w the w-string (last line before the weights), should be either 'w' or 'w-sparse' * @return the appropriate weightvector */ public static WeightVector parseWeights(BufferedReader in,int features,int classes,double bias,boolean sparse) throws IOException{ if(sparse){ if(classes==2) return new BinarySparseVector(in,features,bias); else return new MultipleSparseVector(in,features,classes,bias); } else { if(classes==2) return new BinaryLibLinearVector(in,features,bias); else return new MultipleLibLinearVector(in,features,classes,bias); } } public abstract double[] computeAllProbs(Collection<Integer> ints); public abstract short computeBestClass(Collection<Integer> ints); //For binary classifiers public abstract static class BinaryVector extends WeightVector { private static final long serialVersionUID = 1L; public BinaryVector(double bias, int features, int classes) { super(bias, features, classes); } protected abstract double computeScore(Collection<Integer> ints); public double[] computeAllProbs(Collection<Integer> ints){ double[] ret=new double[2]; double prob=(1.0/(1.0+Math.exp(-computeScore(ints)))); ret[0]=prob; ret[1]=1.0-prob; return ret; } public short computeBestClass(Collection<Integer> ints) { if(computeScore(ints)>0) return 0; else return 1; } } public static class BinaryLibLinearVector extends BinaryVector { private static final long serialVersionUID = 1L; private float[] weights; public BinaryLibLinearVector(BufferedReader in,int features,double bias) throws IOException { super(bias,features,2); weights=new float[features+1]; String str; for(int i=0;(str=in.readLine())!=null;++i) weights[i]=Float.parseFloat(str); } protected double computeScore(Collection<Integer> ints){ double sum=(bias>0.0?bias*weights[features]:0.0); for(Integer i:ints){ if((i-1)<features) sum+=weights[i-1]; } return sum; } } public static class BinarySparseVector extends BinaryVector { private static final long serialVersionUID = 1L; private HashMap<Integer,Float> weightMap; public BinarySparseVector(BinaryLibLinearVector vec){ super(vec.bias,vec.features,2); weightMap=new HashMap<Integer,Float>(); for(int i=0;i<vec.features;++i){ if(vec.weights[i]!=0) weightMap.put(i,vec.weights[i]); } if(bias>0) weightMap.put(features,vec.weights[features]); //Bias feature } public BinarySparseVector(BufferedReader in,int features,double bias) throws IOException { super(bias,features,2); weightMap=new HashMap<Integer,Float>(); String str; for(int i=0;(str=in.readLine())!=null;++i){ Float f=Float.parseFloat(str); if(f!=0){ weightMap.put(Integer.valueOf(i),f); } } } protected double computeScore(Collection<Integer> ints){ double sum=bias>0?(weightMap.containsKey(features)?bias*weightMap.get(features):0.d):0.d; for(Integer i:ints){ if((i-1)<features && weightMap.containsKey(i-1)) sum+=weightMap.get(i-1); } return sum; } } //For multiclass classifiers public abstract static class MultipleVector extends WeightVector { private static final long serialVersionUID = 1L; public MultipleVector(double bias, int features, int classes) { super(bias, features, classes); } protected abstract double[] computeScores(Collection<Integer> ints); public double[] computeAllProbs(Collection<Integer> ints) { double[] ret=new double[classes]; double[] scores=computeScores(ints); double sum=0.0; for(short i=0;i<classes;++i){ ret[i]=(1.0/(1.0+Math.exp(-scores[i]))); sum+=ret[i]; } for(short i=0;i<classes;++i) ret[i]/=sum; return ret; } public short computeBestClass(Collection<Integer> ints) { short ret=0; double[] scores=computeScores(ints); for(short i=0;i<classes;++i){ if(scores[i]>scores[ret]) ret=i; } return ret; } } public static class MultipleLibLinearVector extends MultipleVector { private static final long serialVersionUID = 1L; private float[][] weights; public MultipleLibLinearVector(BufferedReader in,int features,int classes,double bias) throws IOException { super(bias,features,classes); weights=new float[classes][features+1]; String str; for(int i=0;(str=in.readLine())!=null;++i){ String[] values=str.split(" "); for(int j=0;j<classes;++j) weights[j][i]=Float.parseFloat(values[j]); } } protected double[] computeScores(Collection<Integer> ints){ double[] ret=new double[classes]; for(int i=0;i<classes;++i){ double curvalue=(bias>0?bias*weights[i][features]:0); for(Integer in:ints){ if((in-1)<features) curvalue+=weights[i][in-1]; } ret[i]=curvalue; } return ret; } } public static class MultipleSparseVector extends MultipleVector { private static final long serialVersionUID = 1L; private HashMap<Integer,WeightArray> weightMap; public MultipleSparseVector(MultipleLibLinearVector vec){ super(vec.bias,vec.features,vec.classes); weightMap=new HashMap<Integer,WeightArray>(); for(int i=0;i<vec.features;++i){ WeightArray wa=new WeightArray(classes); boolean notNull=false; for(int j=0;j<vec.classes;++j){ wa.weights[j]=vec.weights[j][i]; notNull=(notNull || wa.weights[j]!=0); } if(notNull) weightMap.put(i,wa); } //Don't forget the bias feature if(bias>0){ WeightArray wa=new WeightArray(classes); for(int j=0;j<classes;++j) wa.weights[j]=vec.weights[j][features]; weightMap.put(features,wa); } } public MultipleSparseVector(BufferedReader in,int features,int classes,double bias) throws IOException { super(bias,features,classes); weightMap=new HashMap<Integer,WeightArray>(); String str; for(int i=0;(str=in.readLine())!=null;++i){ WeightArray weights=new WeightArray(classes); int j=0; boolean nonZero=false; for(String w:str.split(" ")){ float f=Float.parseFloat(w); weights.weights[j++]=f; nonZero=nonZero || f!=0; } if(nonZero) weightMap.put(Integer.valueOf(i),weights); } } protected double[] computeScores(Collection<Integer> ints){ double[] ret=new double[classes]; for(int i=0;i<classes;++i){ double curvalue=bias>0?(weightMap.containsKey(features)?bias*weightMap.get(features).weights[i]:0d):0d; for(Integer in:ints){ if(weightMap.containsKey(in-1) && (in-1)<features) curvalue+=weightMap.get(in-1).weights[i]; } ret[i]=curvalue; } return ret; } private static class WeightArray implements Serializable { private static final long serialVersionUID = 1L; float[] weights; public WeightArray(int size){ weights=new float[size]; } } } }
gpl-2.0
matejsuchanek/pywikibot-scripts
importdata.py
2739
#!/usr/bin/python import re from datetime import datetime import pywikibot pywikibot.handle_args() site = pywikibot.Site('wikidata', 'wikidata') repo = site.data_repository() direct = pywikibot.input('File directory: ') date = pywikibot.WbTime(year=2021, month=1, day=1, site=repo) ref_item = 'Q106655495' with open(direct, 'r', encoding='utf-8') as file_data: next(file_data) # header for line in file_data: if not line: continue split = line.split('\t') item = pywikibot.ItemPage(repo, split[0]) item.get() hasNewClaim = False upToDateClaims = [] count = int(split[1]) for claim in item.claims.get('P1082', []): if claim.getRank() == 'preferred': claim.setRank('normal') upToDateClaims.append(claim) if (claim.qualifiers.get('P585') and claim.qualifiers['P585'][0].target_equals(date)): hasNewClaim = True break if hasNewClaim is True: continue newClaim = pywikibot.Claim(repo, 'P1082') newClaim.setTarget(pywikibot.WbQuantity(count, site=repo)) newClaim.setRank('preferred') newClaim_date = pywikibot.Claim(repo, 'P585', is_qualifier=True) newClaim_date.setTarget(date) newClaim.addQualifier(newClaim_date) newClaim_criter = pywikibot.Claim(repo, 'P1013', is_qualifier=True) newClaim_criter.setTarget(pywikibot.ItemPage(repo, 'Q2641256')) newClaim.addQualifier(newClaim_criter) newClaim_men = pywikibot.Claim(repo, 'P1540', is_qualifier=True) newClaim_men.setTarget(pywikibot.WbQuantity(int(split[2]), site=repo)) newClaim.addQualifier(newClaim_men) newClaim_women = pywikibot.Claim(repo, 'P1539', is_qualifier=True) newClaim_women.setTarget(pywikibot.WbQuantity(int(split[3]), site=repo)) newClaim.addQualifier(newClaim_women) ref = pywikibot.Claim(repo, 'P248', is_reference=True) ref.setTarget(pywikibot.ItemPage(repo, ref_item)) now = datetime.now() access_date = pywikibot.Claim(repo, 'P813', is_reference=True) access_date.setTarget(pywikibot.WbTime(year=now.year, month=now.month, day=now.day, site=repo)) newClaim.addSources([ref, access_date]) data = {'claims':[newClaim.toJSON()]} for upToDateClaim in upToDateClaims: data['claims'].append(upToDateClaim.toJSON()) item.editEntity( data, asynchronous=True, summary='Adding [[Property:P1082]]: %d per data from [[Q3504917]], ' 'see [[%s]]' % (count, ref_item))
gpl-2.0
dsoprea/PySchedules
setup.py
1360
from setuptools import setup, find_packages version = '0.2.22' setup(name='pyschedules', version=version, description="Interface to Schedules Direct.", long_description="""\ A complete library to pull channels, schedules, actors, lineups, and QAM-maps (channels.conf) data from Schedules Direct.""", classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)', 'Programming Language :: Python', 'Topic :: Home Automation', 'Topic :: Multimedia :: Video :: Capture', 'Topic :: Software Development :: Libraries :: Python Modules', ], keywords='dvb television tv cable schedules direct channel channels qam', author='Dustin Oprea', author_email='[email protected]', url='https://github.com/dsoprea/PySchedules', license='GPL2', packages=['pyschedules/examples'] + find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=True, install_requires=[ 'parsedatetime', ], entry_points=""" # -*- Entry points: -*- """, scripts=[ 'scripts/qam' ] ),
gpl-2.0
jabbalaci/PrimCom
h.py
31814
#!/usr/bin/env python """ PrimCom ======= "Boost your productivity with PrimCom." Manage and access your personal knowledge base easily. Some rules: ----------- * Every key has an associated value, an object. This object must have a "doc", an "action", and a "tags" key. * Tags cannot start with an underscore (they have a special meaning). * The first tag is special, it will be used elsewhere too. So choose the very first tag carefully and make sure it's informative. * Tags must be at least 2 characters long. Also, they cannot be numbers (numbers have a special meaning). """ from __future__ import (absolute_import, division, print_function, unicode_literals) import time start_time = time.time() import atexit import json import os import re import readline import sys from collections import OrderedDict from threading import Thread from urlparse import urljoin import requests import apps import config as cfg from lib import clipboard, common, fs from lib.clipboard import text_to_clipboards from lib.common import bold, cindex, exit_signal, my_exit, open_url, requires from modules import (colored_line_numbers, conferences, header, my_ip, pidcheck, reddit, selected_lines, show, urlshortener, userpass) # If you want the command "less" to use colors, follow the steps in this post: # https://ubuntuincident.wordpress.com/2013/06/05/syntax-highlighted-less-in-command-line/ # these are all re-set in read_json() hdict = OrderedDict() # will be set later tag2keys = OrderedDict() # will be set later #search_result = [] # will be updated after each search last_key = None # will be updated after each command autocomplete_commands = [] # will be filled later (used for autocomplete) dependencies = { # command: package installation 'pygmentize': 'sudo apt-get install python-pygments', 'xsel': 'sudo apt-get install xsel', } LOAD_JSON = cfg.LOAD_JSON ############# ## Helpers ## ############# class NoLastKeyError(Exception): pass def check_dependencies(): for prg in dependencies: if not fs.which(prg): print("Warning: {0} is not available.".format(prg)) print("tip: {0}".format(dependencies[prg])) def completer(text, state): # for autocomplete if re.search(r'^\d+\.', text): # if it starts with a number pos = text.find('.') num = text[:pos] text = text[pos+1:] options = [x for x in autocomplete_commands if x.startswith(text)] try: return num + '.' + options[state] except IndexError: return None else: # normal case options = [x for x in autocomplete_commands if x.startswith(text)] try: return options[state] except IndexError: return None def truncate_histfile(hfile): """ Leave the last N lines of histfile. """ hfile_bak = hfile + ".bak" if os.path.isfile(hfile): os.system("tail -{N} {hf} >{hf_bak}".format(N=cfg.TRUNCATE_HISTFILE_TO_LINES, hf=hfile, hf_bak=hfile_bak)) if os.path.isfile(hfile_bak): os.unlink(hfile) os.rename(hfile_bak, hfile) def setup_history_and_tab_completion(): histfile = "{root}/.history".format(root=cfg.ROOT) # truncate_histfile(histfile) # readline.set_completer(completer) readline.parse_and_bind("tab: complete") if os.path.isfile(histfile): readline.read_history_file(histfile) atexit.register(readline.write_history_file, histfile) def get_db_by_key(key): """ Having a key, tell which DB the item belongs to. """ o = hdict[key] action = o["action"] if action[0] == "cat": val = action[1] return val[:val.find('/')] elif action[0] == "open_url": return "urls" # return None def fname_to_abs(fname): """ In the json files, file names are given like this: "flask/hello.py". Let's convert it to absolute path. """ return "{root}/data/{f}".format(root=cfg.ROOT, f=fname) ############# ## Classes ## ############# class SearchHits(object): inp = None hits = [] @staticmethod def reset(): SearchHits.inp = None SearchHits.hits = [] @staticmethod def show_hint(inp): SearchHits.reset() # SearchHits.inp = inp.lower() for o in hdict.itervalues(): for t in o["tags"]: if inp in t.lower(): #li.append(t) SearchHits.add(t) # SearchHits.remove_duplicates_and_keep_order() # #if li: if SearchHits.hits: #show_tag_list(li) SearchHits.show_tag_list() else: print('Wat?') @staticmethod def add(tag): SearchHits.hits.append(Hit(tag)) @staticmethod def remove_duplicates_and_keep_order(): my_set = set() cleaned = [] for hit in SearchHits.hits: if hit.tag not in my_set: cleaned.append(hit) my_set.add(hit.tag) # SearchHits.hits = cleaned @staticmethod def show_tag_list(li=None): if li: SearchHits.reset() for tag in li: SearchHits.add(tag) for index, e in enumerate(SearchHits.hits, start=1): sys.stdout.write(e.to_str(index)) sys.stdout.write(' ') print() ########## class Hit(object): def __init__(self, tag, key=None): if not key: # normal "constructor": self.tag = tag self.keys = tag2keys[tag] if len(self.keys) == 1: self.o = hdict[self.keys[0]] else: self.o = None else: # alternative "constructor": self.keys = [key] self.o = hdict[key] self.tag = self.o["tags"][0] def __str__(self): return self.tag def is_link(self): if self.o and self.o["action"][0] == "open_url": return True # return False def inspect(self, what): o = self.o if o: if what in ('doc', 'action', 'tags'): print(o[what]) elif what == 'json': print(json.dumps(o, indent=4)) elif what in ('url', 'link'): if self.is_link(): print(o["action"][1]) elif what == 'key': print(self.keys[0]) elif what == 'edit': if len(self.keys) == 1: edit(self.keys[0]) elif what == 'jet': if len(self.keys) == 1: edit_entry(self.keys[0]) else: print("Wat?") def to_str(self, index): s = "" if self.is_link(): s += cindex('({0}) '.format(index), color=cfg.colors[cfg.g.BACKGROUND]["cindex_link"]) else: s += cindex('({0}) '.format(index)) s += self.tag if len(self.keys) > 1: s += '...' return s ########## ## Core ## ########## def process(d): t2k = OrderedDict() # tag2keys # for k in d.iterkeys(): o = d[k] if not(("doc" in o) and ("action" in o) and ("tags" in o)): print("Error: '{k}' must have doc, action, and tags.".format(k=k)) my_exit(1) if len(o["doc"]) == 0: print("Error: '{k}' must have a valid doc.".format(k=k)) my_exit(1) if len(o["tags"]) == 0: print("Error: '{k}' must have at least one tag.".format(k=k)) my_exit(1) for t in o["tags"]: t = t.strip() if t[0] == '_': print("Error: the tag {tag} cannot start with an underscore.".format(tag=t)) my_exit(1) if len(t) == 1: print("Error: the tag '{t}' in {k} is too short.".format(t=t, k=k)) my_exit(1) if t in t2k: t2k[t].append(k) else: t2k[t] = [k] # return t2k def read_json(verbose=True): global hdict, tag2keys, search_result, last_key # hdict = OrderedDict() tag2keys = OrderedDict() search_result = [] last_key = None # for db in LOAD_JSON: tmp = OrderedDict() with open(fname_to_abs(db)) as f: tmp = json.load(f, object_pairs_hook=OrderedDict) for k in tmp: hdict[k] = tmp[k] if verbose: print("# {db} reloaded".format(db=db)) # # sort hdict items by date hdict = OrderedDict(sorted(hdict.iteritems(), key=lambda x: x[1]["meta"]["date"])) # tag2keys = process(hdict) def process_extras(fname, o): """ Currently implemented extras: * cb() -> copy file content to the clipboards """ extra = o.get("extra") if not extra: return # else for e in extra: if e == "cb()": text_to_clipboards(open(fname).read().rstrip("\n")) else: print("Warning: unknown extra option: {e}".format(e=e)) def extract_urls(fname): with open(fname) as f: return re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', f.read()) def show_urls(key): o = hdict[key] # action = o["action"] verb = action[0] if verb == 'cat': fname = fname_to_abs(action[1]) else: return # OK, we have the fname li = extract_urls(fname) for index, url in enumerate(li, start=1): print("[{i}] {url}".format(i=index, url=url)) print("[q] <<") while True: try: inp = raw_input("~~> ").strip() except (KeyboardInterrupt, EOFError): print() return None if len(inp) == 0: continue if inp == 'q': return None if inp == 'qq': my_exit(0) try: index = int(inp) - 1 if index < 0: raise IndexError open_url(li[index]) return except IndexError: print("out of range...") except ValueError: print('Wat?') def subcommand(li): def is_link(k): return Hit(tag=None, key=k).is_link() for index, k in enumerate(li, start=1): if is_link(k): pre = cindex('[{0}]'.format(index), color=cfg.colors[cfg.g.BACKGROUND]["cindex_link"]) else: pre = cindex('[{0}]'.format(index)) print("{pre} {main_tag} ({doc})".format( pre=pre, main_tag=hdict[k]["tags"][0], doc=hdict[k]["doc"] )) print("[q] <<") while True: try: inp = raw_input("~~> ").strip() except (KeyboardInterrupt, EOFError): print() return None if len(inp) == 0: continue if inp == 'q': return None if inp == 'qq': my_exit(0) try: index = int(inp) - 1 if index < 0: raise IndexError perform_action(li[index]) return except IndexError: print("out of range...") except ValueError: print('Wat?') def debug(text): """ for development """ print(os.getcwd()) def command(inp): li = tag2keys[inp] if len(li) > 1: subcommand(li) else: perform_action(li[0]) def perform_action(key, search_term=""): global last_key last_key = key # o = hdict[key] action = o["action"] verb = action[0] if verb == 'cat': fname = fname_to_abs(action[1]) colored_line_numbers.cat(fname, o, search_term) process_extras(fname, o) elif verb == 'open_url': open_url(action[1], o["doc"]) else: print("Error: unknown action: {a}.".format(a=verb)) my_exit(1) def view_edit_json(key): db = get_db_by_key(key) os.system("{ed} {f}".format(ed=cfg.EDITOR, f="{root}/data/{db}.json".format(root=cfg.ROOT, db=db))) def to_clipboards(key): if fs.which("xsel"): o = hdict[key] # action = o["action"] verb = action[0] if verb == 'cat': with open(fname_to_abs(action[1])) as f: text_to_clipboards(f.read().rstrip("\n")) else: print("Warning: xsel is not installed, cannot copy to clipboards.") def path_to_clipboards(key): if fs.which("xsel"): o = hdict[key] # action = o["action"] verb = action[0] if verb == 'cat': f = fname_to_abs(action[1]) print('#', f) text_to_clipboards(f) else: print("Warning: xsel is not installed, cannot copy to clipboards.") def key_to_file(key): """ We have a key and figure out its corresponding file. It only makes sense if the action is "cat". """ if key is None: return None # o = hdict[key] # action = o["action"] verb = action[0] if verb == 'cat': f = fname_to_abs(action[1]) return f # else, if it's a URL to open return None def show_doc(key): o = hdict[key] print(o["doc"]) @requires(cfg.EDITOR) def edit(key): o = hdict[key] # action = o["action"] verb = action[0] if verb == 'cat': os.system("{ed} {fname}".format(ed=cfg.EDITOR, fname=fname_to_abs(action[1]))) @requires(cfg.GEDIT) def gedit(key): o = hdict[key] # action = o["action"] verb = action[0] if verb == 'cat': os.system("{ed} {fname} &".format(ed=cfg.GEDIT, fname=fname_to_abs(action[1]))) def less(key): o = hdict[key] # action = o["action"] verb = action[0] if verb == 'cat': os.system("less {fname}".format(fname=fname_to_abs(action[1]))) def first_google_hit(keyword): url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=" + keyword r = requests.get(url) d = r.json() return d["responseData"]["results"][0]["url"] def cmd_google(keyword): open_url("https://www.google.com/search?q=" + keyword) def cmd_def(word): keyword = "{w} meaning".format(w=word) cmd_google(keyword) def cmd_youtube(keyword): open_url("https://www.youtube.com/results?search_query=" + keyword) def cmd_go1(keyword, site=None): if not site: q = keyword else: q = "site:{site} {kw}".format(site=site, kw=keyword) # url = first_google_hit(q) open_url(url) def open_pep(num): url = 'http://www.python.org/dev/peps' if num: url = "{url}/pep-{num}".format(url=url, num=num.zfill(4)) # open_url(url) def toggle_line_numbers(): cfg.SHOW_LINE_NUMBERS = not cfg.SHOW_LINE_NUMBERS print('show line numbers:', 'on' if cfg.SHOW_LINE_NUMBERS else 'off') def add_item(): os.system("python2 {root}/add_item.py".format(root=cfg.ROOT)) def edit_entry(key): db = get_db_by_key(key) dbfile = "{root}/data/{db}.json".format(root=cfg.ROOT, db=db) d = OrderedDict() d[key] = hdict[key] tmpfile = '{root}/tmp/temp.{pid}.json'.format(root=cfg.ROOT, pid=os.getpid()) with open(tmpfile, 'w') as f: json.dump(d, f, indent=4) assert os.path.isfile(tmpfile) os.system("{ed} {fname}".format(ed=cfg.EDITOR, fname=tmpfile)) # with open(tmpfile) as f: d = json.load(f, object_pairs_hook=OrderedDict) with open(dbfile) as f: dbdict = json.load(f, object_pairs_hook=OrderedDict) # dbdict[key] = d[key] os.unlink(tmpfile) # tmpfile = "{root}/tmp/{db}.json.bak".format(root=cfg.ROOT, db=db) os.rename(dbfile, tmpfile) assert os.path.isfile(tmpfile) with open(dbfile, 'w') as f: json.dump(dbdict, f, indent=4) print("# edited") read_json() def version(): text = """ PrimCom {v} ({date}) by Laszlo Szathmary ([email protected]), 2013--2014 """.format(v=cfg.__version__, date=cfg.__date__) print(text.strip()) def print_header(): header.header() def change_dir(inp): bak = os.getcwd() # if inp == 'cd': os.chdir(os.path.expanduser('~')) elif inp == 'cd -': os.chdir(change_dir.prev_dir) elif inp.startswith('cd '): dest = inp.split()[1] try: os.chdir(dest) except OSError: print('Warning! No such file or directory') # print(os.getcwd()) # static variable: change_dir.prev_dir = bak def username_password(): """ Generate username and password. This is used for online registrations. The function has a static variable called "password", set in init(). If you provide your email in the file email.txt, you can also copy it to the clipboards. """ username = userpass.get_username() password = userpass.get_password(length=12) try: email = open("{root}/email.txt".format(root=cfg.ROOT)).read().strip() except IOError: email = None print(""" [1] {u:21} (username, copy to clipboard) [2] {p:21} (password, copy to clipboard) [3] {e:21} (email, copy to clipboard) [q] << """.strip().format(u=username, p=password, e=email)) while True: try: inp = raw_input("~~> ").strip() except (KeyboardInterrupt, EOFError): print() return if len(inp) == 0: continue elif inp == 'q': return elif inp == 'qq': common.my_exit(0) elif inp == '1': text_to_clipboards(username, prefix="username") elif inp == '2': text_to_clipboards(password, prefix="password") username_password.password = password elif inp == '3': if email: text_to_clipboards(email, prefix="email") else: print("Warning! You have no email specified.") print("Tip: create an email.txt file in the PrimCom folder.") else: print('Wat?') @exit_signal.connect def clear_password(sender): """ Password removal. """ if clipboard.read_primary() == username_password.password: clipboard.to_primary("") if clipboard.read_clipboard() == username_password.password: clipboard.to_clipboard("") if username_password.password: username_password.password = None @requires(cfg.EDITOR) def menu(): print("[{0:.3f}s]".format(time.time() - start_time), end='\n') # while True: try: #inp = raw_input(bold('pc> ')).strip() inp = raw_input(bold('{prompt}> '.format(prompt=os.getcwd()))).strip() except (KeyboardInterrupt, EOFError): print() my_exit(0) if len(inp) == 0: continue if inp in ('h', 'help()'): info() elif inp in ('q', 'qq', ':q', ':x', 'quit()', 'exit()'): my_exit(0) elif inp in ('c', 'clear()'): os.system('clear') print_header() elif inp in ('light()', 'dark()'): if inp == 'light()': cfg.g.BACKGROUND = cfg.LIGHT else: cfg.g.BACKGROUND = cfg.DARK elif inp in ('t', 'tags()', 'all()', 'd'): SearchHits.show_tag_list(tag2keys.keys()) elif inp == 'p': os.system("python3") # default elif inp == 'p2': os.system("python2") elif inp == 'p3': os.system("python3") elif inp == 'bpy': os.system("bpython") elif inp == 'ipy': os.system("ipython") elif inp == 'last()': print(last_key) elif inp == '!!': if last_key: perform_action(last_key) elif inp.startswith('!'): cmd = inp[1:] os.system(cmd) elif inp == 'edit()': if last_key: edit(last_key) elif inp == 'gedit()': if last_key: gedit(last_key) elif inp == 'less()': if last_key: less(last_key) elif inp in ('urls()', 'links()'): if last_key: show_urls(last_key) elif inp in ('cb()', 'tocb()'): if last_key: to_clipboards(last_key) elif inp == 'path()': if last_key: path_to_clipboards(last_key) elif inp == "doc()": if last_key: show_doc(last_key) elif inp == 'json.reload()': read_json() elif inp in ('json.view()', 'json.edit()'): if last_key: view_edit_json(last_key) read_json() elif inp in ("json.edit(this)", "jet()"): if last_key: edit_entry(last_key) elif inp == 'reddit()': reddit.reddit() elif inp == 'conferences()': conferences.conferences() elif inp == 'mute()': apps.radio.radio(None, stop=True) elif inp == 'myip()': my_ip.show_my_ip() elif inp in ('v', 'version()'): version() elif inp == 'commands()': show_commands() elif inp == 'add()': add_item() read_json() elif inp == 'hits()': SearchHits.show_tag_list() elif inp.startswith("pymotw:"): site = "pymotw.com" cmd_go1(inp[inp.find(':')+1:], site=site) elif inp.startswith("go:"): cmd_google(inp[inp.find(':')+1:]) elif inp.startswith("go1:"): cmd_go1(inp[inp.find(':')+1:]) elif inp.startswith("imdb:"): site = "imdb.com" cmd_go1(inp[inp.find(':')+1:], site=site) elif inp.startswith("amazon:"): site = "amazon.com" cmd_go1(inp[inp.find(':')+1:], site=site) elif inp.startswith("youtube:"): cmd_youtube(inp[inp.find(':')+1:]) elif inp.startswith("wp:"): site = "wikipedia.org" cmd_go1(inp[inp.find(':')+1:], site=site) elif inp.startswith("lib:") or inp.startswith("lib2:"): site = "docs.python.org/2/library/" cmd_go1(inp[inp.find(':')+1:], site=site) elif inp.startswith("lib3:"): site = "docs.python.org/3/library/" cmd_go1(inp[inp.find(':')+1:], site=site) elif inp.startswith("golib:"): site = "http://golang.org/pkg/" lib = inp[inp.find(':')+1:] open_url(urljoin(site, lib)) elif inp.startswith("shorten:"): urlshortener.shorten_url(inp[inp.find(':')+1:]) elif inp.startswith("def:"): cmd_def(inp[inp.find(':')+1:]) elif inp.startswith("pep:"): open_pep(inp[inp.find(':')+1:]) elif inp == 'pep()': open_pep(None) elif inp == 'show()': show.show() elif inp == 'numbers()': toggle_line_numbers() elif re.search(r"^l([\d,-]+)\.(sh|py|py2|py3|cb|cb\(>\))$", inp): fname = key_to_file(last_key) selected_lines.process_selected_lines(inp, fname) elif inp == 'cd' or inp.startswith('cd '): change_dir(inp) elif inp == 'pwd()': print(os.getcwd()) elif inp == 'userpass()': username_password() elif inp == 'apps()': apps.menu.main() elif inp == 'k': os.system("konsole 2>/dev/null &") elif inp.startswith("filter:"): term = inp[inp.find(':')+1:] if last_key: perform_action(last_key, term) elif inp.startswith("app:"): val = inp[inp.find(':')+1:] if not val: apps.menu.main() else: apps.menu.start_app(val) # shortcuts elif inp == 'radio()': apps.menu.start_app_by_shortcut('radio') # disabled, always show the search hits #elif inp in tag2keys: # tag = inp # command(tag) elif re.search(r'^\d+$', inp): try: index = int(inp) - 1 if index < 0: raise IndexError tag = SearchHits.hits[index].tag command(tag) except IndexError: print("out of range...") elif re.search(r'^\d+\.(doc|action|tags|json|url|link|key|jet|edit)(\(\))?$', inp): try: pos = inp.find('.') index = int(inp[:pos]) - 1 what = inp[pos+1:].rstrip("()") if index < 0: raise IndexError hit = SearchHits.hits[index] hit.inspect(what) except IndexError: print("out of range...") elif re.search(r'^this.(doc|action|tags|json|url|link|key|jet|edit)(\(\))?$', inp): try: if not last_key: raise NoLastKeyError pos = inp.find('.') what = inp[pos+1:].rstrip("()") hit = Hit(tag=None, key=last_key) hit.inspect(what) except NoLastKeyError: pass elif inp == 'pid()': pidcheck.pid_alert() elif inp == 'debug()': debug(None) elif inp == 'song()': print("Playing:", apps.radio.get_song()) else: if len(inp) == 1: print("too short...") else: inp = inp.lower() SearchHits.show_hint(inp) # ------------------------------------- autocomplete_commands += [ 'debug()', # for development only 'light()', 'dark()', 'help()', 'tags()', 'all()', 'last()', 'doc()', 'edit()', 'gedit()', 'less()', 'bash', 'python', # to be used as !bash and !python 'urls()', 'links()', 'cb()', 'tocb()', 'path()', 'json.reload()', 'json.view()', 'json.edit()', 'jet()', 'this.doc', 'this.action', 'this.tags', 'this.json', 'this.url', 'this.link', 'this.key', 'this.jet()', 'this.edit()', 'hits()', 'reddit()', 'radio()', 'mute()', 'song()', 'conferences()', 'myip()', 'commands()', 'add()', 'clear()', 'quit()', 'exit()', 'version()', 'doc', 'action', 'tags', 'json', 'url', 'link', 'key', 'pid()', 'show()', 'numbers()', 'pwd()', 'userpass()', 'apps()', ] def info(): # If you add something to it, add it to the # global autocomplete_commands list too! text = """ h - this help (or: help()) t, d - available tags (or: tags(), all()) p - python shell <key> - call the action that is associated to <key> <number> - select a key from the previously shown list of keys last() - show last key (debug) doc() - show the doc of the last item !! - call last command !cmd - execute shell command (ex.: !date) edit() - edit the file last shown gedit() - open the file last shown with gedit less() - open the file last shown with less urls() - show URLs in the file last shown tocb() - copy the output of the last command to the clipboards (or: cb()) path() - copy the path of the file last shown to the clipboards json .reload() - reload the json "database" .view() - view the json "database" .edit() - edit the json "database" .edit(this) - edit the json entry of the last selection (or: jet()) NUM - where NUM is the number of a tag in the search list .doc, .action, .tags, .key, .json, .url, .link, .jet, .edit this .doc, .action, .tags, .json, .url, .link, .key, .jet, .edit hits() - latest search hits reddit() - reddit... radio() - radio player... song() - title of the current song on radio show() - show the content of the clipboard in the browser conferences() - Python conferences mute() - stop radio player myip() - my public IP address v - version (or: version()) commands() - list available commands (a command has the form cmd:param) add() - add new item pid() - pid alert... light(), dark() - adjust colors to background numbers() - toggle line numbers cd - change directory pwd() - print working directory userpass() - generate user name and password apps() - applications c - clear screen (or: clear()) q - quit (or: qq, qq(), quit(), exit()) """ print(text.strip()) # ------------------------------------- autocomplete_commands += [ 'pymotw:', 'go:', 'go1:', 'imdb:', 'youtube:', 'amazon:', 'wp:', 'lib:', 'lib2:', 'lib3:', 'shorten:', 'filter:', 'pep:', 'def:', 'golib:', ] def show_commands(): # If you add something to it, add it to the # global autocomplete_commands list too! text = """ Available commands: ------------------- pymotw: - open on PyMOTW, e.g. pymotw:atexit go: - Google search list go1: - open first google hit imdb: - open on IMDb youtube: - open on YouTube wp: - open on wikipedia lib: - look up in Python 2 Standard Library (or: lib2:) lib3: - look up in Python 3 Standard Library shorten: - shorten URL filter: - filter lines of a file that contain a search term pep: - open PEP, e.g. pep:8 def: - define a word golib: - open on Go standard library """ print(text.strip()) # ------------------------------------- def init(): """ Do some initialization. """ if not hasattr(username_password, "password"): username_password.password = None def cleanup(): # threads are subscribed to this signal exit_signal.send() # print("cleanup called") def check_command_line_arguments(): args = sys.argv[1:] for arg in args: if arg in ('-c', '--clear'): os.system("clear") elif arg in ('-k', '--kill'): # suicide mode: do the caching and terminate print("Waiting for the threads to finish...") background_reads(block=True) print("Quit.") sys.exit(0) else: print("Error: unknown option: {}".format(arg), file=sys.stderr) sys.exit(1) def background_reads(block=False): """ Start these jobs in the background. These things are necessary but they take some seconds to complete. Idea: show the prompt right away then finish these things a bit later. If block is True (used in suicide mode), then we are waiting here until all threads are stopped. """ t1 = Thread(target=check_dependencies) t2 = Thread(target=setup_history_and_tab_completion) t3 = Thread(target=read_json, kwargs={'verbose': False}) t4 = Thread(target=colored_line_numbers.cache_pygmentize) t1.start(); t2.start(); t3.start(); t4.start() if block: t1.join(); t2.join(); t3.join(); t4.join() def main(): background_reads() # print_header() menu() ############################################################################# if __name__ == "__main__": init() atexit.register(cleanup) check_command_line_arguments() main()
gpl-2.0
AlanGuerraQuispe/SisAtuxPerfumeria
atux-dao/src/main/java/com/aw/core/dao/DAOHbmInterceptor.java
273
package com.aw.core.dao; import java.util.List; /** * User: JCM * Date: 26/11/2007 */ public interface DAOHbmInterceptor { boolean onUpdateFields(Class entityClass, Object entity, List<String> fieldNames, List fieldValues, List<String> pkNames, List pkValues) ; }
gpl-2.0
swapnilaptara/tao-aptara-assess
taoQtiItem/views/js/qtiCreator/model/interactions/PortableCustomInteraction.js
1311
define([ 'lodash', 'taoQtiItem/qtiCreator/model/mixin/editable', 'taoQtiItem/qtiCreator/model/mixin/editableInteraction', 'taoQtiItem/qtiCreator/model/helper/portableElement', 'taoQtiItem/qtiCreator/editor/customInteractionRegistry', 'taoQtiItem/qtiItem/core/interactions/CustomInteraction' ], function(_, editable, editableInteraction, portableElement, ciRegistry, Interaction){ "use strict"; var _throwMissingImplementationError = function(pci, fnName){ throw fnName + ' not available for pci of type ' + pci.typeIdentifier; }; var methods = {}; _.extend(methods, editable); _.extend(methods, editableInteraction); _.extend(methods, portableElement.getDefaultMethods(ciRegistry)); _.extend(methods, { createChoice : function(){ var creator = ciRegistry.getCreator(this.typeIdentifier); if(_.isFunction(creator.createChoice)){ return creator.createChoice(this); }else{ _throwMissingImplementationError(this, 'createChoice'); } }, getDefaultMarkupTemplateData : function(){ return { responseIdentifier : this.attr('responseIdentifier') }; } }); return Interaction.extend(methods); });
gpl-2.0
amdj/common
src/arma_numpy.cpp
11016
// arma_numpy.cpp // // last-edit-by: J.A. de Jong // // Description: Conversion functions from PyArrayObjects to Armadillo // objects and vice versa // ////////////////////////////////////////////////////////////////////// #define PY_ARRAY_UNIQUE_SYMBOL npy_array #define NO_IMPORT_ARRAY #include "arma_numpy.h" #include <string.h> // Check functions bool check_vd(PyObject * input){ // std::cout << "Check if it is a double array...\n"; bool res= (PyArray_CheckExact(input) && (PyArray_TYPE((PyArrayObject*) input)==NPY_DOUBLE) && (PyArray_NDIM((PyArrayObject*) input)==1))?true:false; // if(res){ // std::cout << "Is is a double array.\n"; // } return res; } bool check_vc(PyObject * input){ // std::cout << "Check if it is a complex array..\n"; bool res=(PyArray_CheckExact(input) && (PyArray_TYPE((PyArrayObject*) input)==NPY_COMPLEX128) && (PyArray_NDIM((PyArrayObject*) input)==1))?true:false; // if(res){ // std::cout << "Is is a complex array..\n"; // } return res; } bool check_vd2(PyObject * input){ // std::cout << "Check if it is a double array of size 2...\n"; bool res=(PyArray_CheckExact(input) && (PyArray_TYPE((PyArrayObject*) input)==NPY_DOUBLE) && (PyArray_NDIM((PyArrayObject*) input)==1) && (PyArray_DIMS((PyArrayObject*) input)[0]==2) )?true:false; // if(res){ // std::cout << "Is is a double array of size 2..\n"; // } return res; } bool check_vc2(PyObject * input){ // std::cout << "Check if it is a complex array of size 2...\n"; bool res=(PyArray_CheckExact(input) && (PyArray_TYPE((PyArrayObject*) input)==NPY_COMPLEX128) && (PyArray_NDIM((PyArrayObject*) input)==1) && (PyArray_DIMS((PyArrayObject*) input)[0]==2) )?true:false; // if(res){ // std::cout << "Is is a complex array of size 2..\n"; // } return res; } bool check_vd4(PyObject * input){ cout << "Not yet implemented!\n"; return false; } bool check_vc4(PyObject * input){ cout << "Not yet implemented!\n"; return false; } bool check_dmat(PyObject * input){ // std::cout << "Checking if its a dmat...\n"; return (PyArray_CheckExact(input) && (PyArray_TYPE((PyArrayObject*) input)==NPY_DOUBLE) && (PyArray_NDIM((PyArrayObject*) input)==2) ) ? true:false; } bool check_cmat(PyObject * input){ return (PyArray_CheckExact(input) && (PyArray_TYPE((PyArrayObject*) input)==NPY_COMPLEX128) && (PyArray_NDIM((PyArrayObject*) input)==2) ) ? true:false; } bool check_dmat22(PyObject * input){ cout << "Not yet implemented!\n"; return false; } bool check_cmat22(PyObject * input){ cout << "Not yet implemented!\n"; return false; } // Annes conversion functions. In a later stage they have to be // generalized for arrays of arbitrary dimensions PyObject *npy_from_vd(const vd &in) { long int size = in.size(); npy_intp dims[1] = {size}; // This code should be improved massively? if (size == 0) { std::cout << "Size is zero!\n"; return nullptr; } PyArrayObject *array = (PyArrayObject *)PyArray_SimpleNew(1, dims, NPY_DOUBLE); if (array == nullptr) { return nullptr; } double *pydat = (double *)PyArray_DATA(array); memcpy(pydat, in.memptr(), size * sizeof(double)); return PyArray_Return(array); } PyObject *npy_from_vd2(const vd2 &in) { long int size = 2; npy_intp dims[1] = {size}; // This code should be improved massively? if (size == 0) { std::cout << "Size is zero!\n"; return nullptr; } PyArrayObject *array = (PyArrayObject *)PyArray_SimpleNew(1, dims, NPY_DOUBLE); if (array == nullptr) { return nullptr; } double *pydat = (double *)PyArray_DATA(array); memcpy(pydat, in.memptr(), size * sizeof(double)); return PyArray_Return(array); } PyObject *npy_from_vc2(const vc2 &in) { TRACE(0,"npy_from_vc2(vc&)"); long int size = 2; npy_intp dims[1] = {size}; // This code should be improved massively? if (size == 0) { std::cout << "Size is zero!\n"; return nullptr; } PyArrayObject *array = (PyArrayObject *)PyArray_SimpleNew(1, dims, NPY_COMPLEX128); if (array == nullptr) { return nullptr; } npy_cdouble *pydat = (npy_cdouble *)PyArray_DATA(array); memcpy(pydat, in.memptr(), size * sizeof(c)); return PyArray_Return(array); } PyObject *npy_from_vc(const vc &in) { TRACE(0,"npy_from_vc(vc&)"); long int size = in.size(); npy_intp dims[1] = {size}; // This code should be improved massively? if (size == 0) { std::cout << "Size is zero!\n"; return nullptr; } PyArrayObject *array = (PyArrayObject *)PyArray_SimpleNew(1, dims, NPY_COMPLEX128); if (array == nullptr) { std::cout << "Array is null" << std::endl; return nullptr; } npy_cdouble *pydat = (npy_cdouble *)PyArray_DATA(array); memcpy(pydat, in.memptr(), size * sizeof(npy_cdouble)); return (PyObject*)array; } vd vd_from_npy(const PyArrayObject *const in) { npy_intp size=PyArray_DIMS(in)[0]; // Extract first double *pydata = (double *)PyArray_DATA(in); vd result(size); memcpy(result.memptr(),pydata,size*sizeof(double)); return result; } dmat dmat_from_npy(PyArrayObject * in) { arma::uword rows=PyArray_DIMS(in)[0]; // Extract first arma::uword cols=PyArray_DIMS(in)[1]; // Extract second arma::uword size=rows*cols; double *pydata = (double *)PyArray_DATA(in); // cout << "size1: " << size1 << "\n"; // cout << "size2: " << size2 << "\n"; dmat result(rows,cols); // Numpy defaultly saves data C-contiguous, or with the lo if(PyArray_IS_F_CONTIGUOUS(in)) memcpy(result.memptr(),pydata,size*sizeof(double)); else{ // If the input array is C-contiguous, the last index varies the // fastest, or, in other words, the array is stored row-by // row. This is incompatible with the Fortran storage. Therefore, // we first create a fortran-contiguous array and copy from there PyArray_Descr* in_descr=PyArray_DESCR(in); PyArrayObject* pyarray_fortran_contiguous=(PyArrayObject*) PyArray_FromArray( in,in_descr,NPY_ARRAY_F_CONTIGUOUS); memcpy(result.memptr(), PyArray_DATA(pyarray_fortran_contiguous), size*sizeof(double)); } // cout << "Returning result\n"; return result; } cmat cmat_from_npy(PyArrayObject * in) { arma::uword rows=PyArray_DIMS(in)[0]; // Extract first arma::uword cols=PyArray_DIMS(in)[1]; // Extract second arma::uword size=rows*cols; void *pydata = PyArray_DATA(in); cmat result(rows,cols); // Numpy defaultly saves data C-contiguous, or with the lo if(PyArray_IS_F_CONTIGUOUS(in)) memcpy(result.memptr(),pydata,size*sizeof(npy_cdouble)); else{ // If the input array is C-contiguous, the last index varies the // fastest, or, in other words, the array is stored row-by // row. This is incompatible with the Fortran storage. Therefore, // we first create a fortran-contiguous array and copy from there PyArray_Descr* in_descr=PyArray_DESCR(in); PyArrayObject* pyarray_fortran_contiguous=(PyArrayObject*) PyArray_FromArray( in,in_descr,NPY_ARRAY_F_CONTIGUOUS); memcpy(result.memptr(), PyArray_DATA(pyarray_fortran_contiguous), size*sizeof(npy_cdouble)); } // cout << "Returning result\n"; return result; } vd vd_from_npy_nocpy(const PyArrayObject *const in) { npy_intp size=PyArray_DIMS(in)[0]; // Extract first double *pydata = (double *)PyArray_DATA(in); return vd((double*)pydata,size,false,false); } vc vc_from_npy_nocpy(const PyArrayObject *const in) { TRACE(0,"vc_from_npy_nocpy"); npy_intp size=PyArray_DIMS(in)[0]; // Extract first npy_cdouble *pydata = (npy_cdouble*)PyArray_DATA(in); return vc((c*)pydata,size,false,false); } vc vc_from_npy(const PyArrayObject *const in) { npy_intp size=PyArray_DIMS(in)[0]; // Extract first // std::cout << "Test2" << std::endl; npy_cdouble *pydata = (npy_cdouble *)PyArray_DATA(in); // std::cout << "Test3" << std::endl; vc result(size); memcpy(result.memptr(),pydata,size*sizeof(npy_cdouble)); return result; } vc2 vc2_from_npy(const PyArrayObject *const in) { npy_intp size=PyArray_DIMS(in)[0]; // Extract first npy_cdouble *pydata = (npy_cdouble *)PyArray_DATA(in); vc2 result; memcpy(result.memptr(),pydata,size*sizeof(npy_cdouble)); return result; } vd2 vd2_from_npy(const PyArrayObject *const in) { npy_intp size=PyArray_DIMS(in)[0]; // Extract first npy_double *pydata = (npy_double *)PyArray_DATA(in); vd2 result; memcpy(result.memptr(),pydata,size*sizeof(npy_double)); return result; } // Conversion for tranfer matrices PyObject *npy_from_dmat22(const dmat22 &in) { npy_intp dims[2] = {2,2}; PyArrayObject *array = (PyArrayObject *)PyArray_EMPTY(2, dims, NPY_DOUBLE,true); if (array == nullptr) { std::cout << "Array is null" << std::endl; return nullptr; } double *pydat = (double *)PyArray_DATA(array); memcpy(pydat, in.memptr(), 4 * sizeof(double)); return (PyObject*)array; } // Convert Armadillo matrix to Numpy Array PyObject *npy_from_dmat(const dmat &in) { // dmat in=in2.t(); npy_intp dims[2] = {(npy_intp) in.n_rows,(npy_intp) in.n_cols}; npy_intp size=(npy_intp) in.n_rows*in.n_cols; // Last PyObject* array = PyArray_EMPTY(2, dims, NPY_DOUBLE, true); if (!array || !PyArray_ISFORTRAN(array)) { std::cout << "Array creation failed" << std::endl; return nullptr; } double *pydat = (double *)PyArray_DATA(array); memcpy(pydat, in.memptr(), size*sizeof(double)); return (PyObject*)array; } PyObject *npy_from_cmat(const cmat &in) { // dmat in=in2.t(); npy_intp dims[2] = {(npy_intp) in.n_rows,(npy_intp) in.n_cols}; npy_intp size=(npy_intp) in.n_rows*in.n_cols; // Last PyObject* array = PyArray_EMPTY(2, dims, NPY_COMPLEX128, true); if (!array || !PyArray_ISFORTRAN(array)) { std::cout << "Array creation failed" << std::endl; return nullptr; } npy_cdouble *pydat = (npy_cdouble *)PyArray_DATA(array); memcpy(pydat, in.memptr(), size*sizeof(npy_cdouble)); return (PyObject*)array; } PyObject *npy_from_cmat22(const cmat22 &in) { npy_intp dims[2] = {2,2}; PyArrayObject *array = (PyArrayObject *)PyArray_EMPTY(2, dims, NPY_COMPLEX128,true); if (array == nullptr) { std::cout << "Array is null" << std::endl; return nullptr; } npy_cdouble *pydat = (npy_cdouble *)PyArray_DATA(array); memcpy(pydat, in.memptr(), 4 * sizeof(npy_cdouble)); return (PyObject*)array; }
gpl-2.0
mrkn/movabletype
php/lib/function.mtcgipath.php
728
<?php # Movable Type (r) Open Source (C) 2001-2010 Six Apart, Ltd. # This program is distributed under the terms of the # GNU General Public License, version 2. # # $Id$ function smarty_function_mtcgipath($args, &$ctx) { // status: complete // parameters: none $path = $ctx->mt->config('CGIPath'); if (substr($path, 0, 1) == '/') { # relative $blog = $ctx->stash('blog'); $host = $blog->site_url(); if (!preg_match('!/$!', $host)) $host .= '/'; if (preg_match('!^(https?://[^/:]+)(:\d+)?/!', $host, $matches)) { $path = $matches[1] . $path; } } if (substr($path, strlen($path) - 1, 1) != '/') $path .= '/'; return $path; } ?>
gpl-2.0
thomas-moulard/visp-deb
src/tracking/dots/vpDot.cpp
24617
/**************************************************************************** * * $Id: vpDot.cpp 4317 2013-07-17 09:40:17Z fspindle $ * * This file is part of the ViSP software. * Copyright (C) 2005 - 2013 by INRIA. All rights reserved. * * This software is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * ("GPL") version 2 as published by the Free Software Foundation. * See the file LICENSE.txt at the root directory of this source * distribution for additional information about the GNU GPL. * * For using ViSP with software that can not be combined with the GNU * GPL, please contact INRIA about acquiring a ViSP Professional * Edition License. * * See http://www.irisa.fr/lagadic/visp/visp.html for more information. * * This software was developed at: * INRIA Rennes - Bretagne Atlantique * Campus Universitaire de Beaulieu * 35042 Rennes Cedex * France * http://www.irisa.fr/lagadic * * If you have questions regarding the use of this file, please contact * INRIA at [email protected] * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * * Description: * Track a white dot. * * Authors: * Eric Marchand * Fabien Spindler * Aurelien Yol * *****************************************************************************/ /* \file vpDot.cpp \brief Track a white dot */ #include <visp/vpDot.h> #include <visp/vpDisplay.h> #include <visp/vpColor.h> // exception handling #include <visp/vpTrackingException.h> #include <vector> /* \class vpDot \brief Track a white dot */ /* spiral size for the dot search */ const unsigned int vpDot::SPIRAL_SEARCH_SIZE = 350; /*! Initialize the tracker with default parameters. - connexityType is set to 4 (see setConnexityType()) - dot maximal size is set to 25% of the image size (see setMaxDotSize()) */ void vpDot::init() { cog.set_u(0); cog.set_v(0); compute_moment = false ; graphics = false ; thickness = 1; maxDotSizePercentage = 0.25 ; // 25 % of the image size mean_gray_level = 0; gray_level_min = 128; gray_level_max = 255; grayLevelPrecision = 0.85; gamma = 1.5 ; m00 = m11 = m02 = m20 = m10 = m01 = mu11 = mu02 = mu20 = 0 ; connexityType = CONNEXITY_4; u_min = u_max = v_min = v_max = 0; gray_level_out = 0; nbMaxPoint = 0; } vpDot::vpDot() : vpTracker() { init() ; } /*! \brief Constructor with initialization of the dot location. \param ip : An image point with sub-pixel coordinates. */ vpDot::vpDot(const vpImagePoint &ip) : vpTracker() { init() ; cog = ip; } /*! \brief Copy constructor. */ vpDot::vpDot(const vpDot& d) : vpTracker() { *this = d ; } /*! \brief Destructor. */ vpDot::~vpDot() { ip_connexities_list.clear() ; } /*! \brief Copy operator. */ vpDot& vpDot::operator=(const vpDot& d) { ip_edges_list = d.ip_edges_list; ip_connexities_list = d.ip_connexities_list; connexityType = d.connexityType; cog = d.getCog(); u_min = d.u_min; v_min = d.v_min; u_max = d.u_max; v_max = d.v_max; graphics = d.graphics ; thickness = d.thickness; maxDotSizePercentage = d.maxDotSizePercentage; gray_level_out = d.gray_level_out; mean_gray_level = d.mean_gray_level ; gray_level_min = d.gray_level_min ; gray_level_max = d.gray_level_max ; grayLevelPrecision = d.grayLevelPrecision; gamma = d.gamma; compute_moment = d.compute_moment ; nbMaxPoint = d.nbMaxPoint; m00 = d.m00; m01 = d.m01; m10 = d.m10; m11 = d.m11; m02 = d.m02; m20 = d.m20; mu11 = d.mu11; mu20 = d.mu20; mu02 = d.mu02; return *this ; } bool vpDot::operator!=(const vpDot& d) { return ( cog != d.getCog() ); } bool vpDot::operator==(const vpDot& d) { return ( cog == d.getCog() ); } /*! This method choose a gray level (default is 0) used to modify the "in" dot level in "out" dot level. This gray level is here needed to stop the recursivity . The pixels of the dot are set to this new gray level "\out\" when connexe() is called. \exception vpTrackingException::initializationError : No valid gray level "out" can be found. This means that the min gray level is set to 0 and the max gray level to 255. This should not occur */ void vpDot::setGrayLevelOut() { if (gray_level_min == 0) { if (gray_level_max == 255) { // gray_level_min = 0 and gray_level_max = 255: this should not occur vpERROR_TRACE("Unable to choose a good \"out\" level") ; throw(vpTrackingException(vpTrackingException::initializationError, "Unable to choose a good \"out\" level")) ; } gray_level_out = static_cast<unsigned char>(gray_level_max + 1u); } } /*! Perform the tracking of a dot by connex components. \param mean_value : Threshold to use for the next call to track() and corresponding to the mean value of the dot intensity. \warning The content of the image is modified thanks to setGrayLevelOut() called before. This method choose a gray level (default is 0) used to modify the "in" dot level in "out" dot level. This gray level is here needed to stop the recursivity . The pixels of the dot are set to this new gray level "\out\". \return vpDot::out if an error occurs, vpDot::in otherwise. \sa setGrayLevelOut() */ bool vpDot::connexe(const vpImage<unsigned char>& I,unsigned int u,unsigned int v, double &mean_value, double &u_cog, double &v_cog, double &n) { std::vector<bool> checkTab(I.getWidth()*I.getHeight(),false); return connexe(I,u,v,mean_value,u_cog,v_cog,n,checkTab); } /*! Perform the tracking of a dot by connex components. \param mean_value : Threshold to use for the next call to track() and corresponding to the mean value of the dot intensity. \warning The content of the image is modified thanks to setGrayLevelOut() called before. This method choose a gray level (default is 0) used to modify the "in" dot level in "out" dot level. This gray level is here needed to stop the recursivity . The pixels of the dot are set to this new gray level "\out\". \return vpDot::out if an error occurs, vpDot::in otherwise. \sa setGrayLevelOut() */ bool vpDot::connexe(const vpImage<unsigned char>& I,unsigned int u,unsigned int v, double &mean_value, double &u_cog, double &v_cog, double &n,std::vector<bool> &checkTab) { unsigned int width = I.getWidth(); unsigned int height= I.getHeight(); // Test if we are in the image if ( (u >= width) || (v >= height) ) { //std::cout << "out of bound" << std::endl; return false; } if(checkTab[u + v*I.getWidth()]) return true; vpImagePoint ip; ip.set_u(u); ip.set_v(v); if (I[v][u] >= gray_level_min && I[v][u] <= gray_level_max) { checkTab[v*I.getWidth() + u] = true; ip_connexities_list.push_back(ip); u_cog += u ; v_cog += v ; n+=1 ; if (n > nbMaxPoint) { vpERROR_TRACE("Too many point %lf (%lf%% of image size). " "This threshold can be modified using the setMaxDotSize() " "method.", n, n / (I.getWidth() * I.getHeight()), nbMaxPoint, maxDotSizePercentage) ; throw(vpTrackingException(vpTrackingException::featureLostError, "Dot to big")) ; } // Bounding box update if (u < this->u_min) this->u_min = u; if (u > this->u_max) this->u_max = u; if (v < this->v_min) this->v_min = v; if (v > this->v_max) this->v_max = v; // Mean value of the dot intensities mean_value = (mean_value *(n-1) + I[v][u]) / n; if (compute_moment==true) { m00++ ; m10 += u ; m01 += v ; m11 += (u*v) ; m20 += u*u ; m02 += v*v ; } } else { //std::cout << "not in" << std::endl; return false; } bool edge = false; //if((int)u-1 >= 0) if(u >= 1) if(!checkTab[u-1 + v*I.getWidth()]) if(!connexe(I,u-1,v, mean_value,u_cog,v_cog, n, checkTab)) edge = true; if(u+1 < I.getWidth()) if(!checkTab[u+1+v*I.getWidth()]) if(!connexe(I,u+1,v,mean_value,u_cog, v_cog, n, checkTab)) edge = true; if(v >= 1) if(!checkTab[u+(v-1)*I.getWidth()]) if(!connexe(I,u, v-1,mean_value,u_cog, v_cog, n, checkTab)) edge = true; if(v+1 < I.getHeight()) if(!checkTab[u+(v+1)*I.getWidth()]) if(!connexe(I,u,v+1,mean_value,u_cog, v_cog, n, checkTab)) edge = true; if (connexityType == CONNEXITY_8) { if(v >= 1 && u >= 1) if(!checkTab[u-1+(v-1)*I.getWidth()]) if(!connexe(I,u-1,v-1,mean_value,u_cog, v_cog, n, checkTab)) edge = true; if(v >= 1 && u+1 < I.getWidth()) if(!checkTab[u+1+(v-1)*I.getWidth()]) if(!connexe(I,u+1,v-1,mean_value,u_cog, v_cog, n, checkTab)) edge = true; if(v+1 < I.getHeight() && u >= 1) if(!checkTab[u-1+(v+1)*I.getWidth()]) if(!connexe(I,u-1,v+1,mean_value, u_cog, v_cog, n, checkTab)) edge = true; if(v+1 < I.getHeight() && u+1 < I.getWidth()) if(!checkTab[u+1+(v+1)*I.getWidth()]) if(!connexe(I,u+1,v+1,mean_value,u_cog, v_cog, n, checkTab)) edge = true; } if(edge){ ip_edges_list.push_back(ip); if (graphics==true) { vpImagePoint ip_(ip); for(unsigned int t=0; t<thickness; t++) { ip_.set_u(ip.get_u() + t); vpDisplay::displayPoint(I, ip_, vpColor::red) ; } //vpDisplay::flush(I); } } return true; } /*! Compute the center of gravity (COG) of the dot using connex components. We assume the origin pixel (u, v) is in the dot. If not, the dot is seach around this origin using a spiral search. \param I : Image to process. \param u : Starting pixel coordinate along the columns from where the dot is searched . \param v : Starting pixel coordinate along the rows from where the dot is searched . \warning The content of the image is modified. \exception vpTrackingException::featureLostError : If the tracking fails. \sa connexe() */ void vpDot::COG(const vpImage<unsigned char> &I, double& u, double& v) { // Set the maximal number of points considering the maximal dot size // image percentage nbMaxPoint = (I.getWidth() * I.getHeight()) * maxDotSizePercentage; // segmentation de l'image apres seuillage // (etiquetage des composante connexe) if (compute_moment) m00 = m11 = m02 = m20 = m10 = m01 = mu11 = mu20 = mu02 = 0; double u_cog = 0 ; double v_cog = 0 ; double npoint = 0 ; this->mean_gray_level = 0 ; ip_connexities_list.clear() ; ip_edges_list.clear(); // Initialise the boundig box this->u_min = I.getWidth(); this->u_max = 0; this->v_min = I.getHeight(); this->v_max = 0; #if 0 // Original version if ( connexe(I, (unsigned int)u, (unsigned int)v, gray_level_min, gray_level_max, mean_gray_level, u_cog, v_cog, npoint) == vpDot::out) { bool sol = false ; unsigned int pas ; for (pas = 2 ; pas <= 25 ; pas ++ )if (sol==false) { for (int k=-1 ; k <=1 ; k++) if (sol==false) for (int l=-1 ; l <=1 ; l++) if (sol==false) { u_cog = 0 ; v_cog = 0 ; ip_connexities_list.clear() ; this->mean_gray_level = 0 ; if (connexe(I, (unsigned int)(u+k*pas),(unsigned int)(v+l*pas), gray_level_min, gray_level_max, mean_gray_level, u_cog, v_cog, npoint) != vpDot::out) { sol = true ; u += k*pas ; v += l*pas ; } } } if (sol == false) { vpERROR_TRACE("Dot has been lost") ; throw(vpTrackingException(vpTrackingException::featureLostError, "Dot has been lost")) ; } } #else // If the dot is not found, search around using a spiral if ( !connexe(I,(unsigned int)u,(unsigned int)v, mean_gray_level, u_cog, v_cog, npoint) ) { bool sol = false ; unsigned int right = 1; unsigned int botom = 1; unsigned int left = 2; unsigned int up = 2; double u_ = u, v_ = v; unsigned int k; // Spiral search from the center to find the nearest dot while( (right < SPIRAL_SEARCH_SIZE) && (sol == false) ) { for (k=1; k <= right; k++) if(sol==false) { u_cog = 0 ; v_cog = 0 ; ip_connexities_list.clear() ; ip_edges_list.clear(); this->mean_gray_level = 0 ; if ( connexe(I, (unsigned int)u_+k, (unsigned int)(v_),mean_gray_level, u_cog, v_cog, npoint) ) { sol = true; u = u_+k; v = v_; } } u_ += k; right += 2; for (k=1; k <= botom; k++) if (sol==false) { u_cog = 0 ; v_cog = 0 ; ip_connexities_list.clear() ; ip_edges_list.clear(); this->mean_gray_level = 0 ; if ( connexe(I, (unsigned int)(u_), (unsigned int)(v_+k),mean_gray_level, u_cog, v_cog, npoint) ) { sol = true; u = u_; v = v_+k; } } v_ += k; botom += 2; for (k=1; k <= left; k++) if (sol==false) { u_cog = 0 ; v_cog = 0 ; ip_connexities_list.clear() ; ip_edges_list.clear(); this->mean_gray_level = 0 ; if ( connexe(I, (unsigned int)(u_-k), (unsigned int)(v_),mean_gray_level,u_cog, v_cog, npoint) ) { sol = true ; u = u_-k; v = v_; } } u_ -= k; left += 2; for (k=1; k <= up; k++) if(sol==false) { u_cog = 0 ; v_cog = 0 ; ip_connexities_list.clear() ; ip_edges_list.clear(); this->mean_gray_level = 0 ; if ( connexe(I, (unsigned int)(u_), (unsigned int)(v_-k),mean_gray_level,u_cog, v_cog, npoint) ) { sol = true ; u = u_; v = v_-k; } } v_ -= k; up += 2; } if (sol == false) { vpERROR_TRACE("Dot has been lost") ; throw(vpTrackingException(vpTrackingException::featureLostError, "Dot has been lost")) ; } } #endif /* vpImagePoint ip; unsigned int i, j; std::list<vpImagePoint>::iterator it; for (it = ip_connexities_list.begin(); it != ip_connexities_list.end(); it ++) { ip = *it; i = (unsigned int) ip.get_i(); j = (unsigned int) ip.get_j(); I[i][j] = 255 ; }*/ u_cog = u_cog/npoint ; v_cog = v_cog/npoint ; u = u_cog ; v = v_cog ; // Initialize the threshold for the next call to track() double Ip = pow((double)this->mean_gray_level/255,1/gamma); if(Ip - (1 - grayLevelPrecision)<0){ gray_level_min = 0 ; } else{ gray_level_min = (unsigned int) (255*pow(Ip - (1 - grayLevelPrecision),gamma)); if (gray_level_min > 255) gray_level_min = 255; } gray_level_max = (unsigned int) (255*pow(Ip + (1 - grayLevelPrecision),gamma)); if (gray_level_max > 255) gray_level_max = 255; //vpCTRACE << "gray_level_min: " << gray_level_min << std::endl; //vpCTRACE << "gray_level_max: " << gray_level_max << std::endl; if (npoint < 5) { vpERROR_TRACE("Dot to small") ; throw(vpTrackingException(vpTrackingException::featureLostError, "Dot to small")) ; } if (npoint > nbMaxPoint) { vpERROR_TRACE("Too many point %lf (%lf%%). Max allowed is %lf (%lf%%). This threshold can be modified using the setMaxDotSize() method.", npoint, npoint / (I.getWidth() * I.getHeight()), nbMaxPoint, maxDotSizePercentage) ; throw(vpTrackingException(vpTrackingException::featureLostError, "Dot to big")) ; } } /*! Maximal size of the region to track in terms of image size percentage. \param percentage : Image size percentage corresponding to the dot maximal size. Values should be in ]0 : 1]. If 1, that means that the dot to track could take up the whole image. During the tracking, if the dot size if bigger than the maximal size allowed an exception is throwed : vpTrackingException::featureLostError. */ void vpDot::setMaxDotSize(double percentage) { if (percentage <= 0.0 || percentage > 1.0) { // print a warning. We keep the default percentage vpTRACE("Max dot size percentage is requested to be set to %lf.", "Value should be in ]0:1]. Value will be set to %lf.", percentage, maxDotSizePercentage); } else { maxDotSizePercentage = percentage; } } /*! Initialize the tracking with a mouse click and update the dot characteristics (center of gravity, moments). Wait a user click in a gray area in the image I. The clicked pixel will be the starting point from which the dot will be tracked. The threshold used to segment the dot is set with the grayLevelPrecision parameter. See the formula in setGrayLevelPrecision() function. The sub pixel coordinates of the dot are updated. To get the center of gravity coordinates of the dot, use getCog(). To compute the moments use setComputeMoments(true) before a call to initTracking(). \warning The content of the image modified since we call track() to compute the dot characteristics. \param I : Image to process. \sa track(), getCog() */ void vpDot::initTracking(const vpImage<unsigned char>& I) { while (vpDisplay::getClick(I, cog) != true) ; unsigned int i = (unsigned int)cog.get_i(); unsigned int j = (unsigned int)cog.get_j(); double Ip = pow((double)I[i][j]/255, 1/gamma); if(Ip - (1 - grayLevelPrecision)<0){ gray_level_min = 0 ; } else{ gray_level_min = (unsigned int) (255*pow(Ip - (1 - grayLevelPrecision),gamma)); if (gray_level_min > 255) gray_level_min = 255; } gray_level_max = (unsigned int) (255*pow(Ip + (1 - grayLevelPrecision),gamma)); if (gray_level_max > 255) gray_level_max = 255; try { track( I ); } catch(...) { vpERROR_TRACE("Error caught") ; throw ; } } /*! Initialize the tracking for a dot supposed to be located at (u,v) and updates the dot characteristics (center of gravity, moments). The threshold used to segment the dot is set to 80 percent of the gray level of the pixel (u,v). The sub pixel coordinates of the dot are updated. To get the center of gravity coordinates of the dot, use getCog(). To compute the moments use setComputeMoments(true) before a call to initTracking(). \warning The content of the image modified since we call track() to compute the dot characteristics. \param I : Image to process. \param ip : Location of the starting point from which the dot will be tracked in the image. \sa track() */ void vpDot::initTracking(const vpImage<unsigned char>& I, const vpImagePoint &ip) { cog = ip ; unsigned int i = (unsigned int)cog.get_i(); unsigned int j = (unsigned int)cog.get_j(); double Ip = pow((double)I[i][j]/255, 1/gamma); if(Ip - (1 - grayLevelPrecision)<0){ gray_level_min = 0 ; } else{ gray_level_min = (unsigned int) (255*pow(Ip - (1 - grayLevelPrecision),gamma)); if (gray_level_min > 255) gray_level_min = 255; } gray_level_max = (unsigned int) (255*pow(Ip + (1 - grayLevelPrecision),gamma)); if (gray_level_max > 255) gray_level_max = 255; try { track( I ); } catch(...) { vpERROR_TRACE("Error caught") ; throw ; } } /*! Initialize the tracking for a dot supposed to be located at (u,v) and updates the dot characteristics (center of gravity, moments). The sub pixel coordinates of the dot are updated. To get the center of gravity coordinates of the dot, use getCog(). To compute the moments use setComputeMoments(true) before a call to initTracking(). \warning The content of the image modified since we call track() to compute the dot characteristics. \param I : Image to process. \param ip : Location of the starting point from which the dot will be tracked in the image. \param gray_level_min : Minimum gray level threshold used to segment the dot; value comprised between 0 and 255. \param gray_level_max : Maximum gray level threshold used to segment the dot; value comprised between 0 and 255. \e gray_level_max should be greater than \e gray_level_min. \sa track(), getCog() */ void vpDot::initTracking(const vpImage<unsigned char>& I, const vpImagePoint &ip, unsigned int gray_level_min, unsigned int gray_level_max) { cog = ip ; this->gray_level_min = gray_level_min; this->gray_level_max = gray_level_max; try { track( I ); } catch(...) { vpERROR_TRACE("Error caught") ; throw ; } } /*! Track and compute the dot characteristics. To get the center of gravity coordinates of the dot, use getCog(). To compute the moments use setComputeMoments(true) before a call to initTracking(). \warning The image is modified (all the pixels that belong to the point are set to white (ie to 255). \param I : Image to process. \sa getCog() */ void vpDot::track(const vpImage<unsigned char> &I) { try{ setGrayLevelOut(); double u = this->cog.get_u(); double v = this->cog.get_v(); COG( I, u, v ) ; this->cog.set_u( u ); this->cog.set_v( v ); if (compute_moment==true) { mu11 = m11 - u*m01; mu02 = m02 - v*m01; mu20 = m20 - u*m10; } if (graphics) { // display a red cross at the center of gravity's location in the image. vpDisplay::displayCross(I, this->cog, 3*thickness+8, vpColor::red, thickness); } } catch(...) { vpERROR_TRACE("Error caught") ; throw ; } } /*! Track and updates the new dot coordinates To compute the moments use setComputeMoments(true) before a call to initTracking() or track(). \warning The image is modified (all the pixels that belong to the point are set to white (ie to 255). \param I : Image to process. \param cog [out] : Sub pixel coordinate of the tracked dot. */ void vpDot::track(const vpImage<unsigned char> &I, vpImagePoint &cog) { track( I ) ; cog = this->cog; } /*! Display in overlay the dot edges and center of gravity. \param I : Image. \param color : The color used for the display. \param thickness : Thickness of the displayed cross located at the dot cog. */ void vpDot::display(const vpImage<unsigned char>& I, vpColor color, unsigned int thickness) { vpDisplay::displayCross(I, cog, 3*thickness+8, color, thickness); std::list<vpImagePoint>::const_iterator it; for (it = ip_edges_list.begin(); it != ip_edges_list.end(); ++it) { vpDisplay::displayPoint(I, *it, color); } } /*! Set the precision of the gray level of the dot. \param grayLevelPrecision : It is a double precision float which value is in ]0,1]: - 1 means full precision, whereas values close to 0 show a very bad accuracy. - Values lower or equal to 0 are brought back to an epsion>0 - Values higher than 1 are brought back to 1 If the initial gray level is I, the gray levels of the dot will be between : \f$Imin=255*\big((\frac{I}{255})^{{\gamma}^{-1}}-(1-grayLevelPrecision)\big)^{\gamma}\f$ and \f$Imax=255*\big((\frac{I}{255})^{{\gamma}^{-1}}+(1-grayLevelPrecision)\big)^{\gamma}\f$ with \f$\gamma=1.5\f$ . \sa setWidth(), setHeight(), setGrayLevelMin(), setGrayLevelMax() */ void vpDot::setGrayLevelPrecision( const double & grayLevelPrecision ) { double epsilon = 0.05; if( grayLevelPrecision<epsilon ) { this->grayLevelPrecision = epsilon; } else if( grayLevelPrecision>1 ) { this->grayLevelPrecision = 1.0; } else { this->grayLevelPrecision = grayLevelPrecision; } } /*! Display the dot center of gravity and its list of edges. \param I : The image used as background. \param cog : The center of gravity. \param edges_list : The list of edges; \param color : Color used to display the dot. \param thickness : Thickness of the dot. */ void vpDot::display(const vpImage<unsigned char>& I,const vpImagePoint &cog, const std::list<vpImagePoint> &edges_list, vpColor color, unsigned int thickness) { vpDisplay::displayCross(I, cog, 3*thickness+8, color, thickness); std::list<vpImagePoint>::const_iterator it; for (it = edges_list.begin(); it != edges_list.end(); ++it) { vpDisplay::displayPoint(I, *it, color); } } /*! Display the dot center of gravity and its list of edges. \param I : The image used as background. \param cog : The center of gravity. \param edges_list : The list of edges; \param color : Color used to display the dot. \param thickness : Thickness of the dot. */ void vpDot::display(const vpImage<vpRGBa>& I,const vpImagePoint &cog, const std::list<vpImagePoint> &edges_list, vpColor color, unsigned int thickness) { vpDisplay::displayCross(I, cog, 3*thickness+8, color, thickness); std::list<vpImagePoint>::const_iterator it; for (it = edges_list.begin(); it != edges_list.end(); ++it) { vpDisplay::displayPoint(I, *it, color); } }
gpl-2.0
baalexander/Video-Streamer-app
Platinum/Neptune/Source/Data/TLS/NptTlsTrustAnchor_0014.cpp
4881
/***************************************************************** | | Neptune - Trust Anchors | | This file is automatically generated by a script, do not edit! | | Copyright (c) 2002-2010, Axiomatic Systems, LLC. | All rights reserved. | | Redistribution and use in source and binary forms, with or without | modification, are permitted provided that the following conditions are met: | * Redistributions of source code must retain the above copyright | notice, this list of conditions and the following disclaimer. | * Redistributions in binary form must reproduce the above copyright | notice, this list of conditions and the following disclaimer in the | documentation and/or other materials provided with the distribution. | * Neither the name of Axiomatic Systems nor the | names of its contributors may be used to endorse or promote products | derived from this software without specific prior written permission. | | THIS SOFTWARE IS PROVIDED BY AXIOMATIC SYSTEMS ''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 AXIOMATIC SYSTEMS BE LIABLE FOR ANY | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ****************************************************************/ #include "NptTls.h" /* Verisign Class 1 Public Primary Certification Authority */ const unsigned char NptTlsTrustAnchor_0014_Data[577] = { 0x30,0x82,0x02,0x3d,0x30,0x82,0x01,0xa6 ,0x02,0x11,0x00,0xcd,0xba,0x7f,0x56,0xf0 ,0xdf,0xe4,0xbc,0x54,0xfe,0x22,0xac,0xb3 ,0x72,0xaa,0x55,0x30,0x0d,0x06,0x09,0x2a ,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x02 ,0x05,0x00,0x30,0x5f,0x31,0x0b,0x30,0x09 ,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55 ,0x53,0x31,0x17,0x30,0x15,0x06,0x03,0x55 ,0x04,0x0a,0x13,0x0e,0x56,0x65,0x72,0x69 ,0x53,0x69,0x67,0x6e,0x2c,0x20,0x49,0x6e ,0x63,0x2e,0x31,0x37,0x30,0x35,0x06,0x03 ,0x55,0x04,0x0b,0x13,0x2e,0x43,0x6c,0x61 ,0x73,0x73,0x20,0x31,0x20,0x50,0x75,0x62 ,0x6c,0x69,0x63,0x20,0x50,0x72,0x69,0x6d ,0x61,0x72,0x79,0x20,0x43,0x65,0x72,0x74 ,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6f ,0x6e,0x20,0x41,0x75,0x74,0x68,0x6f,0x72 ,0x69,0x74,0x79,0x30,0x1e,0x17,0x0d,0x39 ,0x36,0x30,0x31,0x32,0x39,0x30,0x30,0x30 ,0x30,0x30,0x30,0x5a,0x17,0x0d,0x32,0x38 ,0x30,0x38,0x30,0x31,0x32,0x33,0x35,0x39 ,0x35,0x39,0x5a,0x30,0x5f,0x31,0x0b,0x30 ,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02 ,0x55,0x53,0x31,0x17,0x30,0x15,0x06,0x03 ,0x55,0x04,0x0a,0x13,0x0e,0x56,0x65,0x72 ,0x69,0x53,0x69,0x67,0x6e,0x2c,0x20,0x49 ,0x6e,0x63,0x2e,0x31,0x37,0x30,0x35,0x06 ,0x03,0x55,0x04,0x0b,0x13,0x2e,0x43,0x6c ,0x61,0x73,0x73,0x20,0x31,0x20,0x50,0x75 ,0x62,0x6c,0x69,0x63,0x20,0x50,0x72,0x69 ,0x6d,0x61,0x72,0x79,0x20,0x43,0x65,0x72 ,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69 ,0x6f,0x6e,0x20,0x41,0x75,0x74,0x68,0x6f ,0x72,0x69,0x74,0x79,0x30,0x81,0x9f,0x30 ,0x0d,0x06,0x09,0x2a,0x86,0x48,0x86,0xf7 ,0x0d,0x01,0x01,0x01,0x05,0x00,0x03,0x81 ,0x8d,0x00,0x30,0x81,0x89,0x02,0x81,0x81 ,0x00,0xe5,0x19,0xbf,0x6d,0xa3,0x56,0x61 ,0x2d,0x99,0x48,0x71,0xf6,0x67,0xde,0xb9 ,0x8d,0xeb,0xb7,0x9e,0x86,0x80,0x0a,0x91 ,0x0e,0xfa,0x38,0x25,0xaf,0x46,0x88,0x82 ,0xe5,0x73,0xa8,0xa0,0x9b,0x24,0x5d,0x0d ,0x1f,0xcc,0x65,0x6e,0x0c,0xb0,0xd0,0x56 ,0x84,0x18,0x87,0x9a,0x06,0x9b,0x10,0xa1 ,0x73,0xdf,0xb4,0x58,0x39,0x6b,0x6e,0xc1 ,0xf6,0x15,0xd5,0xa8,0xa8,0x3f,0xaa,0x12 ,0x06,0x8d,0x31,0xac,0x7f,0xb0,0x34,0xd7 ,0x8f,0x34,0x67,0x88,0x09,0xcd,0x14,0x11 ,0xe2,0x4e,0x45,0x56,0x69,0x1f,0x78,0x02 ,0x80,0xda,0xdc,0x47,0x91,0x29,0xbb,0x36 ,0xc9,0x63,0x5c,0xc5,0xe0,0xd7,0x2d,0x87 ,0x7b,0xa1,0xb7,0x32,0xb0,0x7b,0x30,0xba ,0x2a,0x2f,0x31,0xaa,0xee,0xa3,0x67,0xda ,0xdb,0x02,0x03,0x01,0x00,0x01,0x30,0x0d ,0x06,0x09,0x2a,0x86,0x48,0x86,0xf7,0x0d ,0x01,0x01,0x02,0x05,0x00,0x03,0x81,0x81 ,0x00,0x4c,0x3f,0xb8,0x8b,0xc6,0x68,0xdf ,0xee,0x43,0x33,0x0e,0x5d,0xe9,0xa6,0xcb ,0x07,0x84,0x4d,0x7a,0x33,0xff,0x92,0x1b ,0xf4,0x36,0xad,0xd8,0x95,0x22,0x36,0x68 ,0x11,0x6c,0x7c,0x42,0xcc,0xf3,0x9c,0x2e ,0xc4,0x07,0x3f,0x14,0xb0,0x0f,0x4f,0xff ,0x90,0x92,0x76,0xf9,0xe2,0xbc,0x4a,0xe9 ,0x8f,0xcd,0xa0,0x80,0x0a,0xf7,0xc5,0x29 ,0xf1,0x82,0x22,0x5d,0xb8,0xb1,0xdd,0x81 ,0x23,0xa3,0x7b,0x25,0x15,0x46,0x30,0x79 ,0x16,0xf8,0xea,0x05,0x4b,0x94,0x7f,0x1d ,0xc2,0x1c,0xc8,0xe3,0xb7,0xf4,0x10,0x40 ,0x3c,0x13,0xc3,0x5f,0x1f,0x53,0xe8,0x48 ,0xe4,0x86,0xb4,0x7b,0xa1,0x35,0xb0,0x7b ,0x25,0xba,0xb8,0xd3,0x8e,0xab,0x3f,0x38 ,0x9d,0x00,0x34,0x00,0x98,0xf3,0xd1,0x71 ,0x94};
gpl-2.0
OS2World/LIB-QT3_Toolkit_Vbox
src/kernel/qprocess.cpp
27180
/**************************************************************************** ** $Id: qprocess.cpp 43 2005-12-19 12:39:14Z dmik $ ** ** Implementation of QProcess class ** ** Created : 20000905 ** ** Copyright (C) 1992-2000 Trolltech AS. All rights reserved. ** ** This file is part of the kernel module of the Qt GUI Toolkit. ** ** This file may be distributed under the terms of the Q Public License ** as defined by Trolltech AS of Norway and appearing in the file ** LICENSE.QPL included in the packaging of this file. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition ** licenses may use this file in accordance with the Qt Commercial License ** Agreement provided with the Software. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/pricing.html or email [email protected] for ** information about Qt Commercial License Agreements. ** See http://www.trolltech.com/qpl/ for QPL licensing information. ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact [email protected] if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include <stdio.h> #include <stdlib.h> #include "qprocess.h" #ifndef QT_NO_PROCESS #include "qapplication.h" #include "private/qinternal_p.h" //#define QT_QPROCESS_DEBUG /*! \class QProcess qprocess.h \brief The QProcess class is used to start external programs and to communicate with them. \ingroup io \ingroup misc \mainclass You can write to the started program's standard input, and can read the program's standard output and standard error. You can pass command line arguments to the program either in the constructor or with setArguments() or addArgument(). The program's working directory can be set with setWorkingDirectory(). If you need to set up environment variables pass them to the start() or launch() functions (see below). The processExited() signal is emitted if the program exits. The program's exit status is available from exitStatus(), although you could simply call normalExit() to see if the program terminated normally. There are two different ways to start a process. If you just want to run a program, optionally passing data to its standard input at the beginning, use one of the launch() functions. If you want full control of the program's standard input (especially if you don't know all the data you want to send to standard input at the beginning), use the start() function. If you use start() you can write to the program's standard input using writeToStdin() and you can close the standard input with closeStdin(). The wroteToStdin() signal is emitted if the data sent to standard input has been written. You can read from the program's standard output using readStdout() or readLineStdout(). These functions return an empty QByteArray if there is no data to read. The readyReadStdout() signal is emitted when there is data available to be read from standard output. Standard error has a set of functions that correspond to the standard output functions, i.e. readStderr(), readLineStderr() and readyReadStderr(). If you use one of the launch() functions the data you pass will be sent to the program's standard input which will be closed once all the data has been written. You should \e not use writeToStdin() or closeStdin() if you use launch(). If you need to send data to the program's standard input after it has started running use start() instead of launch(). Both start() and launch() can accept a string list of strings each of which has the format, key=value, where the keys are the names of environment variables. You can test to see if a program is running with isRunning(). The program's process identifier is available from processIdentifier(). If you want to terminate a running program use tryTerminate(), but note that the program may ignore this. If you \e really want to terminate the program, without it having any chance to clean up, you can use kill(). As an example, suppose we want to start the \c uic command (a Qt command line tool used with \e{Qt Designer}) and perform some operations on the output (the \c uic outputs the code it generates to standard output by default). Suppose further that we want to run the program on the file "small_dialog.ui" with the command line options "-tr i18n". On the command line we would write: \code uic -tr i18n small_dialog.ui \endcode \quotefile process/process.cpp A code snippet for this with the QProcess class might look like this: \skipto UicManager::UicManager() \printline UicManager::UicManager() \printline { \skipto proc = new QProcess( this ); \printline proc = new QProcess( this ); \skipto proc->addArgument( "uic" ); \printuntil this, SLOT(readFromStdout()) ); \skipto if ( !proc->start() ) { \printuntil // error handling \skipto } \printline } \printline } \skipto void UicManager::readFromStdout() \printuntil // Bear in mind that the data might be output in chunks. \skipto } \printline } Although you may need quotes for a file named on the command line (e.g. if it contains spaces) you shouldn't use extra quotes for arguments passed to addArgument() or setArguments(). The readyReadStdout() signal is emitted when there is new data on standard output. This happens asynchronously: you don't know if more data will arrive later. In the above example you could connect the processExited() signal to the slot UicManager::readFromStdout() instead. If you do so, you will be certain that all the data is available when the slot is called. On the other hand, you must wait until the process has finished before doing any processing. Note that if you are expecting a lot of output from the process, you may hit platform-dependent limits to the pipe buffer size. The solution is to make sure you connect to the output, e.g. the readyReadStdout() and readyReadStderr() signals and read the data as soon as it becomes available. Please note that QProcess does not emulate a shell. This means that QProcess does not do any expansion of arguments: a '*' is passed as a '*' to the program and is \e not replaced by all the files, a '$HOME' is also passed literally and is \e not replaced by the environment variable HOME and the special characters for IO redirection ('>', '|', etc.) are also passed literally and do \e not have the special meaning as they have in a shell. Also note that QProcess does not emulate a terminal. This means that certain programs which need direct terminal control, do not work as expected with QProcess. Such programs include console email programs (like pine and mutt) but also programs which require the user to enter a password (like su and ssh). \section1 Notes for OS/2 and Windows users Some OS/2 or Windows commands, for example, \c dir, are not provided by separate applications, but by the command interpreter. If you attempt to use QProcess to execute these commands directly it won't work. One possible solution is to execute the command interpreter itself (\c cmd.exe on OS/2 and on some Windows systems), and ask the interpreter to execute the desired command. Under Windows there are certain problems starting 16-bit applications and capturing their output. Microsoft recommends using an intermediate application to start 16-bit applications. \sa QSocket */ /*! \enum QProcess::Communication This enum type defines the communication channels connected to the process. \value Stdin Data can be written to the process's standard input. \value Stdout Data can be read from the process's standard output. \value Stderr Data can be read from the process's standard error. \value DupStderr Both the process's standard error output \e and its standard output are written to its standard output. (Like Unix's dup2().) This means that nothing is sent to the standard error output. This is especially useful if your application requires that the output on standard output and on standard error must be read in the same order that they are produced. This is a flag, so to activate it you must pass \c{Stdout|Stderr|DupStderr}, or \c{Stdin|Stdout|Stderr|DupStderr} if you want to provide input, to the setCommunication() call. \sa setCommunication() communication() */ /*! Constructs a QProcess object. The \a parent and \a name parameters are passed to the QObject constructor. \sa setArguments() addArgument() start() */ QProcess::QProcess( QObject *parent, const char *name ) : QObject( parent, name ), ioRedirection( FALSE ), notifyOnExit( FALSE ), wroteToStdinConnected( FALSE ), readStdoutCalled( FALSE ), readStderrCalled( FALSE ), comms( Stdin|Stdout|Stderr ) { init(); } /*! Constructs a QProcess with \a arg0 as the command to be executed. The \a parent and \a name parameters are passed to the QObject constructor. The process is not started. You must call start() or launch() to start the process. \sa setArguments() addArgument() start() */ QProcess::QProcess( const QString& arg0, QObject *parent, const char *name ) : QObject( parent, name ), ioRedirection( FALSE ), notifyOnExit( FALSE ), wroteToStdinConnected( FALSE ), readStdoutCalled( FALSE ), readStderrCalled( FALSE ), comms( Stdin|Stdout|Stderr ) { init(); addArgument( arg0 ); } /*! Constructs a QProcess with \a args as the arguments of the process. The first element in the list is the command to be executed. The other elements in the list are the arguments to this command. The \a parent and \a name parameters are passed to the QObject constructor. The process is not started. You must call start() or launch() to start the process. \sa setArguments() addArgument() start() */ QProcess::QProcess( const QStringList& args, QObject *parent, const char *name ) : QObject( parent, name ), ioRedirection( FALSE ), notifyOnExit( FALSE ), wroteToStdinConnected( FALSE ), readStdoutCalled( FALSE ), readStderrCalled( FALSE ), comms( Stdin|Stdout|Stderr ) { init(); setArguments( args ); } /*! Returns the list of arguments that are set for the process. Arguments can be specified with the constructor or with the functions setArguments() and addArgument(). Note that if you want to iterate over the list, you should iterate over a copy, e.g. \code QStringList list = myProcess.arguments(); QStringList::Iterator it = list.begin(); while( it != list.end() ) { myProcessing( *it ); ++it; } \endcode \sa setArguments() addArgument() */ QStringList QProcess::arguments() const { return _arguments; } /*! Clears the list of arguments that are set for the process. \sa setArguments() addArgument() */ void QProcess::clearArguments() { _arguments.clear(); } /*! Sets \a args as the arguments for the process. The first element in the list is the command to be executed. The other elements in the list are the arguments to the command. Any previous arguments are deleted. QProcess does not perform argument substitutions; for example, if you specify "*" or "$DISPLAY", these values are passed to the process literally. If you want to have the same behavior as the shell provides, you must do the substitutions yourself; i.e. instead of specifying a "*" you must specify the list of all the filenames in the current directory, and instead of "$DISPLAY" you must specify the value of the environment variable \c DISPLAY. Note for Windows users. The standard Windows shells, e.g. \c command.com and \c cmd.exe, do not perform file globbing, i.e. they do not convert a "*" on the command line into a list of files in the current directory. For this reason most Windows applications implement their own file globbing, and as a result of this, specifying an argument of "*" for a Windows application is likely to result in the application performing a file glob and ending up with a list of filenames. \sa arguments() addArgument() */ void QProcess::setArguments( const QStringList& args ) { _arguments = args; } /*! Adds \a arg to the end of the list of arguments. The first element in the list of arguments is the command to be executed; the following elements are the command's arguments. \sa arguments() setArguments() */ void QProcess::addArgument( const QString& arg ) { _arguments.append( arg ); } #ifndef QT_NO_DIR /*! Returns the working directory that was set with setWorkingDirectory(), or the current directory if none has been explicitly set. \sa setWorkingDirectory() QDir::current() */ QDir QProcess::workingDirectory() const { return workingDir; } /*! Sets \a dir as the working directory for processes. This does not affect running processes; only processes that are started afterwards are affected. Setting the working directory is especially useful for processes that try to access files with relative paths. \sa workingDirectory() start() */ void QProcess::setWorkingDirectory( const QDir& dir ) { workingDir = dir; } #endif //QT_NO_DIR /*! Returns the communication required with the process, i.e. some combination of the \c Communication flags. \sa setCommunication() */ int QProcess::communication() const { return comms; } /*! Sets \a commFlags as the communication required with the process. \a commFlags is a bitwise OR of the flags defined by the \c Communication enum. The default is \c{Stdin|Stdout|Stderr}. \sa communication() */ void QProcess::setCommunication( int commFlags ) { comms = commFlags; } /*! Returns TRUE if the process has exited normally; otherwise returns FALSE. This implies that this function returns FALSE if the process is still running. \sa isRunning() exitStatus() processExited() */ bool QProcess::normalExit() const { // isRunning() has the side effect that it determines the exit status! if ( isRunning() ) return FALSE; else return exitNormal; } /*! Returns the exit status of the process or 0 if the process is still running. This function returns immediately and does not wait until the process is finished. If normalExit() is FALSE (e.g. if the program was killed or crashed), this function returns 0, so you should check the return value of normalExit() before relying on this value. \sa normalExit() processExited() */ int QProcess::exitStatus() const { // isRunning() has the side effect that it determines the exit status! if ( isRunning() ) return 0; else return exitStat; } /*! Reads the data that the process has written to standard output. When new data is written to standard output, the class emits the signal readyReadStdout(). If there is no data to read, this function returns a QByteArray of size 0: it does not wait until there is something to read. \sa readyReadStdout() readLineStdout() readStderr() writeToStdin() */ QByteArray QProcess::readStdout() { if ( readStdoutCalled ) { return QByteArray(); } readStdoutCalled = TRUE; QMembuf *buf = membufStdout(); readStdoutCalled = FALSE; return buf->readAll(); } /*! Reads the data that the process has written to standard error. When new data is written to standard error, the class emits the signal readyReadStderr(). If there is no data to read, this function returns a QByteArray of size 0: it does not wait until there is something to read. \sa readyReadStderr() readLineStderr() readStdout() writeToStdin() */ QByteArray QProcess::readStderr() { if ( readStderrCalled ) { return QByteArray(); } readStderrCalled = TRUE; QMembuf *buf = membufStderr(); readStderrCalled = FALSE; return buf->readAll(); } /*! Reads a line of text from standard output, excluding any trailing newline or carriage return characters, and returns it. Returns QString::null if canReadLineStdout() returns FALSE. By default, the text is interpreted to be in Latin-1 encoding. If you need other codecs, you can set a different codec with QTextCodec::setCodecForCStrings(). \sa canReadLineStdout() readyReadStdout() readStdout() readLineStderr() */ QString QProcess::readLineStdout() { QByteArray a( 256 ); QMembuf *buf = membufStdout(); if ( !buf->scanNewline( &a ) ) { if ( !canReadLineStdout() ) return QString::null; if ( !buf->scanNewline( &a ) ) return QString( buf->readAll() ); } uint size = a.size(); buf->consumeBytes( size, 0 ); // get rid of terminating \n or \r\n if ( size>0 && a.at( size - 1 ) == '\n' ) { if ( size>1 && a.at( size - 2 ) == '\r' ) a.at( size - 2 ) = '\0'; else a.at( size - 1 ) = '\0'; } return QString( a ); } /*! Reads a line of text from standard error, excluding any trailing newline or carriage return characters and returns it. Returns QString::null if canReadLineStderr() returns FALSE. By default, the text is interpreted to be in Latin-1 encoding. If you need other codecs, you can set a different codec with QTextCodec::setCodecForCStrings(). \sa canReadLineStderr() readyReadStderr() readStderr() readLineStdout() */ QString QProcess::readLineStderr() { QByteArray a( 256 ); QMembuf *buf = membufStderr(); if ( !buf->scanNewline( &a ) ) { if ( !canReadLineStderr() ) return QString::null; if ( !buf->scanNewline( &a ) ) return QString( buf->readAll() ); } uint size = a.size(); buf->consumeBytes( size, 0 ); // get rid of terminating \n or \r\n if ( size>0 && a.at( size - 1 ) == '\n' ) { if ( size>1 && a.at( size - 2 ) == '\r' ) a.at( size - 2 ) = '\0'; else a.at( size - 1 ) = '\0'; } return QString( a ); } /*! \fn void QProcess::launchFinished() This signal is emitted when the process was started with launch(). If the start was successful, this signal is emitted after all the data has been written to standard input. If the start failed, then this signal is emitted immediately. This signal is especially useful if you want to know when you can safely delete the QProcess object when you are not interested in reading from standard output or standard error. \sa launch() QObject::deleteLater() */ /*! Runs the process and writes the data \a buf to the process's standard input. If all the data is written to standard input, standard input is closed. The command is searched for in the path for executable programs; you can also use an absolute path in the command itself. If \a env is null, then the process is started with the same environment as the starting process. If \a env is non-null, then the values in the string list are interpreted as environment setttings of the form \c {key=value} and the process is started with these environment settings. For convenience, there is a small exception to this rule under Unix: if \a env does not contain any settings for the environment variable \c LD_LIBRARY_PATH, then this variable is inherited from the starting process. Returns TRUE if the process could be started; otherwise returns FALSE. Note that you should not use the slots writeToStdin() and closeStdin() on processes started with launch(), since the result is not well-defined. If you need these slots, use start() instead. The process may or may not read the \a buf data sent to its standard input. You can call this function even when a process that was started with this instance is still running. Be aware that if you do this the standard input of the process that was launched first will be closed, with any pending data being deleted, and the process will be left to run out of your control. Similarly, if the process could not be started the standard input will be closed and the pending data deleted. (On operating systems that have zombie processes, Qt will also wait() on the old process.) The object emits the signal launchFinished() when this function call is finished. If the start was successful, this signal is emitted after all the data has been written to standard input. If the start failed, then this signal is emitted immediately. \sa start() launchFinished(); */ bool QProcess::launch( const QByteArray& buf, QStringList *env ) { if ( start( env ) ) { if ( !buf.isEmpty() ) { connect( this, SIGNAL(wroteToStdin()), this, SLOT(closeStdinLaunch()) ); writeToStdin( buf ); } else { closeStdin(); emit launchFinished(); } return TRUE; } else { emit launchFinished(); return FALSE; } } /*! \overload The data \a buf is written to standard input with writeToStdin() using the QString::local8Bit() representation of the strings. */ bool QProcess::launch( const QString& buf, QStringList *env ) { if ( start( env ) ) { if ( !buf.isEmpty() ) { connect( this, SIGNAL(wroteToStdin()), this, SLOT(closeStdinLaunch()) ); writeToStdin( buf ); } else { closeStdin(); emit launchFinished(); } return TRUE; } else { emit launchFinished(); return FALSE; } } /* This private slot is used by the launch() functions to close standard input. */ void QProcess::closeStdinLaunch() { disconnect( this, SIGNAL(wroteToStdin()), this, SLOT(closeStdinLaunch()) ); closeStdin(); emit launchFinished(); } /*! \fn QProcess::PID QProcess::processIdentifier() Returns platform dependent information about the process. This can be used together with platform specific system calls. Under Unix the return value is the PID of the process, or -1 if no process belongs to this object. Under OS/2 the return value is the PID of the process, or (~1) if no process belongs to this object. Under Windows it is a pointer to the \c PROCESS_INFORMATION struct, or 0 if no process is belongs to this object. Use of this function's return value is likely to be non-portable. */ /*! \fn void QProcess::readyReadStdout() This signal is emitted when the process has written data to standard output. You can read the data with readStdout(). Note that this signal is only emitted when there is new data and not when there is old, but unread data. In the slot connected to this signal, you should always read everything that is available at that moment to make sure that you don't lose any data. \sa readStdout() readLineStdout() readyReadStderr() */ /*! \fn void QProcess::readyReadStderr() This signal is emitted when the process has written data to standard error. You can read the data with readStderr(). Note that this signal is only emitted when there is new data and not when there is old, but unread data. In the slot connected to this signal, you should always read everything that is available at that moment to make sure that you don't lose any data. \sa readStderr() readLineStderr() readyReadStdout() */ /*! \fn void QProcess::processExited() This signal is emitted when the process has exited. \sa isRunning() normalExit() exitStatus() start() launch() */ /*! \fn void QProcess::wroteToStdin() This signal is emitted if the data sent to standard input (via writeToStdin()) was actually written to the process. This does not imply that the process really read the data, since this class only detects when it was able to write the data to the operating system. But it is now safe to close standard input without losing pending data. \sa writeToStdin() closeStdin() */ /*! \overload The string \a buf is handled as text using the QString::local8Bit() representation. */ void QProcess::writeToStdin( const QString& buf ) { QByteArray tmp = buf.local8Bit(); tmp.resize( buf.length() ); writeToStdin( tmp ); } /* * Under Windows the implementation is not so nice: it is not that easy to * detect when one of the signals should be emitted; therefore there are some * timers that query the information. * To keep it a little efficient, use the timers only when they are needed. * They are needed, if you are interested in the signals. So use * connectNotify() and disconnectNotify() to keep track of your interest. */ /*! \reimp */ void QProcess::connectNotify( const char * signal ) { #if defined(QT_QPROCESS_DEBUG) qDebug( "QProcess::connectNotify(): signal %s has been connected", signal ); #endif if ( !ioRedirection ) if ( qstrcmp( signal, SIGNAL(readyReadStdout()) )==0 || qstrcmp( signal, SIGNAL(readyReadStderr()) )==0 ) { #if defined(QT_QPROCESS_DEBUG) qDebug( "QProcess::connectNotify(): set ioRedirection to TRUE" ); #endif setIoRedirection( TRUE ); return; } if ( !notifyOnExit && qstrcmp( signal, SIGNAL(processExited()) )==0 ) { #if defined(QT_QPROCESS_DEBUG) qDebug( "QProcess::connectNotify(): set notifyOnExit to TRUE" ); #endif setNotifyOnExit( TRUE ); return; } if ( !wroteToStdinConnected && qstrcmp( signal, SIGNAL(wroteToStdin()) )==0 ) { #if defined(QT_QPROCESS_DEBUG) qDebug( "QProcess::connectNotify(): set wroteToStdinConnected to TRUE" ); #endif setWroteStdinConnected( TRUE ); return; } } /*! \reimp */ void QProcess::disconnectNotify( const char * ) { if ( ioRedirection && receivers( SIGNAL(readyReadStdout()) ) ==0 && receivers( SIGNAL(readyReadStderr()) ) ==0 ) { #if defined(QT_QPROCESS_DEBUG) qDebug( "QProcess::disconnectNotify(): set ioRedirection to FALSE" ); #endif setIoRedirection( FALSE ); } if ( notifyOnExit && receivers( SIGNAL(processExited()) ) == 0 ) { #if defined(QT_QPROCESS_DEBUG) qDebug( "QProcess::disconnectNotify(): set notifyOnExit to FALSE" ); #endif setNotifyOnExit( FALSE ); } if ( wroteToStdinConnected && receivers( SIGNAL(wroteToStdin()) ) == 0 ) { #if defined(QT_QPROCESS_DEBUG) qDebug( "QProcess::disconnectNotify(): set wroteToStdinConnected to FALSE" ); #endif setWroteStdinConnected( FALSE ); } } #endif // QT_NO_PROCESS
gpl-2.0
Hejtman/ultraGarden
server/utils/weather.py
1586
import requests class Weather: # datetime.fromtimestamp(['dt']).strftime('%Y-%m-%d %H:%M:%S') def __init__(self, params): self.params = "&".join("{}={}".format(key, value) for key, value in params.items()) def get_weather(self): # self.value['main']['temp_min', 'temp', 'temp_max', 'humidity'] return requests.get("http://api.openweathermap.org/data/2.5/weather?" + self.params).json() def get_forecast(self): # [?]['main']['temp_min', 'temp', 'temp_max', 'humidity','dt'] return requests.get("http://api.openweathermap.org/data/2.5/forecast?" + self.params).json()['list'] class WeatherSensor(Weather): def __init__(self, key, name, args): Weather.__init__(self, args) self.name = name self.key = key self.value = None def read_value(self): w = self.get_weather() if w: self.value = w['main'][self.key] # UNIT TESTS: if __name__ == '__main__': PARAMS = { 'APPID': 'aa432246c65701ad7ab5c55d83e717b5', 'q': 'Brno,cz', 'units': 'metric' } weather = Weather(PARAMS) assert(weather.get_weather()['name'] == 'Brno') assert(weather.get_weather()['name'] == 'Brno') temperature = WeatherSensor('temp', 'Brno temperature', PARAMS) temperature.read_value() assert(temperature.value > -100) humidity = WeatherSensor('humidity', 'Brno humidity', PARAMS) humidity.read_value() assert(humidity.value > 0) assert(len(weather.get_forecast()) > 30) assert(len(weather.get_forecast()) > 30)
gpl-2.0
1905410/Misago
misago/core/tests/test_exceptionhandlers.py
3563
from django.core import exceptions as django_exceptions from django.core.exceptions import PermissionDenied from django.http import Http404 from django.test import TestCase from misago.users.models import Ban from .. import exceptionhandler from ..exceptions import Banned INVALID_EXCEPTIONS = ( django_exceptions.ObjectDoesNotExist, django_exceptions.ViewDoesNotExist, TypeError, ValueError, KeyError, ) class IsMisagoExceptionTests(TestCase): def test_is_misago_exception_true_for_handled_exceptions(self): """ exceptionhandler.is_misago_exception recognizes handled exceptions """ for exception in exceptionhandler.HANDLED_EXCEPTIONS: self.assertTrue(exceptionhandler.is_misago_exception(exception())) def test_is_misago_exception_false_for_not_handled_exceptions(self): """ exceptionhandler.is_misago_exception fails to recognize other exceptions """ for exception in INVALID_EXCEPTIONS: self.assertFalse(exceptionhandler.is_misago_exception(exception())) class GetExceptionHandlerTests(TestCase): def test_exception_handlers_list(self): """HANDLED_EXCEPTIONS length matches that of EXCEPTION_HANDLERS""" self.assertEqual(len(exceptionhandler.HANDLED_EXCEPTIONS), len(exceptionhandler.EXCEPTION_HANDLERS)) def test_get_exception_handler_for_handled_exceptions(self): """Exception handler has correct handler for every Misago exception""" for exception in exceptionhandler.HANDLED_EXCEPTIONS: exceptionhandler.get_exception_handler(exception()) def test_get_exception_handler_for_non_handled_exceptio(self): """Exception handler has no handler for non-supported exception""" for exception in INVALID_EXCEPTIONS: with self.assertRaises(ValueError): exceptionhandler.get_exception_handler(exception()) class HandleAPIExceptionTests(TestCase): def test_banned(self): """banned exception is correctly handled""" ban = Ban(user_message="This is test ban!") response = exceptionhandler.handle_api_exception( Banned(ban), None) self.assertEqual(response.status_code, 403) self.assertEqual( response.data['ban']['message']['html'], "<p>This is test ban!</p>") def test_permission_denied(self): """permission denied exception is correctly handled""" response = exceptionhandler.handle_api_exception( PermissionDenied(), None) self.assertEqual(response.status_code, 403) self.assertEqual(response.data['detail'], "Permission denied.") def test_permission_message_denied(self): """permission denied with message is correctly handled""" exception = PermissionDenied("You shall not pass!") response = exceptionhandler.handle_api_exception(exception, None) self.assertEqual(response.status_code, 403) self.assertEqual(response.data['detail'], "You shall not pass!") def test_unhandled_exception(self): """our exception handler is not interrupting other exceptions""" for exception in INVALID_EXCEPTIONS: response = exceptionhandler.handle_api_exception(exception(), None) self.assertIsNone(response) response = exceptionhandler.handle_api_exception(Http404(), None) self.assertEqual(response.status_code, 404) self.assertEqual(response.data['detail'], "Not found.")
gpl-2.0
rsmuc/health_monitoring_plugins
test/testagent/snmp_fd.py
1194
import ctypes import netsnmpapi class fd_set(ctypes.Structure): _fields_ = [('fds_bits', ctypes.c_long * 32)] class Timeval(ctypes.Structure): _fields_ = [("tv_sec", ctypes.c_long), ("tv_usec", ctypes.c_long)] def FD_SET(fd, fd_set): """Set fd in fd_set, where fd can may be in range of 0..FD_SETSIZE-1 (FD_SETSIZE is 1024 on Linux).""" l64_offset = fd / 64 bit_in_l64_idx = fd % 64; fd_set.fds_bits[l64_offset] = fd_set.fds_bits[l64_offset] | (2**bit_in_l64_idx) def FD_ISSET(fd, fd_set): """Check if fd is in fd_set.""" l64_offset = fd / 64 bit_in_l64_idx = fd % 64; if fd_set.fds_bits[l64_offset] & (2**bit_in_l64_idx) > 0: return True return False def netsnmp_event_fd(): """Return each netsnmp file descriptor by number.""" maxfd = ctypes.c_int(0) fdset = fd_set() timeval = Timeval(0, 0) fakeblock = ctypes.c_int(1) netsnmpapi.libnsa.snmp_select_info( ctypes.byref(maxfd), ctypes.byref(fdset), ctypes.byref(timeval), ctypes.byref(fakeblock) ) for fd in range(0, maxfd.value): if FD_ISSET(fd, fdset): yield fd
gpl-2.0
drthomas21/CS454
assignments/assignment5/routes/api.js
1466
var config = require("../config.json"); var Api = config.api.comicvine; var superagent = require('superagent'); module.exports = function(server) { server.get('/api/search',function(req,res) { superagent .get(Api.request_url+"/characters") .query({"api_key":Api.api_key}) .query({"filter":"name:"+req.query.name}) .query({"field_list":"aliases,name,deck,id,real_name,image"}) .query({"limit":20}) .query({"format":"json"}) .end(function(error,result) { if(result && result.body) { res.json({ success: result.body.error == "OK", message: result.body.error, results: result.body.results }); } else { res.json({ success: true, message: "", results: [] }); } }); }); server.get('/api/character/:id',function(req,res){ superagent .get(Api.request_url+"/character/4005-"+req.params.id) .query({"api_key":Api.api_key}) .query({"field_list":"aliases,name,description,deck,character_friends,character_enemies,id,powers,real_name,publisher,image,origin,teams"}) .query({"format":"json"}) .end(function(error,result){ if(result && result.body) { res.json({ success: result.body.error == "OK", message: result.body.error, character: result.body.results }); } else { res.json({ success: true, message: "", character: null }); } }); }); };
gpl-2.0
Droces/casabio
vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/Qualcomm/R2D65RedStbl13.php
780
<?php /* * This file is part of PHPExifTool. * * (c) 2012 Romain Neutron <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Qualcomm; use PHPExiftool\Driver\AbstractTag; class R2D65RedStbl13 extends AbstractTag { protected $Id = 'r2_d65_red_stbl[13]'; protected $Name = 'R2D65RedStbl13'; protected $FullName = 'Qualcomm::Main'; protected $GroupName = 'Qualcomm'; protected $g0 = 'MakerNotes'; protected $g1 = 'Qualcomm'; protected $g2 = 'Camera'; protected $Type = '?'; protected $Writable = false; protected $Description = 'R2 D65 Red Stbl 13'; protected $flag_Permanent = true; }
gpl-2.0
tdcribb/bookofrelations
wp-content/plugins/buddypress/bp-themes/bp-default/homepage.php
14570
<?php /* Template Name: Homepage */ ?> <?php get_header(); ?> <div id="primary"> <div id="content" role="main"> <div class="homepage-info"> <div class="hp-left"> <div class="hp-descr"> <span class="hp-descr-title">Welcome to Book of Relations</span></br> <span class="hp-descr-subtitle">Don't let your family stories be forgotten</span></br></br> You fit into a bigger context than you probably think. Our past has created our present. How we are interconnected with our ancestors, al the way down to our parents, is a fascinating area of study. But have you ever wondered how all of our ancestors may have been rlated to each other?</br></br> We aren't just talking about blood relations, or relations by marriage, but relationships founded on geography, neighborhoods, businesses, travels and travails shared by people of a community.</br></br> As a member, you are able to access all of the data in our archives that directly and indirectly relate to you. With a better understanding of our past, we can have a grasp on who we may become in the future.</br></br> This is your opportunity to keep the past alive for generations to come. </div> <div id="hp-statement"> “Thank you, Book of Relations! I can’t tell you how much I appreciate the opportunity to retell all these family stories before it’s too late! My grandchildren will be able to find these and know aobut their family history, even when I’m not here to tell them. Thank you!”</br> -- David, South Carolina </div> </div> <div class="hp-right"> <div id="hp-vid"> <iframe width="350" height="225" src="http://www.youtube.com/embed/6LqKnnV7jGE?feature=player_detailpage" frameborder="0" allowfullscreen></iframe> </div> <div class="hp-comments"> Register to gain access to the Complete Library of Family Stories and begin adding your own stories today.</br> <span>It's FREE!</span> </div> <?php global $bp; ?> <?php if(empty($bp->signup->step)) : $bp->signup->step='request-details';?> <form action="<?php echo bp_get_root_domain().'/'.BP_REGISTER_SLUG;?>" name="signup_form" id="signup_form" class="standard-form hp-register-form" method="post" enctype="multipart/form-data"> <?php if ( 'request-details' == bp_get_current_signup_step() ) : ?> <?php do_action( 'template_notices' ); ?> <?php do_action( 'bp_before_account_details_fields' ); ?> <div class="register-section" id="basic-details-section"> <?php /***** Basic Account Details ******/ ?> <!-- <h4><//?php _e( 'Account Details', 'buddypress' ); ?></h4> --> <div class="reg-form-input"> <label for="signup_username"><?php _e( 'Username', 'buddypress' ); ?> <?php _e( '(required)', 'buddypress' ); ?>NO spaces</label> <?php do_action( 'bp_signup_username_errors' ); ?> <input type="text" name="signup_username" id="signup_username" value="<?php bp_signup_username_value(); ?>" /> </div> <div class="reg-form-input"> <label for="signup_email"><?php _e( 'Email Address', 'buddypress' ); ?> <?php _e( '(required)', 'buddypress' ); ?></label> <?php do_action( 'bp_signup_email_errors' ); ?> <input type="text" name="signup_email" id="signup_email" value="<?php bp_signup_email_value(); ?>" /> </div> <div class="reg-form-input"> <label for="signup_password"><?php _e( 'Choose a Password', 'buddypress' ); ?> <?php _e( '(required)', 'buddypress' ); ?></label> <?php do_action( 'bp_signup_password_errors' ); ?> <input type="password" name="signup_password" id="signup_password" value="" /> </div> <div class="reg-form-input"> <label for="signup_password_confirm"><?php _e( 'Confirm Password', 'buddypress' ); ?> <?php _e( '(required)', 'buddypress' ); ?></label> <?php do_action( 'bp_signup_password_confirm_errors' ); ?> <input type="password" name="signup_password_confirm" id="signup_password_confirm" value="" /> </div> </div><!-- #basic-details-section --> <?php do_action( 'bp_after_account_details_fields' ); ?> <?php /***** Extra Profile Details ******/ ?> <?php if ( bp_is_active( 'xprofile' ) ) : ?> <?php do_action( 'bp_before_signup_profile_fields' ); ?> <div class="register-section" id="profile-details-section"> <!-- <h4><//?php _e( 'Profile Details', 'buddypress' ); ?></h4> --> <?php /* Use the profile field loop to render input fields for the 'base' profile field group */ ?> <?php if ( bp_is_active( 'xprofile' ) ) : if ( bp_has_profile( 'profile_group_id=1' ) ) : while ( bp_profile_groups() ) : bp_the_profile_group(); ?> <?php while ( bp_profile_fields() ) : bp_the_profile_field(); ?> <div class="editfield" rel="<?php echo bp_the_profile_field_name(); ?>"> <?php if ( 'textbox' == bp_get_the_profile_field_type() ) : ?> <label for="<?php bp_the_profile_field_input_name(); ?>"><?php bp_the_profile_field_name(); ?> <?php if ( bp_get_the_profile_field_is_required() ) : ?><?php _e( '(required)', 'buddypress' ); ?><?php endif; ?></label> <?php do_action( 'bp_' . bp_get_the_profile_field_input_name() . '_errors' ); ?> <input type="text" name="<?php bp_the_profile_field_input_name(); ?>" id="<?php bp_the_profile_field_input_name(); ?>" value="<?php bp_the_profile_field_edit_value(); ?>" /> <?php endif; ?> <?php if ( 'textarea' == bp_get_the_profile_field_type() ) : ?> <label for="<?php bp_the_profile_field_input_name(); ?>"><?php bp_the_profile_field_name(); ?> <?php if ( bp_get_the_profile_field_is_required() ) : ?><?php _e( '(required)', 'buddypress' ); ?><?php endif; ?></label> <?php do_action( 'bp_' . bp_get_the_profile_field_input_name() . '_errors' ); ?> <textarea rows="5" cols="40" name="<?php bp_the_profile_field_input_name(); ?>" id="<?php bp_the_profile_field_input_name(); ?>"><?php bp_the_profile_field_edit_value(); ?></textarea> <?php endif; ?> <?php if ( 'selectbox' == bp_get_the_profile_field_type() ) : ?> <label for="<?php bp_the_profile_field_input_name(); ?>"><?php bp_the_profile_field_name(); ?> <?php if ( bp_get_the_profile_field_is_required() ) : ?><?php _e( '(required)', 'buddypress' ); ?><?php endif; ?></label> <?php do_action( 'bp_' . bp_get_the_profile_field_input_name() . '_errors' ); ?> <select name="<?php bp_the_profile_field_input_name(); ?>" id="<?php bp_the_profile_field_input_name(); ?>"> <?php bp_the_profile_field_options(); ?> </select> <?php endif; ?> <?php if ( 'multiselectbox' == bp_get_the_profile_field_type() ) : ?> <label for="<?php bp_the_profile_field_input_name(); ?>"><?php bp_the_profile_field_name(); ?> <?php if ( bp_get_the_profile_field_is_required() ) : ?><?php _e( '(required)', 'buddypress' ); ?><?php endif; ?></label> <?php do_action( 'bp_' . bp_get_the_profile_field_input_name() . '_errors' ); ?> <select name="<?php bp_the_profile_field_input_name(); ?>" id="<?php bp_the_profile_field_input_name(); ?>" multiple="multiple"> <?php bp_the_profile_field_options(); ?> </select> <?php endif; ?> <?php if ( 'radio' == bp_get_the_profile_field_type() ) : ?> <div class="radio"> <span class="label"><?php bp_the_profile_field_name(); ?> <?php if ( bp_get_the_profile_field_is_required() ) : ?><?php _e( '(required)', 'buddypress' ); ?><?php endif; ?></span> <?php do_action( 'bp_' . bp_get_the_profile_field_input_name() . '_errors' ); ?> <?php bp_the_profile_field_options(); ?> <?php if ( !bp_get_the_profile_field_is_required() ) : ?> <a class="clear-value" href="javascript:clear( '<?php bp_the_profile_field_input_name(); ?>' );"><?php _e( 'Clear', 'buddypress' ); ?></a> <?php endif; ?> </div> <?php endif; ?> <?php if ( 'checkbox' == bp_get_the_profile_field_type() ) : ?> <div class="checkbox"> <span class="label"><?php bp_the_profile_field_name(); ?> <?php if ( bp_get_the_profile_field_is_required() ) : ?><?php _e( '(required)', 'buddypress' ); ?><?php endif; ?></span> <?php do_action( 'bp_' . bp_get_the_profile_field_input_name() . '_errors' ); ?> <?php bp_the_profile_field_options(); ?> </div> <?php endif; ?> <?php if ( 'datebox' == bp_get_the_profile_field_type() ) : ?> <div class="datebox"> <label for="<?php bp_the_profile_field_input_name(); ?>_day"><?php bp_the_profile_field_name(); ?> <?php if ( bp_get_the_profile_field_is_required() ) : ?><?php _e( '(required)', 'buddypress' ); ?><?php endif; ?></label> <?php do_action( 'bp_' . bp_get_the_profile_field_input_name() . '_errors' ); ?> <select name="<?php bp_the_profile_field_input_name(); ?>_day" id="<?php bp_the_profile_field_input_name(); ?>_day"> <?php bp_the_profile_field_options( 'type=day' ); ?> </select> <select name="<?php bp_the_profile_field_input_name(); ?>_month" id="<?php bp_the_profile_field_input_name(); ?>_month"> <?php bp_the_profile_field_options( 'type=month' ); ?> </select> <select name="<?php bp_the_profile_field_input_name(); ?>_year" id="<?php bp_the_profile_field_input_name(); ?>_year"> <?php bp_the_profile_field_options( 'type=year' ); ?> </select> </div> <?php endif; ?> <?php if ( bp_current_user_can( 'bp_xprofile_change_field_visibility' ) ) : ?> <p class="field-visibility-settings-toggle" id="field-visibility-settings-toggle-<?php bp_the_profile_field_id() ?>"> <?php printf( __( 'This field can be seen by: <span class="current-visibility-level">%s</span>', 'buddypress' ), bp_get_the_profile_field_visibility_level_label() ) ?> <a href="#" class="visibility-toggle-link">Change</a> </p> <div class="field-visibility-settings" id="field-visibility-settings-<?php bp_the_profile_field_id() ?>"> <fieldset> <legend><?php _e( 'Who can see this field?', 'buddypress' ) ?></legend> <?php bp_profile_visibility_radio_buttons() ?> </fieldset> <a class="field-visibility-settings-close" href="#"><?php _e( 'Close', 'buddypress' ) ?></a> </div> <?php else : ?> <p class="field-visibility-settings-notoggle" id="field-visibility-settings-toggle-<?php bp_the_profile_field_id() ?>"> <?php printf( __( 'This field can be seen by: <span class="current-visibility-level">%s</span>', 'buddypress' ), bp_get_the_profile_field_visibility_level_label() ) ?> </p> <?php endif ?> <?php do_action( 'bp_custom_profile_edit_fields' ); ?> <p class="description"><?php bp_the_profile_field_description(); ?></p> </div> <?php endwhile; ?> <input type="hidden" name="signup_profile_field_ids" id="signup_profile_field_ids" value="<?php bp_the_profile_group_field_ids(); ?>" /> <?php endwhile; endif; endif; ?> </div><!-- #profile-details-section --> <!-- <//?php do_action( 'bp_after_signup_profile_fields' ); ?> --> <?php endif; ?> <div id="agree-terms"><input type="checkbox" class="agree-checkbox" /> I agree to the <span class="reg-accept-terms policy-link">Terms of Use and Privacy Policy</span> for Book of Relations. </div> <?php do_action( 'bp_before_registration_submit_buttons' ); ?> <div class="submit"> <div id="cover-submit"></div> <input type="submit" name="signup_submit" id="signup_submit" value="REGISTER" /> </div> <?php do_action( 'bp_after_registration_submit_buttons' ); ?> <?php wp_nonce_field( 'bp_new_signup' ); ?> <?php endif; // request-details signup step ?> <?php if ( 'completed-confirmation' == bp_get_current_signup_step() ) : ?> <h2><?php _e( 'Sign Up Complete!', 'buddypress' ); ?></h2> <?php do_action( 'template_notices' ); ?> <?php do_action( 'bp_before_registration_confirmed' ); ?> <?php if ( bp_registration_needs_activation() ) : ?> <p><?php _e( 'You have successfully created your account!</br> To begin using this site you will need to activate your account via the email we have just sent to your address.', 'buddypress' ); ?></p> <?php else : ?> <p><?php _e( 'You have successfully created your account!</br> Please log in using the username and password you have just created.', 'buddypress' ); ?></p> <?php endif; ?> <?php do_action( 'bp_after_registration_confirmed' ); ?> <?php endif; // completed-confirmation signup step ?> <?php do_action( 'bp_custom_signup_steps' ); ?> </form> <?php endif; ?> <div class="hp-reg-publish"> Or register as a Publishing Member to begin adding your own chapters into the Book of Relations. <a class="memb-btn-link" href="/membership-options"> <img id="membership-btn" src="/wp-content/images/register/member-opt-btn.png" /> </a> </div> </div> </div> </div><!-- #content --> </div><!-- #primary --> <?php get_footer(); ?>
gpl-2.0
Karniyarik/karniyarik
karniyarik-web/src/main/java/com/karniyarik/web/citydeals/CityDealRSSGenerator.java
5966
package com.karniyarik.web.citydeals; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import com.karniyarik.common.util.StringUtil; import com.karniyarik.web.json.LinkedLabel; import com.karniyarik.web.servlet.image.ImageServlet; import com.sun.syndication.feed.synd.SyndContent; import com.sun.syndication.feed.synd.SyndContentImpl; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndEntryImpl; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.feed.synd.SyndFeedImpl; import com.sun.syndication.feed.synd.SyndImage; import com.sun.syndication.feed.synd.SyndImageImpl; public class CityDealRSSGenerator { //http://feeds.feedburner.com/sehirfirsatlari/rss/adana public CityDealRSSGenerator() { } public SyndFeed generateCityRSS(CityResult result,int maxNumberOfDeals) { try { List<CityDealResult> cityDeals = new CityDealConverter(result.getValue(), Integer.MAX_VALUE, CityDealConverter.SORT_DPERCENTAGE, false).getCityDeals(); int addedDealCount = 0; Date date = new Date(); SyndFeed feed = new SyndFeedImpl(); feed.setFeedType("rss_2.0"); feed.setAuthor("[email protected]"); feed.setDescription(result.getName() + " şehir fırsatlarının tümünü bulabileceğiniz RSS kanalı"); feed.setEncoding(StringUtil.DEFAULT_ENCODING); feed.setTitle("Karnıyarık "+ result.getName() +" Şehir Fırsatları"); feed.setLink("http://www.karniyarik.com/sehirfirsatlari/rss/" + result.getName().toLowerCase(Locale.ENGLISH)); SyndImage feedImage = new SyndImageImpl(); feedImage.setLink(feed.getLink()); feedImage.setTitle(feed.getTitle()); feedImage.setUrl("http://www.karniyarik.com/images/logo/karniyarik86x86.png"); feed.setImage(feedImage); feed.setLanguage("tr"); feed.setPublishedDate(date); List<SyndEntry> entries = new ArrayList<SyndEntry>(); for(CityDealResult cityDeal: cityDeals) { if(addedDealCount == maxNumberOfDeals) break; SyndEntry entry = new SyndEntryImpl(); entry.setAuthor("[email protected]"); entry.setTitle(CityDealConverter.getTitle(cityDeal, 100)); //entry.setLink(cityDeal.getShareURL()); String productURL = cityDeal.getShareURL(); productURL = productURL.replace("source=web", "source=rss"); entry.setLink(productURL); entry.setPublishedDate(cityDeal.getStartDate()); entry.setSource(feed); entry.setUpdatedDate(cityDeal.getStartDate()); SyndContent content = new SyndContentImpl(); content.setType("text/html"); StringBuffer htmlContent = new StringBuffer(); htmlContent.append("<div>"); htmlContent.append("<div style='width:180px;height:200px;float:left;margin-right:10px;'>"); htmlContent.append("<a href='");htmlContent.append(productURL);htmlContent.append("'>"); String imgUrl = ImageServlet.getImageRszUrl("http://www.karniyarik.com", cityDeal.getImage(), cityDeal.getImageName(), 180, 140); htmlContent.append("<img style='width:180px;height:140px;' src='");htmlContent.append(imgUrl);htmlContent.append("'/>"); htmlContent.append("</a>"); htmlContent.append("<div style='width:180px;background-color:#81AB00;border:1px solid #AAC652;line-height:40px;text-align:center;vertical-align:center;margin-top:10px;font-size:20px;'>"); htmlContent.append("<a style='color:white;text-decoration:none;' href='");htmlContent.append(productURL);htmlContent.append("'>"); htmlContent.append("Satın Al"); htmlContent.append("</a>"); htmlContent.append("</div>"); htmlContent.append("</div>"); htmlContent.append("<div style='display:table;min-width:540px;height:200px;'>"); htmlContent.append("<div style='font-size:16px;height:140px;display:inline-block;color:#6F6F6F;overflow:hidden;'>"); htmlContent.append(LinkedLabel.getShortenedLabel(cityDeal.getDescription(), 350)); htmlContent.append("<a style='color:white;text-decoration:none;' href='");htmlContent.append(productURL);htmlContent.append("'>"); htmlContent.append("Devamı için tıklayınız"); htmlContent.append("</a>"); htmlContent.append("</div>"); htmlContent.append("<div style='font-size:11px;font-weight:bold;width:240px;text-align:center;margin-top:10px;height:40px;line-height:16px;'>"); htmlContent.append("<div style='background-color:#EFEFEF;color:#222222;float:left;width:80px;'><div>Fiyat<br><span style='font-size:16px !important;line-height:24px;'>"); htmlContent.append(cityDeal.getDiscountPrice()); htmlContent.append(" "); htmlContent.append(cityDeal.getPriceCurrency()); htmlContent.append("</span></div></div>"); htmlContent.append("<div style='background-color:#AAC652;color:#446A00;float:left;width:80px;'><div>Eski Fiyat<br><span style='font-size:16px !important;line-height:24px;'>"); htmlContent.append(cityDeal.getPrice()); htmlContent.append(" "); htmlContent.append(cityDeal.getPriceCurrency()); htmlContent.append("</span></div></div>"); htmlContent.append("<div style='background-color:#81AB00;color:#FFFFFF;float:left;width:80px;'><div>Kazanç<br><span style='font-size:16px !important;line-height:24px;'>"); htmlContent.append(cityDeal.getDiscountPercentage()); htmlContent.append("</span></div></div>"); htmlContent.append("</div>"); htmlContent.append("</div>"); htmlContent.append("</div>"); content.setValue(htmlContent.toString()); entry.setDescription(content); entries.add(entry); addedDealCount++; } feed.setEntries(entries); return feed; } catch (Throwable e) { e.printStackTrace(); return null; } } public static void main(String[] args) { } }
gpl-2.0
meijmOrg/Repo-test
freelance-hr-component/src/java/com/yh/hr/component/gw/service/GwFlowUseOutService.java
420
package com.yh.hr.component.gw.service; import java.util.List; import com.yh.hr.res.gw.dto.GwFlowDTO; import com.yh.platform.core.exception.ServiceException; /** * 岗位资源释放服务接口 * @author liuhw * 2016-8-23 */ public interface GwFlowUseOutService{ /** * 释放 * @param list * @throws ServiceException */ public void useOut(List<GwFlowDTO> list) throws ServiceException; }
gpl-2.0
AnvilLabDE/AnvilCore
src/anvil/Minefabser/API/base/AnvilPlayer.java
966
package anvil.Minefabser.API.base; import java.sql.SQLException; import java.util.UUID; import org.bukkit.entity.Player; import org.json.simple.parser.ParseException; public class AnvilPlayer extends AnvilSender { private UUID uniqueID; /** * Erstellt/lädt einen AnvilPlayer basierend auf einem {@link AnvilSender}, welcher auf einem {@link AnvilSubject} basiert * * @param {@link Player} der dem AnvilPlayer zugeordnet sein soll * @throws SQLException * @throws ParseException */ public AnvilPlayer(Player p) throws SQLException, ParseException { super(p); this.uniqueID = p.getUniqueId(); } /** * Gibt den {@link Player} zum AnvilPlayer zurück * * @return {@link Player} */ public Player getPlayer() { return (Player) super.getCommandSender(); } /** * Gibt die UniqueID ({@link UUID}) des AnvilUser zurück * * @return UniqueID - {@link UUID} */ public UUID getUniqueID() { return this.uniqueID; } }
gpl-2.0
lab313ru/idados_dosbox
idados/dosbox_local_impl.cpp
2216
#include <segment.hpp> #include <srarea.hpp> //-------------------------------------------------------------------------- // installs or uninstalls debugger specific idc functions inline bool register_idc_funcs(bool) { return true; } //-------------------------------------------------------------------------- void idaapi rebase_if_required_to(ea_t new_base) { ea_t currentbase = new_base; ea_t imagebase = inf.baseaddr<<4; msg("imagebase = %a newbase=%a\n", imagebase, new_base); if ( imagebase != currentbase ) { adiff_t delta = currentbase - imagebase; delta /= 16; msg("delta = %d\n", delta); int code = rebase_program(currentbase - imagebase, MSF_FIXONCE); if ( code != MOVE_SEGM_OK ) { msg("Failed to rebase program, error code %d\n", code); warning("IDA failed to rebase the program.\n" "Most likely it happened because of the debugger\n" "segments created to reflect the real memory state.\n\n" "Please stop the debugger and rebase the program manually.\n" "For that, please select the whole program and\n" "use Edit, Segments, Rebase program with delta 0x%08a", currentbase - imagebase); } warning("Database rebased to %ah\n", new_base); } } //-------------------------------------------------------------------------- static bool init_plugin(void) { #ifndef RPC_CLIENT if (!init_subsystem()) return false; #endif if ( !netnode::inited() || is_miniidb() || inf.is_snapshot() ) { //dosbox is always remote. return debugger.is_remote(); } if ( inf.filetype != f_EXE && inf.filetype != f_COM ) return false; // only MSDOS EXE or COM files if ( ph.id != PLFM_386 ) return false; // only IBM PC return true; } //-------------------------------------------------------------------------- inline void term_plugin(void) { } //-------------------------------------------------------------------------- char comment[] = "Userland dosbox debugger plugin."; char help[] = "Userland dosbox debugger plugin.\n" "\n" "This module lets you debug programs running in DOSBox.\n";
gpl-2.0
taipeicity/i-voting
components/com_surveyforce/models/place_login.php
1161
<?php /** * @package Surveyforce * @version 1.2-modified * @copyright JooPlce Team, 臺北市政府資訊局, Copyright (C) 2016. All rights reserved. * @license GPL-2.0+ * @author JooPlace Team, 臺北市政府資訊局- http://doit.gov.taipei/ */ defined('_JEXEC') or die('Restricted access'); jimport('joomla.application.component.modellist'); /** * Place_login Model. */ class SurveyforceModelPlace_login extends JModelItem { public function __construct() { parent::__construct(); } public function populateState() { $app = JFactory::getApplication(); $jinput = $app->input; $params = $app->getParams(); $survey_id = $params->get('survey_id'); $this->setState('survey.id', $survey_id); $this->setState('params', $params); } public function getSurveyParams() { $app = JFactory::getApplication(); $params = $app->getParams(); return $params; } public function getSurveyConfig() { $params = JComponentHelper::getParams('com_surveyforce'); return $params; } }
gpl-2.0
WillisWare/loki
Mil.AirForce.Loki.Tests/Properties/AssemblyInfo.cs
1461
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("Loki Test Project")] [assembly: AssemblyDescription("Unit tests for the Loki application.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("U.S. Air Force")] [assembly: AssemblyProduct("LOKI")] [assembly: AssemblyCopyright("Copyright © USAF 2015")] [assembly: AssemblyTrademark("USAF, LOKI")] [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("29790134-8f49-4cf3-b312-99857ea33fc5")] // 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.4.2.0")] [assembly: AssemblyFileVersion("1.4.2.0")]
gpl-2.0
tvwerkhoven/FOAM
ui/devicectrl.cc
3877
/* devicectrl.cc -- generic device controller Copyright (C) 2010--2011 Tim van Werkhoven <[email protected]> This file is part of FOAM. FOAM 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. FOAM 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 FOAM. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <string> #include <pthread.h> #include "protocol.h" #include "devicectrl.h" using namespace std; DeviceCtrl::DeviceCtrl(Log &log, const string h, const string p, const string n): host(h), port(p), devname(n), protocol(host, port, devname), log(log), ok(false), calib(false), init(false), errormsg("Not connected") { log.term(format("%s(name=%s)", __PRETTY_FUNCTION__, n.c_str())); // Open control connection, register basic callbacks protocol.slot_message = sigc::mem_fun(this, &DeviceCtrl::on_message_common); protocol.slot_connected = sigc::mem_fun(this, &DeviceCtrl::on_connected); } DeviceCtrl::~DeviceCtrl() { log.term(format("%s", __PRETTY_FUNCTION__)); } void DeviceCtrl::connect() { log.term(format("%s (%s:%s, %s)", __PRETTY_FUNCTION__, host.c_str(), port.c_str(), devname.c_str())); protocol.connect(); } void DeviceCtrl::send_cmd(const string &cmdstr) { lastcmd = cmdstr; protocol.write(cmdstr); string cmdcp = cmdstr; string cmd = popword(cmdcp); string what = popword(cmdcp); set<string>::iterator it = cmd_ign_list.find(what); if (it == cmd_ign_list.end()) log.add(Log::DEBUG, devname + ": -> " + cmdstr); log.term(format("%s (%s)", __PRETTY_FUNCTION__, cmdstr.c_str())); } void DeviceCtrl::on_message_common(string line) { log.term(format("%s (%s)", __PRETTY_FUNCTION__, line.c_str())); // Save line for passing to on_message() string orig = line; string stat = popword(line); string cmd = popword(line); if (stat != "ok") { ok = false; errormsg = line; log.add(Log::ERROR, devname + ": <- " + stat + " " + cmd + " " + line); } else { ok = true; set<string>::iterator it = cmd_ign_list.find(cmd); if (it == cmd_ign_list.end()) log.add(Log::OK, devname + ": <- " + stat + " " + cmd + " " + line); // Common functions are complete, call on_message for further parsing. // DeviceCtrl::on_message() is virtual so it will call the derived class first. // Only call in case of success on_message(orig); } } void DeviceCtrl::on_message(string line) { // Discard first 'ok' or 'err' (DeviceCtrl::on_message_common() already parsed this) string stat = popword(line); // Parse list of commands device can accept here string what = popword(line); if (what == "commands") { // The rest should be semicolon-delimited commands: "<cmd> [opts]; <cmd2> [opts];" etc. int ncmds = popint32(line); devcmds.clear(); for (int i=0; i<ncmds; i++) { string cmd = popword(line, ";"); if (cmd == "") break; devcmds.push_back(cmd); } // Sort alphabetically & notify GUI of update devcmds.sort(); signal_commands(); return; } else log.add(Log::WARNING, "Unknown response: " + devname + ": <- " + stat + " " + what); signal_message(); } void DeviceCtrl::on_connected(bool conn) { log.term(format("%s (%d)", __PRETTY_FUNCTION__, conn)); if (conn) send_cmd("get commands"); else { ok = false; errormsg = "Not connected"; devcmds.clear(); //! @todo should we explictly disconnect the socket here too? Otherwise protocol will reconnect immediately. } signal_connect(); }
gpl-2.0
tonglin/pdPm
public_html/typo3_src-6.1.7/typo3/sysext/t3editor/res/jslib/ts_codecompletion/completionresult.js
3887
/*************************************************************** * Copyright notice * * (c) 2008-2010 Stephan Petzl <[email protected]> and Christian Kartnig <[email protected]> * All rights reserved * * This script is part of the TYPO3 project. The TYPO3 project is * free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * The GNU General Public License can be found at * http://www.gnu.org/copyleft/gpl.html. * A copy is found in the textfile GPL.txt and important notices to the license * from the author is found in LICENSE.txt distributed with these scripts. * * * This script 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. * * This copyright notice MUST APPEAR in all copies of the script! ***************************************************************/ /** * @fileoverview contains the CompletionResult class */ /** * @class this class post-processes the result from the codecompletion, so that it can be * displayed in the next step. * @constructor * @param tsRef the TsRef Tree * @param tsTreeNode the current Node in the codetree built by the parser * @return a new CompletionResult instance */ var CompletionResult = function(tsRef,tsTreeNode) { var currentTsTreeNode = tsTreeNode; var tsRef = tsRef; /** * returns the type of the currentTsTreeNode */ this.getType = function() { var val = currentTsTreeNode.getValue(); if (tsRef.isType(val)) { return tsRef.getType(val); } else { return null; } } /** * returns a list of possible path completions (proposals), which is: * a list of the children of the current TsTreeNode (= userdefined properties) * and a list of properties allowed for the current object in the TsRef * remove all words from list that don't start with the string in filter * @param {String} filter beginning of the words contained in the proposal list * @returns an Array of Proposals */ this.getFilteredProposals = function(filter) { var defined = new Array(); var propArr = new Array(); var childNodes = currentTsTreeNode.getChildNodes(); var value = currentTsTreeNode.getValue(); // first get the childNodes of the Node (=properties defined by the user) for (key in childNodes) { if (typeof(childNodes[key].value) != "undefined" && childNodes[key].value != null) { propObj = new Object(); propObj.word = key; if(tsRef.typeHasProperty(value,childNodes[key].name)){ propObj.cssClass = 'definedTSREFProperty'; propObj.type = childNodes[key].value; } else { propObj.cssClass = 'userProperty'; if (tsRef.isType(childNodes[key].value)) { propObj.type = childNodes[key].value; } else { propObj.type = ''; } } propArr.push(propObj); defined[key] = true; } } // then get the tsref properties var props = tsRef.getPropertiesFromTypeId(currentTsTreeNode.getValue()); for (key in props) { // show just the TSREF properties - no properties of the array-prototype and no properties which have been defined by the user if (props[key].value != null && defined[key]!=true) { propObj = new Object(); propObj.word = key; propObj.cssClass = 'undefinedTSREFProperty'; propObj.type = props[key].value; propArr.push(propObj); } } var result = []; var wordBeginning = ""; for (var i=0; i < propArr.length;i++) { wordBeginning = propArr[i].word.substring(0, filter.length); if (filter == "" || filter == null || wordBeginning.toLowerCase() == filter.toLowerCase()) { result.push(propArr[i]); } } return result; } }
gpl-2.0
calipho-sib/nextprot-api
core/src/main/java/org/nextprot/api/core/service/impl/peff/PEFFModResPsi.java
3399
package org.nextprot.api.core.service.impl.peff; import org.nextprot.api.commons.constants.AnnotationCategory; import org.nextprot.api.core.domain.annotation.Annotation; import java.util.EnumSet; import java.util.List; import java.util.Optional; import java.util.function.Function; /** * A Modified residue with PSI-MOD identifier * * <p> * if a ptm is not mapped to PSI-MOD it is collected in a list of ModResInfos * </p> * * Created by fnikitin on 05/05/15. */ public class PEFFModResPsi extends PEFFPTMInformation { private final Function<String, Optional<String>> uniprotModToPsi; private final Function<String, Optional<String>> uniprotModToPsiName; private final List<Annotation> unmappedUniprotModAnnotations; public PEFFModResPsi(String isoformAccession, List<Annotation> isoformAnnotations, Function<String, Optional<String>> uniprotModToPsi, Function<String, Optional<String>> uniprotModToPsiName, List<Annotation> unmappedUniprotModAnnotations) { super(isoformAccession, isoformAnnotations, EnumSet.of(AnnotationCategory.MODIFIED_RESIDUE, AnnotationCategory.CROSS_LINK, AnnotationCategory.DISULFIDE_BOND, AnnotationCategory.LIPIDATION_SITE), Key.MOD_RES_PSI); this.uniprotModToPsi = uniprotModToPsi; this.uniprotModToPsiName = uniprotModToPsiName; this.unmappedUniprotModAnnotations = unmappedUniprotModAnnotations; } @Override protected String getModAccession(Annotation annotation) { return uniprotModToPsi.apply(annotation.getCvTermAccessionCode()).orElse(""); } @Override protected String getModName(Annotation annotation) { return uniprotModToPsiName.apply(annotation.getCvTermAccessionCode()).orElse(""); } @Override protected void formatAnnotation(Annotation annotation, StringBuilder sb) { if (annotation.getAPICategory() == AnnotationCategory.DISULFIDE_BOND) { formatDisulfideBond(annotation, sb); } else { String modAccession = getModAccession(annotation); if (modAccession.isEmpty()) { unmappedUniprotModAnnotations.add(annotation); } else { sb .append("(") .append(annotation.getStartPositionForIsoform(isoformAccession)) .append("|") .append(modAccession) .append("|") .append(getModName(annotation)) .append(")") ; } } } private void formatDisulfideBond(Annotation disulfideBondAnnotation, StringBuilder sb) { Integer startPos = disulfideBondAnnotation.getStartPositionForIsoform(isoformAccession); Integer endPos = disulfideBondAnnotation.getEndPositionForIsoform(isoformAccession); sb .append("(") .append((startPos != null) ? startPos : "?") .append("|MOD:00798|") .append("half cystine") .append(")") .append("(") .append((endPos != null) ? endPos : "?") .append("|MOD:00798|") .append("half cystine") .append(")") ; } }
gpl-2.0
albatrossdigital/liftoff-provision
Provision/Config/Drushrc/provision_drushrc_aegir.tpl.php
623
<?php /** * @file * Template file for an Aegir-wide drushrc file. */ print "<?php \n\n"; print "# A list of Aegir features and their enabled status.\n"; print "\$options['hosting_features'] = ". var_export($hosting_features, TRUE) . ";\n\n"; print "# A list of modules to be excluded because the hosting feature is not enabled.\n"; print "\$options['exclude'] = ". var_export($drush_exclude, TRUE) . ";\n\n"; print "# A list of paths that drush should include even when working outside\n"; print "# the context of the hostmaster site.\n"; print "\$options['include'] = ". var_export($drush_include, TRUE) . ";\n"; ?>
gpl-2.0
dinhhieu89/wp-chungcu84
wp-content/themes/dt-the7/inc/presets/skin08r.php
13287
<?php $presets["skin08r"] = array ( 'preset' => 'skin08r', 'header-logo_regular' => array ( 0 => '/inc/presets/images/full/skin08r.header-logo-regular.png?w=42&h=61', 1 => 0, ), 'header-logo_hd' => array ( 0 => '/inc/presets/images/full/skin08r.header-logo-hd.png?w=84&h=122', 1 => 0, ), 'bottom_bar-logo_regular' => array ( 0 => '/inc/presets/images/full/skin08r.bottom-bar-logo-regular.png?w=24&h=39', 1 => 0, ), 'bottom_bar-logo_hd' => array ( 0 => '/inc/presets/images/full/skin08r.bottom-bar-logo-hd.png?w=48&h=78', 1 => 0, ), 'general-floating_menu_show_logo' => '1', 'general-floating_menu_logo_regular' => array ( 0 => '/inc/presets/images/full/skin08r.general-floating-menu-logo-regular.png?w=24&h=39', 1 => 0, ), 'general-floating_menu_logo_hd' => array ( 0 => '/inc/presets/images/full/skin08r.general-floating-menu-logo-hd.png?w=48&h=78', 1 => 0, ), 'general-bg_color' => '#ffffff', 'general-bg_opacity' => 100, 'general-bg_image' => array ( 'image' => '', 'repeat' => 'repeat', 'position_x' => 'center', 'position_y' => 'top', ), 'general-bg_fullscreen' => false, 'general-content_width' => '1250px', 'general-layout' => 'boxed', 'general-box_width' => '1280px', 'general-boxed_bg_color' => '#ffffff', 'general-boxed_bg_image' => array ( 'image' => '/inc/presets/images/full/skin08r.general-boxed-bg-image.jpg', 'repeat' => 'no-repeat', 'position_x' => 'center', 'position_y' => 'center', ), 'general-boxed_bg_fullscreen' => '1', 'general-show_titles' => '1', 'general-title_align' => 'left', 'general-show_breadcrumbs' => '1', 'general-responsive' => '1', 'general-accent_bg_color' => '#3b8ced', 'general-border_radius' => 5, 'general-show_rel_posts' => '1', 'general-rel_posts_head_title' => 'Related posts', 'general-rel_posts_max' => 6, 'general-smooth_scroll' => 'off', 'fonts-font_family' => 'Open Sans', 'fonts-normal_size' => 13, 'fonts-normal_size_line_height' => 22, 'fonts-small_size' => 12, 'fonts-small_size_line_height' => 21, 'fonts-big_size' => 14, 'fonts-big_size_line_height' => 24, 'fonts-h1_font_family' => 'Open Sans', 'fonts-h1_font_size' => 51, 'fonts-h1_line_height' => 57, 'fonts-h1_uppercase' => false, 'fonts-h2_font_family' => 'Open Sans', 'fonts-h2_font_size' => 37, 'fonts-h2_line_height' => 43, 'fonts-h2_uppercase' => false, 'fonts-h3_font_family' => 'Open Sans', 'fonts-h3_font_size' => 25, 'fonts-h3_line_height' => 31, 'fonts-h3_uppercase' => false, 'fonts-h4_font_family' => 'Open Sans', 'fonts-h4_font_size' => 19, 'fonts-h4_line_height' => 25, 'fonts-h4_uppercase' => false, 'fonts-h5_font_family' => 'Open Sans', 'fonts-h5_font_size' => 16, 'fonts-h5_line_height' => 23, 'fonts-h5_uppercase' => false, 'fonts-h6_font_family' => 'Open Sans', 'fonts-h6_font_size' => 14, 'fonts-h6_line_height' => 23, 'fonts-h6_uppercase' => false, 'buttons-s_font_family' => 'Open Sans:600', 'buttons-s_font_size' => 11, 'buttons-s_uppercase' => false, 'buttons-s_line_height' => 26, 'buttons-m_font_family' => 'Open Sans', 'buttons-m_font_size' => 14, 'buttons-m_uppercase' => false, 'buttons-m_line_height' => 36, 'buttons-l_font_family' => 'Open Sans', 'buttons-l_font_size' => 16, 'buttons-l_uppercase' => false, 'buttons-l_line_height' => 46, 'top_bar-bg_color' => '#3b8ced', 'top_bar-bg_opacity' => 100, 'top_bar-bg_image' => array ( 'image' => '', 'repeat' => 'repeat', 'position_x' => 'center', 'position_y' => 'center', ), 'top_bar-text_color' => '#ffffff', 'header-bg_color' => '#ffffff', 'header-bg_image' => array ( 'image' => '', 'repeat' => 'repeat', 'position_x' => 'center', 'position_y' => 'top', ), 'header-transparent_bg_color' => '#ffffff', 'header-transparent_bg_opacity' => 100, 'header-bg_height' => 60, 'header-layout' => 'left', 'header-show_floating_menu' => '1', 'content-headers_color' => '#3a3a3a', 'content-primary_text_color' => '#888888', 'stripes-stripe_1_color' => '#f6f6f6', 'stripes-stripe_1_bg_image' => array ( 'image' => '', 'repeat' => 'repeat', 'position_x' => 'center', 'position_y' => 'center', ), 'stripes-stripe_1_headers_color' => '#3a3a3a', 'stripes-stripe_1_text_color' => '#888888', 'stripes-stripe_2_color' => '#262626', 'stripes-stripe_2_bg_image' => array ( 'image' => '', 'repeat' => 'repeat', 'position_x' => 'center', 'position_y' => 'center', ), 'stripes-stripe_2_headers_color' => '#ffffff', 'stripes-stripe_2_text_color' => '#f4f4f4', 'stripes-stripe_3_color' => '#a2d3f7', 'stripes-stripe_3_bg_image' => array ( 'image' => '/inc/presets/images/full/skin08r.stripes-stripe-3-bg-image.jpg', 'repeat' => 'repeat', 'position_x' => 'center', 'position_y' => 'center', ), 'stripes-stripe_3_headers_color' => '#3d3d3d', 'stripes-stripe_3_text_color' => '#3d3d3d', 'sidebar-bg_color' => '#f6f6f6', 'sidebar-bg_image' => array ( 'image' => '', 'repeat' => 'repeat', 'position_x' => 'center', 'position_y' => 'center', ), 'sidebar-headers_color' => '#3a3a3a', 'sidebar-primary_text_color' => '#888888', 'footer-bg_color' => '#26282c', 'footer-bg_image' => array ( 'image' => '', 'repeat' => 'repeat', 'position_x' => 'center', 'position_y' => 'top', ), 'footer-headers_color' => '#3a3a3a', 'footer-primary_text_color' => '#888888', 'bottom_bar-bg_color' => '#303135', 'bottom_bar-bg_image' => array ( 'image' => '', 'repeat' => 'repeat', 'position_x' => 'center', 'position_y' => 'top', ), 'bottom_bar-color' => '#888888', 'bottom_bar-credits' => '1', 'top_bar-font_size' => 'small', 'top_bar-bg_mode' => 'solid', 'menu-font_family' => 'Open Sans', 'menu-font_size' => 15, 'menu-font_uppercase' => false, 'menu-next_level_indicator' => false, 'menu-font_color' => '#3a3a3a', 'menu-hover_font_color_mode' => 'accent', 'menu-hover_font_color' => '#3a3a3a', 'menu-hover_font_color_gradient' => array ( 0 => '#dd3333', 1 => '#0ce6ab', ), 'menu-decoration_style' => 'upwards', 'menu-hover_decoration_color_mode' => 'accent', 'menu-hover_decoration_color' => '#a7e673', 'menu-hover_decoration_color_gradient' => array ( 0 => '#eeee22', 1 => '#0bed56', ), 'top_bar-paddings' => 6, 'menu-iconfont_size' => 14, 'menu-items_distance' => 28, 'submenu-font_family' => 'Open Sans', 'submenu-font_size' => 12, 'submenu-font_uppercase' => false, 'submenu-next_level_indicator' => '1', 'submenu-font_color' => '#888888', 'submenu-hover_font_color_mode' => 'accent', 'submenu-hover_font_color' => '#895cb8', 'submenu-hover_font_color_gradient' => array ( 0 => '#81d742', 1 => '#eeee22', ), 'submenu-iconfont_size' => 12, 'submenu-items_distance' => 14, 'submenu-bg_color' => '#ffffff', 'submenu-bg_opacity' => 100, 'submenu-bg_width' => 230, 'general-accent_color_mode' => 'color', 'general-accent_bg_color_gradient' => array ( 0 => '#2578e9', 1 => '#3fe7d9', ), 'header-left_layout_elements' => array ( 'top_bar_left' => array ( 0 => 'address', 1 => 'phone', ), 'top_bar_right' => array ( 0 => 'login', 1 => 'cart', 2 => 'social_icons', ), 'nav_area' => array ( 0 => 'search', ), ), 'header-center_layout_elements' => array ( 'top_bar_left' => array ( 0 => 'email', 1 => 'phone', 2 => 'skype', ), 'nav_area' => array ( 0 => 'social_icons', 1 => 'cart', 2 => 'search', ), ), 'header-near_logo_font_size' => 'big', 'header-near_logo_bg_color' => '#888888', 'header-classic_layout_elements' => array ( 'logo_area' => array ( 0 => 'phone', ), 'nav_area' => array ( 0 => 'social_icons', 1 => 'cart', 2 => 'search', ), ), 'header-side_paddings' => 40, 'header-side_position' => 'left', 'header-side_menu_align' => 'left', 'header-side_layout_elements' => array ( 'top' => array ( 0 => 'phone', 1 => 'custom_menu', ), 'bottom' => array ( 0 => 'social_icons', 1 => 'text_area', 2 => 'cart', 3 => 'search', ), ), 'header-woocommerce_cart_icon' => '1', 'header-search_caption' => '', 'header-left_layout_fullwidth' => false, 'header-woocommerce_cart_caption' => 'Cart', 'header-woocommerce_counter_bg_mode' => 'color', 'header-woocommerce_counter_bg_color' => '#6ca9f2', 'header-woocommerce_counter_bg_color_gradient' => array ( 0 => '#dd3333', 1 => '#81d742', ), 'header-login_caption' => 'Login', 'header-soc_icon_color' => '#ffffff', 'header-soc_icon_hover_color' => '#ffffff', 'header-logo_padding_top' => 28, 'header-logo_padding_bottom' => 28, 'float_menu-height' => 60, 'float_menu-bg_color_mode' => 'header_color', 'float_menu-bg_color' => '#ffffff', 'float_menu-transparency' => 100, 'header-side_menu_visibility' => 'always_visible', 'header-side_menu_width' => '280px', 'header-side_menu_lines' => '0', 'header-side_menu_lines_color' => '#eeeeee', 'header-classic_menu_bg_mode' => 'disabled', 'header-classic_menu_bg_color' => '#cccccc', 'header-center_menu_bg_mode' => 'content_line', 'header-center_menu_bg_color' => '#ededed', 'header-soc_icon_bg_color_mode' => 'disabled', 'header-soc_icon_bg_color' => '#959ca6', 'header-soc_icon_bg_color_gradient' => array ( 0 => '#8224e3', 1 => '#43d8c7', ), 'header-soc_icon_hover_bg_color_mode' => 'color', 'header-soc_icon_hover_bg_color' => '#6ca9f2', 'header-soc_icon_hover_bg_color_gradient' => array ( 0 => '#ef5689', 1 => '#a6ff16', ), 'general-title_size' => 'h3', 'general-title_height' => 90, 'general-title_bg_mode' => 'transparent_bg', 'general-title_bg_color' => '#fafafa', 'general-breadcrumbs_color' => '#bcbcbc', 'general-breadcrumbs_bg_color' => 'disabled', 'general-title_bg_image' => array ( 'image' => '/images/backgrounds/patterns/full/brickwall.gif', 'repeat' => 'no-repeat', 'position_x' => 'center', 'position_y' => 'center', ), 'general-title_bg_fullscreen' => false, 'general-title_bg_fixed' => false, 'general-title_bg_parallax' => '', 'buttons-style' => 'flat', 'buttons-color_mode' => 'accent', 'buttons-color' => '#81d742', 'buttons-color_gradient' => array ( 0 => '#dd3333', 1 => '#3a892a', ), 'buttons-s_border_radius' => 5, 'buttons-m_border_radius' => 5, 'buttons-l_border_radius' => 5, 'general-style' => 'minimalistic', 'general-title_color' => '#3a3a3a', 'image_hover-style' => 'scale', 'image_hover-color_mode' => 'accent', 'image_hover-color' => '#26282c', 'image_hover-color_gradient' => array ( 0 => '#000000', 1 => '#303030', ), 'image_hover-opacity' => 60, 'image_hover-with_icons_opacity' => 94, 'general-next_prev_in_album' => '1', 'general-show_back_button_in_album' => '1', 'general-album_back_button_target_page_id' => 16237, 'general-album_meta_on' => '1', 'general-album_meta_date' => '1', 'general-album_meta_author' => false, 'general-album_meta_categories' => '1', 'general-album_meta_comments' => false, 'general-boxed_bg_fixed' => '1', 'sidebar-width' => 26, 'sidebar-vertical_distance' => 84, 'sidebar-divider-vertical' => '1', 'sidebar-divider-horizontal' => '1', 'header-mobile-first_switch-after' => 870, 'header-mobile-first_switch-logo' => 'mobile', 'header-mobile-second_switch-after' => 400, 'header-mobile-second_switch-logo' => 'mobile', 'header-mobile-menu_color' => 'accent', 'header-mobile-menu_color-background' => '#f94dda', 'header-mobile-menu_color-text' => '#000000', 'general-mobile_logo-regular' => array ( 0 => '/inc/presets/images/full/skin08r.general-mobile-logo-regular.png?w=42&h=61', 1 => 0, ), 'general-mobile_logo-hd' => array ( 0 => '/inc/presets/images/full/skin08r.general-mobile-logo-hd.png?w=84&h=122', 1 => 0, ), 'general-mobile_logo-padding_top' => '28', 'general-mobile_logo-padding_bottom' => '28', 'footer-style' => 'transparent_bg_line', 'footer-slide-out-mode' => '0', 'footer-paddings-top-bottom' => 50, 'footer-paddings-columns' => 22, 'bottom_bar-style' => 'full_width_line', 'footer-collapse_after' => 970, 'header-background' => 'normal', 'header-menu_text_color_mode' => 'light', 'header-menu_hover_color_mode' => 'light', 'header-menu_top_bar_color_mode' => 'light', 'header-bg_opacity' => 100, 'header-bg_fullscreen' => false, 'header-bg_fixed' => false, 'header-center_menu_bg_opacity' => 100, 'header-classic_menu_bg_opacity' => 35, 'header-side_menu_lines_opacity' => 100, 'general-bg_fixed' => false, 'header-style' => 'solid_background', 'general-responsiveness-treshold' => 970, 'header-side_menu_dropdown_style' => 'side', 'header-decoration' => 'shadow', 'header-decoration_color' => '#232c37', 'sidebar-visual_style' => 'with_dividers', ); ?>
gpl-2.0
JozefAB/neoacu
administrator/components/com_guru/views/guruquiz/tmpl/editformsbox.php
34520
<?php /*------------------------------------------------------------------------ # com_guru # ------------------------------------------------------------------------ # author iJoomla # copyright Copyright (C) 2013 ijoomla.com. All Rights Reserved. # @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL # Websites: http://www.ijoomla.com # Technical Support: Forum - http://www.ijoomla.com/forum/index/ -------------------------------------------------------------------------*/ defined( '_JEXEC' ) or die( 'Restricted access' ); $doc =JFactory::getDocument(); $doc->addScript('components/com_guru/js/jquery.DOMWindow.js'); JHTML::_('behavior.modal'); JHtml::_('behavior.calendar'); $program = $this->program; if($program->id == ""){ $program_id = 0; } else{ $program_id = $program->id; } $lists = $program->lists; $mmediam = $this->mmediam; $mainmedia = $this->mainmedia; $configuration = guruAdminModelguruQuiz::getConfigs(); $temp_size = $configuration->lesson_window_size_back; $temp_size_array = explode("x", $temp_size); $width = $temp_size_array["1"]-20; $height = $temp_size_array["0"]-20; $db = JFactory::getDBO(); $sql = "Select datetype FROM #__guru_config where id=1 "; $db->setQuery($sql); $format_date = $db->loadColumn(); $dateformat = $format_date[0]; $amount_quest = guruAdminModelguruQuiz::getAmountQuestions($program->id); $format = "%m-%d-%Y"; switch($dateformat){ case "d-m-Y H:i:s": $format = "%d-%m-%Y %H:%M:%S"; break; case "d/m/Y H:i:s": $format = "%d/%m/%Y %H:%M:%S"; break; case "m-d-Y H:i:s": $format = "%m-%d-%Y %H:%M:%S"; break; case "m/d/Y H:i:s": $format = "%m/%d/%Y %H:%M:%S"; break; case "Y-m-d H:i:s": $format = "%Y-%m-%d %H:%M:%S"; break; case "Y/m/d H:i:s": $format = "%Y/%m/%d %H:%M:%S"; break; case "d-m-Y": $format = "%d-%m-%Y"; break; case "d/m/Y": $format = "%d/%m/%Y"; break; case "m-d-Y": $format = "%m-%d-%Y"; break; case "m/d/Y": $format = "%m/%d/%Y"; break; case "Y-m-d": $format = "%Y-%m-%d"; break; case "Y/m/d": $format = "%Y/%m/%d"; break; } ?> <script language="javascript" type="text/javascript"> function submitbutton (pressbutton){ var form = document.adminForm; if (pressbutton=='save' || pressbutton=='apply') { if (form['name'].value == "") { alert( "<?php echo JText::_("JS_INSERT_CMPNAME");?>" ); } else if (form['author'].value == "- select -") { alert( "<?php echo JText::_("GURU_CS_PLSINSAUTHOR");?>" ); } else { submitform( pressbutton ); } } else { submitform( pressbutton ); } } //Joomla.submitbutton2 = function(pressbutton){ function submitbutton2(pressbutton) { var form = document.adminForm; if (pressbutton=='savesbox') { if (form['name'].value == "") { alert( "<?php echo JText::_("GURU_TASKS_JS_NAME");?>" ); } else{ //var screen_id = document.getElementById('screen').value; submitform(pressbutton); } } } function loadjscssfile(filename, filetype){ if (filetype=="js"){ //if filename is a external JavaScript file var fileref=document.createElement('script'); fileref.setAttribute("type","text/javascript"); fileref.setAttribute("src", filename); } else if (filetype=="css"){ //if filename is an external CSS file var fileref=document.createElement("link"); fileref.setAttribute("rel", "stylesheet"); fileref.setAttribute("type", "text/css"); fileref.setAttribute("href", filename); } if (typeof fileref!="undefined"){ document.getElementsByTagName("head")[0].appendChild(fileref); } } function loadprototipe(){ loadjscssfile("<?php echo JURI::base().'components/com_guru/views/gurutasks/tmpl/prototype-1.6.0.2.js' ?>","js"); } function addmedia (idu, name, asoc_file, description) { loadprototipe(); var url = 'index.php?option=com_guru&controller=guruTasks&tmpl=component&format=raw&task=ajax_request2&type=quiz&id='+idu; myAjax= new Ajax(url, { method: 'get', asynchronous: 'true', onSuccess: function(transport) { to_be_replaced=parent.document.getElementById('media_15'); to_be_replaced.innerHTML = '&nbsp;'; to_be_replaced.innerHTML += transport; parent.document.getElementById("media_"+99).style.display=""; parent.document.getElementById("description_med_99").innerHTML=''+name; parent.document.getElementById('before_menu_med_'+replace_m).style.display = 'none'; parent.document.getElementById('after_menu_med_'+replace_m).style.display = ''; parent.document.getElementById('db_media_'+replace_m).value = idu; replace_edit_link = parent.document.getElementById('a_edit_media_'+replace_m); replace_edit_link.href = 'index.php?option=com_guru&controller=guruQuiz&tmpl=component&task=editsbox&cid[]='+ idu; var qwe='&nbsp;'+transport.responseText+'<br /><div style="text-align:center"><i>'+ name +'</i></div><div style="text-align:center"><i>' + description + '</i></div>'; //window.parent.test1(qwe); window.parent.test(replace_m, idu,qwe); }, onCreate: function(){ } }); myAjax.request(); window.parent.setTimeout('document.getElementById("sbox-window").close()', 1); return true; } function publish(x){ var req = new Request.HTML({ async: false, method: 'get', url: 'index.php?option=com_guru&controller=guruQuiz&tmpl=component&format=raw&task=ajax_request&id='+x+'&action=publish', data: { 'do' : '1' }, onComplete: function(response){ document.getElementById('publishing'+x).innerHTML='<a class="icon-ok" style="cursor: pointer; text-decoration: none;" onclick="javascript:unpublish(\''+x+'\');"></a>'; } }).send(); } function unpublish(x){ var req = new Request.HTML({ async: false, method: 'get', url: 'index.php?option=com_guru&controller=guruQuiz&tmpl=component&format=raw&task=ajax_request&id='+x+'&action=unpublish', data: { 'do' : '1' }, onComplete: function(response){ document.getElementById('publishing'+x).innerHTML='<a class="icon-remove" style="cursor: pointer; text-decoration: none;" onclick="javascript:publish(\''+x+'\');"></a>'; } }).send(); } function editOptionsQ(){ display = document.getElementById("button-options2").style.display; if(display == "none"){ document.getElementById("button-options2").style.display = ""; } else{ document.getElementById("button-options2").style.display = "none"; } } jQuery(document).click(function(e){ if (jQuery(e.target).attr('id') != 'guru-dropdown-toggle' && jQuery(e.target).attr('id') != 'icon-bell' && jQuery(e.target).attr('id') != 'badge-important' && jQuery(e.target).attr('id') != 'new-options-button2'){ if(eval(document.getElementById("button-options2"))){ document.getElementById("button-options2").style.display = "none"; } } }) function showContent1(href){ first = true; jQuery( '#myModal1 .modal-bodyc iframe').attr('src', href); screen_height = window.innerHeight; document.getElementById('myModal1').style.height = (screen_height -110)+'px'; document.getElementById('quiz_edit_lesson').style.height = (screen_height -150)+'px'; } function showContent2(href){ first = true; jQuery( '#myModal2 .modal-bodyc iframe').attr('src', href); screen_height = window.innerHeight; document.getElementById('myModal2').style.height = (screen_height -100)+'px'; document.getElementById('quiz_edit_lesson2').style.height = (screen_height -120)+'px'; } jQuery('body').click(function () { if(!first){ jQuery('#myModal1 .modal-bodyc iframe').attr('src', ''); } else{ first = false; } }); </script> <style> #rowquestion { background-color:#ffffff; } #rowquestion tr{ background-color:#ffffff; } #rowquestion td{ background-color:#ffffff; } div.modal{ left:25%; width:90%; padding:13px; } </style> <script> function delete_temp_m(i){ document.getElementById('trm'+i).style.display = 'none'; document.getElementById('mediafiletodel').value = document.getElementById('mediafiletodel').value+','+i; } function delete_q(i){ document.getElementById('trque'+i).style.display = 'none'; document.getElementById('deleteq').value = document.getElementById('deleteq').value+','+i; } </script> <div style="float:right"> <div id="toolbar" class="btn-toolbar pull-right no-margin"> <div id="toolbar-apply" class="btn-wrapper"> <button class="btn btn-success" onclick="javascript:submitbutton2('savesbox');"> <span class="icon-apply icon-white"></span> Save </button> </div> </div> </div> <div id="myModal1" class="modal hide" style=""> <div class="modal-header"> <button type="button" id="close" class="close" data-dismiss="modal" aria-hidden="true">x</button> </div> <div class="modal-bodyc" style="background-color:#FFFFFF;" > <iframe style="" id="quiz_edit_lesson" width="100%" frameborder="0"></iframe> </div> </div> <div id="myModal2" class="modal hide" style=""> <div class="modal-header"> <button type="button" id="close" class="close" data-dismiss="modal" aria-hidden="true">x</button> </div> <div class="modal-bodyc" style="background-color:#FFFFFF;" > <iframe style="" id="quiz_edit_lesson2" width="100%" frameborder="0"></iframe> </div> </div> <form method="post" name="adminForm" id="adminForm" enctype="multipart/form-data"> <input type="hidden" name="page_width" value="0" /> <input type="hidden" name="page_height" value="0" /> <script type="text/javascript"> <?php if($configuration->back_size_type == "1"){ echo 'document.adminForm.page_width.value="'.$width.'";'; echo 'document.adminForm.page_height.value="'.$height.'";'; } ?> </script> <ul id="gurutabs" data-tabs="tabs" class="nav nav-tabs"> <li class="active"><a href="#tab1" data-toggle="tab"><?php echo JText::_("GURU_GENERAL");?></a></li> <li><a href="#tab2" data-toggle="tab"><?php echo JText::_("GURU_QUESTIONS");?></a></li> <li><a href="#tab3" data-toggle="tab"><?php echo JText::_("GURU_PUBLISHING");?></a></li> </ul> <div class="tab-content" style="border-top:none!important;"> <div class="tab-pane active" id="tab1"> <div class="well"><?php if ($program_id<1) echo JText::_('GURU_NEWQUIZ'); else echo JText::_('GURU_EDITQUIZ');?></div> <table class="adminform"> <tr> <td width="15%"> <?php echo JText::_('GURU_NAME'); ?>:<font color="#ff0000">*</font> </td> <td> <input class="inputbox" type="text" id="name" name="name" size="40" maxlength="255" value="<?php echo $program->name; ?>" /> <span class="editlinktip hasTip" title="<?php echo JText::_("GURU_TIP_QUIZ_NAME"); ?>" > <img border="0" src="components/com_guru/images/icons/tooltip.png"> </span> </td> </tr> <tr> <td> <?php echo JText::_('GURU_AUTHOR'); ?>:<font color="#ff0000">*</font></td> <td> <?php echo $lists['author']; ?> <span class="editlinktip hasTip" title="<?php echo JText::_("GURU_TIP_AUTHOR"); ?>" > <img border="0" src="components/com_guru/images/icons/tooltip.png"> </span> </td> </tr> <tr> <td> <?php echo JText::_('GURU_PRODDESC');?>: </td> <td> <textarea name="description" id="description" cols="40" rows="8"><?php echo stripslashes($program->description); ?></textarea> <span class="editlinktip hasTip" title="<?php echo JText::_("GURU_TIP_QUIZ_PRODDESC"); ?>" > <img border="0" src="components/com_guru/images/icons/tooltip.png"> </span> </td> </tr> <tr> <td width="15%"> <?php echo JText::_('GURU_MINIMUM_SCORE_QUIZ'); ?>: </td> <td> <?php if (isset($program->max_score)){ $program->max_score = $program->max_score; } else{ $program->max_score = 70; } ?> <input class="input-mini" type="text" id="max_score_pass" name="max_score_pass" value="<?php echo $program->max_score; ?>" style="float:left !important;" />&nbsp; <span style="float:left !important; padding-top:4px; padding-left:19px;">% &nbsp;</span> <select id="show_max_score_pass" name="show_max_score_pass" style="float:left !important;" class="input-small" > <option value="0" <?php if($program->pbl_max_score == "0"){echo 'selected="selected"'; } ?>><?php echo JText::_("GURU_SHOW"); ?></option> <option value="1" <?php if($program->pbl_max_score == "1"){echo 'selected="selected"'; } ?>><?php echo JText::_("GURU_HIDE"); ?></option> </select> <span class="editlinktip hasTip" title="<?php echo JText::_('GURU_MAX_SCORE_TOOLTIP'); ?>" > <img border="0" src="components/com_guru/images/icons/tooltip.png"> </span> </td> </tr> <tr> <td width="15%"> <?php echo JText::_('GURU_QUIZ_CAN_BE_TAKEN'); ?>: </td> <td> <select id="nb_quiz_taken" name="nb_quiz_taken" style="float:left !important;" class="input-small" > <option value="1" <?php if($program->time_quiz_taken == "1"){echo 'selected="selected"'; }?> >1</option> <option value="2" <?php if($program->time_quiz_taken == "2"){echo 'selected="selected"'; }?> >2</option> <option value="3" <?php if($program->time_quiz_taken == "3"){echo 'selected="selected"'; }?> >3</option> <option value="4" <?php if($program->time_quiz_taken == "4"){echo 'selected="selected"'; }?> >4</option> <option value="5" <?php if($program->time_quiz_taken == "5"){echo 'selected="selected"'; }?> >5</option> <option value="6" <?php if($program->time_quiz_taken == "6"){echo 'selected="selected"'; }?> >6</option> <option value="7" <?php if($program->time_quiz_taken == "7"){echo 'selected="selected"'; }?> >7</option> <option value="8" <?php if($program->time_quiz_taken == "8"){echo 'selected="selected"'; }?> >8</option> <option value="9" <?php if($program->time_quiz_taken == "9"){echo 'selected="selected"'; }?> >9</option> <option value="10"<?php if($program->time_quiz_taken == "10"){echo 'selected="selected"'; }?> >10</option> <option value="11" <?php if($program->time_quiz_taken == "11"){echo 'selected="selected"'; }?>><?php echo JText::_("GURU_UNLIMPROMO");?></option> </select> <span style="float:left !important;padding-top:4px;padding-left:2px;">&nbsp;<?php echo JText::_("GURU_TIMES_T"); ?>&nbsp;</span> <select id="show_nb_quiz_taken" name="show_nb_quiz_taken" style="float:left !important;" class="input-small" > <option value="0" <?php if($program->show_nb_quiz_taken == "0"){echo 'selected="selected"'; } ?>><?php echo JText::_("GURU_SHOW"); ?></option> <option value="1" <?php if($program->show_nb_quiz_taken == "1"){echo 'selected="selected"'; } ?>><?php echo JText::_("GURU_HIDE"); ?></option> </select>&nbsp; <span class="editlinktip hasTip" title="<?php echo JText::_('GURU_TIMES_TAKEN_TOOLTIP'); ?>" > <img border="0" src="components/com_guru/images/icons/tooltip.png"> </span> </td> </tr> <tr> <td width="15%"> <?php echo JText::_('GURU_SELECT_UP_TO'); ?>: </td> <td style="padding-top:5px" nowrap="nowrap"> <select id="nb_quiz_select_up" name="nb_quiz_select_up" > <?php if(isset($amount_quest) && $amount_quest !=0 ){ for($i=$amount_quest; $i>=1; $i--){?> <option value="<?php echo $i;?>" <?php if($program->nb_quiz_select_up == $i){echo 'selected="selected"'; }?> ><?php echo $i;?></option> <?php } } else{ ?> <option value="text1"><?php echo "Please add questions first";?></option> <?php } ?> </select> <span style="float:left !important;">&nbsp;<?php echo JText::_('GURU_QUESTION_RANDOM'); ?>&nbsp;</span> <select id="show_nb_quiz_select_up" name="show_nb_quiz_select_up" style="float:left !important;" class="input-small" > <option value="0" <?php if($program->show_nb_quiz_select_up == "0"){echo 'selected="selected"'; } ?>><?php echo JText::_("GURU_SHOW"); ?></option> <option value="1" <?php if($program->show_nb_quiz_select_up == "1"){echo 'selected="selected"'; } ?>><?php echo JText::_("GURU_HIDE"); ?></option> </select>&nbsp; <span class="editlinktip hasTip" title="<?php echo JText::_('GURU_QUESTIONS_NUMBER_TOOLTIP'); ?>" > <img border="0" src="components/com_guru/images/icons/tooltip.png"> </span> </td> </tr> <tr> <td width="15%"> <?php echo JText::_('GURU_QUESTIONS_PER_PAGE'); ?>: </td> <td style="padding-top:5px"> <?php $questions_per_page = $program->questions_per_page; ?> <select name="questions_per_page"> <option value="5" <?php if($questions_per_page == "5"){echo 'selected="selected"';} ?> >5</option> <option value="10" <?php if($questions_per_page == "10"){echo 'selected="selected"';} ?> >10</option> <option value="15" <?php if($questions_per_page == "15"){echo 'selected="selected"';} ?> >15</option> <option value="20" <?php if($questions_per_page == "20"){echo 'selected="selected"';} ?> >20</option> <option value="25" <?php if($questions_per_page == "25"){echo 'selected="selected"';} ?> >25</option> <option value="30" <?php if($questions_per_page == "30"){echo 'selected="selected"';} ?> >30</option> <option value="50" <?php if($questions_per_page == "50"){echo 'selected="selected"';} ?> >50</option> <option value="100" <?php if($questions_per_page == "100"){echo 'selected="selected"';} ?> >100</option> <option value="0" <?php if($questions_per_page == "0"){echo 'selected="selected"';} ?> >All</option> </select> &nbsp; <span class="editlinktip hasTip" title="<?php echo JText::_('GURU_QUESTIONS_PER_PAGE_TOOLTIP'); ?>" > <img border="0" src="components/com_guru/images/icons/tooltip.png"> </span> </td> </tr> <tr> <td style=" font-weight:bold; font-size:25px" >Timer:</td> </tr> <tr> <td width="15%"> <?php echo JText::_('GURU_QUIZ_LIMIT_TIME'); ?>: </td> <td style="padding-top:5px"> <?php if (isset($program->limit_time)){ $program->limit_time = $program->limit_time; } else{ $program->limit_time = 3; } ?> <input class="input-mini" type="text" id="limit_time_l" name="limit_time_l" maxlength="255" value="<?php echo $program->limit_time; ?>" style="float:left !important;" /> <span style="float:left !important; padding-top:4px; padding-left:2px;">&nbsp;<?php echo JText::_('GURU_PROGRAM_DETAILS_MINUTES'); ?>&nbsp;</span> <select id="show_limit_time" name="show_limit_time" style="float:left !important;" class="input-small" > <option value="0" <?php if($program->show_limit_time == "0"){echo 'selected="selected"'; } ?>><?php echo JText::_("GURU_SHOW"); ?></option> <option value="1" <?php if($program->show_limit_time == "1"){echo 'selected="selected"'; } ?>><?php echo JText::_("GURU_HIDE"); ?></option> </select>&nbsp; <span class="editlinktip hasTip" title="<?php echo JText::_('GURU_QUIZ_LIMIT_TIME_TOOLTIP'); ?>" > <img border="0" src="components/com_guru/images/icons/tooltip.png"> </span> </td> </tr> <tr> <td width="15%"> <?php echo JText::_('GURU_SHOW_COUNTDOWN'); ?>: </td> <td style="padding-top:9px"> <select id="show_countdown" name="show_countdown" style="float:left !important;" class="input-small" > <option value="0" <?php if($program->show_countdown == "0"){echo 'selected="selected"'; } ?>><?php echo JText::_("GURU_SHOW"); ?></option> <option value="1" <?php if($program->show_countdown == "1"){echo 'selected="selected"'; } ?>><?php echo JText::_("GURU_HIDE"); ?></option> </select>&nbsp; <span class="editlinktip hasTip" title="<?php echo JText::_('GURU_SHOW_COUNTDOWN_TOOLTIP'); ?>" > <img border="0" src="components/com_guru/images/icons/tooltip.png"> </span> </td> </tr> <tr> <td width="15%"> <?php echo JText::_('GURU_FINISH_ALERT'); ?>: </td> <td style="padding-top:5px"> <?php if (isset($program->limit_time_f)){ $program->limit_time_f = $program->limit_time_f; } else{ $program->limit_time_f = 1; } ?> <input class="input-mini" type="text" id="limit_time_f" name="limit_time_f" maxlength="255" value="<?php echo $program->limit_time_f; ?>" style="float:left !important;" /> <span style="float:left !important; padding-top:4px; padding-left:2px;">&nbsp;<?php echo JText::_('GURU_MINUTES_BEFORE_IS_UP'); ?>&nbsp;</span> <select id="show_finish_alert" name="show_finish_alert" style="float:left !important;" class="input-small" > <option value="0" <?php if($program->show_finish_alert == "0"){echo 'selected="selected"'; } ?>><?php echo JText::_("GURU_SHOW"); ?></option> <option value="1" <?php if($program->show_finish_alert == "1"){echo 'selected="selected"'; } ?>><?php echo JText::_("GURU_HIDE"); ?></option> </select>&nbsp; <span class="editlinktip hasTip" title="<?php echo JText::_('GURU_FINISH_ALERT_TOOLTIP'); ?>" > <img border="0" src="components/com_guru/images/icons/tooltip.png"> </span> </td> </tr> </table> </div> <div class="tab-pane" id="tab2"> <div class="well"><?php if ($program_id<1) echo JText::_('GURU_NEWQUIZ'); else echo JText::_('GURU_EDITQUIZ');?></div> <div style="float:left;"> <div id="new-options2" style="position:relative;"> <input type="button" id="new-options-button2" onclick="editOptionsQ();" class="btn btn-success g_toggle_button" value="<?php echo JText::_('GURU_ADD_QUESTION').'&nbsp; &#9660;'; ?>"> <div id="button-options2" class="button-options" style="display:none;"> <ul style="font-size: 14px;"> <li> <a data-toggle="modal" data-target="#myModal1" onClick = "showContent1('index.php?option=com_guru&controller=guruQuiz&task=addquestion&tmpl=component&cid[]=<?php echo $program->id;?>&type=true_false&new_add=1');" href="#"><?php echo JText::_("GURU_QUIZ_TRUE_FALSE"); ?></a> </li> <li> <a data-toggle="modal" data-target="#myModal1" onClick = "showContent1('index.php?option=com_guru&controller=guruQuiz&task=addquestion&tmpl=component&cid[]=<?php echo $program->id;?>&type=single&new_add=1');" href="#"><?php echo JText::_("GURU_QUIZ_SINGLE_CHOICE"); ?></a> </li> <li> <a data-toggle="modal" data-target="#myModal1" onClick = "showContent1('index.php?option=com_guru&controller=guruQuiz&task=addquestion&tmpl=component&cid[]=<?php echo $program->id;?>&type=multiple&new_add=1');" href="#"><?php echo JText::_("GURU_QUIZ_MULTIPLE_CHOICE"); ?></a> </li> <li> <a data-toggle="modal" data-target="#myModal1" onClick = "showContent1('index.php?option=com_guru&controller=guruQuiz&task=addquestion&tmpl=component&cid[]=<?php echo $program->id;?>&type=essay&new_add=1');" href="#"><?php echo JText::_("GURU_QUIZ_ESSAY"); ?></a> </li> </ul> </div> </div> </div> <table id="articleList" class="table" > <tbody id="rowquestion"> <tr> <td><?php echo JHtml::_('grid.sort', '<i class="icon-menu-2"></i>', 'a.ordering', @$listDirn, @$listOrder, null, 'asc', 'JGRID_HEADING_ORDERING'); ?></td> <td></td> <td><strong><?php echo JText::_('GURU_QUESTION');?></strong></td> <td><strong><?php echo JText::_('GURU_TYPE');?></strong></td> <td><strong><?php echo JText::_('GURU_REMOVE');?></strong></td> <td><strong><?php echo JText::_('GURU_EDIT');?></strong></td> <td><strong><?php echo JText::_('GURU_PUBLISHED');?></strong></td> </tr> <?php if(isset($_POST['deleteq'])) $hide_q2del = $_POST['deleteq']; else $hide_q2del = ','; $hide_q2del = explode(',', $hide_q2del); foreach ($mmediam as $mmedial) { $link2_remove = '<font color="#FF0000"><span onClick="delete_q('.$mmedial->id.')">Remove</span></font>';?> <tr id="trque<?php echo $mmedial->id; ?>" <?php if(in_array($mmedial->id,$hide_q2del)) { ?> style="display:none" <?php } ?>> <td> <span class="sortable-handler active" style="cursor: move;"> <i class="icon-menu"></i> </span> <input type="text" class="input-mini" value="<?php echo @$mmedial->order; ?>" name="order[]" style="display:none;"> </td> <td width="5%" style="visibility:hidden;"><?php $checked = JHTML::_('grid.id', $i, $mmedial->media_id); echo $checked;?></td> <td id="tdq<?php echo $mmedial->id?>" width="39%"> <a data-toggle="modal" data-target="#myModal2" onClick = "showContent2('index.php?option=com_guru&controller=guruQuiz&task=addquestion&tmpl=component&cid[]=<?php echo $program->id.'&qid='.$mmedial->id;?>&type=<?php echo $mmedial->type;?>');" href="#"><?php if (strlen ($mmedial->question_content) >55){echo substr(str_replace("\'","&acute;" ,$mmedial->question_content),0,55).'...';}else{echo str_replace("\'","&acute;" ,$mmedial->question_content);}?></a> </td> <td width="15%"> <?php echo $mmedial->type; ?> </td> <td><?php echo $link2_remove; ?></td> <td> <a data-toggle="modal" data-target="#myModal1" onClick = "showContent1('index.php?option=com_guru&controller=guruQuiz&task=addquestion&tmpl=component&cid[]=<?php echo $program->id.'&qid='.$mmedial->id;?>&type=<?php echo $mmedial->type;?>');" href="#"><?php echo JText::_('GURU_EDIT');?></a> </td> <td id="publishing<?php echo $mmedial->id; ?>"> <?php if($mmedial->published == 1) { echo '<a class="icon-ok" style="cursor: pointer; text-decoration: none;" onclick="javascript:unpublish(\''.$mmedial->id.'\');"></a>'; } else{ echo '<a class="icon-remove" style="cursor: pointer; text-decoration: none;" onclick="javascript:publish(\''.$mmedial->id.'\');"></a>'; } ?> </td> </tr> <?php }?> <input type="hidden" value="<?php if (isset($_POST['newquizq'])) echo $_POST['newquizq'];?>" id="newquizq" name="newquizq" > <input type="hidden" value="<?php if (isset($_POST['deleteq'])) echo $_POST['deleteq'];?>" id="deleteq" name="deleteq" > </tbody> </table> </div> <div class="tab-pane" id="tab3"> <div class="well"><?php if ($program_id<1) echo JText::_('GURU_NEWDAY'); else echo JText::_('GURU_EDITDAY');?></div> <table class="adminform"> <tr> <td width="15%"> <?php echo JText::_('GURU_PRODLPBS'); ?> </td> <td width="85%"> <?php echo $lists['published']; ?> </td> </tr> <tr> <td valign="top" align="right"> <?php echo JText::_('GURU_PRODLSPUB'); ?> </td> <td> <?php if ($program->id<1){ $start_publish = date("".$dateformat."", time()); } else{ $start_publish = date("".$dateformat."", strtotime($program->startpublish)); } echo JHTML::_('calendar', $start_publish, 'startpublish', 'startpublish', $format, array('class'=>'inputbox', 'size'=>'25', 'maxlength'=>'19')); ?> </td> </tr> <tr> <td valign="top" align="right"> <?php echo JText::_('GURU_PRODLEPUB'); ?> </td> <td> <?php if(substr($program->endpublish,0,4) =='0000' || $program->endpublish == JText::_('GURU_NEVER')|| $program->id<1) $program->endpublish = ""; else $program->endpublish = date("".$dateformat."", strtotime($program->endpublish)); echo JHTML::_('calendar', $program->endpublish, 'endpublish', 'endpublish', $format, array('class'=>'inputbox', 'size'=>'25', 'maxlength'=>'19')); ?> </td> </tr> </table> </div> </div> <input type="hidden" name="id" value="<?php echo $program_id; ?>" /> <input type="hidden" name="task" value="" /> <input type="hidden" name="option" value="com_guru" /> <input type="hidden" name="image" value="<?php if(isset($_POST['image'])) echo $_POST['image']; else echo $program->image;?>" /> <input type="hidden" name="controller" value="guruQuiz" /> <input type="hidden" name="is_from_modal" value="1"> <a id="close_gb" style="display:none;">#</a> </form>
gpl-2.0
ultragdb/konsole
src/Vt102Emulation.cpp
56857
/* This file is part of Konsole, an X terminal. Copyright 2007-2008 by Robert Knight <[email protected]> Copyright 1997,1998 by Lars Doelle <[email protected]> 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. */ // Own #include "Vt102Emulation.h" // Standard #include <stdio.h> #include <unistd.h> // Qt #include <QtCore/QEvent> #include <QtCore/QTimer> #include <QtGui/QKeyEvent> // KDE #include <KLocalizedString> #include <KDebug> // Konsole #include "KeyboardTranslator.h" #include "Screen.h" #include "TerminalDisplay.h" using Konsole::Vt102Emulation; /* The VT100 has 32 special graphical characters. The usual vt100 extended xterm fonts have these at 0x00..0x1f. QT's iso mapping leaves 0x00..0x7f without any changes. But the graphicals come in here as proper unicode characters. We treat non-iso10646 fonts as VT100 extended and do the requiered mapping from unicode to 0x00..0x1f. The remaining translation is then left to the QCodec. */ // assert for i in [0..31] : vt100extended(vt100_graphics[i]) == i. unsigned short Konsole::vt100_graphics[32] = { // 0/8 1/9 2/10 3/11 4/12 5/13 6/14 7/15 0x0020, 0x25C6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0, 0x00b1, 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, 0xF800, 0xF801, 0x2500, 0xF803, 0xF804, 0x251c, 0x2524, 0x2534, 0x252c, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00b7 }; Vt102Emulation::Vt102Emulation() : Emulation(), _titleUpdateTimer(new QTimer(this)) { _titleUpdateTimer->setSingleShot(true); QObject::connect(_titleUpdateTimer , SIGNAL(timeout()) , this , SLOT(updateTitle())); initTokenizer(); reset(); } Vt102Emulation::~Vt102Emulation() {} void Vt102Emulation::clearEntireScreen() { _currentScreen->clearEntireScreen(); bufferedUpdate(); } void Vt102Emulation::reset() { // Save the current codec so we can set it later. // Ideally we would want to use the profile setting const QTextCodec* currentCodec = codec(); resetTokenizer(); resetModes(); resetCharset(0); _screen[0]->reset(); resetCharset(1); _screen[1]->reset(); if (currentCodec) setCodec(currentCodec); else setCodec(LocaleCodec); bufferedUpdate(); } /* ------------------------------------------------------------------------- */ /* */ /* Processing the incoming byte stream */ /* */ /* ------------------------------------------------------------------------- */ /* Incoming Bytes Event pipeline This section deals with decoding the incoming character stream. Decoding means here, that the stream is first separated into `tokens' which are then mapped to a `meaning' provided as operations by the `Screen' class or by the emulation class itself. The pipeline proceeds as follows: - Tokenizing the ESC codes (onReceiveChar) - VT100 code page translation of plain characters (applyCharset) - Interpretation of ESC codes (processToken) The escape codes and their meaning are described in the technical reference of this program. */ // Tokens ------------------------------------------------------------------ -- /* Since the tokens are the central notion if this section, we've put them in front. They provide the syntactical elements used to represent the terminals operations as byte sequences. They are encodes here into a single machine word, so that we can later switch over them easily. Depending on the token itself, additional argument variables are filled with parameter values. The tokens are defined below: - CHR - Printable characters (32..255 but DEL (=127)) - CTL - Control characters (0..31 but ESC (= 27), DEL) - ESC - Escape codes of the form <ESC><CHR but `[]()+*#'> - ESC_DE - Escape codes of the form <ESC><any of `()+*#%'> C - CSI_PN - Escape codes of the form <ESC>'[' {Pn} ';' {Pn} C - CSI_PS - Escape codes of the form <ESC>'[' {Pn} ';' ... C - CSI_PR - Escape codes of the form <ESC>'[' '?' {Pn} ';' ... C - CSI_PE - Escape codes of the form <ESC>'[' '!' {Pn} ';' ... C - VT52 - VT52 escape codes - <ESC><Chr> - <ESC>'Y'{Pc}{Pc} - XTE_HA - Xterm window/terminal attribute commands of the form <ESC>`]' {Pn} `;' {Text} <BEL> (Note that these are handled differently to the other formats) The last two forms allow list of arguments. Since the elements of the lists are treated individually the same way, they are passed as individual tokens to the interpretation. Further, because the meaning of the parameters are names (althought represented as numbers), they are includes within the token ('N'). */ #define TY_CONSTRUCT(T,A,N) ( ((((int)N) & 0xffff) << 16) | ((((int)A) & 0xff) << 8) | (((int)T) & 0xff) ) #define TY_CHR( ) TY_CONSTRUCT(0,0,0) #define TY_CTL(A ) TY_CONSTRUCT(1,A,0) #define TY_ESC(A ) TY_CONSTRUCT(2,A,0) #define TY_ESC_CS(A,B) TY_CONSTRUCT(3,A,B) #define TY_ESC_DE(A ) TY_CONSTRUCT(4,A,0) #define TY_CSI_PS(A,N) TY_CONSTRUCT(5,A,N) #define TY_CSI_PN(A ) TY_CONSTRUCT(6,A,0) #define TY_CSI_PR(A,N) TY_CONSTRUCT(7,A,N) #define TY_VT52(A) TY_CONSTRUCT(8,A,0) #define TY_CSI_PG(A) TY_CONSTRUCT(9,A,0) #define TY_CSI_PE(A) TY_CONSTRUCT(10,A,0) const int MAX_ARGUMENT = 4096; // Tokenizer --------------------------------------------------------------- -- /* The tokenizer's state The state is represented by the buffer (tokenBuffer, tokenBufferPos), and accompanied by decoded arguments kept in (argv,argc). Note that they are kept internal in the tokenizer. */ void Vt102Emulation::resetTokenizer() { tokenBufferPos = 0; argc = 0; argv[0] = 0; argv[1] = 0; } void Vt102Emulation::addDigit(int digit) { if (argv[argc] < MAX_ARGUMENT) argv[argc] = 10 * argv[argc] + digit; } void Vt102Emulation::addArgument() { argc = qMin(argc + 1, MAXARGS - 1); argv[argc] = 0; } void Vt102Emulation::addToCurrentToken(int cc) { tokenBuffer[tokenBufferPos] = cc; tokenBufferPos = qMin(tokenBufferPos + 1, MAX_TOKEN_LENGTH - 1); } // Character Class flags used while decoding const int CTL = 1; // Control character const int CHR = 2; // Printable character const int CPN = 4; // TODO: Document me const int DIG = 8; // Digit const int SCS = 16; // Select Character Set const int GRP = 32; // TODO: Document me const int CPS = 64; // Character which indicates end of window resize void Vt102Emulation::initTokenizer() { int i; quint8* s; for (i = 0; i < 256; ++i) charClass[i] = 0; for (i = 0; i < 32; ++i) charClass[i] |= CTL; for (i = 32; i < 256; ++i) charClass[i] |= CHR; for (s = (quint8*)"@ABCDGHILMPSTXZcdfry"; *s; ++s) charClass[*s] |= CPN; // resize = \e[8;<row>;<col>t for (s = (quint8*)"t"; *s; ++s) charClass[*s] |= CPS; for (s = (quint8*)"0123456789"; *s; ++s) charClass[*s] |= DIG; for (s = (quint8*)"()+*%"; *s; ++s) charClass[*s] |= SCS; for (s = (quint8*)"()+*#[]%"; *s; ++s) charClass[*s] |= GRP; resetTokenizer(); } /* Ok, here comes the nasty part of the decoder. Instead of keeping an explicit state, we deduce it from the token scanned so far. It is then immediately combined with the current character to form a scanning decision. This is done by the following defines. - P is the length of the token scanned so far. - L (often P-1) is the position on which contents we base a decision. - C is a character or a group of characters (taken from 'charClass'). - 'cc' is the current character - 's' is a pointer to the start of the token buffer - 'p' is the current position within the token buffer Note that they need to applied in proper order. */ #define lec(P,L,C) (p == (P) && s[(L)] == (C)) #define lun( ) (p == 1 && cc >= 32 ) #define les(P,L,C) (p == (P) && s[L] < 256 && (charClass[s[(L)]] & (C)) == (C)) #define eec(C) (p >= 3 && cc == (C)) #define ees(C) (p >= 3 && cc < 256 && (charClass[cc] & (C)) == (C)) #define eps(C) (p >= 3 && s[2] != '?' && s[2] != '!' && s[2] != '>' && cc < 256 && (charClass[cc] & (C)) == (C)) #define epp( ) (p >= 3 && s[2] == '?') #define epe( ) (p >= 3 && s[2] == '!') #define egt( ) (p >= 3 && s[2] == '>') #define Xpe (tokenBufferPos >= 2 && tokenBuffer[1] == ']') #define Xte (Xpe && cc == 7 ) #define ces(C) (cc < 256 && (charClass[cc] & (C)) == (C) && !Xte) #define CNTL(c) ((c)-'@') const int ESC = 27; const int DEL = 127; // process an incoming unicode character void Vt102Emulation::receiveChar(int cc) { if (cc == DEL) return; //VT100: ignore. if (ces(CTL)) { // DEC HACK ALERT! Control Characters are allowed *within* esc sequences in VT100 // This means, they do neither a resetTokenizer() nor a pushToToken(). Some of them, do // of course. Guess this originates from a weakly layered handling of the X-on // X-off protocol, which comes really below this level. if (cc == CNTL('X') || cc == CNTL('Z') || cc == ESC) resetTokenizer(); //VT100: CAN or SUB if (cc != ESC) { processToken(TY_CTL(cc+'@' ),0,0); return; } } // advance the state addToCurrentToken(cc); int* s = tokenBuffer; const int p = tokenBufferPos; if (getMode(MODE_Ansi)) { if (lec(1,0,ESC)) { return; } if (lec(1,0,ESC+128)) { s[0] = ESC; receiveChar('['); return; } if (les(2,1,GRP)) { return; } if (Xte ) { processWindowAttributeChange(); resetTokenizer(); return; } if (Xpe ) { return; } if (lec(3,2,'?')) { return; } if (lec(3,2,'>')) { return; } if (lec(3,2,'!')) { return; } if (lun( )) { processToken( TY_CHR(), applyCharset(cc), 0); resetTokenizer(); return; } if (lec(2,0,ESC)) { processToken( TY_ESC(s[1]), 0, 0); resetTokenizer(); return; } if (les(3,1,SCS)) { processToken( TY_ESC_CS(s[1],s[2]), 0, 0); resetTokenizer(); return; } if (lec(3,1,'#')) { processToken( TY_ESC_DE(s[2]), 0, 0); resetTokenizer(); return; } if (eps( CPN)) { processToken( TY_CSI_PN(cc), argv[0],argv[1]); resetTokenizer(); return; } // resize = \e[8;<row>;<col>t if (eps(CPS)) { processToken( TY_CSI_PS(cc, argv[0]), argv[1], argv[2]); resetTokenizer(); return; } if (epe( )) { processToken( TY_CSI_PE(cc), 0, 0); resetTokenizer(); return; } if (ees(DIG)) { addDigit(cc-'0'); return; } if (eec(';')) { addArgument(); return; } for (int i = 0; i <= argc; i++) { if (epp()) processToken(TY_CSI_PR(cc,argv[i]), 0, 0); else if (egt()) processToken(TY_CSI_PG(cc), 0, 0); // spec. case for ESC]>0c or ESC]>c else if (cc == 'm' && argc - i >= 4 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 2) { // ESC[ ... 48;2;<red>;<green>;<blue> ... m -or- ESC[ ... 38;2;<red>;<green>;<blue> ... m i += 2; processToken(TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_RGB, (argv[i] << 16) | (argv[i+1] << 8) | argv[i+2]); i += 2; } else if (cc == 'm' && argc - i >= 2 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 5) { // ESC[ ... 48;5;<index> ... m -or- ESC[ ... 38;5;<index> ... m i += 2; processToken(TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_256, argv[i]); } else processToken(TY_CSI_PS(cc,argv[i]), 0, 0); } resetTokenizer(); } else { // VT52 Mode if (lec(1,0,ESC)) return; if (les(1,0,CHR)) { processToken( TY_CHR(), s[0], 0); resetTokenizer(); return; } if (lec(2,1,'Y')) return; if (lec(3,1,'Y')) return; if (p < 4) { processToken(TY_VT52(s[1] ), 0, 0); resetTokenizer(); return; } processToken(TY_VT52(s[1]), s[2], s[3]); resetTokenizer(); return; } } void Vt102Emulation::processWindowAttributeChange() { // Describes the window or terminal session attribute to change // See Session::UserTitleChange for possible values int attributeToChange = 0; int i; for (i = 2; i < tokenBufferPos && tokenBuffer[i] >= '0' && tokenBuffer[i] <= '9'; i++) { attributeToChange = 10 * attributeToChange + (tokenBuffer[i]-'0'); } if (tokenBuffer[i] != ';') { reportDecodingError(); return; } QString newValue; newValue.reserve(tokenBufferPos-i-2); for (int j = 0; j < tokenBufferPos-i-2; j++) newValue[j] = tokenBuffer[i+1+j]; _pendingTitleUpdates[attributeToChange] = newValue; _titleUpdateTimer->start(20); } void Vt102Emulation::updateTitle() { QListIterator<int> iter( _pendingTitleUpdates.keys() ); while (iter.hasNext()) { int arg = iter.next(); emit titleChanged( arg , _pendingTitleUpdates[arg] ); } _pendingTitleUpdates.clear(); } // Interpreting Codes --------------------------------------------------------- /* Now that the incoming character stream is properly tokenized, meaning is assigned to them. These are either operations of the current _screen, or of the emulation class itself. The token to be interpreteted comes in as a machine word possibly accompanied by two parameters. Likewise, the operations assigned to, come with up to two arguments. One could consider to make up a proper table from the function below. The technical reference manual provides more information about this mapping. */ void Vt102Emulation::processToken(int token, int p, int q) { switch (token) { case TY_CHR( ) : _currentScreen->displayCharacter (p ); break; //UTF16 // 127 DEL : ignored on input case TY_CTL('@' ) : /* NUL: ignored */ break; case TY_CTL('A' ) : /* SOH: ignored */ break; case TY_CTL('B' ) : /* STX: ignored */ break; case TY_CTL('C' ) : /* ETX: ignored */ break; case TY_CTL('D' ) : /* EOT: ignored */ break; case TY_CTL('E' ) : reportAnswerBack ( ); break; //VT100 case TY_CTL('F' ) : /* ACK: ignored */ break; case TY_CTL('G' ) : emit stateSet(NOTIFYBELL); break; //VT100 case TY_CTL('H' ) : _currentScreen->backspace ( ); break; //VT100 case TY_CTL('I' ) : _currentScreen->tab ( ); break; //VT100 case TY_CTL('J' ) : _currentScreen->newLine ( ); break; //VT100 case TY_CTL('K' ) : _currentScreen->newLine ( ); break; //VT100 case TY_CTL('L' ) : _currentScreen->newLine ( ); break; //VT100 case TY_CTL('M' ) : _currentScreen->toStartOfLine ( ); break; //VT100 case TY_CTL('N' ) : useCharset ( 1); break; //VT100 case TY_CTL('O' ) : useCharset ( 0); break; //VT100 case TY_CTL('P' ) : /* DLE: ignored */ break; case TY_CTL('Q' ) : /* DC1: XON continue */ break; //VT100 case TY_CTL('R' ) : /* DC2: ignored */ break; case TY_CTL('S' ) : /* DC3: XOFF halt */ break; //VT100 case TY_CTL('T' ) : /* DC4: ignored */ break; case TY_CTL('U' ) : /* NAK: ignored */ break; case TY_CTL('V' ) : /* SYN: ignored */ break; case TY_CTL('W' ) : /* ETB: ignored */ break; case TY_CTL('X' ) : _currentScreen->displayCharacter ( 0x2592); break; //VT100 case TY_CTL('Y' ) : /* EM : ignored */ break; case TY_CTL('Z' ) : _currentScreen->displayCharacter ( 0x2592); break; //VT100 case TY_CTL('[' ) : /* ESC: cannot be seen here. */ break; case TY_CTL('\\' ) : /* FS : ignored */ break; case TY_CTL(']' ) : /* GS : ignored */ break; case TY_CTL('^' ) : /* RS : ignored */ break; case TY_CTL('_' ) : /* US : ignored */ break; case TY_ESC('D' ) : _currentScreen->index ( ); break; //VT100 case TY_ESC('E' ) : _currentScreen->nextLine ( ); break; //VT100 case TY_ESC('H' ) : _currentScreen->changeTabStop (true ); break; //VT100 case TY_ESC('M' ) : _currentScreen->reverseIndex ( ); break; //VT100 case TY_ESC('Z' ) : reportTerminalType ( ); break; case TY_ESC('c' ) : reset ( ); break; case TY_ESC('n' ) : useCharset ( 2); break; case TY_ESC('o' ) : useCharset ( 3); break; case TY_ESC('7' ) : saveCursor ( ); break; case TY_ESC('8' ) : restoreCursor ( ); break; case TY_ESC('=' ) : setMode (MODE_AppKeyPad); break; case TY_ESC('>' ) : resetMode (MODE_AppKeyPad); break; case TY_ESC('<' ) : setMode (MODE_Ansi ); break; //VT100 case TY_ESC_CS('(', '0') : setCharset (0, '0'); break; //VT100 case TY_ESC_CS('(', 'A') : setCharset (0, 'A'); break; //VT100 case TY_ESC_CS('(', 'B') : setCharset (0, 'B'); break; //VT100 case TY_ESC_CS(')', '0') : setCharset (1, '0'); break; //VT100 case TY_ESC_CS(')', 'A') : setCharset (1, 'A'); break; //VT100 case TY_ESC_CS(')', 'B') : setCharset (1, 'B'); break; //VT100 case TY_ESC_CS('*', '0') : setCharset (2, '0'); break; //VT100 case TY_ESC_CS('*', 'A') : setCharset (2, 'A'); break; //VT100 case TY_ESC_CS('*', 'B') : setCharset (2, 'B'); break; //VT100 case TY_ESC_CS('+', '0') : setCharset (3, '0'); break; //VT100 case TY_ESC_CS('+', 'A') : setCharset (3, 'A'); break; //VT100 case TY_ESC_CS('+', 'B') : setCharset (3, 'B'); break; //VT100 case TY_ESC_CS('%', 'G') : setCodec (Utf8Codec ); break; //LINUX case TY_ESC_CS('%', '@') : setCodec (LocaleCodec ); break; //LINUX case TY_ESC_DE('3' ) : /* Double height line, top half */ _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); break; case TY_ESC_DE('4' ) : /* Double height line, bottom half */ _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); break; case TY_ESC_DE('5' ) : /* Single width, single height line*/ _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , false); _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false); break; case TY_ESC_DE('6' ) : /* Double width, single height line*/ _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true); _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false); break; case TY_ESC_DE('8' ) : _currentScreen->helpAlign ( ); break; // resize = \e[8;<row>;<col>t case TY_CSI_PS('t', 8) : setImageSize( p /*lines */, q /* columns */ ); emit imageResizeRequest(QSize(q, p)); break; // change tab text color : \e[28;<color>t color: 0-16,777,215 case TY_CSI_PS('t', 28) : emit changeTabTextColorRequest ( p ); break; case TY_CSI_PS('K', 0) : _currentScreen->clearToEndOfLine ( ); break; case TY_CSI_PS('K', 1) : _currentScreen->clearToBeginOfLine ( ); break; case TY_CSI_PS('K', 2) : _currentScreen->clearEntireLine ( ); break; case TY_CSI_PS('J', 0) : _currentScreen->clearToEndOfScreen ( ); break; case TY_CSI_PS('J', 1) : _currentScreen->clearToBeginOfScreen ( ); break; case TY_CSI_PS('J', 2) : _currentScreen->clearEntireScreen ( ); break; case TY_CSI_PS('J', 3) : clearHistory(); break; case TY_CSI_PS('g', 0) : _currentScreen->changeTabStop (false ); break; //VT100 case TY_CSI_PS('g', 3) : _currentScreen->clearTabStops ( ); break; //VT100 case TY_CSI_PS('h', 4) : _currentScreen-> setMode (MODE_Insert ); break; case TY_CSI_PS('h', 20) : setMode (MODE_NewLine ); break; case TY_CSI_PS('i', 0) : /* IGNORE: attached printer */ break; //VT100 case TY_CSI_PS('l', 4) : _currentScreen-> resetMode (MODE_Insert ); break; case TY_CSI_PS('l', 20) : resetMode (MODE_NewLine ); break; case TY_CSI_PS('s', 0) : saveCursor ( ); break; case TY_CSI_PS('u', 0) : restoreCursor ( ); break; case TY_CSI_PS('m', 0) : _currentScreen->setDefaultRendition ( ); break; case TY_CSI_PS('m', 1) : _currentScreen-> setRendition (RE_BOLD ); break; //VT100 case TY_CSI_PS('m', 4) : _currentScreen-> setRendition (RE_UNDERLINE); break; //VT100 case TY_CSI_PS('m', 5) : _currentScreen-> setRendition (RE_BLINK ); break; //VT100 case TY_CSI_PS('m', 7) : _currentScreen-> setRendition (RE_REVERSE ); break; case TY_CSI_PS('m', 10) : /* IGNORED: mapping related */ break; //LINUX case TY_CSI_PS('m', 11) : /* IGNORED: mapping related */ break; //LINUX case TY_CSI_PS('m', 12) : /* IGNORED: mapping related */ break; //LINUX case TY_CSI_PS('m', 22) : _currentScreen->resetRendition (RE_BOLD ); break; case TY_CSI_PS('m', 24) : _currentScreen->resetRendition (RE_UNDERLINE); break; case TY_CSI_PS('m', 25) : _currentScreen->resetRendition (RE_BLINK ); break; case TY_CSI_PS('m', 27) : _currentScreen->resetRendition (RE_REVERSE ); break; case TY_CSI_PS('m', 30) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 0); break; case TY_CSI_PS('m', 31) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 1); break; case TY_CSI_PS('m', 32) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 2); break; case TY_CSI_PS('m', 33) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 3); break; case TY_CSI_PS('m', 34) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 4); break; case TY_CSI_PS('m', 35) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 5); break; case TY_CSI_PS('m', 36) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 6); break; case TY_CSI_PS('m', 37) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 7); break; case TY_CSI_PS('m', 38) : _currentScreen->setForeColor (p, q); break; case TY_CSI_PS('m', 39) : _currentScreen->setForeColor (COLOR_SPACE_DEFAULT, 0); break; case TY_CSI_PS('m', 40) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 0); break; case TY_CSI_PS('m', 41) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 1); break; case TY_CSI_PS('m', 42) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 2); break; case TY_CSI_PS('m', 43) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 3); break; case TY_CSI_PS('m', 44) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 4); break; case TY_CSI_PS('m', 45) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 5); break; case TY_CSI_PS('m', 46) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 6); break; case TY_CSI_PS('m', 47) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 7); break; case TY_CSI_PS('m', 48) : _currentScreen->setBackColor (p, q); break; case TY_CSI_PS('m', 49) : _currentScreen->setBackColor (COLOR_SPACE_DEFAULT, 1); break; case TY_CSI_PS('m', 90) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 8); break; case TY_CSI_PS('m', 91) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 9); break; case TY_CSI_PS('m', 92) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 10); break; case TY_CSI_PS('m', 93) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 11); break; case TY_CSI_PS('m', 94) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 12); break; case TY_CSI_PS('m', 95) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 13); break; case TY_CSI_PS('m', 96) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 14); break; case TY_CSI_PS('m', 97) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 15); break; case TY_CSI_PS('m', 100) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 8); break; case TY_CSI_PS('m', 101) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 9); break; case TY_CSI_PS('m', 102) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 10); break; case TY_CSI_PS('m', 103) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 11); break; case TY_CSI_PS('m', 104) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 12); break; case TY_CSI_PS('m', 105) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 13); break; case TY_CSI_PS('m', 106) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 14); break; case TY_CSI_PS('m', 107) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 15); break; case TY_CSI_PS('n', 5) : reportStatus ( ); break; case TY_CSI_PS('n', 6) : reportCursorPosition ( ); break; case TY_CSI_PS('q', 0) : /* IGNORED: LEDs off */ break; //VT100 case TY_CSI_PS('q', 1) : /* IGNORED: LED1 on */ break; //VT100 case TY_CSI_PS('q', 2) : /* IGNORED: LED2 on */ break; //VT100 case TY_CSI_PS('q', 3) : /* IGNORED: LED3 on */ break; //VT100 case TY_CSI_PS('q', 4) : /* IGNORED: LED4 on */ break; //VT100 case TY_CSI_PS('x', 0) : reportTerminalParms ( 2); break; //VT100 case TY_CSI_PS('x', 1) : reportTerminalParms ( 3); break; //VT100 case TY_CSI_PN('@' ) : _currentScreen->insertChars (p ); break; case TY_CSI_PN('A' ) : _currentScreen->cursorUp (p ); break; //VT100 case TY_CSI_PN('B' ) : _currentScreen->cursorDown (p ); break; //VT100 case TY_CSI_PN('C' ) : _currentScreen->cursorRight (p ); break; //VT100 case TY_CSI_PN('D' ) : _currentScreen->cursorLeft (p ); break; //VT100 case TY_CSI_PN('G' ) : _currentScreen->setCursorX (p ); break; //LINUX case TY_CSI_PN('H' ) : _currentScreen->setCursorYX (p, q); break; //VT100 case TY_CSI_PN('I' ) : _currentScreen->tab (p ); break; case TY_CSI_PN('L' ) : _currentScreen->insertLines (p ); break; case TY_CSI_PN('M' ) : _currentScreen->deleteLines (p ); break; case TY_CSI_PN('P' ) : _currentScreen->deleteChars (p ); break; case TY_CSI_PN('S' ) : _currentScreen->scrollUp (p ); break; case TY_CSI_PN('T' ) : _currentScreen->scrollDown (p ); break; case TY_CSI_PN('X' ) : _currentScreen->eraseChars (p ); break; case TY_CSI_PN('Z' ) : _currentScreen->backtab (p ); break; case TY_CSI_PN('c' ) : reportTerminalType ( ); break; //VT100 case TY_CSI_PN('d' ) : _currentScreen->setCursorY (p ); break; //LINUX case TY_CSI_PN('f' ) : _currentScreen->setCursorYX (p, q); break; //VT100 case TY_CSI_PN('r' ) : setMargins (p, q); break; //VT100 case TY_CSI_PN('y' ) : /* IGNORED: Confidence test */ break; //VT100 case TY_CSI_PR('h', 1) : setMode (MODE_AppCuKeys); break; //VT100 case TY_CSI_PR('l', 1) : resetMode (MODE_AppCuKeys); break; //VT100 case TY_CSI_PR('s', 1) : saveMode (MODE_AppCuKeys); break; //FIXME case TY_CSI_PR('r', 1) : restoreMode (MODE_AppCuKeys); break; //FIXME case TY_CSI_PR('l', 2) : resetMode (MODE_Ansi ); break; //VT100 case TY_CSI_PR('h', 3) : setMode (MODE_132Columns); break; //VT100 case TY_CSI_PR('l', 3) : resetMode (MODE_132Columns); break; //VT100 case TY_CSI_PR('h', 4) : /* IGNORED: soft scrolling */ break; //VT100 case TY_CSI_PR('l', 4) : /* IGNORED: soft scrolling */ break; //VT100 case TY_CSI_PR('h', 5) : _currentScreen-> setMode (MODE_Screen ); break; //VT100 case TY_CSI_PR('l', 5) : _currentScreen-> resetMode (MODE_Screen ); break; //VT100 case TY_CSI_PR('h', 6) : _currentScreen-> setMode (MODE_Origin ); break; //VT100 case TY_CSI_PR('l', 6) : _currentScreen-> resetMode (MODE_Origin ); break; //VT100 case TY_CSI_PR('s', 6) : _currentScreen-> saveMode (MODE_Origin ); break; //FIXME case TY_CSI_PR('r', 6) : _currentScreen->restoreMode (MODE_Origin ); break; //FIXME case TY_CSI_PR('h', 7) : _currentScreen-> setMode (MODE_Wrap ); break; //VT100 case TY_CSI_PR('l', 7) : _currentScreen-> resetMode (MODE_Wrap ); break; //VT100 case TY_CSI_PR('s', 7) : _currentScreen-> saveMode (MODE_Wrap ); break; //FIXME case TY_CSI_PR('r', 7) : _currentScreen->restoreMode (MODE_Wrap ); break; //FIXME case TY_CSI_PR('h', 8) : /* IGNORED: autorepeat on */ break; //VT100 case TY_CSI_PR('l', 8) : /* IGNORED: autorepeat off */ break; //VT100 case TY_CSI_PR('s', 8) : /* IGNORED: autorepeat on */ break; //VT100 case TY_CSI_PR('r', 8) : /* IGNORED: autorepeat off */ break; //VT100 case TY_CSI_PR('h', 9) : /* IGNORED: interlace */ break; //VT100 case TY_CSI_PR('l', 9) : /* IGNORED: interlace */ break; //VT100 case TY_CSI_PR('s', 9) : /* IGNORED: interlace */ break; //VT100 case TY_CSI_PR('r', 9) : /* IGNORED: interlace */ break; //VT100 case TY_CSI_PR('h', 12) : /* IGNORED: Cursor blink */ break; //att610 case TY_CSI_PR('l', 12) : /* IGNORED: Cursor blink */ break; //att610 case TY_CSI_PR('s', 12) : /* IGNORED: Cursor blink */ break; //att610 case TY_CSI_PR('r', 12) : /* IGNORED: Cursor blink */ break; //att610 case TY_CSI_PR('h', 25) : setMode (MODE_Cursor ); break; //VT100 case TY_CSI_PR('l', 25) : resetMode (MODE_Cursor ); break; //VT100 case TY_CSI_PR('s', 25) : saveMode (MODE_Cursor ); break; //VT100 case TY_CSI_PR('r', 25) : restoreMode (MODE_Cursor ); break; //VT100 case TY_CSI_PR('h', 40) : setMode(MODE_Allow132Columns ); break; // XTERM case TY_CSI_PR('l', 40) : resetMode(MODE_Allow132Columns ); break; // XTERM case TY_CSI_PR('h', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM case TY_CSI_PR('l', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM case TY_CSI_PR('s', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM case TY_CSI_PR('r', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM case TY_CSI_PR('h', 47) : setMode (MODE_AppScreen); break; //VT100 case TY_CSI_PR('l', 47) : resetMode (MODE_AppScreen); break; //VT100 case TY_CSI_PR('s', 47) : saveMode (MODE_AppScreen); break; //XTERM case TY_CSI_PR('r', 47) : restoreMode (MODE_AppScreen); break; //XTERM case TY_CSI_PR('h', 67) : /* IGNORED: DECBKM */ break; //XTERM case TY_CSI_PR('l', 67) : /* IGNORED: DECBKM */ break; //XTERM case TY_CSI_PR('s', 67) : /* IGNORED: DECBKM */ break; //XTERM case TY_CSI_PR('r', 67) : /* IGNORED: DECBKM */ break; //XTERM // XTerm defines the following modes: // SET_VT200_MOUSE 1000 // SET_VT200_HIGHLIGHT_MOUSE 1001 // SET_BTN_EVENT_MOUSE 1002 // SET_ANY_EVENT_MOUSE 1003 // //Note about mouse modes: //There are four mouse modes which xterm-compatible terminals can support - 1000,1001,1002,1003 //Konsole currently supports mode 1000 (basic mouse press and release) and mode 1002 (dragging the mouse). //TODO: Implementation of mouse modes 1001 (something called hilight tracking) and //1003 (a slight variation on dragging the mouse) // case TY_CSI_PR('h', 1000) : setMode (MODE_Mouse1000); break; //XTERM case TY_CSI_PR('l', 1000) : resetMode (MODE_Mouse1000); break; //XTERM case TY_CSI_PR('s', 1000) : saveMode (MODE_Mouse1000); break; //XTERM case TY_CSI_PR('r', 1000) : restoreMode (MODE_Mouse1000); break; //XTERM case TY_CSI_PR('h', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM case TY_CSI_PR('l', 1001) : resetMode (MODE_Mouse1001); break; //XTERM case TY_CSI_PR('s', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM case TY_CSI_PR('r', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM case TY_CSI_PR('h', 1002) : setMode (MODE_Mouse1002); break; //XTERM case TY_CSI_PR('l', 1002) : resetMode (MODE_Mouse1002); break; //XTERM case TY_CSI_PR('s', 1002) : saveMode (MODE_Mouse1002); break; //XTERM case TY_CSI_PR('r', 1002) : restoreMode (MODE_Mouse1002); break; //XTERM case TY_CSI_PR('h', 1003) : setMode (MODE_Mouse1003); break; //XTERM case TY_CSI_PR('l', 1003) : resetMode (MODE_Mouse1003); break; //XTERM case TY_CSI_PR('s', 1003) : saveMode (MODE_Mouse1003); break; //XTERM case TY_CSI_PR('r', 1003) : restoreMode (MODE_Mouse1003); break; //XTERM case TY_CSI_PR('h', 1005) : setMode (MODE_Mouse1005); break; //XTERM case TY_CSI_PR('l', 1005) : resetMode (MODE_Mouse1005); break; //XTERM case TY_CSI_PR('s', 1005) : saveMode (MODE_Mouse1005); break; //XTERM case TY_CSI_PR('r', 1005) : restoreMode (MODE_Mouse1005); break; //XTERM case TY_CSI_PR('h', 1015) : setMode (MODE_Mouse1015); break; //URXVT case TY_CSI_PR('l', 1015) : resetMode (MODE_Mouse1015); break; //URXVT case TY_CSI_PR('s', 1015) : saveMode (MODE_Mouse1015); break; //URXVT case TY_CSI_PR('r', 1015) : restoreMode (MODE_Mouse1015); break; //URXVT case TY_CSI_PR('h', 1034) : /* IGNORED: 8bitinput activation */ break; //XTERM case TY_CSI_PR('h', 1047) : setMode (MODE_AppScreen); break; //XTERM case TY_CSI_PR('l', 1047) : _screen[1]->clearEntireScreen(); resetMode(MODE_AppScreen); break; //XTERM case TY_CSI_PR('s', 1047) : saveMode (MODE_AppScreen); break; //XTERM case TY_CSI_PR('r', 1047) : restoreMode (MODE_AppScreen); break; //XTERM //FIXME: Unitoken: save translations case TY_CSI_PR('h', 1048) : saveCursor ( ); break; //XTERM case TY_CSI_PR('l', 1048) : restoreCursor ( ); break; //XTERM case TY_CSI_PR('s', 1048) : saveCursor ( ); break; //XTERM case TY_CSI_PR('r', 1048) : restoreCursor ( ); break; //XTERM //FIXME: every once new sequences like this pop up in xterm. // Here's a guess of what they could mean. case TY_CSI_PR('h', 1049) : saveCursor(); _screen[1]->clearEntireScreen(); setMode(MODE_AppScreen); break; //XTERM case TY_CSI_PR('l', 1049) : resetMode(MODE_AppScreen); restoreCursor(); break; //XTERM //FIXME: weird DEC reset sequence case TY_CSI_PE('p' ) : /* IGNORED: reset ( ) */ break; //FIXME: when changing between vt52 and ansi mode evtl do some resetting. case TY_VT52('A' ) : _currentScreen->cursorUp ( 1); break; //VT52 case TY_VT52('B' ) : _currentScreen->cursorDown ( 1); break; //VT52 case TY_VT52('C' ) : _currentScreen->cursorRight ( 1); break; //VT52 case TY_VT52('D' ) : _currentScreen->cursorLeft ( 1); break; //VT52 case TY_VT52('F' ) : setAndUseCharset (0, '0'); break; //VT52 case TY_VT52('G' ) : setAndUseCharset (0, 'B'); break; //VT52 case TY_VT52('H' ) : _currentScreen->setCursorYX (1,1 ); break; //VT52 case TY_VT52('I' ) : _currentScreen->reverseIndex ( ); break; //VT52 case TY_VT52('J' ) : _currentScreen->clearToEndOfScreen ( ); break; //VT52 case TY_VT52('K' ) : _currentScreen->clearToEndOfLine ( ); break; //VT52 case TY_VT52('Y' ) : _currentScreen->setCursorYX (p-31,q-31 ); break; //VT52 case TY_VT52('Z' ) : reportTerminalType ( ); break; //VT52 case TY_VT52('<' ) : setMode (MODE_Ansi ); break; //VT52 case TY_VT52('=' ) : setMode (MODE_AppKeyPad); break; //VT52 case TY_VT52('>' ) : resetMode (MODE_AppKeyPad); break; //VT52 case TY_CSI_PG('c' ) : reportSecondaryAttributes( ); break; //VT100 default: reportDecodingError(); break; }; } void Vt102Emulation::clearScreenAndSetColumns(int columnCount) { setImageSize(_currentScreen->getLines(),columnCount); clearEntireScreen(); setDefaultMargins(); _currentScreen->setCursorYX(0,0); } void Vt102Emulation::sendString(const char* s , int length) { if ( length >= 0 ) emit sendData(s,length); else emit sendData(s,qstrlen(s)); } void Vt102Emulation::reportCursorPosition() { char tmp[20]; snprintf(tmp, sizeof(tmp), "\033[%d;%dR", _currentScreen->getCursorY()+1, _currentScreen->getCursorX()+1); sendString(tmp); } void Vt102Emulation::reportTerminalType() { // Primary device attribute response (Request was: ^[[0c or ^[[c (from TT321 Users Guide)) // VT220: ^[[?63;1;2;3;6;7;8c (list deps on emul. capabilities) // VT100: ^[[?1;2c // VT101: ^[[?1;0c // VT102: ^[[?6v if (getMode(MODE_Ansi)) sendString("\033[?1;2c"); // I'm a VT100 else sendString("\033/Z"); // I'm a VT52 } void Vt102Emulation::reportSecondaryAttributes() { // Seconday device attribute response (Request was: ^[[>0c or ^[[>c) if (getMode(MODE_Ansi)) sendString("\033[>0;115;0c"); // Why 115? ;) else sendString("\033/Z"); // FIXME I don't think VT52 knows about it but kept for // konsoles backward compatibility. } /* DECREPTPARM – Report Terminal Parameters ESC [ <sol>; <par>; <nbits>; <xspeed>; <rspeed>; <clkmul>; <flags> x http://vt100.net/docs/vt100-ug/chapter3.html */ void Vt102Emulation::reportTerminalParms(int p) { char tmp[100]; /* sol=1: This message is a request; report in response to a request. par=1: No parity set nbits=1: 8 bits per character xspeed=112: 9600 rspeed=112: 9600 clkmul=1: The bit rate multiplier is 16. flags=0: None */ snprintf(tmp, sizeof(tmp), "\033[%d;1;1;112;112;1;0x", p); // not really true. sendString(tmp); } void Vt102Emulation::reportStatus() { sendString("\033[0n"); //VT100. Device status report. 0 = Ready. } void Vt102Emulation::reportAnswerBack() { // FIXME - Test this with VTTEST // This is really obsolete VT100 stuff. const char* ANSWER_BACK = ""; sendString(ANSWER_BACK); } /*! `cx',`cy' are 1-based. `eventType' indicates the button pressed (0-2) or a general mouse release (3). eventType represents the kind of mouse action that occurred: 0 = Mouse button press or release 1 = Mouse drag */ void Vt102Emulation::sendMouseEvent(int cb, int cx, int cy , int eventType) { if (cx < 1 || cy < 1) return; // normal buttons are passed as 0x20 + button, // mouse wheel (buttons 4,5) as 0x5c + button if (cb >= 4) cb += 0x3c; //Mouse motion handling if ((getMode(MODE_Mouse1002) || getMode(MODE_Mouse1003)) && eventType == 1) cb += 0x20; //add 32 to signify motion event char command[32]; command[0] = '\0'; if (getMode(MODE_Mouse1015)) { snprintf(command, sizeof(command), "\033[%d;%d;%dM", cb + 0x20, cx, cy); } else if (getMode(MODE_Mouse1005)) { if (cx <= 2015 && cy <= 2015) { // The xterm extension uses UTF-8 (up to 2 bytes) to encode // coordinate+32, no matter what the locale is. We could easily // convert manually, but QString can also do it for us. QChar coords[2]; coords[0] = cx + 0x20; coords[1] = cy + 0x20; QString coordsStr = QString(coords, 2); QByteArray utf8 = coordsStr.toUtf8(); snprintf(command, sizeof(command), "\033[M%c%s", cb + 0x20, (const char *)utf8); } } else if (cx <= 223 && cy <= 223) { snprintf(command, sizeof(command), "\033[M%c%c%c", cb + 0x20, cx + 0x20, cy + 0x20); } sendString(command); } void Vt102Emulation::sendText(const QString& text) { if (!text.isEmpty()) { QKeyEvent event(QEvent::KeyPress, 0, Qt::NoModifier, text); sendKeyEvent(&event); // expose as a big fat keypress event } } void Vt102Emulation::sendKeyEvent(QKeyEvent* event) { const Qt::KeyboardModifiers modifiers = event->modifiers(); KeyboardTranslator::States states = KeyboardTranslator::NoState; // get current states if (getMode(MODE_NewLine)) states |= KeyboardTranslator::NewLineState; if (getMode(MODE_Ansi)) states |= KeyboardTranslator::AnsiState; if (getMode(MODE_AppCuKeys)) states |= KeyboardTranslator::CursorKeysState; if (getMode(MODE_AppScreen)) states |= KeyboardTranslator::AlternateScreenState; if (getMode(MODE_AppKeyPad) && (modifiers & Qt::KeypadModifier)) states |= KeyboardTranslator::ApplicationKeypadState; // check flow control state if (modifiers & Qt::ControlModifier) { switch (event->key()) { case Qt::Key_S: emit flowControlKeyPressed(true); break; case Qt::Key_Q: case Qt::Key_C: // cancel flow control emit flowControlKeyPressed(false); break; } } // lookup key binding if (_keyTranslator) { KeyboardTranslator::Entry entry = _keyTranslator->findEntry( event->key() , modifiers, states); // send result to terminal QByteArray textToSend; // special handling for the Alt (aka. Meta) modifier. pressing // Alt+[Character] results in Esc+[Character] being sent // (unless there is an entry defined for this particular combination // in the keyboard modifier) const bool wantsAltModifier = entry.modifiers() & entry.modifierMask() & Qt::AltModifier; const bool wantsMetaModifier = entry.modifiers() & entry.modifierMask() & Qt::MetaModifier; const bool wantsAnyModifier = entry.state() & entry.stateMask() & KeyboardTranslator::AnyModifierState; if ( modifiers & Qt::AltModifier && !(wantsAltModifier || wantsAnyModifier) && !event->text().isEmpty() ) { textToSend.prepend("\033"); } if ( modifiers & Qt::MetaModifier && !(wantsMetaModifier || wantsAnyModifier) && !event->text().isEmpty() ) { textToSend.prepend("\030@s"); } if ( entry.command() != KeyboardTranslator::NoCommand ) { TerminalDisplay * currentView = _currentScreen->currentTerminalDisplay(); if (entry.command() & KeyboardTranslator::EraseCommand) { textToSend += eraseChar(); } else if (entry.command() & KeyboardTranslator::ScrollPageUpCommand) currentView->scrollScreenWindow(ScreenWindow::ScrollPages, -1); else if (entry.command() & KeyboardTranslator::ScrollPageDownCommand) currentView->scrollScreenWindow(ScreenWindow::ScrollPages, 1); else if (entry.command() & KeyboardTranslator::ScrollLineUpCommand) currentView->scrollScreenWindow(ScreenWindow::ScrollLines, -1); else if (entry.command() & KeyboardTranslator::ScrollLineDownCommand) currentView->scrollScreenWindow(ScreenWindow::ScrollLines, 1); else if (entry.command() & KeyboardTranslator::ScrollUpToTopCommand) currentView->scrollScreenWindow(ScreenWindow::ScrollLines, - currentView->screenWindow()->currentLine()); else if (entry.command() & KeyboardTranslator::ScrollDownToBottomCommand) currentView->scrollScreenWindow(ScreenWindow::ScrollLines, lineCount()); } else if (!entry.text().isEmpty()) { textToSend += _codec->fromUnicode(entry.text(true,modifiers)); } else textToSend += _codec->fromUnicode(event->text()); sendData(textToSend.constData(), textToSend.length()); } else { // print an error message to the terminal if no key translator has been // set QString translatorError = i18n("No keyboard translator available. " "The information needed to convert key presses " "into characters to send to the terminal " "is missing."); reset(); receiveData(translatorError.toAscii().constData(), translatorError.count()); } } /* ------------------------------------------------------------------------- */ /* */ /* VT100 Charsets */ /* */ /* ------------------------------------------------------------------------- */ // Character Set Conversion ------------------------------------------------ -- /* The processing contains a VT100 specific code translation layer. It's still in use and mainly responsible for the line drawing graphics. These and some other glyphs are assigned to codes (0x5f-0xfe) normally occupied by the latin letters. Since this codes also appear within control sequences, the extra code conversion does not permute with the tokenizer and is placed behind it in the pipeline. It only applies to tokens, which represent plain characters. This conversion it eventually continued in TerminalDisplay.C, since it might involve VT100 enhanced fonts, which have these particular glyphs allocated in (0x00-0x1f) in their code page. */ #define CHARSET _charset[_currentScreen==_screen[1]] // Apply current character map. unsigned short Vt102Emulation::applyCharset(unsigned short c) { if (CHARSET.graphic && 0x5f <= c && c <= 0x7e) return vt100_graphics[c - 0x5f]; if (CHARSET.pound && c == '#') return 0xa3; //This mode is obsolete return c; } /* "Charset" related part of the emulation state. This configures the VT100 charset filter. While most operation work on the current _screen, the following two are different. */ void Vt102Emulation::resetCharset(int scrno) { _charset[scrno].cu_cs = 0; qstrncpy(_charset[scrno].charset, "BBBB", 4); _charset[scrno].sa_graphic = false; _charset[scrno].sa_pound = false; _charset[scrno].graphic = false; _charset[scrno].pound = false; } void Vt102Emulation::setCharset(int n, int cs) // on both screens. { _charset[0].charset[n & 3] = cs; useCharset(_charset[0].cu_cs); _charset[1].charset[n & 3] = cs; useCharset(_charset[1].cu_cs); } void Vt102Emulation::setAndUseCharset(int n, int cs) { CHARSET.charset[n & 3] = cs; useCharset(n & 3); } void Vt102Emulation::useCharset(int n) { CHARSET.cu_cs = n & 3; CHARSET.graphic = (CHARSET.charset[n & 3] == '0'); CHARSET.pound = (CHARSET.charset[n & 3] == 'A'); //This mode is obsolete } void Vt102Emulation::setDefaultMargins() { _screen[0]->setDefaultMargins(); _screen[1]->setDefaultMargins(); } void Vt102Emulation::setMargins(int t, int b) { _screen[0]->setMargins(t, b); _screen[1]->setMargins(t, b); } void Vt102Emulation::saveCursor() { CHARSET.sa_graphic = CHARSET.graphic; CHARSET.sa_pound = CHARSET.pound; //This mode is obsolete // we are not clear about these //sa_charset = charsets[cScreen->_charset]; //sa_charset_num = cScreen->_charset; _currentScreen->saveCursor(); } void Vt102Emulation::restoreCursor() { CHARSET.graphic = CHARSET.sa_graphic; CHARSET.pound = CHARSET.sa_pound; //This mode is obsolete _currentScreen->restoreCursor(); } /* ------------------------------------------------------------------------- */ /* */ /* Mode Operations */ /* */ /* ------------------------------------------------------------------------- */ /* Some of the emulations state is either added to the state of the screens. This causes some scoping problems, since different emulations choose to located the mode either to the current _screen or to both. For strange reasons, the extend of the rendition attributes ranges over all screens and not over the actual _screen. We decided on the precise precise extend, somehow. */ // "Mode" related part of the state. These are all booleans. void Vt102Emulation::resetModes() { // MODE_Allow132Columns is not reset here // to match Xterm's behaviour (see Xterm's VTReset() function) resetMode(MODE_132Columns); saveMode(MODE_132Columns); resetMode(MODE_Mouse1000); saveMode(MODE_Mouse1000); resetMode(MODE_Mouse1001); saveMode(MODE_Mouse1001); resetMode(MODE_Mouse1002); saveMode(MODE_Mouse1002); resetMode(MODE_Mouse1003); saveMode(MODE_Mouse1003); resetMode(MODE_Mouse1005); saveMode(MODE_Mouse1005); resetMode(MODE_Mouse1015); saveMode(MODE_Mouse1015); resetMode(MODE_AppScreen); saveMode(MODE_AppScreen); resetMode(MODE_AppCuKeys); saveMode(MODE_AppCuKeys); resetMode(MODE_AppKeyPad); saveMode(MODE_AppKeyPad); resetMode(MODE_NewLine); setMode(MODE_Ansi); } void Vt102Emulation::setMode(int m) { _currentModes.mode[m] = true; switch (m) { case MODE_132Columns: if (getMode(MODE_Allow132Columns)) clearScreenAndSetColumns(132); else _currentModes.mode[m] = false; break; case MODE_Mouse1000: case MODE_Mouse1001: case MODE_Mouse1002: case MODE_Mouse1003: emit programUsesMouseChanged(false); break; case MODE_AppScreen : _screen[1]->clearSelection(); setScreen(1); break; } if (m < MODES_SCREEN || m == MODE_NewLine) { _screen[0]->setMode(m); _screen[1]->setMode(m); } } void Vt102Emulation::resetMode(int m) { _currentModes.mode[m] = false; switch (m) { case MODE_132Columns: if (getMode(MODE_Allow132Columns)) clearScreenAndSetColumns(80); break; case MODE_Mouse1000 : case MODE_Mouse1001 : case MODE_Mouse1002 : case MODE_Mouse1003 : emit programUsesMouseChanged(true); break; case MODE_AppScreen : _screen[0]->clearSelection(); setScreen(0); break; } if (m < MODES_SCREEN || m == MODE_NewLine) { _screen[0]->resetMode(m); _screen[1]->resetMode(m); } } void Vt102Emulation::saveMode(int m) { _savedModes.mode[m] = _currentModes.mode[m]; } void Vt102Emulation::restoreMode(int m) { if (_savedModes.mode[m]) setMode(m); else resetMode(m); } bool Vt102Emulation::getMode(int m) { return _currentModes.mode[m]; } char Vt102Emulation::eraseChar() const { KeyboardTranslator::Entry entry = _keyTranslator->findEntry( Qt::Key_Backspace, 0, 0); if (entry.text().count() > 0) return entry.text()[0]; else return '\b'; } #if 0 // print contents of the scan buffer static void hexdump(int* s, int len) { int i; for (i = 0; i < len; i++) { if (s[i] == '\\') printf("\\\\"); else if ((s[i]) > 32 && s[i] < 127) printf("%c", s[i]); else printf("\\%04x(hex)", s[i]); } } #endif // return contents of the scan buffer static QString hexdump2(int* s, int len) { int i; char dump[128]; QString returnDump; for (i = 0; i < len; i++) { if (s[i] == '\\') snprintf(dump, sizeof(dump), "%s", "\\\\"); else if ((s[i]) > 32 && s[i] < 127) snprintf(dump, sizeof(dump), "%c", s[i]); else snprintf(dump, sizeof(dump), "\\%04x(hex)", s[i]); returnDump.append(QString(dump)); } return returnDump; } void Vt102Emulation::reportDecodingError() { if (tokenBufferPos == 0 || (tokenBufferPos == 1 && (tokenBuffer[0] & 0xff) >= 32)) return; // printf("Undecodable sequence: "); // hexdump(tokenBuffer, tokenBufferPos); // printf("\n"); QString outputError = QString("Undecodable sequence: "); outputError.append(hexdump2(tokenBuffer, tokenBufferPos)); kDebug() << outputError; } #include "Vt102Emulation.moc"
gpl-2.0
erlfas/DBLPCommunities
src/test/java/communities3/TestAlgorithm.java
106
package communities3; public class TestAlgorithm { public static void main(String[] args) { } }
gpl-2.0
suitmyself/Physika
Physika_Src/Physika_Dynamics/PDM/PDM_base.cpp
32383
/* * @file PDM_base.cpp * @Basic PDMBase class. basic class of PDM * @author Wei Chen * * This file is part of Physika, a versatile physics simulation library. * Copyright (C) 2013 Physika Group. * * This Source Code Form is subject to the terms of the GNU General Public License v2.0. * If a copy of the GPL was not distributed with this file, you can obtain one at: * http://www.gnu.org/licenses/gpl-2.0.html * */ #include <iostream> #include <iomanip> #include "Physika_Core/Utilities/physika_assert.h" #include "Physika_IO/Volumetric_Mesh_IO/volumetric_mesh_io.h" #include "Physika_Geometry/Volumetric_Meshes/volumetric_mesh.h" #include "Physika_Geometry/Volumetric_Meshes/volumetric_mesh_internal.h" #include "Physika_Geometry/Volumetric_Meshes/tri_mesh.h" #include "Physika_Geometry/Volumetric_Meshes/tet_mesh.h" #include "Physika_Dynamics/PDM/PDM_base.h" #include "Physika_Dynamics/PDM/PDM_Plugins/PDM_plugin_base.h" #include "Physika_Dynamics/PDM/PDM_Step_Methods/PDM_Collision_Methods/PDM_collision_method_base.h" #include "Physika_Dynamics/PDM/PDM_Step_Methods/PDM_Collision_Methods/PDM_collision_method_grid_2d.h" #include "Physika_Dynamics/PDM/PDM_Step_Methods/PDM_Collision_Methods/PDM_collision_method_grid_3d.h" #include "Physika_Dynamics/PDM/PDM_Step_Methods/PDM_step_method_base.h" #include "Physika_Core/Utilities/math_utilities.h" namespace Physika{ template <typename Scalar, int Dim> PDMBase<Scalar, Dim>::PDMBase() :DriverBase(),gravity_(9.8),pause_simulation_(true),mesh_(NULL), time_step_id_(0), wait_time_per_step_(0) { } template <typename Scalar, int Dim> PDMBase<Scalar, Dim>::PDMBase(unsigned int start_frame, unsigned int end_frame, Scalar frame_rate, Scalar max_dt, bool write_to_file) :DriverBase<Scalar>(start_frame,end_frame,frame_rate,max_dt,write_to_file),gravity_(9.8), pause_simulation_(true),mesh_(NULL),time_step_id_(0), wait_time_per_step_(0) { } template <typename Scalar, int Dim> PDMBase<Scalar, Dim>::~PDMBase() { delete this->mesh_; } // virtual function template<typename Scalar, int Dim> void PDMBase<Scalar, Dim>::initConfiguration(const std::string & file_name) { // to do } template<typename Scalar, int Dim> void PDMBase<Scalar, Dim>::printConfigFileFormat() { // to do } template<typename Scalar, int Dim> void PDMBase<Scalar, Dim>::initSimulationData() { // to do } template<typename Scalar, int Dim> void PDMBase<Scalar, Dim>::advanceStep(Scalar dt) { //plugin operation, begin time step PDMPluginBase<Scalar, Dim> * plugin = NULL; for(unsigned int i=0; i<this->plugins_.size(); i++) { plugin = dynamic_cast<PDMPluginBase<Scalar, Dim>*>(this->plugins_[i]); if (plugin) { plugin->onBeginTimeStep(this->time_, dt); } } if(this->step_method_ == NULL) { std::cerr<<"No step method specified, program abort;\n"; std::exit(EXIT_FAILURE); } if(this->pause_simulation_ == false) { Timer timer; timer.startTimer(); std::system("cls"); std::cout<<"**********************************************************\n"; std::cout<<"TIME STEP : "<<this->time_step_id_<<std::endl; std::cout<<"dt : "<<dt<<std::endl; std::cout<<"**********************************************************\n"; //need further consideration if (dt > 1e-8) { this->step_method_->advanceStep(dt); this->time_step_id_++; } this->time_ += dt; timer.stopTimer(); std::cout<<"**********************************************************\n"; std::cout<<"TIME STEP COST: "<<timer.getElapsedTime()<<std::endl; std::cout<<"**********************************************************\n"; Sleep(this->wait_time_per_step_); } //plugin operation, end time step for (unsigned int i=0; i<this->plugins_.size(); i++) { plugin = dynamic_cast<PDMPluginBase<Scalar, Dim>*>(this->plugins_[i]); if(plugin) { plugin->onEndTimeStep(this->time_, dt); } } } template<typename Scalar, int Dim> Scalar PDMBase<Scalar, Dim>::computeTimeStep() { // to do return this->max_dt_; } template<typename Scalar, int Dim> bool PDMBase<Scalar, Dim>::withRestartSupport()const { // to do return false; } template<typename Scalar, int Dim> void PDMBase<Scalar, Dim>::write(const std::string & file_name) { // to do } template<typename Scalar, int Dim> void PDMBase<Scalar, Dim>::read(const std::string & file_name) { // to do } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::addPlugin(DriverPluginBase<Scalar>* plugin) { if(plugin==NULL) { std::cerr<<"Warning: NULL plugin provided, operation ignored!\n"; return; } if(dynamic_cast<PDMPluginBase<Scalar, Dim> *>(plugin) == NULL) { std::cerr<<"Warning: Wrong type of plugin provided, operation ignored!\n"; return; } plugin->setDriver(this); this->plugins_.push_back(plugin); } template <typename Scalar, int Dim> Scalar PDMBase<Scalar, Dim>::gravity() const { return this->gravity_; } template <typename Scalar, int Dim> Scalar PDMBase<Scalar, Dim>::delta(unsigned int par_idx) const { if(par_idx >= this->particles_.size()) { std::cerr<<"Particle index out of range.\n"; std::exit(EXIT_FAILURE); } return this->particles_[par_idx].delta(); } template <typename Scalar, int Dim> VolumetricMesh<Scalar, Dim> * PDMBase<Scalar, Dim>::mesh() { return this->mesh_; } template <typename Scalar, int Dim> unsigned int PDMBase<Scalar, Dim>::numSimParticles() const { return this->particles_.size(); } template <typename Scalar, int Dim> Vector<Scalar, Dim> PDMBase<Scalar, Dim>::particleDisplacement(unsigned int par_idx) const { return this->particleCurrentPosition(par_idx) - this->particleRestPosition(par_idx); } template <typename Scalar, int Dim> const Vector<Scalar, Dim> & PDMBase<Scalar, Dim>::particleRestPosition(unsigned int par_idx) const { if(par_idx >= this->particles_.size()) { std::cerr<<" Particle index out of range. \n"; std::exit(EXIT_FAILURE); } return this->particles_[par_idx].position(); } template <typename Scalar, int Dim> const Vector<Scalar, Dim> & PDMBase<Scalar, Dim>::particleCurrentPosition(unsigned int par_idx) const { if(par_idx >= this->particle_cur_pos_.size()) { std::cerr<<" Particle index out of range. \n"; std::exit(EXIT_FAILURE); } return this->particle_cur_pos_[par_idx]; } template <typename Scalar, int Dim> const Vector<Scalar, Dim> & PDMBase<Scalar, Dim>::particleVelocity(unsigned int par_idx) const { if(par_idx >= this->particles_.size()) { std::cerr<<" Particle index out of range. \n"; std::exit(EXIT_FAILURE); } return this->particles_[par_idx].velocity(); } template <typename Scalar, int Dim> const Vector<Scalar, Dim> & PDMBase<Scalar, Dim>::particleForce(unsigned int par_idx)const { if(par_idx >= this->particle_force_.size()) { std::cerr<<" Particle index out of range. \n"; std::exit(EXIT_FAILURE); } return this->particle_force_[par_idx]; } template <typename Scalar, int Dim> Scalar PDMBase<Scalar, Dim>::particleMass(unsigned int par_idx) const { if(par_idx >= this->particle_force_.size()) { std::cerr<<" Particle index out of range. \n"; std::exit(EXIT_FAILURE); } return this->particles_[par_idx].mass(); } template <typename Scalar, int Dim> PDMParticle<Scalar, Dim> & PDMBase<Scalar, Dim>::particle(unsigned int par_idx) { if(par_idx >= this->particles_.size()) { std::cerr<<" Particle index out of range. \n"; std::exit(EXIT_FAILURE); } return this->particles_[par_idx]; } template <typename Scalar, int Dim> const PDMParticle<Scalar, Dim> & PDMBase<Scalar, Dim>::particle(unsigned int par_idx) const { if(par_idx >= this->particles_.size()) { std::cerr<<" Particle index out of range. \n"; std::exit(EXIT_FAILURE); } return this->particles_[par_idx]; } template <typename Scalar, int Dim> const PDMStepMethodBase<Scalar, Dim> * PDMBase<Scalar, Dim>::stepMethod() const { return this->step_method_; } template <typename Scalar, int Dim> PDMStepMethodBase<Scalar, Dim> * PDMBase<Scalar, Dim>::stepMethod() { return this->step_method_; } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::setGravity(Scalar gravity) { this->gravity_ = gravity; } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::setDelta(unsigned int par_idx, Scalar delta) { if(par_idx >= this->particles_.size()) { std::cerr<<"Particle index out of range.\n"; std::exit(EXIT_FAILURE); } this->particles_[par_idx].setDelta(delta); } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::setHomogeneousDelta(Scalar delta) { if (delta < 0) { std::cerr<<"error: delta should be greater than 0.\n"; std::exit(EXIT_FAILURE); } for (unsigned int i=0; i<this->particles_.size(); i++) { this->particles_[i].setDelta(delta); } } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::setDeltaVec(const std::vector<Scalar> & delta_vec) { if(delta_vec.size() < this->particles_.size()) { std::cerr<<"the size of delta_vec must be no less than the number of particles.\n "; std::exit(EXIT_FAILURE); } for (unsigned int i=0; i<this->particles_.size(); i++) { this->particles_[i].setDelta(delta_vec[i]); } } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::setMassViaHomogeneousDensity(Scalar density) { if (this->numSimParticles() == 0) { std::cerr<<"The driver contains no particle, please initialize from mesh!\n"; std::exit(EXIT_FAILURE); } for (unsigned int par_id = 0; par_id < this->numSimParticles(); par_id++) { PDMParticle<Scalar, Dim> & particle = this->particle(par_id); particle.setMass(density*particle.volume()); } } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::setAnisotropicMatrix(unsigned int par_idx, const SquareMatrix<Scalar, Dim> & anisotropic_matrix) { if(par_idx >= this->particles_.size()) { std::cerr<<"Particle index out of range.\n"; std::exit(EXIT_FAILURE); } this->particles_[par_idx].setAnistropicMatrix(anisotropic_matrix); } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::setHomogeneousAnisotropicMatrix(const SquareMatrix<Scalar, Dim> & anisotropic_matrix) { for (unsigned int i=0; i<this->particles_.size(); i++) this->particles_[i].setAnistropicMatrix(anisotropic_matrix); } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::setHomogeneousEpStretchLimit(Scalar ep_stretch_limit) { for (unsigned int par_id = 0; par_id < this->numSimParticles(); par_id++) { PDMParticle<Scalar, Dim> & particle = this->particle(par_id); std::list<PDMFamily<Scalar, Dim> > & family = particle.family(); for (std::list<PDMFamily<Scalar, Dim> >::iterator iter = family.begin(); iter != family.end(); iter++) iter->setEpStretchLimit(ep_stretch_limit); } } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::setHomogeneousEbStretchLimit(Scalar eb_stretch_limit) { for (unsigned int par_id = 0; par_id < this->numSimParticles(); par_id++) { PDMParticle<Scalar, Dim> & particle = this->particle(par_id); std::list<PDMFamily<Scalar, Dim> > & family = particle.family(); for (std::list<PDMFamily<Scalar, Dim> >::iterator iter = family.begin(); iter != family.end(); iter++) iter->setEbStretchLimit(eb_stretch_limit); } } template <typename Scalar, int Dim> void PDMBase<Scalar,Dim>::setParticleRestPos(unsigned int par_idx, const Vector<Scalar,Dim> & pos) { if(par_idx >= this->particles_.size()) { std::cerr<<" Particle index out of range. \n"; std::exit(EXIT_FAILURE); } this->particles_[par_idx].setPosition(pos); } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::setParticleDisplacement(unsigned int par_idx, const Vector<Scalar, Dim> & u) { if(par_idx >= this->particle_cur_pos_.size()) { std::cerr<<" Particle index out of range. \n"; std::exit(EXIT_FAILURE); } this->particle_cur_pos_[par_idx] = this->particleRestPosition(par_idx)+u; } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::addParticleDisplacement(unsigned int par_idx, const Vector<Scalar,Dim> & u) { if(par_idx >= this->particle_cur_pos_.size()) { std::cerr<<" Particle index out of range. \n"; std::exit(EXIT_FAILURE); } this->particle_cur_pos_[par_idx] += u; } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::resetParticleDisplacement() { for(unsigned int i=0; i<this->particle_cur_pos_.size(); i++) { this->particle_cur_pos_[i] = this->particleRestPosition(i); } } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::setParticleVelocity(unsigned int par_idx, const Vector<Scalar,Dim> & v) { if(par_idx >= this->particles_.size()) { std::cerr<<" Particle index out of range. \n"; std::exit(EXIT_FAILURE); } this->particles_[par_idx].setVelocity(v); } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::addParticleVelocity(unsigned int par_idx, const Vector<Scalar,Dim> & v) { if(par_idx >= this->particles_.size()) { std::cerr<<" Particle index out of range. \n"; std::exit(EXIT_FAILURE); } this->particles_[par_idx].addVelocity(v); } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::resetParticleVelocity() { for(unsigned int i=0; i<this->particles_.size(); i++) { this->particles_[i].setVelocity(Vector<Scalar,Dim>(0)); } } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::setParticleForce(unsigned int par_idx, const Vector<Scalar, Dim> & f ) { if(par_idx >= this->particle_force_.size()) { std::cerr<<" Particle index out of range. \n"; std::exit(EXIT_FAILURE); } this->particle_force_[par_idx] = f; } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::addParticleForce(unsigned int par_idx, const Vector<Scalar, Dim> & f) { if(par_idx >= this->particle_force_.size()) { std::cerr<<" Particle index out of range. \n"; std::exit(EXIT_FAILURE); } this->particle_force_[par_idx] += f; } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::resetParticleForce() { for (unsigned int i=0; i<this->particle_force_.size(); i++) { this->particle_force_[i] = Vector<Scalar,Dim>(0); } } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::setParticleCurPos(unsigned int par_idx, const Vector<Scalar, Dim> & cur_pos) { if(par_idx >= this->particle_force_.size()) { std::cerr<<" Particle index out of range. \n"; std::exit(EXIT_FAILURE); } this->particle_cur_pos_[par_idx] = cur_pos; } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::addParticleCurPos(unsigned int par_idx, const Vector<Scalar, Dim> & u) { this->addParticleDisplacement(par_idx,u); } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::resetParticleCurPos() { this->resetParticleDisplacement(); } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::setParticleMass(unsigned int par_idx, Scalar mass) { if(par_idx >= this->particle_force_.size()) { std::cerr<<" Particle index out of range. \n"; std::exit(EXIT_FAILURE); } this->particles_[par_idx].setMass(mass); } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::resetParticleMass() { for(unsigned int i=0; i<this->particles_.size(); i++) { this->particles_[i].setMass(1.0); } } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::autoSetParticlesViaMesh(const std::string & file_name, Scalar max_delta_ratio,const SquareMatrix<Scalar, Dim> & anisotropic_matrix = SquareMatrix<Scalar, Dim>::identityMatrix()) { VolumetricMesh<Scalar, Dim> * mesh = VolumetricMeshIO<Scalar, Dim>::load(file_name); Vector<Scalar, Dim> bb_min_corner(std::numeric_limits<Scalar>::max()); Vector<Scalar, Dim> bb_max_corner(std::numeric_limits<Scalar>::lowest()); for (unsigned int vert_id = 0; vert_id < mesh->vertNum(); vert_id++) { Vector<Scalar, Dim> vert_pos = mesh->vertPos(vert_id); for (unsigned int i = 0; i < Dim; i++) { bb_min_corner[i] = min(bb_min_corner[i], vert_pos[i]); bb_max_corner[i] = max(bb_max_corner[i], vert_pos[i]); } } std::cout<<"bb_min_corner: "<<bb_min_corner<<std::endl; std::cout<<"bb_max_corner: "<<bb_max_corner<<std::endl; PHYSIKA_ASSERT(mesh->elementType() == VolumetricMeshInternal::TET); Scalar min_edge_len = std::numeric_limits<Scalar>::max(); for (unsigned int ele_id = 0; ele_id < mesh->eleNum(); ele_id++) { std::vector<Vector<Scalar, Dim> > ele_pos_vec; mesh->eleVertPos(ele_id, ele_pos_vec); for (unsigned int i = 0; i < 4; i++) for (unsigned int j = i+1; j < 4; j++) { Vector<Scalar, Dim> edge = ele_pos_vec[j] - ele_pos_vec[i]; min_edge_len = min(min_edge_len, edge.norm()); } } Scalar max_delta = max_delta_ratio * min_edge_len; std::cout<<"min_edge_len: "<<min_edge_len<<std::endl; std::cout<<"max_delta: "<<max_delta<<std::endl; Vector<Scalar, Dim> start_bin_point = bb_min_corner - 0.1*min_edge_len; Vector<Scalar, Dim> end_bin_point = bb_max_corner + 0.1*min_edge_len; Scalar max_length = std::numeric_limits<Scalar>::lowest(); for (unsigned int i = 0; i < Dim; i++) max_length = max(max_length, end_bin_point[i] - start_bin_point[i]); Scalar unify_spacing = 1.1*max_delta; unsigned int unify_num = max_length/unify_spacing + 1; std::cout<<"start_bin_point: "<<start_bin_point<<std::endl; std::cout<<"end_bin_point: "<<end_bin_point<<std::endl; std::cout<<"unify_spacing: "<<unify_spacing<<std::endl; std::cout<<"unify_num: "<<unify_num<<std::endl; this->setParticlesViaMesh(mesh, max_delta, true, start_bin_point, unify_spacing, unify_num, anisotropic_matrix); } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::setParticlesViaMesh(const std::string & file_name, Scalar max_delta, bool use_hash_bin = false, const Vector<Scalar, Dim> & start_bin_point = Vector<Scalar, Dim>(0), Scalar unify_spacing = 0.0, unsigned int unify_num = 0, const SquareMatrix<Scalar, Dim> & anisotropic_matrix = SquareMatrix<Scalar, Dim>::identityMatrix()) { VolumetricMesh<Scalar, Dim> * mesh = VolumetricMeshIO<Scalar, Dim>::load(file_name); this->setParticlesViaMesh(mesh, max_delta, use_hash_bin, start_bin_point, unify_spacing, unify_num, anisotropic_matrix); } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::setParticlesViaMesh(VolumetricMesh<Scalar, Dim> * mesh, Scalar max_delta, bool use_hash_bin = false, const Vector<Scalar, Dim> & start_bin_point = Vector<Scalar, Dim>(0), Scalar unify_spacing = 0.0, unsigned int unify_num = 0, const SquareMatrix<Scalar, Dim> & anisotropic_matrix = SquareMatrix<Scalar, Dim>::identityMatrix()) { this->mesh_ = mesh; this->particles_.clear(); PDMParticle<Scalar, Dim> particle; for(unsigned int ele_id = 0; ele_id < this->mesh_->eleNum(); ele_id++) { Vector<Scalar, Dim> particle_pos(0.0); for (unsigned int ver_id = 0; ver_id < this->mesh_->eleVertNum(); ver_id++) { particle_pos += this->mesh_->eleVertPos(ele_id, ver_id); } particle_pos /= this->mesh_->eleVertNum(); particle.setPosition(particle_pos); this->particles_.push_back(particle); } this->initVolumeWithMesh(); this->setHomogeneousAnisotropicMatrix(anisotropic_matrix); std::cout<<"particle size: "<<this->particles_.size()<<std::endl; std::cout<<"particle vec is initialized!\n"; this->particle_cur_pos_.clear(); this->particle_force_.clear(); this->particle_cur_pos_.resize(this->particles_.size()); this->particle_force_.resize(this->particles_.size()); //initialize current position of each particle this->resetParticleDisplacement(); this->resetParticleForce(); // initialize max family member via max delta this->initParticleFamilyViaMaxDelta(max_delta, use_hash_bin, start_bin_point, unify_spacing, unify_num); //defaultly set homogeneous delta and init particle family member this->setHomogeneousDelta(max_delta); this->initParticleFamilyMember(); } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::autoSetParticlesAtVertexViaMesh(const std::string & file_name, Scalar max_delta_ratio,const SquareMatrix<Scalar, Dim> & anisotropic_matrix = SquareMatrix<Scalar, Dim>::identityMatrix()) { VolumetricMesh<Scalar, Dim> * mesh = VolumetricMeshIO<Scalar, Dim>::load(file_name); Vector<Scalar, Dim> bb_min_corner(std::numeric_limits<Scalar>::max()); Vector<Scalar, Dim> bb_max_corner(std::numeric_limits<Scalar>::lowest()); for (unsigned int vert_id = 0; vert_id < mesh->vertNum(); vert_id++) { Vector<Scalar, Dim> vert_pos = mesh->vertPos(vert_id); for (unsigned int i = 0; i < Dim; i++) { bb_min_corner[i] = min(bb_min_corner[i], vert_pos[i]); bb_max_corner[i] = max(bb_max_corner[i], vert_pos[i]); } } std::cout<<"bb_min_corner: "<<bb_min_corner<<std::endl; std::cout<<"bb_max_corner: "<<bb_max_corner<<std::endl; PHYSIKA_ASSERT(mesh->elementType() == VolumetricMeshInternal::TET); Scalar min_edge_len = std::numeric_limits<Scalar>::max(); for (unsigned int ele_id = 0; ele_id < mesh->eleNum(); ele_id++) { std::vector<Vector<Scalar, Dim> > ele_pos_vec; mesh->eleVertPos(ele_id, ele_pos_vec); for (unsigned int i = 0; i < 4; i++) for (unsigned int j = i+1; j < 4; j++) { Vector<Scalar, Dim> edge = ele_pos_vec[j] - ele_pos_vec[i]; min_edge_len = min(min_edge_len, edge.norm()); } } Scalar max_delta = max_delta_ratio * min_edge_len; std::cout<<"min_edge_len: "<<min_edge_len<<std::endl; std::cout<<"max_delta: "<<max_delta<<std::endl; Vector<Scalar, Dim> start_bin_point = bb_min_corner - 0.1*min_edge_len; Vector<Scalar, Dim> end_bin_point = bb_max_corner + 0.1*min_edge_len; Scalar max_length = std::numeric_limits<Scalar>::lowest(); for (unsigned int i = 0; i < Dim; i++) max_length = max(max_length, end_bin_point[i] - start_bin_point[i]); Scalar unify_spacing = 1.1*max_delta; unsigned int unify_num = max_length/unify_spacing + 1; std::cout<<"start_bin_point: "<<start_bin_point<<std::endl; std::cout<<"end_bin_point: "<<end_bin_point<<std::endl; std::cout<<"unify_spacing: "<<unify_spacing<<std::endl; std::cout<<"unify_num: "<<unify_num<<std::endl; this->setParticlesAtVertexViaMesh(mesh, max_delta, true, start_bin_point, unify_spacing, unify_num, anisotropic_matrix); } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::setParticlesAtVertexViaMesh(const std::string & file_name, Scalar max_delta, bool use_hash_bin = false, const Vector<Scalar, Dim> & start_bin_point = Vector<Scalar, Dim>(0), Scalar unify_spacing = 0.0, unsigned int unify_num = 0, const SquareMatrix<Scalar, Dim> & anisotropic_matrix = SquareMatrix<Scalar, Dim>::identityMatrix()) { VolumetricMesh<Scalar, Dim> * mesh = VolumetricMeshIO<Scalar, Dim>::load(file_name); this->setParticlesAtVertexViaMesh(mesh, max_delta, use_hash_bin, start_bin_point, unify_spacing, unify_num, anisotropic_matrix); } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::setParticlesAtVertexViaMesh(VolumetricMesh<Scalar, Dim> * mesh, Scalar max_delta, bool use_hash_bin = false, const Vector<Scalar, Dim> & start_bin_point = Vector<Scalar, Dim>(0), Scalar unify_spacing = 0.0, unsigned int unify_num = 0, const SquareMatrix<Scalar, Dim> & anisotropic_matrix = SquareMatrix<Scalar, Dim>::identityMatrix()) { this->mesh_ = mesh; //init particles this->particles_.clear(); PDMParticle<Scalar, Dim> particle; for (unsigned int ver_id = 0; ver_id < this->mesh_->vertNum(); ver_id++) { Vector<Scalar, Dim> particle_pos = this->mesh_->vertPos(ver_id); particle.setPosition(particle_pos); this->particles_.push_back(particle); } //reset volume for (unsigned int par_id = 0; par_id < this->particles_.size(); par_id++) this->particles_[par_id].setVolume(0.0); //init volume for (unsigned int ele_id = 0; ele_id < this->mesh_->eleNum(); ele_id++) { std::vector<unsigned int> ele_vertex_vec; this->mesh_->eleVertIndex(ele_id, ele_vertex_vec); Scalar ave_vol = this->mesh_->eleVolume(ele_id)/ele_vertex_vec.size(); for (unsigned int ver_id = 0; ver_id < ele_vertex_vec.size(); ver_id++) { unsigned int par_id = ele_vertex_vec[ver_id]; this->particles_[par_id].addVolume(ave_vol); } } this->setHomogeneousAnisotropicMatrix(anisotropic_matrix); std::cout<<"particle size: "<<this->particles_.size()<<std::endl; std::cout<<"particle vec is initialized!\n"; this->particle_cur_pos_.clear(); this->particle_force_.clear(); this->particle_cur_pos_.resize(this->particles_.size()); this->particle_force_.resize(this->particles_.size()); //initialize current position of each particle this->resetParticleDisplacement(); this->resetParticleForce(); // initialize max family member via max delta this->initParticleFamilyViaMaxDelta(max_delta, use_hash_bin, start_bin_point, unify_spacing, unify_num); //defaultly set homogeneous delta and init particle family member this->setHomogeneousDelta(max_delta); this->initParticleFamilyMember(); } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::initParticleFamilyMember() { this->updateParticleFamilyMember(); // initial size of family need to be set for each particle for (unsigned int i=0; i<this->particles_.size(); i++) { PDMParticle<Scalar, Dim> & particle = this->particles_[i]; unsigned int init_num = particle.validFamilySize(); particle.setInitFamilySize(init_num); } } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::updateParticleFamilyMember() { for (unsigned int i=0; i<this->particles_.size(); i++) { this->particles_[i].updateFamilyMember(); } } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::setStepMethod(PDMStepMethodBase<Scalar, Dim> * step_method) { if(step_method == NULL) { std::cerr<<"NULL step method\n"; std::exit(EXIT_FAILURE); } this->step_method_ = step_method; this->step_method_->setPDMDriver(this); } template <typename Scalar, int Dim> unsigned int PDMBase<Scalar, Dim>::timeStepId() const { return this->time_step_id_; } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::pauseSimulation() { this->pause_simulation_ = true; } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::forwardSimulation() { this->pause_simulation_ = false; } template <typename Scalar, int Dim> bool PDMBase<Scalar, Dim>::isSimulationPause() const { return this->pause_simulation_; } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::setWaitTimePerStep(unsigned int wait_time_per_step) { this->wait_time_per_step_ = wait_time_per_step; } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::initParticleFamilyViaMaxDelta(Scalar max_delta, bool use_hash_bin, const Vector<Scalar, Dim> & start_bin_point, Scalar unify_spacing, unsigned int unify_num) { // initialize the family of each material points if (use_hash_bin) { PDMCollisionMethodGrid<Scalar,Dim> collision_method; collision_method.setUnifySpacing(unify_spacing); collision_method.setUnifyBinNum(unify_num); collision_method.setBinStartPoint(start_bin_point); collision_method.setDriver(this); collision_method.initParticleFamily(max_delta); } else { for(unsigned int i =0; i<this->particles_.size(); i++) { Scalar delta_squared = max_delta*max_delta; for(unsigned int j= 0; j<this->particles_.size(); j++) { // if(|X_i - X_j| <= delta) if ( (i != j) &&(this->particleRestPosition(i)-this->particleRestPosition(j)).normSquared() <= delta_squared) { Vector<Scalar, Dim> rest_relative_pos = this->particleRestPosition(j) - this->particleRestPosition(i); Vector<Scalar, Dim> cur_relative_pos = this->particleCurrentPosition(j) - this->particleCurrentPosition(i); const SquareMatrix<Scalar, Dim> anisotropic_matrix = this->particles_[i].anisotropicMatrix(); PDMFamily<Scalar, Dim> family(j, rest_relative_pos, anisotropic_matrix); family.setCurRelativePos(cur_relative_pos); this->particles_[i].addFamily(family); } } if (i%10000 == 0) std::cout<<"particle: "<<i<<std::endl; } } //set particle direct neighbor this->setParticleDirectNeighbor(); } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::initVolumeWithMesh() { PHYSIKA_ASSERT(this->particles_.size() == this->mesh_->eleNum()); // set particle volume for (unsigned int i=0; i<this->mesh_->eleNum(); i++) { this->particles_[i].setVolume(this->mesh_->eleVolume(i)); } } template <typename Scalar, int Dim> void PDMBase<Scalar, Dim>::setParticleDirectNeighbor() { std::cout<<"set particle direct neighbor......\n"; #pragma omp parallel for for (long long par_id = 0; par_id < this->particles_.size(); par_id++) { std::list<PDMFamily<Scalar, Dim> > & family = this->particles_[par_id].family(); std::list<PDMFamily<Scalar, Dim> >::iterator end_iter = family.end(); for (std::list<PDMFamily<Scalar, Dim> >::iterator iter = family.begin(); iter != end_iter; iter++) { unsigned int fir_ele_id = par_id; unsigned int sec_ele_id = iter->id(); std::vector<unsigned int> fir_ele_vert; std::vector<unsigned int> sec_ele_vert; this->mesh_->eleVertIndex(fir_ele_id, fir_ele_vert); this->mesh_->eleVertIndex(sec_ele_id, sec_ele_vert); PHYSIKA_ASSERT(fir_ele_vert.size() == sec_ele_vert.size()); PHYSIKA_ASSERT(fir_ele_vert.size()==3 || fir_ele_vert.size()==4); unsigned int share_vertex_num = 0; for (unsigned int i=0; i<fir_ele_vert.size(); i++) for (unsigned int j=0; j<sec_ele_vert.size(); j++) { if (fir_ele_vert[i] == sec_ele_vert[j]) share_vertex_num++; } PHYSIKA_ASSERT(share_vertex_num < fir_ele_vert.size()); if (share_vertex_num == fir_ele_vert.size()-1) this->particles_[fir_ele_id].addDirectNeighbor(sec_ele_id); } } } //explicit instantiations template class PDMBase<float,2>; template class PDMBase<float,3>; template class PDMBase<double,2>; template class PDMBase<double,3>; }// end of namespace Physika
gpl-2.0
planetguy32/Utils
src/main/java/me/planetguy/lib/asyncworld/AsyncBlockUpdate.java
3374
package me.planetguy.lib.asyncworld; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import net.minecraft.world.World; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.gameevent.TickEvent; import cpw.mods.fml.common.gameevent.TickEvent.Phase; //TODO make it actually work public class AsyncBlockUpdate { public static class TickEntry implements Comparable<TickEntry>, Callable{ private final int timeInTicks; private final World w; private final int x; private final int y; private final int z; @Override public int compareTo(TickEntry a) { return timeInTicks-a.timeInTicks; } public TickEntry(World w, int x, int y, int z, int timeFromNow) { this.timeInTicks=timeFromNow+tick; this.w=w; this.x=x; this.y=y; this.z=z; } @Override public Object call() throws Exception { try { //we must lock our chunk here since we didn't sort by chunks in synchronized(AsyncWorld.getChunk(w, x, z)) { ((IAsyncTickable)AsyncWorld.getBlock(w, x, y, z)).onAsyncLocalUpdate(w, x, y, z); } }catch(ClassCastException ignored) { // try/catch is probably faster than checked cast; we assume that no one improperly posts updates } return null; } } private static ExecutorService theThreadPool=Executors.newCachedThreadPool(); //monotonically increases forever, but not valid across games or sessions - persist ticks in relative formats private static int tick=0; private static Map<World, Queue<TickEntry>[]> globalScheduledTicks=new HashMap<World, Queue<TickEntry>[]>(); public static void onTick(final TickEvent.WorldTickEvent e) { if(e.phase==Phase.START) { Queue<TickEntry>[] entries=getOrCreateQueue(e.world); for(Queue<TickEntry> scheduledTicks:entries) { //go in serial over these //this provides the local locking guaranteed in IAsyncTickable List<Callable<Void>> tasks=new ArrayList<Callable<Void>>(); TickEntry te=scheduledTicks.peek(); while(te.timeInTicks<=tick) { tasks.add(scheduledTicks.remove()); te=scheduledTicks.peek(); } try { theThreadPool.invokeAll(tasks); } catch (InterruptedException e1) { e1.printStackTrace(); } } } else { //not Phase.START -> Phase.END tick++; } } private static Queue<TickEntry>[] getOrCreateQueue(World w){ Queue<TickEntry>[] entries=globalScheduledTicks.get(w); if(entries==null) { //first async tick scheduled entries=new Queue[9]; for(int i=0; i<entries.length; i++) { entries[i]=new ArrayDeque<TickEntry>(); } globalScheduledTicks.put(w, entries); } return entries; } /* * When scheduled, ticks are placed in one of 9 buckets, such that ticks within the same bucket are either in the same * chunk as, or more than 16 blocks from, any other tick in that bucket. */ public static int getRegionFor(int x, int z) { return (x>>4) % 3 + ((z>>4) % 3)*3; } public static void scheduleAsyncTick(World w, int x, int y, int z, int delay) { int regionToScheduleIn=(x>>4) % 3 + 3*((z>>4) % 3); getOrCreateQueue(w)[regionToScheduleIn].add(new TickEntry(w,x,y,z,delay)); } }
gpl-2.0
maman/sar
src/lib/SAR/helpers/Authentication.php
2421
<?php /** * SAR Authenticate Middleware * * This file contains the authentication middleware for Slim Framework. * this middleware ensures that the client has logged in and the required * previlleges to access the requested resources. * * PHP version 5.4 * * LICENSE: This source file is subject to version 2 of the GNU General Public * License that is avalaible in the LICENSE file on the project root directory. * If you did not receive a copy of the LICENSE file, please send a note to * [email protected] so I can mail you a copy immidiately. * * @author Achmad Mahardi <[email protected]> * @copyright 2014 Achmad Mahardi * @license GNU General Public License v2 * @link https://github.com/maman/sar */ namespace SAR\helpers; use Slim\Middleware; class Authentication extends Middleware { protected $settings = array( 'login.url' => '/', 'realm' => 'Protected Area', ); public function __construct(array $config = array()) { $this->config = array_merge($this->settings, $config); } public function call() { $req = $this->app->request(); $this->formAuth($req); } public function formAuth($req) { $app = $this->app; $config = $this->config; $this->app->hook('slim.before.dispatch', function () use ($app, $req, $config) { // $secured_urls = isset($config['security.urls']) && is_array($config['security.urls']) ? $config['security.urls'] : array(); $secured_urls = $config['security.urls']; foreach ($secured_urls as $url) { $patternAsRegex = $url['path']; if (substr($url['path'], -1) === '/') { $patternAsRegex = $patternAsRegex . '?'; } $patternAsRegex = '@^' . $patternAsRegex . '$@'; if (preg_match($patternAsRegex, $req->getPathInfo())) { if (!isset($_SESSION['nip']) && !isset($_SESSION['username']) && !isset($_SESSION['role']) && !isset($_SESSION['matkul'])) { if ($req->getPath() !== $config['login.url']) { $app->flash('error', 'Login Required'); $app->redirect($config['login.url']); } } } } }); $this->next->call(); } }
gpl-2.0
jnuc093/4_okdiet
wp-content/plugins/w3-total-cache/configs/0.9.3-ConfigKeys.php
51260
<?php /* * Descriptors of configuration keys * for config */ $keys = array( 'cluster.messagebus.debug' => array( 'type' => 'boolean', 'default' => false ), 'cluster.messagebus.enabled' => array( 'type' => 'boolean', 'default' => false ), 'cluster.messagebus.sns.region' => array( 'type' => 'string', 'default' => '' ), 'cluster.messagebus.sns.api_key' => array( 'type' => 'string', 'default' => '' ), 'cluster.messagebus.sns.api_secret' => array( 'type' => 'string', 'default' => '' ), 'cluster.messagebus.sns.topic_arn' => array( 'type' => 'string', 'default' => '' ), 'dbcache.debug' => array( 'type' => 'boolean', 'default' => false ), 'dbcache.enabled' => array( 'type' => 'boolean', 'default' => false ), 'dbcache.engine' => array( 'type' => 'string', 'default' => 'file' ), 'dbcache.file.gc' => array( 'type' => 'integer', 'default' => 3600 ), 'dbcache.file.locking' => array( 'type' => 'boolean', 'default' => false ), 'dbcache.lifetime' => array( 'type' => 'integer', 'default' => 180 ), 'dbcache.memcached.persistant' => array( 'type' => 'boolean', 'default' => true ), 'dbcache.memcached.servers' => array( 'type' => 'array', 'default' => array( '127.0.0.1:11211' ) ), 'dbcache.reject.cookie' => array( 'type' => 'array', 'default' => array() ), 'dbcache.reject.logged' => array( 'type' => 'boolean', 'default' => true ), 'dbcache.reject.sql' => array( 'type' => 'array', 'default' => array( 'gdsr_', 'wp_rg_' ) ), 'dbcache.reject.uri' => array( 'type' => 'array', 'default' => array() ), 'dbcache.reject.words' => array( 'type' => 'array', 'default' => array( '^\s*insert\b', '^\s*delete\b', '^\s*update\b', '^\s*replace\b', '^\s*create\b', '^\s*alter\b', '^\s*show\b', '^\s*set\b', '\bautoload\s+=\s+\'yes\'', '\bsql_calc_found_rows\b', '\bfound_rows\(\)', '\bw3tc_request_data\b' ) ), 'objectcache.enabled' => array( 'type' => 'boolean', 'default' => false ), 'objectcache.debug' => array( 'type' => 'boolean', 'default' => false ), 'objectcache.engine' => array( 'type' => 'string', 'default' => 'file' ), 'objectcache.file.gc' => array( 'type' => 'integer', 'default' => 3600 ), 'objectcache.file.locking' => array( 'type' => 'boolean', 'default' => false ), 'objectcache.memcached.servers' => array( 'type' => 'array', 'default' => array( '127.0.0.1:11211' ) ), 'objectcache.memcached.persistant' => array( 'type' => 'boolean', 'default' => true ), 'objectcache.groups.global' => array( 'type' => 'array', 'default' => array( 'users', 'userlogins', 'usermeta', 'user_meta', 'site-transient', 'site-options', 'site-lookup', 'blog-lookup', 'blog-details', 'rss', 'global-posts' ) ), 'objectcache.groups.nonpersistent' => array( 'type' => 'array', 'default' => array( 'comment', 'counts', 'plugins' ) ), 'objectcache.lifetime' => array( 'type' => 'integer', 'default' => 180 ), 'objectcache.purge.all' => array( 'type' => 'boolean', 'default' => false ), 'fragmentcache.enabled' => array( 'type' => 'boolean', 'default' => false ), 'fragmentcache.debug' => array( 'type' => 'boolean', 'default' => false ), 'fragmentcache.engine' => array( 'type' => 'string', 'default' => 'file' ), 'fragmentcache.file.gc' => array( 'type' => 'integer', 'default' => 3600 ), 'fragmentcache.file.locking' => array( 'type' => 'boolean', 'default' => false ), 'fragmentcache.memcached.servers' => array( 'type' => 'array', 'default' => array( '127.0.0.1:11211' ) ), 'fragmentcache.memcached.persistant' => array( 'type' => 'boolean', 'default' => true ), 'fragmentcache.lifetime' => array( 'type' => 'integer', 'default' => 180 ), 'fragmentcache.groups' => array( 'type' => 'array', 'default' => array() ), 'pgcache.enabled' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.comment_cookie_ttl' => array( 'type' => 'integer', 'default' => 1800 ), 'pgcache.debug' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.engine' => array( 'type' => 'string', 'default' => 'file_generic' ), 'pgcache.file.gc' => array( 'type' => 'integer', 'default' => 3600 ), 'pgcache.file.nfs' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.file.locking' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.lifetime' => array( 'type' => 'integer', 'default' => 3600 ), 'pgcache.memcached.servers' => array( 'type' => 'array', 'default' => array( '127.0.0.1:11211' ) ), 'pgcache.memcached.persistant' => array( 'type' => 'boolean', 'default' => true ), 'pgcache.check.domain' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.cache.query' => array( 'type' => 'boolean', 'default' => true ), 'pgcache.cache.home' => array( 'type' => 'boolean', 'default' => true ), 'pgcache.cache.feed' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.cache.nginx_handle_xml' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.cache.ssl' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.cache.404' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.cache.flush' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.cache.headers' => array( 'type' => 'array', 'default' => array( 'Last-Modified', 'Content-Type', 'X-Pingback', 'P3P' ) ), 'pgcache.compatibility' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.remove_charset' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.accept.uri' => array( 'type' => 'array', 'default' => array( 'sitemap(_index)?\.xml(\.gz)?', '[a-z0-9_\-]+-sitemap([0-9]+)?\.xml(\.gz)?' ) ), 'pgcache.accept.files' => array( 'type' => 'array', 'default' => array( 'wp-comments-popup.php', 'wp-links-opml.php', 'wp-locations.php' ) ), 'pgcache.accept.qs' => array( 'type' => 'array', 'default' => array() ), 'pgcache.reject.front_page' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.reject.logged' => array( 'type' => 'boolean', 'default' => true ), 'pgcache.reject.logged_roles' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.reject.roles' => array( 'type' => 'array', 'default' => array() ), 'pgcache.reject.uri' => array( 'type' => 'array', 'default' => array( 'wp-.*\.php', 'index\.php' ) ), 'pgcache.reject.ua' => array( 'type' => 'array', 'default' => array() ), 'pgcache.reject.cookie' => array( 'type' => 'array', 'default' => array('wptouch_switch_toggle') ), 'pgcache.reject.request_head' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.purge.front_page' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.purge.home' => array( 'type' => 'boolean', 'default' => true ), 'pgcache.purge.post' => array( 'type' => 'boolean', 'default' => true ), 'pgcache.purge.comments' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.purge.author' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.purge.terms' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.purge.archive.daily' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.purge.archive.monthly' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.purge.archive.yearly' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.purge.feed.blog' => array( 'type' => 'boolean', 'default' => true ), 'pgcache.purge.feed.comments' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.purge.feed.author' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.purge.feed.terms' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.purge.feed.types' => array( 'type' => 'array', 'default' => array( 'rss2' ) ), 'pgcache.purge.postpages_limit' => array( 'type' => 'integer', 'default' => 10 ), 'pgcache.purge.pages' => array( 'type' => 'array', 'default' => array() ), 'pgcache.purge.sitemap_regex' => array( 'type' => 'string', 'default' => '([a-z0-9_\-]*?)sitemap([a-z0-9_\-]*)?\.xml' ), 'pgcache.prime.enabled' => array( 'type' => 'boolean', 'default' => false ), 'pgcache.prime.interval' => array( 'type' => 'integer', 'default' => 900 ), 'pgcache.prime.limit' => array( 'type' => 'integer', 'default' => 10 ), 'pgcache.prime.sitemap' => array( 'type' => 'string', 'default' => '' ), 'pgcache.prime.post.enabled' => array( 'type' => 'boolean', 'default' => false ), 'minify.enabled' => array( 'type' => 'boolean', 'default' => false ), 'minify.auto' => array( 'type' => 'boolean', 'default' => true ), 'minify.debug' => array( 'type' => 'boolean', 'default' => false ), 'minify.engine' => array( 'type' => 'string', 'default' => 'file' ), 'minify.file.gc' => array( 'type' => 'integer', 'default' => 86400 ), 'minify.file.nfs' => array( 'type' => 'boolean', 'default' => false ), 'minify.file.locking' => array( 'type' => 'boolean', 'default' => false ), 'minify.memcached.servers' => array( 'type' => 'array', 'default' => array( '127.0.0.1:11211' ) ), 'minify.memcached.persistant' => array( 'type' => 'boolean', 'default' => true ), 'minify.rewrite' => array( 'type' => 'boolean', 'default' => true ), 'minify.options' => array( 'type' => 'array', 'default' => array() ), 'minify.symlinks' => array( 'type' => 'array', 'default' => array() ), 'minify.lifetime' => array( 'type' => 'integer', 'default' => 86400 ), 'minify.upload' => array( 'type' => 'boolean', 'default' => true ), 'minify.html.enable' => array( 'type' => 'boolean', 'default' => false ), 'minify.html.engine' => array( 'type' => 'string', 'default' => 'html' ), 'minify.html.reject.feed' => array( 'type' => 'boolean', 'default' => false ), 'minify.html.inline.css' => array( 'type' => 'boolean', 'default' => false ), 'minify.html.inline.js' => array( 'type' => 'boolean', 'default' => false ), 'minify.html.strip.crlf' => array( 'type' => 'boolean', 'default' => false ), 'minify.html.comments.ignore' => array( 'type' => 'array', 'default' => array( 'google_ad_', 'RSPEAK_' ) ), 'minify.css.enable' => array( 'type' => 'boolean', 'default' => true ), 'minify.css.engine' => array( 'type' => 'string', 'default' => 'css' ), 'minify.css.combine' => array( 'type' => 'boolean', 'default' => false ), 'minify.css.strip.comments' => array( 'type' => 'boolean', 'default' => false ), 'minify.css.strip.crlf' => array( 'type' => 'boolean', 'default' => false ), 'minify.css.imports' => array( 'type' => 'string', 'default' => '' ), 'minify.css.groups' => array( 'type' => 'array', 'default' => array() ), 'minify.js.enable' => array( 'type' => 'boolean', 'default' => true ), 'minify.js.engine' => array( 'type' => 'string', 'default' => 'js' ), 'minify.js.combine.header' => array( 'type' => 'boolean', 'default' => false ), 'minify.js.header.embed_type' => array( 'type' => 'string', 'default' => 'blocking' ), 'minify.js.combine.body' => array( 'type' => 'boolean', 'default' => false ), 'minify.js.body.embed_type' => array( 'type' => 'string', 'default' => 'blocking' ), 'minify.js.combine.footer' => array( 'type' => 'boolean', 'default' => false ), 'minify.js.footer.embed_type' => array( 'type' => 'string', 'default' => 'blocking' ), 'minify.js.strip.comments' => array( 'type' => 'boolean', 'default' => false ), 'minify.js.strip.crlf' => array( 'type' => 'boolean', 'default' => false ), 'minify.js.groups' => array( 'type' => 'array', 'default' => array() ), 'minify.yuijs.path.java' => array( 'type' => 'string', 'default' => 'java' ), 'minify.yuijs.path.jar' => array( 'type' => 'string', 'default' => 'yuicompressor.jar' ), 'minify.yuijs.options.line-break' => array( 'type' => 'integer', 'default' => 5000 ), 'minify.yuijs.options.nomunge' => array( 'type' => 'boolean', 'default' => false ), 'minify.yuijs.options.preserve-semi' => array( 'type' => 'boolean', 'default' => false ), 'minify.yuijs.options.disable-optimizations' => array( 'type' => 'boolean', 'default' => false ), 'minify.yuicss.path.java' => array( 'type' => 'string', 'default' => 'java' ), 'minify.yuicss.path.jar' => array( 'type' => 'string', 'default' => 'yuicompressor.jar' ), 'minify.yuicss.options.line-break' => array( 'type' => 'integer', 'default' => 5000 ), 'minify.ccjs.path.java' => array( 'type' => 'string', 'default' => 'java' ), 'minify.ccjs.path.jar' => array( 'type' => 'string', 'default' => 'compiler.jar' ), 'minify.ccjs.options.compilation_level' => array( 'type' => 'string', 'default' => 'SIMPLE_OPTIMIZATIONS' ), 'minify.ccjs.options.formatting' => array( 'type' => 'string', 'default' => '' ), 'minify.csstidy.options.remove_bslash' => array( 'type' => 'boolean', 'default' => true ), 'minify.csstidy.options.compress_colors' => array( 'type' => 'boolean', 'default' => true ), 'minify.csstidy.options.compress_font-weight' => array( 'type' => 'boolean', 'default' => true ), 'minify.csstidy.options.lowercase_s' => array( 'type' => 'boolean', 'default' => false ), 'minify.csstidy.options.optimise_shorthands' => array( 'type' => 'integer', 'default' => 1 ), 'minify.csstidy.options.remove_last_;' => array( 'type' => 'boolean', 'default' => false ), 'minify.csstidy.options.case_properties' => array( 'type' => 'integer', 'default' => 1 ), 'minify.csstidy.options.sort_properties' => array( 'type' => 'boolean', 'default' => false ), 'minify.csstidy.options.sort_selectors' => array( 'type' => 'boolean', 'default' => false ), 'minify.csstidy.options.merge_selectors' => array( 'type' => 'integer', 'default' => 2 ), 'minify.csstidy.options.discard_invalid_properties' => array( 'type' => 'boolean', 'default' => false ), 'minify.csstidy.options.css_level' => array( 'type' => 'string', 'default' => 'CSS2.1' ), 'minify.csstidy.options.preserve_css' => array( 'type' => 'boolean', 'default' => false ), 'minify.csstidy.options.timestamp' => array( 'type' => 'boolean', 'default' => false ), 'minify.csstidy.options.template' => array( 'type' => 'string', 'default' => 'default' ), 'minify.htmltidy.options.clean' => array( 'type' => 'boolean', 'default' => false ), 'minify.htmltidy.options.hide-comments' => array( 'type' => 'boolean', 'default' => true ), 'minify.htmltidy.options.wrap' => array( 'type' => 'integer', 'default' => 0 ), 'minify.reject.logged' => array( 'type' => 'boolean', 'default' => false ), 'minify.reject.ua' => array( 'type' => 'array', 'default' => array() ), 'minify.reject.uri' => array( 'type' => 'array', 'default' => array() ), 'minify.reject.files.js' => array( 'type' => 'array', 'default' => array() ), 'minify.reject.files.css' => array( 'type' => 'array', 'default' => array() ), 'minify.cache.files' => array( 'type' => 'array', 'default' => array('https://ajax.useso.com') ), 'cdn.enabled' => array( 'type' => 'boolean', 'default' => false ), 'cdn.debug' => array( 'type' => 'boolean', 'default' => false ), 'cdn.engine' => array( 'type' => 'string', 'default' => 'maxcdn' ), 'cdn.uploads.enable' => array( 'type' => 'boolean', 'default' => true ), 'cdn.includes.enable' => array( 'type' => 'boolean', 'default' => true ), 'cdn.includes.files' => array( 'type' => 'string', 'default' => '*.css;*.js;*.gif;*.png;*.jpg;*.xml' ), 'cdn.theme.enable' => array( 'type' => 'boolean', 'default' => true ), 'cdn.theme.files' => array( 'type' => 'string', 'default' => '*.css;*.js;*.gif;*.png;*.jpg;*.ico;*.ttf;*.otf,*.woff' ), 'cdn.minify.enable' => array( 'type' => 'boolean', 'default' => true ), 'cdn.custom.enable' => array( 'type' => 'boolean', 'default' => true ), 'cdn.custom.files' => array( 'type' => 'array', 'default' => array( 'favicon.ico', '{wp_content_dir}/gallery/*', '{wp_content_dir}/uploads/avatars/*', '{plugins_dir}/wordpress-seo/css/xml-sitemap.xsl', '{plugins_dir}/wp-minify/min*', '{plugins_dir}/*.js', '{plugins_dir}/*.css', '{plugins_dir}/*.gif', '{plugins_dir}/*.jpg', '{plugins_dir}/*.png', ) ), 'cdn.import.external' => array( 'type' => 'boolean', 'default' => false ), 'cdn.import.files' => array( 'type' => 'string', 'default' => false ), 'cdn.queue.interval' => array( 'type' => 'integer', 'default' => 900 ), 'cdn.queue.limit' => array( 'type' => 'integer', 'default' => 25 ), 'cdn.force.rewrite' => array( 'type' => 'boolean', 'default' => false ), 'cdn.autoupload.enabled' => array( 'type' => 'boolean', 'default' => false ), 'cdn.autoupload.interval' => array( 'type' => 'integer', 'default' => 3600 ), 'cdn.canonical_header' => array( 'type' => 'boolean', 'default' => false ), 'cdn.ftp.host' => array( 'type' => 'string', 'default' => '' ), 'cdn.ftp.user' => array( 'type' => 'string', 'default' => '' ), 'cdn.ftp.pass' => array( 'type' => 'string', 'default' => '' ), 'cdn.ftp.path' => array( 'type' => 'string', 'default' => '' ), 'cdn.ftp.pasv' => array( 'type' => 'boolean', 'default' => false ), 'cdn.ftp.domain' => array( 'type' => 'array', 'default' => array() ), 'cdn.ftp.ssl' => array( 'type' => 'string', 'default' => 'auto' ), 'cdn.s3.key' => array( 'type' => 'string', 'default' => '' ), 'cdn.s3.secret' => array( 'type' => 'string', 'default' => '' ), 'cdn.s3.bucket' => array( 'type' => 'string', 'default' => '' ), 'cdn.s3.cname' => array( 'type' => 'array', 'default' => array() ), 'cdn.s3.ssl' => array( 'type' => 'string', 'default' => 'auto' ), 'cdn.cf.key' => array( 'type' => 'string', 'default' => '' ), 'cdn.cf.secret' => array( 'type' => 'string', 'default' => '' ), 'cdn.cf.bucket' => array( 'type' => 'string', 'default' => '' ), 'cdn.cf.id' => array( 'type' => 'string', 'default' => '' ), 'cdn.cf.cname' => array( 'type' => 'array', 'default' => array() ), 'cdn.cf.ssl' => array( 'type' => 'string', 'default' => 'auto' ), 'cdn.cf2.key' => array( 'type' => 'string', 'default' => '' ), 'cdn.cf2.secret' => array( 'type' => 'string', 'default' => '' ), 'cdn.cf2.id' => array( 'type' => 'string', 'default' => '' ), 'cdn.cf2.cname' => array( 'type' => 'array', 'default' => array() ), 'cdn.cf2.ssl' => array( 'type' => 'string', 'default' => '' ), 'cdn.rscf.user' => array( 'type' => 'string', 'default' => '' ), 'cdn.rscf.key' => array( 'type' => 'string', 'default' => '' ), 'cdn.rscf.location' => array( 'type' => 'string', 'default' => 'us' ), 'cdn.rscf.container' => array( 'type' => 'string', 'default' => '' ), 'cdn.rscf.cname' => array( 'type' => 'array', 'default' => array() ), 'cdn.rscf.ssl' => array( 'type' => 'string', 'default' => 'auto' ), 'cdn.azure.user' => array( 'type' => 'string', 'default' => '' ), 'cdn.azure.key' => array( 'type' => 'string', 'default' => '' ), 'cdn.azure.container' => array( 'type' => 'string', 'default' => '' ), 'cdn.azure.cname' => array( 'type' => 'array', 'default' => array() ), 'cdn.azure.ssl' => array( 'type' => 'string', 'default' => 'auto' ), 'cdn.mirror.domain' => array( 'type' => 'array', 'default' => array() ), 'cdn.mirror.ssl' => array( 'type' => 'string', 'default' => 'auto' ), 'cdn.netdna.alias' => array( 'type' => 'string', 'default' => '' ), 'cdn.netdna.consumerkey' => array( 'type' => 'string', 'default' => '' ), 'cdn.netdna.consumersecret' => array( 'type' => 'string', 'default' => '' ), 'cdn.netdna.authorization_key' => array( 'type' => 'string', 'default' => '' ), 'cdn.netdna.domain' => array( 'type' => 'array', 'default' => array() ), 'cdn.netdna.ssl' => array( 'type' => 'string', 'default' => 'auto' ), 'cdn.netdna.zone_id' => array( 'type' => 'integer', 'default' => 0 ), 'cdn.maxcdn.authorization_key' => array( 'type' => 'string', 'default' => '' ), 'cdn.maxcdn.domain' => array( 'type' => 'array', 'default' => array() ), 'cdn.maxcdn.ssl' => array( 'type' => 'string', 'default' => 'auto' ), 'cdn.maxcdn.zone_id' => array( 'type' => 'integer', 'default' => 0 ), 'cdn.cotendo.username' => array( 'type' => 'string', 'default' => '' ), 'cdn.cotendo.password' => array( 'type' => 'string', 'default' => '' ), 'cdn.cotendo.zones' => array( 'type' => 'array', 'default' => array() ), 'cdn.cotendo.domain' => array( 'type' => 'array', 'default' => array() ), 'cdn.cotendo.ssl' => array( 'type' => 'string', 'default' => 'auto' ), 'cdn.akamai.username' => array( 'type' => 'string', 'default' => '' ), 'cdn.akamai.password' => array( 'type' => 'string', 'default' => '' ), 'cdn.akamai.email_notification' => array( 'type' => 'array', 'default' => array() ), 'cdn.akamai.action' => array( 'type' => 'string', 'default' => 'invalidate' ), 'cdn.akamai.zone' => array( 'type' => 'string', 'default' => 'production' ), 'cdn.akamai.domain' => array( 'type' => 'array', 'default' => array() ), 'cdn.akamai.ssl' => array( 'type' => 'string', 'default' => 'auto' ), 'cdn.edgecast.account' => array( 'type' => 'string', 'default' => '' ), 'cdn.edgecast.token' => array( 'type' => 'string', 'default' => '' ), 'cdn.edgecast.domain' => array( 'type' => 'array', 'default' => array() ), 'cdn.edgecast.ssl' => array( 'type' => 'string', 'default' => 'auto' ), 'cdn.att.account' => array( 'type' => 'string', 'default' => '' ), 'cdn.att.token' => array( 'type' => 'string', 'default' => '' ), 'cdn.att.domain' => array( 'type' => 'array', 'default' => array() ), 'cdn.att.ssl' => array( 'type' => 'string', 'default' => 'auto' ), 'cdn.reject.admins' => array( 'type' => 'boolean', 'default' => false ), 'cdn.reject.logged_roles' => array( 'type' => 'boolean', 'default' => false ), 'cdn.reject.roles' => array( 'type' => 'array', 'default' => array() ), 'cdn.reject.ua' => array( 'type' => 'array', 'default' => array() ), 'cdn.reject.uri' => array( 'type' => 'array', 'default' => array() ), 'cdn.reject.files' => array( 'type' => 'array', 'default' => array( '{uploads_dir}/wpcf7_captcha/*', '{uploads_dir}/imagerotator.swf', '{plugins_dir}/wp-fb-autoconnect/facebook-platform/channel.html' ) ), 'cdn.reject.ssl' => array( 'type' => 'boolean', 'default' => false ), 'cdncache.enabled' => array( 'type' => 'boolean', 'default' => false ), 'cloudflare.enabled' => array( 'type' => 'boolean', 'default' => false ), 'cloudflare.email' => array( 'type' => 'string', 'default' => '' ), 'cloudflare.key' => array( 'type' => 'string', 'default' => '' ), 'cloudflare.zone' => array( 'type' => 'string', 'default' => '' ), 'cloudflare.ips.ip4' => array( 'type' => 'array', 'default' => array("204.93.240.0/24", "204.93.177.0/24", "199.27.128.0/21", "173.245.48.0/20", "103.22.200.0/22", "141.101.64.0/18", "108.162.192.0/18","190.93.240.1/20","188.114.96.0/20", "198.41.128.0/17") ), 'cloudflare.ips.ip6' => array( 'type' => 'array', 'default' => array("2400:cb00::/32", "2606:4700::/32", "2803:f800::/32") ), 'varnish.enabled' => array( 'type' => 'boolean', 'default' => false ), 'varnish.debug' => array( 'type' => 'boolean', 'default' => false ), 'varnish.servers' => array( 'type' => 'array', 'default' => array() ), 'browsercache.enabled' => array( 'type' => 'boolean', 'default' => true ), 'browsercache.no404wp' => array( 'type' => 'boolean', 'default' => false ), 'browsercache.no404wp.exceptions' => array( 'type' => 'array', 'default' => array( 'robots\.txt', 'sitemap(_index)?\.xml(\.gz)?', '[a-z0-9_\-]+-sitemap([0-9]+)?\.xml(\.gz)?' ) ), 'browsercache.cssjs.last_modified' => array( 'type' => 'boolean', 'default' => true ), 'browsercache.cssjs.compression' => array( 'type' => 'boolean', 'default' => true ), 'browsercache.cssjs.expires' => array( 'type' => 'boolean', 'default' => false ), 'browsercache.cssjs.lifetime' => array( 'type' => 'integer', 'default' => 31536000 ), 'browsercache.cssjs.nocookies' => array( 'type' => 'boolean', 'default' => false ), 'browsercache.cssjs.cache.control' => array( 'type' => 'boolean', 'default' => false ), 'browsercache.cssjs.cache.policy' => array( 'type' => 'string', 'default' => 'cache_public_maxage' ), 'browsercache.cssjs.etag' => array( 'type' => 'boolean', 'default' => false ), 'browsercache.cssjs.w3tc' => array( 'type' => 'boolean', 'default' => false ), 'browsercache.cssjs.replace' => array( 'type' => 'boolean', 'default' => false ), 'browsercache.html.compression' => array( 'type' => 'boolean', 'default' => true ), 'browsercache.html.last_modified' => array( 'type' => 'boolean', 'default' => true ), 'browsercache.html.expires' => array( 'type' => 'boolean', 'default' => false ), 'browsercache.html.lifetime' => array( 'type' => 'integer', 'default' => 3600 ), 'browsercache.html.cache.control' => array( 'type' => 'boolean', 'default' => false ), 'browsercache.html.cache.policy' => array( 'type' => 'string', 'default' => 'cache_public_maxage' ), 'browsercache.html.etag' => array( 'type' => 'boolean', 'default' => false ), 'browsercache.html.w3tc' => array( 'type' => 'boolean', 'default' => false ), 'browsercache.html.replace' => array( 'type' => 'boolean', 'default' => false ), 'browsercache.other.last_modified' => array( 'type' => 'boolean', 'default' => true ), 'browsercache.other.compression' => array( 'type' => 'boolean', 'default' => true ), 'browsercache.other.expires' => array( 'type' => 'boolean', 'default' => false ), 'browsercache.other.lifetime' => array( 'type' => 'integer', 'default' => 31536000 ), 'browsercache.other.nocookies' => array( 'type' => 'boolean', 'default' => false ), 'browsercache.other.cache.control' => array( 'type' => 'boolean', 'default' => false ), 'browsercache.other.cache.policy' => array( 'type' => 'string', 'default' => 'cache_public_maxage' ), 'browsercache.other.etag' => array( 'type' => 'boolean', 'default' => false ), 'browsercache.other.w3tc' => array( 'type' => 'boolean', 'default' => false ), 'browsercache.other.replace' => array( 'type' => 'boolean', 'default' => false ), 'browsercache.timestamp' => array( 'type' => 'string', 'default' => '' ), 'browsercache.replace.exceptions' => array ( 'type' => 'array', 'default' => array() ), 'mobile.enabled' => array( 'type' => 'boolean', 'default' => false ), 'mobile.rgroups' => array( 'type' => 'array', 'default' => array( 'high' => array( 'theme' => '', 'enabled' => false, 'redirect' => '', 'agents' => array( 'acer\ s100', 'android', 'archos5', 'bada', 'bb10', 'blackberry9500', 'blackberry9530', 'blackberry9550', 'blackberry\ 9800', 'cupcake', 'docomo\ ht\-03a', 'dream', 'froyo', 'googlebot-mobile', 'htc\ hero', 'htc\ magic', 'htc_dream', 'htc_magic', 'iemobile/7.0', 'incognito', 'ipad', 'iphone', 'ipod', 'kindle', 'lg\-gw620', 'liquid\ build', 'maemo', 'mot\-mb200', 'mot\-mb300', 'nexus\ one', 'nexus\ 7', 'opera\ mini', 's8000', 'samsung\-s8000', 'series60.*webkit', 'series60/5\.0', 'sonyericssone10', 'sonyericssonu20', 'sonyericssonx10', 't\-mobile\ mytouch\ 3g', 't\-mobile\ opal', 'tattoo', 'touch', 'webmate', 'webos' ) ), 'low' => array( 'theme' => '', 'enabled' => false, 'redirect' => '', 'agents' => array( '2\.0\ mmp', '240x320', 'alcatel', 'amoi', 'asus', 'au\-mic', 'audiovox', 'avantgo', 'bb10', 'benq', 'bird', 'blackberry', 'blazer', 'cdm', 'cellphone', 'danger', 'ddipocket', 'docomo', 'dopod', 'elaine/3\.0', 'ericsson', 'eudoraweb', 'fly', 'haier', 'hiptop', 'hp\.ipaq', 'htc', 'huawei', 'i\-mobile', 'iemobile', 'iemobile/7', 'iemobile/9', 'j\-phone', 'kddi', 'konka', 'kwc', 'kyocera/wx310k', 'lenovo', 'lg', 'lg/u990', 'lge\ vx', 'midp', 'midp\-2\.0', 'mmef20', 'mmp', 'mobilephone', 'mot\-v', 'motorola', 'msie\ 10\.0', 'netfront', 'newgen', 'newt', 'nintendo\ ds', 'nintendo\ wii', 'nitro', 'nokia', 'novarra', 'o2', 'openweb', 'opera\ mobi', 'opera\.mobi', 'p160u', 'palm', 'panasonic', 'pantech', 'pdxgw', 'pg', 'philips', 'phone', 'playbook', 'playstation\ portable', 'portalmmm', '\bppc\b', 'proxinet', 'psp', 'qtek', 'sagem', 'samsung', 'sanyo', 'sch', 'sch\-i800', 'sec', 'sendo', 'sgh', 'sharp', 'sharp\-tq\-gx10', 'small', 'smartphone', 'softbank', 'sonyericsson', 'sph', 'symbian', 'symbian\ os', 'symbianos', 'toshiba', 'treo', 'ts21i\-10', 'up\.browser', 'up\.link', 'uts', 'vertu', 'vodafone', 'wap', 'willcome', 'windows\ ce', 'windows\.ce', 'winwap', 'xda', 'xoom', 'zte' ) ) ) ), 'referrer.enabled' => array( 'type' => 'boolean', 'default' => false ), 'referrer.rgroups' => array( 'type' => 'array', 'default' => array( 'search_engines' => array( 'theme' => '', 'enabled' => false, 'redirect' => '', 'referrers' => array( 'google\.com', 'yahoo\.com', 'bing\.com', 'ask\.com', 'msn\.com' ) ) ) ), 'common.support' => array( 'type' => 'string', 'default' => '' ), 'common.install' => array( 'type' => 'integer', 'default' => 0 ), 'common.tweeted' => array( 'type' => 'boolean', 'default' => false ), 'config.check' => array( 'type' => 'boolean', 'default' => true ), 'config.path' => array( 'type' => 'string', 'default' => '' ), 'widget.latest.items' => array( 'type' => 'integer', 'default' => 3 ), 'widget.latest_news.items' => array( 'type' => 'integer', 'default' => 5 ), 'widget.pagespeed.enabled' => array( 'type' => 'boolean', 'default' => true ), 'widget.pagespeed.key' => array( 'type' => 'string', 'default' => '' ), 'notes.wp_content_changed_perms' => array( 'type' => 'boolean', 'default' => true ), 'notes.wp_content_perms' => array( 'type' => 'boolean', 'default' => true ), 'notes.theme_changed' => array( 'type' => 'boolean', 'default' => false ), 'notes.wp_upgraded' => array( 'type' => 'boolean', 'default' => false ), 'notes.plugins_updated' => array( 'type' => 'boolean', 'default' => false ), 'notes.cdn_upload' => array( 'type' => 'boolean', 'default' => false ), 'notes.cdn_reupload' => array( 'type' => 'boolean', 'default' => false ), 'notes.need_empty_pgcache' => array( 'type' => 'boolean', 'default' => false ), 'notes.need_empty_minify' => array( 'type' => 'boolean', 'default' => false ), 'notes.need_empty_objectcache' => array( 'type' => 'boolean', 'default' => false ), 'notes.root_rules' => array( 'type' => 'boolean', 'default' => true ), 'notes.rules' => array( 'type' => 'boolean', 'default' => true ), 'notes.pgcache_rules_wpsc' => array( 'type' => 'boolean', 'default' => true ), 'notes.support_us' => array( 'type' => 'boolean', 'default' => true ), 'notes.no_curl' => array( 'type' => 'boolean', 'default' => true ), 'notes.no_zlib' => array( 'type' => 'boolean', 'default' => true ), 'notes.zlib_output_compression' => array( 'type' => 'boolean', 'default' => true ), 'notes.no_permalink_rules' => array( 'type' => 'boolean', 'default' => true ), 'notes.browsercache_rules_no404wp' => array( 'type' => 'boolean', 'default' => true ), 'notes.cloudflare_plugin' => array( 'type' => 'boolean', 'default' => true ), 'timelimit.email_send' => array( 'type' => 'integer', 'default' => 180 ), 'timelimit.varnish_purge' => array( 'type' => 'integer', 'default' => 300 ), 'timelimit.cache_flush' => array( 'type' => 'integer', 'default' => 600 ), 'timelimit.cache_gc' => array( 'type' => 'integer', 'default' => 600 ), 'timelimit.cdn_upload' => array( 'type' => 'integer', 'default' => 600 ), 'timelimit.cdn_delete' => array( 'type' => 'integer', 'default' => 300 ), 'timelimit.cdn_purge' => array( 'type' => 'integer', 'default' => 300 ), 'timelimit.cdn_import' => array( 'type' => 'integer', 'default' => 600 ), 'timelimit.cdn_test' => array( 'type' => 'integer', 'default' => 300 ), 'timelimit.cdn_container_create' => array( 'type' => 'integer', 'default' => 300 ), 'timelimit.cloudflare_api_request' => array( 'type' => 'integer', 'default' => 180 ), 'timelimit.domain_rename' => array( 'type' => 'integer', 'default' => 120 ), 'timelimit.minify_recommendations' => array( 'type' => 'integer', 'default' => 600 ), 'minify.auto.filename_length' => array( 'type' => 'integer', 'default' => 150 ), 'minify.auto.disable_filename_length_test' => array( 'type' => 'boolean', 'default' => false, ), 'common.instance_id' => array( 'type' => 'integer', 'default' => 0 ), 'common.force_master' => array( 'type' => 'boolean', 'default' => true, 'master_only' => 'true' ), 'newrelic.enabled' => array( 'type' => 'boolean', 'default' => false, ), 'newrelic.api_key' => array( 'type' => 'string', 'default' => '', 'master_only' => 'true' ), 'newrelic.account_id' => array( 'type' => 'string', 'default' => '', 'master_only' => 'true' ), 'newrelic.application_id' => array( 'type' => 'integer', 'default' => 0, ), 'newrelic.appname' => array( 'type' => 'string', 'default' => '', ), 'newrelic.accept.logged_roles' => array( 'type' => 'boolean', 'default' => true ), 'newrelic.accept.roles' => array( 'type' => 'array', 'default' => array('contributor') ), 'newrelic.use_php_function' => array ( 'type' => 'boolean', 'default' => true, ), 'notes.new_relic_page_load_notification' => array( 'type' => 'boolean', 'default' => true ), 'newrelic.appname_prefix' => array ( 'type' => 'string', 'default' => 'Child Site - ' ), 'newrelic.merge_with_network' => array ( 'type' => 'boolean', 'default' => true ), 'newrelic.cache_time' => array( 'type' => 'integer', 'default' => 5 ), 'newrelic.enable_xmit' => array( 'type' => 'boolean', 'default' => false ), 'newrelic.use_network_wide_id' => array( 'type' => 'boolean', 'default' => false, 'master_only' => 'true' ), 'pgcache.late_init' => array ( 'type' => 'boolean', 'default' => false ), 'newrelic.include_rum' => array( 'type' => 'boolean', 'default' => true, ), 'extensions.settings' => array( 'type' => 'array', 'default' => array( 'genesis.theme' => array( 'wp_head' => '0', 'genesis_header' => '1', 'genesis_do_nav' => '1', 'genesis_do_subnav' => '1', 'loop_front_page' => '1', 'loop_single' => '1', 'loop_single_excluded' => '', 'loop_single_genesis_comments' => '0', 'loop_single_genesis_pings' => '0', 'sidebar' => '0', 'sidebar_excluded' => '', 'genesis_footer' => '1', 'wp_footer' => '0', 'fragment_reject_logged_roles' => '1', 'fragment_reject_logged_roles_on_actions' => array( 0 => 'genesis_loop', 1 => 'wp_head', 2 => 'wp_footer', ), 'fragment_reject_roles' => array( 0 => 'administrator', ), ), ) ), 'extensions.active' => array( 'type' => 'array', 'default' => array() ), 'plugin.license_key' => array( 'type' => 'string', 'default' => '', 'master_only' => true ), 'plugin.type' => array( 'type' => 'string', 'default' => '', 'master_only' => true ) ); /* * Descriptors of configuration keys * for admin config */ $keys_admin = array( 'browsercache.configuration_sealed' => array( 'type' => 'boolean', 'default' => false, 'master_only' => 'true' ), 'cdn.configuration_sealed' => array( 'type' => 'boolean', 'default' => false, 'master_only' => 'true' ), 'cloudflare.configuration_sealed' => array( 'type' => 'boolean', 'default' => false, 'master_only' => 'true' ), 'common.install' => array( 'type' => 'integer', 'default' => 0, 'master_only' => 'true' ), 'common.visible_by_master_only' => array( 'type' => 'boolean', 'default' => true, 'master_only' => 'true' ), 'dbcache.configuration_sealed' => array( 'type' => 'boolean', 'default' => false, 'master_only' => 'true' ), 'minify.configuration_sealed' => array( 'type' => 'boolean', 'default' => false, 'master_only' => 'true' ), 'objectcache.configuration_sealed' => array( 'type' => 'boolean', 'default' => false, 'master_only' => 'true' ), 'pgcache.configuration_sealed' => array( 'type' => 'boolean', 'default' => false, 'master_only' => 'true' ), 'previewmode.enabled' => array( 'type' => 'boolean', 'default' => false, 'master_only' => 'true' ), 'varnish.configuration_sealed' => array( 'type' => 'boolean', 'default' => false, 'master_only' => 'true' ), 'fragmentcache.configuration_sealed' => array( 'type' => 'boolean', 'default' => false, 'master_only' => 'true' ) ,'newrelic.configuration_sealed' => array( 'type' => 'boolean', 'default' => false, 'master_only' => 'true' ) ,'extensions.configuration_sealed' => array( 'type' => 'array', 'default' => array(), 'master_only' => 'true' ) ,'notes.minify_error' => array( 'type' => 'boolean', 'default' => false ) ,'minify.error.last' => array( 'type' => 'string', 'default' => '' ), 'minify.error.notification' => array( 'type' => 'string', 'default' => '' ), 'minify.error.notification.last' => array( 'type' => 'integer', 'default' => 0 ), 'minify.error.file' => array( 'type' => 'string', 'default' => '' ), 'notes.remove_w3tc' => array( 'type' => 'boolean', 'default' => false ) ); $keys_admin['common.install']['default'] = time(); /* * Descriptors how sealed configuration keys affect overriding */ $sealing_keys_scope = array( array( 'key' => 'browsercache.configuration_sealed', 'prefix' => 'browsercache.' ), array( 'key' => 'cdn.configuration_sealed', 'prefix' => 'cdn.' ), array( 'key' => 'cloudflare.configuration_sealed', 'prefix' => 'cloudflare.' ), array( 'key' => 'dbcache.configuration_sealed', 'prefix' => 'dbcache.' ), array( 'key' => 'minify.configuration_sealed', 'prefix' => 'minify.' ), array( 'key' => 'objectcache.configuration_sealed', 'prefix' => 'objectcache.' ), array( 'key' => 'fragmentcache.configuration_sealed', 'prefix' => 'fragmentcache.' ), array( 'key' => 'pgcache.configuration_sealed', 'prefix' => 'pgcache.' ), array( 'key' => 'varnish.configuration_sealed', 'prefix' => 'varnish.' ), array( 'key' => 'extensions.active.configuration_sealed', 'prefix' => 'extensions.active' ), array( 'key' => 'extensions.configuration_sealed', 'prefix' => 'extensions.' ) );
gpl-2.0
mpaulus88/logo
sites/all/themes/localhost_logo/js/map_production.js
2105
(function(b){var g,c=[],d,f,h,m,n=function(b){b.preventDefault();b.returnValue=!1;console.log("clicked")};b(function(){h=b(".views-field-title a");var j=0;d=b(".views-row");d.hide();console.log(d);b(".views-field-field-geofield .field-content").each(function(){g=b(this).text();console.log(g);m=/POINT(.*)/;var a=g.replace(m,"$1"),a=a.replace("(",""),a=a.replace(")","");console.log(a);c[j]=a.split(" ");console.log(b(".views-field-title:eq("+j+") a").text());j++});console.log(c);h.attr("href","#").css("cursor", "default");b("#gmap").css({height:"600px",width:"100%"});var k=new google.maps.StyledMapType([{featureType:"landscape.natural.landcover",elementType:"labels.text.stroke",stylers:[{visibility:"off"}]},{elementType:"labels.text",stylers:[{visibility:"off"}]},{featureType:"water",stylers:[{visibility:"on"},{color:"#353632"}]},{featureType:"landscape",stylers:[{color:"#d4d1d0"}]}],{name:"Styled Map"}),l={zoom:2,center:new google.maps.LatLng(30.8466,4.3524),scrollwheel:!1,panControl:!1,zoomControl:!1, scaleControl:!1,streetViewControl:!1,overviewMapControl:!1,MapTypeControl:!1,mapTypeControlOptions:{mapTypeIds:[google.maps.MapTypeId.ROADMAP,"map_style"]}};f=new google.maps.Map(document.getElementById("gmap"),l);f.mapTypes.set("map_style",k);f.setMapTypeId("map_style");for(var k=new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|F0F0F0",null,null,null,new google.maps.Size(15,23),new google.maps.Point(0,0),new google.maps.Point(10,34)),l=new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_shadow", new google.maps.Size(40,37),new google.maps.Point(0,0),new google.maps.Point(12,35)),p=[],a=0;a<c.length;a++){console.log(c.length-1);console.log(c);var e=new google.maps.LatLng(c[a][2],c[a][1]),e=new google.maps.Marker({map:f,icon:k,shadow:l,id:a,position:e,title:b(".views-field-title:eq("+a+") a").text()});p.push(e);e.set("id",a);google.maps.event.addListener(e,"click",function(){console.log(a);console.log(this.get("id"));d.fadeOut(400);d.eq(this.get("id")).fadeIn(400)})}h.bind("click",n)})})(jQuery);
gpl-2.0
metaindu/MetaphysicsIndustries.Giza
DefinitionError.cs
2701
 // MetaphysicsIndustries.Giza - A Parsing System // Copyright (C) 2008-2021 Metaphysics Industries, Inc. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 // USA using System; using System.Collections.Generic; namespace MetaphysicsIndustries.Giza { /* NDefinitions are graphs of interconnected nodes. The graphs of nodes that result from using the supergrammar are not all of the possible graphs that Spanner can deal with. That is, there are other graphs that could be constructed manually, or by some system other than GrammarCompiler, that would still work. The purpose of the DefinitionChecker then, is to confirm that a given NDefinition can be used by Spanner (a looser requirement), and NOT to confirm that the NDefinition conforms to what the supergrammar can output (a narrower requirement). */ public class DefinitionError : Error { public static readonly ErrorType NextNodeLinksOutsideOfDefinition = new ErrorType(name:"NextNodeLinksOutsideOfDefinition", descriptionFormat:"NextNodeLinksOutsideOfDefinition" ); public static readonly ErrorType StartNodeHasWrongParentDefinition = new ErrorType(name:"StartNodeHasWrongParentDefinition", descriptionFormat:"StartNodeHasWrongParentDefinition" ); public static readonly ErrorType EndNodeHasWrongParentDefinition = new ErrorType(name:"EndNodeHasWrongParentDefinition", descriptionFormat:"EndNodeHasWrongParentDefinition" ); public static readonly ErrorType LeadingReferenceCycle = new ErrorType(name:"LeadingReferenceCycle", descriptionFormat:"LeadingReferenceCycle" ); public static readonly ErrorType NodeHasNoPathFromStart = new ErrorType(name:"NodeHasNoPathFromStart"); public static readonly ErrorType NodeHasNoPathToEnd = new ErrorType(name:"NodeHasNoPathToEnd"); public Node Node; public List<NDefinition> Cycle; } }
gpl-2.0
vlewin/e-shop
app/controllers/addresses_controller.rb
2190
class AddressesController < ApplicationController before_action :set_address, only: [:show, :edit, :update, :destroy, :delete] after_action :verify_authorized, except: [ :new, :create ] def index authorize :addresses, :index? addresses = Address.preload(:user, :billing_orders, :shipping_orders) @items = find_and_paginate(addresses, order: 'recipient ASC') render(partial: 'addresses', layout: false) and return if request.xhr? end def show end def new @address = Address.new end def edit end def create @address = Address.new(address_params) @address.user_id = current_user.id if @address.save flash[:notice] = _('Address was successfully created.') if current_user.admin? redirect_to addresses_path else redirect_to :back end else if current_user.admin? render :new else redirect_to :back end end # redirect_to_back_or_default addresses_url end def update if @address.update(address_params) flash[:notice] = _('Address was successfully updated.') if current_user.admin? redirect_to addresses_path else redirect_to :back end else if current_user.admin? render :new else redirect_to :back end end # redirect_to_back_or_default addresses_url end def delete if @address.inactive! flash[:notice] = _('Address was successfully destroyed.') else flash[:alert] = @address.errors.full_messages.join(', ') end redirect_to account_path end def destroy if @address.destroy flash[:notice] = _('Address was successfully destroyed.') else flash[:alert] = @address.errors.full_messages.join(', ') end redirect_to_back_or_default addresses_url end private def set_address @address = if current_user.admin? Address.find(params[:id]) else current_user.addresses.active.find(params[:id]) end authorize @address end def address_params params.require(:address).permit(:recipient, :city, :street, :zip_code, :phone) end end
gpl-2.0
JamesLinEngineer/RKMC
addons/plugin.video.phstreams/resources/lib/modules/debrid.py
967
# -*- coding: utf-8 -*- ''' Exodus Add-on Copyright (C) 2016 Exodus 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/>. ''' def debridDict(): return { 'realdebrid': [], 'premiumize': [], 'alldebrid': [], 'rpnet': [] } def status(): return False def resolver(url, debrid): return
gpl-2.0
conan513/SingleCore_TC
src/server/game/AI/CreatureAI.cpp
13998
/* * Copyright (C) 2008-2018 TrinityCore <https://www.trinitycore.org/> * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "CreatureAI.h" #include "AreaBoundary.h" #include "Creature.h" #include "CreatureAIImpl.h" #include "CreatureTextMgr.h" #include "Language.h" #include "Log.h" #include "Map.h" #include "MapReference.h" #include "MotionMaster.h" #include "Player.h" #include "SpellMgr.h" #include "TemporarySummon.h" #include "Vehicle.h" #include "World.h" //Disable CreatureAI when charmed void CreatureAI::OnCharmed(bool apply) { if (apply) { me->NeedChangeAI = true; me->IsAIEnabled = false; } } AISpellInfoType* UnitAI::AISpellInfo; AISpellInfoType* GetAISpellInfo(uint32 i) { return &UnitAI::AISpellInfo[i]; } CreatureAI::CreatureAI(Creature* creature) : UnitAI(creature), me(creature), _boundary(nullptr), m_MoveInLineOfSight_locked(false), m_canSeeEvenInPassiveMode(false) { } CreatureAI::~CreatureAI() { } void CreatureAI::Talk(uint8 id, WorldObject const* whisperTarget /*= nullptr*/) { sCreatureTextMgr->SendChat(me, id, whisperTarget); } void CreatureAI::DoZoneInCombat(Creature* creature /*= nullptr*/, float maxRangeToNearestTarget /* = 250.0f*/) { if (!creature) creature = me; if (!creature->CanHaveThreatList()) return; Map* map = creature->GetMap(); if (!map->IsDungeon()) //use IsDungeon instead of Instanceable, in case battlegrounds will be instantiated { TC_LOG_ERROR("misc", "DoZoneInCombat call for map that isn't an instance (creature entry = %d)", creature->GetTypeId() == TYPEID_UNIT ? creature->ToCreature()->GetEntry() : 0); return; } if (!creature->HasReactState(REACT_PASSIVE) && !creature->GetVictim()) { if (Unit* nearTarget = creature->SelectNearestTarget(maxRangeToNearestTarget)) creature->AI()->AttackStart(nearTarget); else if (creature->IsSummon()) { if (Unit* summoner = creature->ToTempSummon()->GetSummoner()) { Unit* target = summoner->getAttackerForHelper(); if (!target && summoner->CanHaveThreatList() && !summoner->getThreatManager().isThreatListEmpty()) target = summoner->getThreatManager().getHostilTarget(); if (target && (creature->IsFriendlyTo(summoner) || creature->IsHostileTo(target))) creature->AI()->AttackStart(target); } } } // Intended duplicated check, the code above this should select a victim // If it can't find a suitable attack target then we should error out. if (!creature->HasReactState(REACT_PASSIVE) && !creature->GetVictim()) { TC_LOG_ERROR("misc.dozoneincombat", "DoZoneInCombat called for creature that has empty threat list (creature entry = %u)", creature->GetEntry()); return; } Map::PlayerList const& playerList = map->GetPlayers(); if (playerList.isEmpty()) return; for (Map::PlayerList::const_iterator itr = playerList.begin(); itr != playerList.end(); ++itr) { if (Player* player = itr->GetSource()) { if (player->IsGameMaster()) continue; if (player->IsAlive()) { creature->SetInCombatWith(player); player->SetInCombatWith(creature); creature->AddThreat(player, 0.0f); } /* Causes certain things to never leave the threat list (Priest Lightwell, etc): for (Unit::ControlList::const_iterator itr = player->m_Controlled.begin(); itr != player->m_Controlled.end(); ++itr) { creature->SetInCombatWith(*itr); (*itr)->SetInCombatWith(creature); creature->AddThreat(*itr, 0.0f); }*/ } } } // scripts does not take care about MoveInLineOfSight loops // MoveInLineOfSight can be called inside another MoveInLineOfSight and cause stack overflow void CreatureAI::MoveInLineOfSight_Safe(Unit* who) { if (m_MoveInLineOfSight_locked == true) return; m_MoveInLineOfSight_locked = true; MoveInLineOfSight(who); m_MoveInLineOfSight_locked = false; } void CreatureAI::MoveInLineOfSight(Unit* who) { if (me->GetVictim()) return; if (me->GetCreatureType() == CREATURE_TYPE_NON_COMBAT_PET) // non-combat pets should just stand there and look good;) return; if (me->HasReactState(REACT_AGGRESSIVE) && me->CanStartAttack(who, false)) AttackStart(who); //else if (who->GetVictim() && me->IsFriendlyTo(who) // && me->IsWithinDistInMap(who, sWorld->getIntConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS)) // && me->CanStartAttack(who->GetVictim(), true)) /// @todo if we use true, it will not attack it when it arrives // me->GetMotionMaster()->MoveChase(who->GetVictim()); } // Distract creature, if player gets too close while stealthed/prowling void CreatureAI::TriggerAlert(Unit const* who) const { // If there's no target, or target isn't a player do nothing if (!who || who->GetTypeId() != TYPEID_PLAYER) return; // If this unit isn't an NPC, is already distracted, is in combat, is confused, stunned or fleeing, do nothing if (me->GetTypeId() != TYPEID_UNIT || me->IsInCombat() || me->HasUnitState(UNIT_STATE_CONFUSED | UNIT_STATE_STUNNED | UNIT_STATE_FLEEING | UNIT_STATE_DISTRACTED)) return; // Only alert for hostiles! if (me->IsCivilian() || me->HasReactState(REACT_PASSIVE) || !me->IsHostileTo(who) || !me->_IsTargetAcceptable(who)) return; // Send alert sound (if any) for this creature me->SendAIReaction(AI_REACTION_ALERT); // Face the unit (stealthed player) and set distracted state for 5 seconds me->SetFacingTo(me->GetAngle(who->GetPositionX(), who->GetPositionY()), true); me->StopMoving(); me->GetMotionMaster()->MoveDistract(5 * IN_MILLISECONDS); } void CreatureAI::EnterEvadeMode(EvadeReason why) { if (!_EnterEvadeMode(why)) return; TC_LOG_DEBUG("entities.unit", "Creature %u enters evade mode.", me->GetEntry()); if (!me->GetVehicle()) // otherwise me will be in evade mode forever { if (Unit* owner = me->GetCharmerOrOwner()) { me->GetMotionMaster()->Clear(false); me->GetMotionMaster()->MoveFollow(owner, PET_FOLLOW_DIST, me->GetFollowAngle(), MOTION_SLOT_ACTIVE); } else { // Required to prevent attacking creatures that are evading and cause them to reenter combat // Does not apply to MoveFollow me->AddUnitState(UNIT_STATE_EVADE); me->GetMotionMaster()->MoveTargetedHome(); } } Reset(); if (me->IsVehicle()) // use the same sequence of addtoworld, aireset may remove all summons! me->GetVehicleKit()->Reset(true); } /*void CreatureAI::AttackedBy(Unit* attacker) { if (!me->GetVictim()) AttackStart(attacker); }*/ void CreatureAI::SetGazeOn(Unit* target) { if (me->IsValidAttackTarget(target)) { if (!me->IsFocusing(nullptr, true)) AttackStart(target); me->SetReactState(REACT_PASSIVE); } } bool CreatureAI::UpdateVictimWithGaze() { if (!me->IsInCombat()) return false; if (me->HasReactState(REACT_PASSIVE)) { if (me->GetVictim()) return true; else me->SetReactState(REACT_AGGRESSIVE); } if (Unit* victim = me->SelectVictim()) if (!me->IsFocusing(nullptr, true)) AttackStart(victim); return me->GetVictim() != nullptr; } bool CreatureAI::UpdateVictim() { if (!me->IsInCombat()) return false; if (!me->HasReactState(REACT_PASSIVE)) { if (Unit* victim = me->SelectVictim()) if (!me->IsFocusing(nullptr, true)) AttackStart(victim); return me->GetVictim() != nullptr; } else if (me->getThreatManager().isThreatListEmpty()) { EnterEvadeMode(EVADE_REASON_NO_HOSTILES); return false; } return true; } bool CreatureAI::_EnterEvadeMode(EvadeReason /*why*/) { if (!me->IsAlive()) return false; me->RemoveAurasOnEvade(); // sometimes bosses stuck in combat? me->DeleteThreatList(); me->CombatStop(true); me->SetLootRecipient(nullptr); me->ResetPlayerDamageReq(); me->SetLastDamagedTime(0); me->SetCannotReachTarget(false); if (me->IsInEvadeMode()) return false; return true; } const uint32 BOUNDARY_VISUALIZE_CREATURE = 15425; const float BOUNDARY_VISUALIZE_CREATURE_SCALE = 0.25f; const int8 BOUNDARY_VISUALIZE_STEP_SIZE = 1; const int32 BOUNDARY_VISUALIZE_FAILSAFE_LIMIT = 750; const float BOUNDARY_VISUALIZE_SPAWN_HEIGHT = 5.0f; int32 CreatureAI::VisualizeBoundary(uint32 duration, Unit* owner, bool fill) const { typedef std::pair<int32, int32> coordinate; if (!owner) return -1; if (!_boundary || _boundary->empty()) return LANG_CREATURE_MOVEMENT_NOT_BOUNDED; std::queue<coordinate> Q; std::unordered_set<coordinate> alreadyChecked; std::unordered_set<coordinate> outOfBounds; Position startPosition = owner->GetPosition(); if (!CheckBoundary(&startPosition)) { // fall back to creature position startPosition = me->GetPosition(); if (!CheckBoundary(&startPosition)) { // fall back to creature home position startPosition = me->GetHomePosition(); if (!CheckBoundary(&startPosition)) return LANG_CREATURE_NO_INTERIOR_POINT_FOUND; } } float spawnZ = startPosition.GetPositionZ() + BOUNDARY_VISUALIZE_SPAWN_HEIGHT; bool boundsWarning = false; Q.push({ 0,0 }); while (!Q.empty()) { coordinate front = Q.front(); bool hasOutOfBoundsNeighbor = false; for (coordinate off : std::initializer_list<coordinate>{{1,0}, {0,1}, {-1,0}, {0,-1}}) { coordinate next(front.first + off.first, front.second + off.second); if (next.first > BOUNDARY_VISUALIZE_FAILSAFE_LIMIT || next.first < -BOUNDARY_VISUALIZE_FAILSAFE_LIMIT || next.second > BOUNDARY_VISUALIZE_FAILSAFE_LIMIT || next.second < -BOUNDARY_VISUALIZE_FAILSAFE_LIMIT) { boundsWarning = true; continue; } if (alreadyChecked.find(next) == alreadyChecked.end()) // never check a coordinate twice { Position nextPos(startPosition.GetPositionX() + next.first*BOUNDARY_VISUALIZE_STEP_SIZE, startPosition.GetPositionY() + next.second*BOUNDARY_VISUALIZE_STEP_SIZE, startPosition.GetPositionZ()); if (CheckBoundary(&nextPos)) Q.push(next); else { outOfBounds.insert(next); hasOutOfBoundsNeighbor = true; } alreadyChecked.insert(next); } else if (outOfBounds.find(next) != outOfBounds.end()) hasOutOfBoundsNeighbor = true; } if (fill || hasOutOfBoundsNeighbor) if (TempSummon* point = owner->SummonCreature(BOUNDARY_VISUALIZE_CREATURE, Position(startPosition.GetPositionX() + front.first*BOUNDARY_VISUALIZE_STEP_SIZE, startPosition.GetPositionY() + front.second*BOUNDARY_VISUALIZE_STEP_SIZE, spawnZ), TEMPSUMMON_TIMED_DESPAWN, duration * IN_MILLISECONDS)) { point->SetObjectScale(BOUNDARY_VISUALIZE_CREATURE_SCALE); point->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_STUNNED | UNIT_FLAG_IMMUNE_TO_NPC); if (!hasOutOfBoundsNeighbor) point->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); } Q.pop(); } return boundsWarning ? LANG_CREATURE_MOVEMENT_MAYBE_UNBOUNDED : 0; } bool CreatureAI::CheckBoundary(Position const* who) const { if (!who) who = me; if (_boundary) for (AreaBoundary const* boundary : *_boundary) if (!boundary->IsWithinBoundary(who)) return false; return true; } void CreatureAI::SetBoundary(CreatureBoundary const* boundary) { _boundary = boundary; me->DoImmediateBoundaryCheck(); } bool CreatureAI::CheckInRoom() { if (CheckBoundary()) return true; else { EnterEvadeMode(EVADE_REASON_BOUNDARY); return false; } } Creature* CreatureAI::DoSummon(uint32 entry, const Position& pos, uint32 despawnTime, TempSummonType summonType) { return me->SummonCreature(entry, pos, summonType, despawnTime); } Creature* CreatureAI::DoSummon(uint32 entry, WorldObject* obj, float radius, uint32 despawnTime, TempSummonType summonType) { Position pos = obj->GetRandomNearPosition(radius); return me->SummonCreature(entry, pos, summonType, despawnTime); } Creature* CreatureAI::DoSummonFlyer(uint32 entry, WorldObject* obj, float flightZ, float radius, uint32 despawnTime, TempSummonType summonType) { Position pos = obj->GetRandomNearPosition(radius); pos.m_positionZ += flightZ; return me->SummonCreature(entry, pos, summonType, despawnTime); }
gpl-2.0
rahulrathore44/ParkandCompanyCSharp
Park-and-Company/PageObject/ActivityIncentiveTemplate.cs
5153
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using OpenQA.Selenium; using OpenQA.Selenium.Support.PageObjects; using Park_and_Company.BaseClasses; using Park_and_Company.ComponentHelper; using Park_and_Company.PageObject.IncentivePage; namespace Park_and_Company.PageObject { public class ActivityIncentiveTemplate : PageBase { private IWebDriver driver; public ActivityIncentiveTemplate(IWebDriver _driver) : base(_driver) { this.driver = _driver; } [FindsBy(How = How.XPath,Using = "//a[text()='Program Incentive']")] private IWebElement ProgramIncentive; [FindsBy(How = How.XPath,Using = "//button[text()='Add']")] private IWebElement Add; [FindsBy(How = How.XPath,Using = "//a[text()='Validation']")] private IWebElement Validation; [FindsBy(How = How.XPath,Using = "//div[@id='validationstep']/parent::div/following-sibling::button")] private IWebElement ValidationNext; [FindsBy(How = How.XPath,Using = "//button[text()='Finish']")] private IWebElement Finish; [FindsBy(How = How.XPath,Using = "//div[@id='accordion']/descendant::div[@id='rendered'][position()=4]/button")] private IWebElement ProgramIncentiveNext; public void AddProgramIncentive(string acCode, string acType, string desc, string points) { JavaScriptExecutorHelper.ScrollElementAndClick(ProgramIncentive); GenericHelper.WaitForLoadingMask(); GenericHelper.WaitForElement(Add); Add.Click(); ProgramIncentive addInc = new ProgramIncentive(driver); addInc.AddProgramIncentive(acCode, acType, desc, points); Thread.Sleep(500); ProgramIncentiveNext.Click(); JavaScriptExecutorHelper.ScrollElementAndClick(ProgramIncentive); GenericHelper.WaitForLoadingMask(); } public void CheckValidationField(bool fName, bool lName, bool eMail, bool acCode, bool date) { JavaScriptExecutorHelper.ScrollElementAndClick(Validation); GenericHelper.WaitForLoadingMask(); Validation val = new Validation(driver); val.CheckValidationField(fName, lName, eMail, acCode, date); JavaScriptExecutorHelper.ScrollElementAndClick(ValidationNext); Validation.Click(); GenericHelper.WaitForLoadingMask(); } public void ClickFinish() { Finish.Click(); } public void SelectProgramName(string pName, string pDesc) { SelectProgramPage spPage = new SelectProgramPage(driver); spPage.SelectProgramName(pName, pDesc); } public void SelectProgramVisibilityStartDate(string day, string month, string year) { SelectProgramDatesPage spdPage = new SelectProgramDatesPage(driver); spdPage.SelectProgramVisibilityStartDate(day, month, year); } public void SelectProgramVisibilityEndDate(string day, string month, string year) { SelectProgramDatesPage spdPage = new SelectProgramDatesPage(driver); spdPage.SelectProgramVisibilityEndDate(day, month, year); } public void SelectProgramStartDate(string day, string month, string year) { SelectProgramDatesPage spdPage = new SelectProgramDatesPage(driver); spdPage.SelectProgramStartDate(day, month, year); } public void SelectProgramEndDate(string day, string month, string year) { SelectProgramDatesPage spdPage = new SelectProgramDatesPage(driver); spdPage.SelectProgramEndDate(day, month, year); } public void SelectProgramLastSubmitDate(string day, string month, string year) { SelectProgramDatesPage spdPage = new SelectProgramDatesPage(driver); spdPage.SelectProgramLastSubmitDate(day, month, year); } public void SelectProgramCloseDates(string day, string month, string year) { SelectProgramDatesPage spdPage = new SelectProgramDatesPage(driver); spdPage.SelectProgramCloseDates(day, month, year); } public void AddPoints(string maxPointAllow, string pointExpire, string myPointMsg) { ConfigureProgramPage cpPage = new ConfigureProgramPage(driver); cpPage.AddPoints(maxPointAllow, pointExpire, myPointMsg); } public void AddPointType(string type, string poitAlloc) { ConfigureProgramPage cpPage = new ConfigureProgramPage(driver); cpPage.AddPointType(type, poitAlloc); } public void AddEligibleGroup(string grpName) { EligibleGroupPage egPage = new EligibleGroupPage(driver); egPage.AddEligibleGroup(grpName); } } }
gpl-2.0
Robert0Trebor/robert
TMessagesProj/src/main/java/org/vidogram/messenger/exoplayer/c/e/i.java
1434
package org.vidogram.messenger.exoplayer.c.e; import org.vidogram.messenger.exoplayer.MediaFormat; final class i extends e { private final org.vidogram.messenger.exoplayer.f.m b; private boolean c; private long d; private int e; private int f; public i(org.vidogram.messenger.exoplayer.c.m paramm) { super(paramm); paramm.a(MediaFormat.a()); this.b = new org.vidogram.messenger.exoplayer.f.m(10); } public void a() { this.c = false; } public void a(long paramLong, boolean paramBoolean) { if (!paramBoolean) return; this.c = true; this.d = paramLong; this.e = 0; this.f = 0; } public void a(org.vidogram.messenger.exoplayer.f.m paramm) { if (!this.c) return; int i = paramm.b(); if (this.f < 10) { int j = Math.min(i, 10 - this.f); System.arraycopy(paramm.a, paramm.d(), this.b.a, this.f, j); if (j + this.f == 10) { this.b.b(6); this.e = (this.b.r() + 10); } } i = Math.min(i, this.e - this.f); this.a.a(paramm, i); this.f = (i + this.f); } public void b() { if ((!this.c) || (this.e == 0) || (this.f != this.e)) return; this.a.a(this.d, 1, this.e, 0, null); this.c = false; } } /* Location: G:\programs\dex2jar-2.0\vidogram-dex2jar.jar * Qualified Name: org.vidogram.messenger.exoplayer.c.e.i * JD-Core Version: 0.6.0 */
gpl-2.0
dsiekiera/modified-bs4
includes/external/shopgate/shopgate_library/classes/helper/logging/strategy/DefaultLogging.php
8299
<?php /** * Shopgate GmbH * * URHEBERRECHTSHINWEIS * * Dieses Plugin ist urheberrechtlich geschützt. Es darf ausschließlich von Kunden der Shopgate GmbH * zum Zwecke der eigenen Kommunikation zwischen dem IT-System des Kunden mit dem IT-System der * Shopgate GmbH über www.shopgate.com verwendet werden. Eine darüber hinausgehende Vervielfältigung, Verbreitung, * öffentliche Zugänglichmachung, Bearbeitung oder Weitergabe an Dritte ist nur mit unserer vorherigen * schriftlichen Zustimmung zulässig. Die Regelungen der §§ 69 d Abs. 2, 3 und 69 e UrhG bleiben hiervon unberührt. * * COPYRIGHT NOTICE * * This plugin is the subject of copyright protection. It is only for the use of Shopgate GmbH customers, * for the purpose of facilitating communication between the IT system of the customer and the IT system * of Shopgate GmbH via www.shopgate.com. Any reproduction, dissemination, public propagation, processing or * transfer to third parties is only permitted where we previously consented thereto in writing. The provisions * of paragraph 69 d, sub-paragraphs 2, 3 and paragraph 69, sub-paragraph e of the German Copyright Act shall remain unaffected. * * @author Shopgate GmbH <[email protected]> */ class Shopgate_Helper_Logging_Strategy_DefaultLogging implements Shopgate_Helper_Logging_Strategy_LoggingInterface { /** @var bool */ private $debug; /** @var bool */ private $useStackTrace; /** @var mixed[] */ private $logFiles = array( self::LOGTYPE_ACCESS => array('path' => '', 'handle' => null, 'mode' => 'a+'), self::LOGTYPE_REQUEST => array('path' => '', 'handle' => null, 'mode' => 'a+'), self::LOGTYPE_ERROR => array('path' => '', 'handle' => null, 'mode' => 'a+'), self::LOGTYPE_DEBUG => array('path' => '', 'handle' => null, 'mode' => 'w+'), ); public function __construct( $accessLogPath = null, $requestLogPath = null, $errorLogPath = null, $debugLogPath = null ) { // fall back to default log paths if none are specified if (empty($accessLogPath)) { $accessLogPath = SHOPGATE_BASE_DIR . DS . 'temp' . DS . 'logs' . DS . ShopgateConfigInterface::SHOPGATE_FILE_PREFIX . 'access.log'; } if (empty($requestLogPath)) { $requestLogPath = SHOPGATE_BASE_DIR . DS . 'temp' . DS . 'logs' . DS . ShopgateConfigInterface::SHOPGATE_FILE_PREFIX . 'request.log'; } if (empty($errorLogPath)) { $errorLogPath = SHOPGATE_BASE_DIR . DS . 'temp' . DS . 'logs' . DS . ShopgateConfigInterface::SHOPGATE_FILE_PREFIX . 'error.log'; } if (empty($debugLogPath)) { $debugLogPath = SHOPGATE_BASE_DIR . DS . 'temp' . DS . 'logs' . DS . ShopgateConfigInterface::SHOPGATE_FILE_PREFIX . 'debug.log'; } $this->setLogFilePaths($accessLogPath, $requestLogPath, $errorLogPath, $debugLogPath); $this->debug = false; $this->useStackTrace = true; } public function enableDebug() { $this->debug = true; } public function disableDebug() { $this->debug = false; } public function isDebugEnabled() { return $this->debug; } public function enableStackTrace() { $this->useStackTrace = true; } public function disableStackTrace() { $this->useStackTrace = false; } public function log($msg, $type = self::LOGTYPE_ERROR, $stackTrace = '') { // build log message $msg = gmdate('d-m-Y H:i:s: ') . $msg . "\n" . ($this->useStackTrace ? $stackTrace ."\n\n" : ''); // determine log file type and append message switch (strtolower($type)) { // write to error log if type is unknown default: $type = self::LOGTYPE_ERROR; // allowed types: case self::LOGTYPE_ERROR: case self::LOGTYPE_ACCESS: case self::LOGTYPE_REQUEST: case self::LOGTYPE_DEBUG: } // if debug logging is requested but not activated, simply return if (($type === self::LOGTYPE_DEBUG) && !$this->debug) { return true; } // open log files if necessary if (!$this->openLogFileHandle($type)) { return false; } // try to log $success = false; if (fwrite($this->logFiles[$type]['handle'], $msg) !== false) { $success = true; } return $success; } public function tail($type = self::LOGTYPE_ERROR, $lines = 20) { if (!isset($this->logFiles[$type])) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_API_UNKNOWN_LOGTYPE, 'Type: ' . $type); } if (!$this->openLogFileHandle($type)) { throw new ShopgateLibraryException(ShopgateLibraryException::INIT_LOGFILE_OPEN_ERROR, 'Type: ' . $type); } if (empty($lines)) { $lines = 20; } $handle = $this->logFiles[$type]['handle']; $lineCounter = $lines; $pos = -2; $beginning = false; $text = ''; while ($lineCounter > 0) { $t = ''; while ($t !== "\n") { if (@fseek($handle, $pos, SEEK_END) == -1) { $beginning = true; break; } $t = @fgetc($handle); $pos--; } $lineCounter--; if ($beginning) { @rewind($handle); } $text = @fgets($handle) . $text; if ($beginning) { break; } } return $text; } /** * Sets the paths to the log files. * * @param string $accessLogPath * @param string $requestLogPath * @param string $errorLogPath * @param string $debugLogPath */ public function setLogFilePaths($accessLogPath, $requestLogPath, $errorLogPath, $debugLogPath) { if (!empty($accessLogPath)) { $this->logFiles[self::LOGTYPE_ACCESS]['path'] = $accessLogPath; } if (!empty($requestLogPath)) { $this->logFiles[self::LOGTYPE_REQUEST]['path'] = $requestLogPath; } if (!empty($errorLogPath)) { $this->logFiles[self::LOGTYPE_ERROR]['path'] = $errorLogPath; } if (!empty($debugLogPath)) { $this->logFiles[self::LOGTYPE_DEBUG]['path'] = $debugLogPath; } } /** * Opens log file handles for the requested log type if necessary. * * Already opened file handles will not be opened again. * * @param string $type The log type, that would be one of the self::LOGTYPE_* constants. * * @return bool true if opening succeeds or the handle is already open; false on error. */ protected function openLogFileHandle($type) { // don't open file handle if already open if (!empty($this->logFiles[$type]['handle'])) { return true; } // set the file handle $this->logFiles[$type]['handle'] = @fopen($this->logFiles[$type]['path'], $this->logFiles[$type]['mode']); // if log files are not writeable continue silently to the next handle // TODO: This seems a bit too silent... How could we get notice of the error? if ($this->logFiles[$type]['handle'] === false) { return false; } return true; } public function keepDebugLog($keep) { if ($keep) { $this->logFiles[self::LOGTYPE_DEBUG]["mode"] = "a+"; } else { $this->logFiles[self::LOGTYPE_DEBUG]["mode"] = "w+"; } } /** * @return mixed[] */ public function getLogFiles() { return $this->logFiles; } }
gpl-2.0
pablanco/taskManager
Android/FlexibleClient/src/com/artech/controls/IGridView.java
756
package com.artech.controls; import com.artech.actions.UIContext; import com.artech.base.metadata.ActionDefinition; import com.artech.base.model.Entity; import com.artech.controllers.ViewData; import com.artech.usercontrols.IGxUserControl; /** * This interface should be implemented for each user control that can be used in a Grid. * @author GMilano * */ public interface IGridView extends IGxUserControl { void addListener(GridEventsListener listener); void update(ViewData data); interface GridEventsListener { UIContext getHostUIContext(); void requestMoreData(); boolean runAction(UIContext context, ActionDefinition action, Entity entity); boolean runDefaultAction(UIContext context, Entity entity); } }
gpl-2.0
Juanjors/LeagueOfSummoners
src/main/java/com/leagueofsummoners/model/dto/riotapi/RiotApiParticipant.java
1409
package com.leagueofsummoners.model.dto.riotapi; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; /* Autores= Juan José Ramírez & Isidoro Martín Fecha= Junio de 2016 Licencia= gp130 Version= 1.0 Descripcion= Proyecto final desarrollo de aplicaciones web. League of Summoners es una aplicación enfocada a los jugadores del popular juego League of Legends, usando esta aplicación podrán acceder a guías, detalles sobre campeones e incluso sus últimas partidas. Copyright (C) 2016 Juan José Ramírez & Isidoro Martín 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/>. */ /** * Este bean representa los datos según los sirve el API de RIOT */ @JsonIgnoreProperties(ignoreUnknown = true) @Data public class RiotApiParticipant { private long championId; private RiotApiParticipantStats stats; }
gpl-2.0
H0zen/M2-server
src/game/ChatCommands/Level4.cpp
18819
/** * MaNGOS is a full featured server for World of Warcraft, supporting * the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8 * * Copyright (C) 2005-2019 MaNGOS project <https://getmangos.eu> * * 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 * * World of Warcraft, and all World of Warcraft or Warcraft art, images, * and lore are copyrighted by Blizzard Entertainment, Inc. */ /// \addtogroup mangosd /// @{ /// \file #include "Common.h" #include "Language.h" #include "Log.h" #include "World.h" #include "ObjectMgr.h" #include "WorldSession.h" #include "Config/Config.h" #include "Util.h" #include "AccountMgr.h" #include "MapManager.h" #include "Player.h" #include "Chat.h" /// Delete a user account and all associated characters in this realm /// \todo This function has to be enhanced to respect the login/realm split (delete char, delete account chars in realm, delete account chars in realm then delete account bool ChatHandler::HandleAccountDeleteCommand(char* args) { if (!*args) { return false; } std::string account_name; uint32 account_id = ExtractAccountId(&args, &account_name); if (!account_id) { return false; } /// Commands not recommended call from chat, but support anyway /// can delete only for account with less security /// This is also reject self apply in fact if (HasLowerSecurityAccount(NULL, account_id, true)) { return false; } AccountOpResult result = sAccountMgr.DeleteAccount(account_id); switch (result) { case AOR_OK: PSendSysMessage(LANG_ACCOUNT_DELETED, account_name.c_str()); break; case AOR_NAME_NOT_EXIST: PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, account_name.c_str()); SetSentErrorMessage(true); return false; case AOR_DB_INTERNAL_ERROR: PSendSysMessage(LANG_ACCOUNT_NOT_DELETED_SQL_ERROR, account_name.c_str()); SetSentErrorMessage(true); return false; default: PSendSysMessage(LANG_ACCOUNT_NOT_DELETED, account_name.c_str()); SetSentErrorMessage(true); return false; } return true; } /** * Collects all GUIDs (and related info) from deleted characters which are still in the database. * * @param foundList a reference to an std::list which will be filled with info data * @param searchString the search string which either contains a player GUID (low part) or a part of the character-name * @return returns false if there was a problem while selecting the characters (e.g. player name not normalizeable) */ bool ChatHandler::GetDeletedCharacterInfoList(DeletedInfoList& foundList, std::string searchString) { QueryResult* resultChar; if (!searchString.empty()) { // search by GUID if (isNumeric(searchString)) { resultChar = CharacterDatabase.PQuery("SELECT guid, deleteInfos_Name, deleteInfos_Account, deleteDate FROM characters WHERE deleteDate IS NOT NULL AND guid = %u", uint32(atoi(searchString.c_str()))); } // search by name else { if (!normalizePlayerName(searchString)) { return false; } resultChar = CharacterDatabase.PQuery("SELECT guid, deleteInfos_Name, deleteInfos_Account, deleteDate FROM characters WHERE deleteDate IS NOT NULL AND deleteInfos_Name " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%'"), searchString.c_str()); } } else { resultChar = CharacterDatabase.Query("SELECT guid, deleteInfos_Name, deleteInfos_Account, deleteDate FROM characters WHERE deleteDate IS NOT NULL"); } if (resultChar) { do { Field* fields = resultChar->Fetch(); DeletedInfo info; info.lowguid = fields[0].GetUInt32(); info.name = fields[1].GetCppString(); info.accountId = fields[2].GetUInt32(); // account name will be empty for nonexistent account sAccountMgr.GetName(info.accountId, info.accountName); info.deleteDate = time_t(fields[3].GetUInt64()); foundList.push_back(info); } while (resultChar->NextRow()); delete resultChar; } return true; } /** * Generate WHERE guids list by deleted info in way preventing return too long where list for existed query string length limit. * * @param itr a reference to an deleted info list iterator, it updated in function for possible next function call if list to long * @param itr_end a reference to an deleted info list iterator end() * @return returns generated where list string in form: 'guid IN (gui1, guid2, ...)' */ std::string ChatHandler::GenerateDeletedCharacterGUIDsWhereStr(DeletedInfoList::const_iterator& itr, DeletedInfoList::const_iterator const& itr_end) { std::ostringstream wherestr; wherestr << "guid IN ('"; for (; itr != itr_end; ++itr) { wherestr << itr->lowguid; if (wherestr.str().size() > MAX_QUERY_LEN - 50) // near to max query { ++itr; break; } DeletedInfoList::const_iterator itr2 = itr; if (++itr2 != itr_end) { wherestr << "','"; } } wherestr << "')"; return wherestr.str(); } /** * Shows all deleted characters which matches the given search string, expected non empty list * * @see ChatHandler::HandleCharacterDeletedListCommand * @see ChatHandler::HandleCharacterDeletedRestoreCommand * @see ChatHandler::HandleCharacterDeletedDeleteCommand * @see ChatHandler::DeletedInfoList * * @param foundList contains a list with all found deleted characters */ void ChatHandler::HandleCharacterDeletedListHelper(DeletedInfoList const& foundList) { if (!m_session) { SendSysMessage(LANG_CHARACTER_DELETED_LIST_BAR); SendSysMessage(LANG_CHARACTER_DELETED_LIST_HEADER); SendSysMessage(LANG_CHARACTER_DELETED_LIST_BAR); } for (DeletedInfoList::const_iterator itr = foundList.begin(); itr != foundList.end(); ++itr) { std::string dateStr = TimeToTimestampStr(itr->deleteDate); if (!m_session) PSendSysMessage(LANG_CHARACTER_DELETED_LIST_LINE_CONSOLE, itr->lowguid, itr->name.c_str(), itr->accountName.empty() ? "<nonexistent>" : itr->accountName.c_str(), itr->accountId, dateStr.c_str()); else PSendSysMessage(LANG_CHARACTER_DELETED_LIST_LINE_CHAT, itr->lowguid, itr->name.c_str(), itr->accountName.empty() ? "<nonexistent>" : itr->accountName.c_str(), itr->accountId, dateStr.c_str()); } if (!m_session) { SendSysMessage(LANG_CHARACTER_DELETED_LIST_BAR); } } /** * Handles the '.character deleted list' command, which shows all deleted characters which matches the given search string * * @see ChatHandler::HandleCharacterDeletedListHelper * @see ChatHandler::HandleCharacterDeletedRestoreCommand * @see ChatHandler::HandleCharacterDeletedDeleteCommand * @see ChatHandler::DeletedInfoList * * @param args the search string which either contains a player GUID or a part of the character-name */ bool ChatHandler::HandleCharacterDeletedListCommand(char* args) { DeletedInfoList foundList; if (!GetDeletedCharacterInfoList(foundList, args)) { return false; } // if no characters have been found, output a warning if (foundList.empty()) { SendSysMessage(LANG_CHARACTER_DELETED_LIST_EMPTY); return false; } HandleCharacterDeletedListHelper(foundList); return true; } /** * Restore a previously deleted character * * @see ChatHandler::HandleCharacterDeletedListHelper * @see ChatHandler::HandleCharacterDeletedRestoreCommand * @see ChatHandler::HandleCharacterDeletedDeleteCommand * @see ChatHandler::DeletedInfoList * * @param delInfo the informations about the character which will be restored */ void ChatHandler::HandleCharacterDeletedRestoreHelper(DeletedInfo const& delInfo) { if (delInfo.accountName.empty()) // account not exist { PSendSysMessage(LANG_CHARACTER_DELETED_SKIP_ACCOUNT, delInfo.name.c_str(), delInfo.lowguid, delInfo.accountId); return; } // check character count uint32 charcount = sAccountMgr.GetCharactersCount(delInfo.accountId); if (charcount >= 10) { PSendSysMessage(LANG_CHARACTER_DELETED_SKIP_FULL, delInfo.name.c_str(), delInfo.lowguid, delInfo.accountId); return; } if (sObjectMgr.GetPlayerGuidByName(delInfo.name)) { PSendSysMessage(LANG_CHARACTER_DELETED_SKIP_NAME, delInfo.name.c_str(), delInfo.lowguid, delInfo.accountId); return; } CharacterDatabase.PExecute("UPDATE characters SET name='%s', account='%u', deleteDate=NULL, deleteInfos_Name=NULL, deleteInfos_Account=NULL WHERE deleteDate IS NOT NULL AND guid = %u", delInfo.name.c_str(), delInfo.accountId, delInfo.lowguid); } /** * Handles the '.character deleted restore' command, which restores all deleted characters which matches the given search string * * The command automatically calls '.character deleted list' command with the search string to show all restored characters. * * @see ChatHandler::HandleCharacterDeletedRestoreHelper * @see ChatHandler::HandleCharacterDeletedListCommand * @see ChatHandler::HandleCharacterDeletedDeleteCommand * * @param args the search string which either contains a player GUID or a part of the character-name */ bool ChatHandler::HandleCharacterDeletedRestoreCommand(char* args) { // It is required to submit at least one argument if (!*args) { return false; } std::string searchString; std::string newCharName; uint32 newAccount = 0; // GCC by some strange reason fail build code without temporary variable std::istringstream params(args); params >> searchString >> newCharName >> newAccount; DeletedInfoList foundList; if (!GetDeletedCharacterInfoList(foundList, searchString)) { return false; } if (foundList.empty()) { SendSysMessage(LANG_CHARACTER_DELETED_LIST_EMPTY); return false; } SendSysMessage(LANG_CHARACTER_DELETED_RESTORE); HandleCharacterDeletedListHelper(foundList); if (newCharName.empty()) { // Drop nonexistent account cases for (DeletedInfoList::iterator itr = foundList.begin(); itr != foundList.end(); ++itr) { HandleCharacterDeletedRestoreHelper(*itr); } } else if (foundList.size() == 1 && normalizePlayerName(newCharName)) { DeletedInfo delInfo = foundList.front(); // update name delInfo.name = newCharName; // if new account provided update deleted info if (newAccount && newAccount != delInfo.accountId) { delInfo.accountId = newAccount; sAccountMgr.GetName(newAccount, delInfo.accountName); } HandleCharacterDeletedRestoreHelper(delInfo); } else { SendSysMessage(LANG_CHARACTER_DELETED_ERR_RENAME); } return true; } /** * Handles the '.character deleted delete' command, which completely deletes all deleted characters which matches the given search string * * @see Player::GetDeletedCharacterGUIDs * @see Player::DeleteFromDB * @see ChatHandler::HandleCharacterDeletedListCommand * @see ChatHandler::HandleCharacterDeletedRestoreCommand * * @param args the search string which either contains a player GUID or a part of the character-name */ bool ChatHandler::HandleCharacterDeletedDeleteCommand(char* args) { // It is required to submit at least one argument if (!*args) { return false; } DeletedInfoList foundList; if (!GetDeletedCharacterInfoList(foundList, args)) { return false; } if (foundList.empty()) { SendSysMessage(LANG_CHARACTER_DELETED_LIST_EMPTY); return false; } SendSysMessage(LANG_CHARACTER_DELETED_DELETE); HandleCharacterDeletedListHelper(foundList); // Call the appropriate function to delete them (current account for deleted characters is 0) for (DeletedInfoList::const_iterator itr = foundList.begin(); itr != foundList.end(); ++itr) { Player::DeleteFromDB(ObjectGuid(HIGHGUID_PLAYER, itr->lowguid), 0, false, true); } return true; } /** * Handles the '.character deleted old' command, which completely deletes all deleted characters deleted with some days ago * * @see Player::DeleteOldCharacters * @see Player::DeleteFromDB * @see ChatHandler::HandleCharacterDeletedDeleteCommand * @see ChatHandler::HandleCharacterDeletedListCommand * @see ChatHandler::HandleCharacterDeletedRestoreCommand * * @param args the search string which either contains a player GUID or a part of the character-name */ bool ChatHandler::HandleCharacterDeletedOldCommand(char* args) { int32 keepDays = sWorld.getConfig(CONFIG_UINT32_CHARDELETE_KEEP_DAYS); if (!ExtractOptInt32(&args, keepDays, sWorld.getConfig(CONFIG_UINT32_CHARDELETE_KEEP_DAYS))) { return false; } if (keepDays < 0) { return false; } Player::DeleteOldCharacters((uint32)keepDays); return true; } bool ChatHandler::HandleCharacterEraseCommand(char* args) { char* nameStr = ExtractLiteralArg(&args); if (!nameStr) { return false; } Player* target; ObjectGuid target_guid; std::string target_name; if (!ExtractPlayerTarget(&nameStr, &target, &target_guid, &target_name)) { return false; } uint32 account_id; if (target) { account_id = target->GetSession()->GetAccountId(); target->GetSession()->KickPlayer(); } else { account_id = sObjectMgr.GetPlayerAccountIdByGUID(target_guid); } std::string account_name; sAccountMgr.GetName(account_id, account_name); Player::DeleteFromDB(target_guid, account_id, true, true); PSendSysMessage(LANG_CHARACTER_DELETED, target_name.c_str(), target_guid.GetCounter(), account_name.c_str(), account_id); return true; } /// Close RA connection bool ChatHandler::HandleQuitCommand(char* /*args*/) { // processed in RASocket SendSysMessage(LANG_QUIT_WRONG_USE_ERROR); return true; } /// Exit the realm bool ChatHandler::HandleServerExitCommand(char* /*args*/) { SendSysMessage(LANG_COMMAND_EXIT); World::StopNow(SHUTDOWN_EXIT_CODE); return true; } /// Display info on users currently in the realm bool ChatHandler::HandleAccountOnlineListCommand(char* args) { uint32 limit; if (!ExtractOptUInt32(&args, limit, 100)) { return false; } ///- Get the list of accounts ID logged to the realm // 0 1 2 3 4 QueryResult* result = LoginDatabase.PQuery("SELECT id, username, last_ip, gmlevel, expansion FROM account WHERE active_realm_id = %u", realmID); return ShowAccountListHelper(result, &limit); } /// Create an account bool ChatHandler::HandleAccountCreateCommand(char* args) { ///- %Parse the command line arguments char* szAcc = ExtractQuotedOrLiteralArg(&args); char* szPassword = ExtractQuotedOrLiteralArg(&args); if (!szAcc || !szPassword) { return false; } // normalized in accmgr.CreateAccount std::string account_name = szAcc; std::string password = szPassword; AccountOpResult result; uint32 expansion = 0; if(ExtractUInt32(&args, expansion)) result = sAccountMgr.CreateAccount(account_name, password, expansion); else result = sAccountMgr.CreateAccount(account_name, password); switch (result) { case AOR_OK: PSendSysMessage(LANG_ACCOUNT_CREATED, account_name.c_str()); break; case AOR_NAME_TOO_LONG: SendSysMessage(LANG_ACCOUNT_TOO_LONG); SetSentErrorMessage(true); return false; case AOR_NAME_ALREADY_EXIST: SendSysMessage(LANG_ACCOUNT_ALREADY_EXIST); SetSentErrorMessage(true); return false; case AOR_DB_INTERNAL_ERROR: PSendSysMessage(LANG_ACCOUNT_NOT_CREATED_SQL_ERROR, account_name.c_str()); SetSentErrorMessage(true); return false; default: PSendSysMessage(LANG_ACCOUNT_NOT_CREATED, account_name.c_str()); SetSentErrorMessage(true); return false; } return true; } /// Set the filters of logging bool ChatHandler::HandleServerLogFilterCommand(char* args) { if (!*args) { SendSysMessage(LANG_LOG_FILTERS_STATE_HEADER); for (int i = 0; i < LOG_FILTER_COUNT; ++i) if (*logFilterData[i].name) { PSendSysMessage(" %-20s = %s", logFilterData[i].name, GetOnOffStr(sLog.HasLogFilter(1 << i))); } return true; } char* filtername = ExtractLiteralArg(&args); if (!filtername) { return false; } bool value; if (!ExtractOnOff(&args, value)) { SendSysMessage(LANG_USE_BOL); SetSentErrorMessage(true); return false; } if (strncmp(filtername, "all", 4) == 0) { sLog.SetLogFilter(LogFilters(0xFFFFFFFF), value); PSendSysMessage(LANG_ALL_LOG_FILTERS_SET_TO_S, GetOnOffStr(value)); return true; } for (int i = 0; i < LOG_FILTER_COUNT; ++i) { if (!*logFilterData[i].name) { continue; } if (!strncmp(filtername, logFilterData[i].name, strlen(filtername))) { sLog.SetLogFilter(LogFilters(1 << i), value); PSendSysMessage(" %-20s = %s", logFilterData[i].name, GetOnOffStr(value)); return true; } } return false; } /// Set the level of logging bool ChatHandler::HandleServerLogLevelCommand(char* args) { if (!*args) { PSendSysMessage("Log level: %u", sLog.GetLogLevel()); return true; } sLog.SetLogLevel(args); return true; } /// @}
gpl-2.0
MARFMS/OwnCloud_NAC
apps/contacts/l10n/es_AR.php
13917
<?php $TRANSLATIONS = array( "Error (de)activating addressbook." => "Error al (des)activar la agenda.", "id is not set." => "La ID no fue asignada.", "Cannot update addressbook with an empty name." => "No se puede actualizar una libreta de direcciones sin nombre.", "No category name given." => "No se a dado un nombre a la categoría.", "Error adding group." => "Error al añadir grupo", "Group ID missing from request." => "ID de grupo faltante en la solicitud.", "Contact ID missing from request." => "ID de contacto faltante en la solicitud.", "No ID provided" => "No fue proporcionada una ID", "Error setting checksum." => "Error al establecer la suma de verificación -checksum-.", "No categories selected for deletion." => "No se seleccionaron categorías para borrar.", "No address books found." => "No se encontraron agendas.", "No contacts found." => "No se encontraron contactos.", "element name is not set." => "el nombre del elemento no fue asignado.", "checksum is not set." => "la suma de comprobación no fue asignada.", "Information about vCard is incorrect. Please reload the page." => "La información sobre la vCard es incorrecta. Por favor, cargá nuevamente la página", "Couldn't find vCard for %d." => "No se pudo encontrar vCard para %d", "Information about vCard is incorrect. Please reload the page: " => "La información sobre la vCard es incorrecta. Por favor, recargá la página:", "Something went FUBAR. " => "Hubo un error irreparable.", "Cannot save property of type \"%s\" as array" => "No se puede guardar la propiedad del tipo \"%s\" como un arreglo", "Missing IM parameter." => "Falta un parámetro del MI.", "Unknown IM: " => "MI desconocido:", "No contact ID was submitted." => "No se mandó ninguna ID de contacto.", "Error reading contact photo." => "Error leyendo la imagen del contacto.", "Error saving temporary file." => "Error al guardar archivo temporal.", "The loading photo is not valid." => "La imagen que se estaba cargando no es válida.", "Contact ID is missing." => "Falta la ID del contacto.", "No photo path was submitted." => "La ruta de la imagen no fue enviada", "File doesn't exist:" => "El archivo no existe:", "Error loading image." => "Error cargando imagen.", "Error getting contact object." => "Error al obtener el contacto.", "Error getting PHOTO property." => "Error al obtener la propiedades de la foto.", "Error saving contact." => "Error al guardar el contacto.", "Error resizing image" => "Error al cambiar el tamaño de la imagen", "Error cropping image" => "Error al recortar la imagen", "Error creating temporary image" => "Error al crear una imagen temporal", "Error finding image: " => "Error al encontrar la imagen", "Key is not set for: " => "La clave no esta asignada para:", "Value is not set for: " => "El valor no esta asignado para:", "Could not set preference: " => "No se pudo asignar la preferencia:", "Error uploading contacts to storage." => "Error al subir contactos al almacenamiento.", "There is no error, the file uploaded with success" => "No hay errores, el archivo fue subido con éxito", "The uploaded file exceeds the upload_max_filesize directive in php.ini" => "El archivo subido excede el valor 'upload_max_filesize' del archivo de configuración php.ini", "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" => "El archivo subido sobrepasa el valor MAX_FILE_SIZE especificada en el formulario HTML", "The uploaded file was only partially uploaded" => "El archivo fue subido parcialmente", "No file was uploaded" => "No se subió ningún archivo ", "Missing a temporary folder" => "Error en la carpera temporal", "Couldn't save temporary image: " => "No fue posible guardar la imagen temporal", "Couldn't load temporary image: " => "No se pudo cargar la imagen temporal", "No file was uploaded. Unknown error" => "El archivo no fue subido. Error desconocido", "Contacts" => "Contactos", "%d_selected_contacts" => "%d_selected_contacts", "Add to..." => "Añadir a...", "Remove from..." => "Borrar de...", "Add group..." => "Añadir grupo", "Indexing contacts" => "Indexando contactos", "Select photo" => "Seleccionar una imagen", "Network or server error. Please inform administrator." => "Error en la red o en el servidor. Por favor informe al administrador.", "Error adding to group." => "Error al añadir al grupo.", "Error removing from group." => "Error al quitar del grupo.", "There was an error opening a mail composer." => "Hubo un error al abrir el escritor de correo electrónico", "Deleting done. Click here to cancel reloading." => "Borrado completo. Haga click para cancerla la recarga. ", "Add address book" => "Añadir agenda", "Import done. Click here to cancel reloading." => "Importación completa. Haga click para cancerla la recarga. ", "Not all files uploaded. Retrying..." => "No fue posible subir todos los archivos. Reintentando...", "Something went wrong with the upload, please retry." => "Algo salió mal durante la subida. Por favor, intentalo nuevamente.", "Error" => "Error", "Importing from {filename}..." => "Importando de {filename}...", "{success} imported, {failed} failed." => "{success} importados, {failed} fallidos.", "Importing..." => "Importando...", "Unable to upload your file as it is a directory or has 0 bytes" => "No fue posible subir el archivo porque es un directorio o porque su tamaño es 0 bytes", "Upload Error" => "Error al subir", "The file you are trying to upload exceed the maximum size for file uploads on this server." => "El archivo que querés subir supera el tamaño máximo permitido en este servidor.", "Upload too large" => "El tamaño del archivo que querés subir es demasiado grande", "Pending" => "Pendientes", "Add group" => "Agregar grupo", "No files selected for upload." => "No hay archivos seleccionados para subir", "Edit profile picture" => "Editar foto de perfil", "Error loading profile picture." => "Error al cargar la imagen del perfil.", "Enter name" => "Escribir nombre", "Enter description" => "Escribir descripción", "Select addressbook" => "Seleccionar agenda", "The address book name cannot be empty." => "El nombre de la agenda no puede estar vacío.", "Is this correct?" => "¿Es esto correcto?", "There was an unknown error when trying to delete this contact" => "Hubo un error desconocido tratando de borrar este contacto", "# groups" => "# grupos", "Some contacts are marked for deletion, but not deleted yet. Please wait for them to be deleted." => "Algunos contactos fuero marcados para ser borrados, pero no fueron borrados todavía. Esperá que lo sean.", "Click to undo deletion of {num} contacts" => "Click para deshacer el borrado de {num} contactos", "Cancelled deletion of {num}" => "Cancelado el borrado de {num}", "Contact is already in this group." => "El contacto ya se encuentra en este grupo", "Contacts are already in this group." => "Los contactos ya se encuentran en este grupo", "Couldn't get contact list." => "No se pudo obtener la lista de contactos.", "Contact is not in this group." => "El contacto no se encuentra en este grupo.", "Contacts are not in this group." => "Los contactos ya se encuentran en este grupo. ", "A group named {group} already exists" => "Un grupo llamado {grup} ya existe", "You can drag groups to\narrange them as you like." => "Podés arrastrar los grupos para \narreglarlos como quieras.", "All" => "Todos", "Favorites" => "Favoritos", "Shared by {owner}" => "Compartidos por {owner}", "Result: " => "Resultado:", " imported, " => "Importado.", " failed." => "error.", "Displayname cannot be empty." => "El nombre a mostrar no puede quedar en blanco", "Show CardDav link" => "Mostrar enlace CardDAV", "Show read-only VCF link" => "Mostrar enlace VCF de sólo lectura", "Download" => "Descargar", "Edit" => "Editar", "Delete" => "Borrar", "Cancel" => "Cancelar", "More..." => "Más...", "Less..." => "Menos...", "You do not have the permissions to read this addressbook." => "No tenés permiso para leer esta agenda.", "You do not have the permissions to update this addressbook." => "No tenés permisos para actualizar esta agenda.", "There was an error updating the addressbook." => "Hubo un error mientras se actualizaba la agenda.", "You do not have the permissions to delete this addressbook." => "No tenés permisos para borrar esta agenda.", "There was an error deleting this addressbook." => "Hubo un error mientras se borraba esta agenda.", "Jabber" => "Jabber", "AIM" => "AIM", "MSN" => "MSN", "Twitter" => "Twitter", "GoogleTalk" => "GoogleTalk", "Facebook" => "Facebook", "XMPP" => "XMPP", "ICQ" => "ICQ", "Yahoo" => "Yahoo", "Skype" => "Skype", "QQ" => "QQ", "GaduGadu" => "GaduGadu", "Work" => "Trabajo", "Home" => "Particular", "Other" => "Otros", "Mobile" => "Celular", "Text" => "Texto", "Voice" => "Voz", "Message" => "Mensaje", "Fax" => "Fax", "Video" => "Video", "Pager" => "Pager", "Internet" => "Internet", "Friends" => "Amigos", "Family" => "Familia", "There was an error deleting properties for this contact." => "Hubo un error al borrar las propiedades de este contacto", "{name}'s Birthday" => "Cumpleaños de {name}", "Contact" => "Contacto", "You do not have the permissions to add contacts to this addressbook." => "No tenés permisos para agregar contactos a esta agenda.", "Could not find the vCard with ID." => "No fue posible encontrar la vCard con ID.", "You do not have the permissions to edit this contact." => "No tenés permisos para editar este contacto.", "Could not find the vCard with ID: " => "No fue posible encontrar la agenda con ID:", "Could not find the Addressbook with ID: " => "No fue posible encontrar la agenda con ID:", "You do not have the permissions to delete this contact." => "No tenés permisos para borrar este contacto.", "There was an error deleting this contact." => "Hubo un error mientras se borraba este contacto.", "Contact not found." => "No se pudo encontrar el contacto", "HomePage" => "Pagina de inicio", "New Group" => "Nuevo grupo", "Settings" => "Configuración", "Address books" => "Agendas", "Import" => "Importar", "Select files to import" => "Seleccionar archivos para importar", "Select files" => "Seleccionar archivos", "Import into:" => "Importar a:", "OK" => "Aceptar", "(De-)select all" => "(De)selecionar todos", "New Contact" => "Nuevo contato", "Download Contact(s)" => "Descargar contacto(s)", "Groups" => "Grupos", "Favorite" => "Favorito", "Delete Contact" => "Borrar contacto", "Close" => "cerrar", "Keyboard shortcuts" => "Atajos de teclado", "Navigation" => "Navegación", "Next contact in list" => "Contacto siguiente en la lista", "Previous contact in list" => "Contacto anterior en la lista", "Expand/collapse current addressbook" => "Expandir/colapsar la agenda", "Next addressbook" => "Siguiente agenda", "Previous addressbook" => "Agenda anterior", "Actions" => "Acciones", "Refresh contacts list" => "Refrescar la lista de contactos", "Add new contact" => "Agregar un nuevo contacto", "Add new addressbook" => "Agregar nueva agenda", "Delete current contact" => "Borrar el contacto seleccionado", "<h3>You have no contacts in your addressbook.</h3><p>Add a new contact or import existing contacts from a VCF file.</p>" => "<h3> No tenes contactos en tu agenda.</h3><p>Agregá un nuevo contacto o importalo desde un contacto existente en un archivo VCF.</p>", "Add contact" => "Agregar contacto", "Compose mail" => "Escribir un correo", "Delete group" => "Borrar grupo", "Delete current photo" => "Eliminar imagen actual", "Edit current photo" => "Editar imagen actual", "Upload new photo" => "Subir nueva imagen", "Select photo from ownCloud" => "Seleccionar imagen desde ownCloud", "First name" => "Nombre", "Additional names" => "Segundo nombre", "Last name" => "Apellido", "Select groups" => "Seleccionar grupos", "Nickname" => "Sobrenombre", "Enter nickname" => "Escribí un sobrenombre", "Title" => "Título", "Enter title" => "Ingrese titulo", "Organization" => "Organización", "Enter organization" => "Ingrese organización", "Birthday" => "Cumpleaños", "Notes go here..." => "Las notas van aquí", "Export as VCF" => "Exportar como VCF", "Add" => "Agregar", "Phone" => "Teléfono", "Email" => "Correo Electrónico", "Instant Messaging" => "Mensajería instantánea", "Address" => "Dirección", "Note" => "Nota", "Web site" => "Página web", "Delete contact" => "Borrar contacto", "Preferred" => "Preferido", "Please specify a valid email address." => "Por favor, escribí una dirección de correo electrónico válida.", "[email protected]" => "[email protected]", "Mail to address" => "Enviar por correo electrónico a la dirección", "Delete email address" => "Eliminar dirección de correo electrónico", "Enter phone number" => "Escribí un número de teléfono", "Delete phone number" => "Eliminar número de teléfono", "Go to web site" => "Ir al sitio web", "Delete URL" => "Borrar URL", "View on map" => "Ver en el mapa", "Delete address" => "Borrar dirección", "1 Main Street" => "Calle principal 1", "Street address" => "Calle de la dirección", "12345" => "12345", "Postal code" => "Código postal", "Your city" => "Tu ciudad", "City" => "Ciudad", "Some region" => "Alguna región", "State or province" => "Estado o provincia", "Your country" => "Tu país", "Country" => "País", "Instant Messenger" => "Mensajero instantáneo", "Delete IM" => "Eliminar IM", "Share" => "Compartir", "Export" => "Exportar", "CardDAV link" => "Enlace a CardDAV", "The temporary image has been removed from cache." => "La imagen temporal fue borrada de la caché", "CardDAV syncing addresses" => "CardDAV está sincronizando direcciones", "more info" => "más información", "Primary address (Kontact et al)" => "Dirección primaria (Kontact y semejantes)", "iOS/OS X" => "iOS/OS X", "Addressbooks" => "Agendas", "New Address Book" => "Nueva agenda", "Name" => "Nombre", "Description" => "Descripción", "Save" => "Guardar" );
gpl-2.0
Adai0808/SummyChou
BlogforSummyChou/articles/migrations/0001_initial.py
1345
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('blog', '0001_initial'), ] operations = [ migrations.CreateModel( name='Article', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('title', models.CharField(max_length=100, verbose_name='\u6807\u9898')), ('brief', models.CharField(max_length=1000, verbose_name='\u7b80\u4ecb')), ('tag', models.CharField(max_length=200, verbose_name='\u6982\u8981')), ('create_timestamp', models.DateTimeField(auto_now_add=True)), ('last_update_timestamp', models.DateTimeField(auto_now=True)), ('label', models.ForeignKey(verbose_name='\u6807\u7b7e', to='blog.Block')), ('owner', models.ForeignKey(verbose_name='\u4f5c\u8005', to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name': '\u6587\u7ae0\u6807\u9898', 'verbose_name_plural': '\u6587\u7ae0\u6807\u9898', }, ), ]
gpl-2.0
magnusvaughan/emmettphotography
wp-content/plugins/easy-google-fonts/views/customizer/control/positioning/border-radius/left.php
1235
<?php /** * Bottom Left Border Radius Control * * Outputs a jquery ui slider to allow the * user to control the bottom left border-radius * of an element. * * @package Easy_Google_Fonts * @author Sunny Johal - Titanium Themes <[email protected]> * @license GPL-2.0+ * @link http://wordpress.org/plugins/easy-google-fonts/ * @copyright Copyright (c) 2015, Titanium Themes * @version 1.3.5 * */ ?> <# // Get settings and defaults. var egfBorderRadiusBottomLeft = typeof egfSettings.border_radius_bottom_left !== "undefined" ? egfSettings.border_radius_bottom_left : data.egf_defaults.border_radius_bottom_left; #> <div class="egf-font-slider-control egf-border-radius-bottom-left-slider"> <span class="egf-slider-title"><?php _e( 'Bottom Left', 'easy-google-fonts' ); ?></span> <div class="egf-font-slider-display"> <span>{{ egfBorderRadiusBottomLeft.amount }}{{ data.egf_defaults.border_radius_bottom_left.unit }}</span> | <a class="egf-font-slider-reset" href="#"><?php _e( 'Reset', 'easy-google-fonts' ); ?></a> </div> <div class="egf-clear" ></div> <!-- Slider --> <div class="egf-slider" value="{{ egfBorderRadiusBottomLeft.amount }}"></div> <div class="egf-clear"></div> </div>
gpl-2.0
IvanSantiago/retopublico
LocationPoller.2/demo/gen/com/commonsware/cwac/locpoll/demo/BuildConfig.java
175
/** Automatically generated file. DO NOT MODIFY */ package com.commonsware.cwac.locpoll.demo; public final class BuildConfig { public final static boolean DEBUG = true; }
gpl-2.0
Remix99/MaNGOS
src/shared/Log.cpp
21523
/* * Copyright (C) 2005-2012 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 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 */ #include "Common.h" #include "Log.h" #include "Policies/SingletonImp.h" #include "Config/Config.h" #include "Util.h" #include "ByteBuffer.h" #include "ProgressBar.h" #include <stdarg.h> #include <fstream> #include <iostream> #include "ace/OS_NS_unistd.h" INSTANTIATE_SINGLETON_1( Log ); LogFilterData logFilterData[LOG_FILTER_COUNT] = { { "transport_moves", "LogFilter_TransportMoves", true }, { "creature_moves", "LogFilter_CreatureMoves", true }, { "visibility_changes", "LogFilter_VisibilityChanges", true }, { "achievement_updates", "LogFilter_AchievementUpdates", true }, { "weather", "LogFilter_Weather", true }, { "player_stats", "LogFilter_PlayerStats", false }, { "sql_text", "LogFilter_SQLText", false }, { "player_moves", "LogFilter_PlayerMoves", false }, { "periodic_effects", "LogFilter_PeriodicAffects", false }, { "ai_and_movegens", "LogFilter_AIAndMovegens", false }, { "damage", "LogFilter_Damage", false }, { "combat", "LogFilter_Combat", false }, { "spell_cast", "LogFilter_SpellCast", false }, { "db_stricted_check", "LogFilter_DbStrictedCheck", true }, { "ahbot_seller", "LogFilter_AhbotSeller", true }, { "ahbot_buyer", "LogFilter_AhbotBuyer", true }, { "pathfinding", "LogFilter_Pathfinding", true }, }; enum LogType { LogNormal = 0, LogDetails, LogDebug, LogError }; const int LogType_count = int(LogError) +1; Log::Log() : raLogfile(NULL), logfile(NULL), gmLogfile(NULL), charLogfile(NULL), dberLogfile(NULL), m_colored(false), m_includeTime(false), m_gmlog_per_account(false) { Initialize(); } void Log::InitColors(const std::string& str) { if (str.empty()) { m_colored = false; return; } int color[4]; std::istringstream ss(str); for(int i = 0; i < LogType_count; ++i) { ss >> color[i]; if(!ss) return; if(color[i] < 0 || color[i] >= Color_count) return; } for(int i = 0; i < LogType_count; ++i) m_colors[i] = Color(color[i]); m_colored = true; } void Log::SetColor(bool stdout_stream, Color color) { #if PLATFORM == PLATFORM_WINDOWS static WORD WinColorFG[Color_count] = { 0, // BLACK FOREGROUND_RED, // RED FOREGROUND_GREEN, // GREEN FOREGROUND_RED | FOREGROUND_GREEN, // BROWN FOREGROUND_BLUE, // BLUE FOREGROUND_RED | FOREGROUND_BLUE,// MAGENTA FOREGROUND_GREEN | FOREGROUND_BLUE, // CYAN FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,// WHITE // YELLOW FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY, // RED_BOLD FOREGROUND_RED | FOREGROUND_INTENSITY, // GREEN_BOLD FOREGROUND_GREEN | FOREGROUND_INTENSITY, FOREGROUND_BLUE | FOREGROUND_INTENSITY, // BLUE_BOLD // MAGENTA_BOLD FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY, // CYAN_BOLD FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY, // WHITE_BOLD FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY }; HANDLE hConsole = GetStdHandle(stdout_stream ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE ); SetConsoleTextAttribute(hConsole, WinColorFG[color]); #else enum ANSITextAttr { TA_NORMAL=0, TA_BOLD=1, TA_BLINK=5, TA_REVERSE=7 }; enum ANSIFgTextAttr { FG_BLACK=30, FG_RED, FG_GREEN, FG_BROWN, FG_BLUE, FG_MAGENTA, FG_CYAN, FG_WHITE, FG_YELLOW }; enum ANSIBgTextAttr { BG_BLACK=40, BG_RED, BG_GREEN, BG_BROWN, BG_BLUE, BG_MAGENTA, BG_CYAN, BG_WHITE }; static uint8 UnixColorFG[Color_count] = { FG_BLACK, // BLACK FG_RED, // RED FG_GREEN, // GREEN FG_BROWN, // BROWN FG_BLUE, // BLUE FG_MAGENTA, // MAGENTA FG_CYAN, // CYAN FG_WHITE, // WHITE FG_YELLOW, // YELLOW FG_RED, // LRED FG_GREEN, // LGREEN FG_BLUE, // LBLUE FG_MAGENTA, // LMAGENTA FG_CYAN, // LCYAN FG_WHITE // LWHITE }; fprintf((stdout_stream? stdout : stderr), "\x1b[%d%sm",UnixColorFG[color],(color>=YELLOW&&color<Color_count ?";1":"")); #endif } void Log::ResetColor(bool stdout_stream) { #if PLATFORM == PLATFORM_WINDOWS HANDLE hConsole = GetStdHandle(stdout_stream ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE ); SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED ); #else fprintf(( stdout_stream ? stdout : stderr ), "\x1b[0m"); #endif } void Log::SetLogLevel(char* level) { int32 newLevel =atoi((char*)level); if (newLevel < LOG_LVL_MINIMAL) newLevel = LOG_LVL_MINIMAL; else if (newLevel > LOG_LVL_DEBUG) newLevel = LOG_LVL_DEBUG; m_logLevel = LogLevel(newLevel); printf("LogLevel is %u\n", m_logLevel); } void Log::SetLogFileLevel(char* level) { int32 newLevel =atoi((char*)level); if (newLevel < LOG_LVL_MINIMAL) newLevel = LOG_LVL_MINIMAL; else if (newLevel > LOG_LVL_DEBUG) newLevel = LOG_LVL_DEBUG; m_logFileLevel = LogLevel(newLevel); printf("LogFileLevel is %u\n", m_logFileLevel); } void Log::Initialize() { /// Common log files data m_logsDir = sConfig.GetStringDefault("LogsDir",""); if (!m_logsDir.empty()) { if ((m_logsDir.at(m_logsDir.length()-1)!='/') && (m_logsDir.at(m_logsDir.length()-1)!='\\')) m_logsDir.append("/"); } m_logsTimestamp = "_" + GetTimestampStr(); /// Open specific log files logfile = openLogFile("LogFile","LogTimestamp","w"); m_gmlog_per_account = sConfig.GetBoolDefault("GmLogPerAccount",false); if (!m_gmlog_per_account) gmLogfile = openLogFile("GMLogFile","GmLogTimestamp","a"); else { // GM log settings for per account case m_gmlog_filename_format = sConfig.GetStringDefault("GMLogFile", ""); if (!m_gmlog_filename_format.empty()) { bool m_gmlog_timestamp = sConfig.GetBoolDefault("GmLogTimestamp",false); size_t dot_pos = m_gmlog_filename_format.find_last_of("."); if (dot_pos!=m_gmlog_filename_format.npos) { if (m_gmlog_timestamp) m_gmlog_filename_format.insert(dot_pos,m_logsTimestamp); m_gmlog_filename_format.insert(dot_pos,"_#%u"); } else { m_gmlog_filename_format += "_#%u"; if (m_gmlog_timestamp) m_gmlog_filename_format += m_logsTimestamp; } m_gmlog_filename_format = m_logsDir + m_gmlog_filename_format; } } charLogfile = openLogFile("CharLogFile","CharLogTimestamp","a"); dberLogfile = openLogFile("DBErrorLogFile",NULL,"a"); raLogfile = openLogFile("RaLogFile",NULL,"a"); worldLogfile = openLogFile("WorldLogFile","WorldLogTimestamp","a"); // Main log file settings m_includeTime = sConfig.GetBoolDefault("LogTime", false); m_logLevel = LogLevel(sConfig.GetIntDefault("LogLevel", 0)); m_logFileLevel = LogLevel(sConfig.GetIntDefault("LogFileLevel", 0)); InitColors(sConfig.GetStringDefault("LogColors", "")); m_logFilter = 0; for(int i = 0; i < LOG_FILTER_COUNT; ++i) if (*logFilterData[i].name) if (sConfig.GetBoolDefault(logFilterData[i].configName, logFilterData[i].defaultState)) m_logFilter |= (1 << i); // Char log settings m_charLog_Dump = sConfig.GetBoolDefault("CharLogDump", false); } FILE* Log::openLogFile(char const* configFileName,char const* configTimeStampFlag, char const* mode) { std::string logfn=sConfig.GetStringDefault(configFileName, ""); if (logfn.empty()) return NULL; if (configTimeStampFlag && sConfig.GetBoolDefault(configTimeStampFlag,false)) { size_t dot_pos = logfn.find_last_of("."); if (dot_pos!=logfn.npos) logfn.insert(dot_pos,m_logsTimestamp); else logfn += m_logsTimestamp; } return fopen((m_logsDir+logfn).c_str(), mode); } FILE* Log::openGmlogPerAccount(uint32 account) { if (m_gmlog_filename_format.empty()) return NULL; char namebuf[MANGOS_PATH_MAX]; snprintf(namebuf,MANGOS_PATH_MAX,m_gmlog_filename_format.c_str(),account); return fopen(namebuf, "a"); } void Log::outTimestamp(FILE* file) { time_t t = time(NULL); tm* aTm = localtime(&t); // YYYY year // MM month (2 digits 01-12) // DD day (2 digits 01-31) // HH hour (2 digits 00-23) // MM minutes (2 digits 00-59) // SS seconds (2 digits 00-59) fprintf(file,"%-4d-%02d-%02d %02d:%02d:%02d ",aTm->tm_year+1900,aTm->tm_mon+1,aTm->tm_mday,aTm->tm_hour,aTm->tm_min,aTm->tm_sec); } void Log::outTime() { time_t t = time(NULL); tm* aTm = localtime(&t); // YYYY year // MM month (2 digits 01-12) // DD day (2 digits 01-31) // HH hour (2 digits 00-23) // MM minutes (2 digits 00-59) // SS seconds (2 digits 00-59) printf("%02d:%02d:%02d ",aTm->tm_hour,aTm->tm_min,aTm->tm_sec); } std::string Log::GetTimestampStr() { time_t t = time(NULL); tm* aTm = localtime(&t); // YYYY year // MM month (2 digits 01-12) // DD day (2 digits 01-31) // HH hour (2 digits 00-23) // MM minutes (2 digits 00-59) // SS seconds (2 digits 00-59) char buf[20]; snprintf(buf,20,"%04d-%02d-%02d_%02d-%02d-%02d",aTm->tm_year+1900,aTm->tm_mon+1,aTm->tm_mday,aTm->tm_hour,aTm->tm_min,aTm->tm_sec); return std::string(buf); } void Log::outString() { if (m_includeTime) outTime(); printf( "\n" ); if (logfile) { outTimestamp(logfile); fprintf(logfile, "\n" ); fflush(logfile); } fflush(stdout); } void Log::outString( const char * str, ... ) { if (!str) return; if (m_colored) SetColor(true,m_colors[LogNormal]); if (m_includeTime) outTime(); va_list ap; va_start(ap, str); vutf8printf(stdout, str, &ap); va_end(ap); if (m_colored) ResetColor(true); printf( "\n" ); if (logfile) { outTimestamp(logfile); va_start(ap, str); vfprintf(logfile, str, ap); fprintf(logfile, "\n" ); va_end(ap); fflush(logfile); } fflush(stdout); } void Log::outError( const char * err, ... ) { if (!err) return; if (m_colored) SetColor(false,m_colors[LogError]); if (m_includeTime) outTime(); va_list ap; va_start(ap, err); vutf8printf(stderr, err, &ap); va_end(ap); if (m_colored) ResetColor(false); fprintf( stderr, "\n" ); if (logfile) { outTimestamp(logfile); fprintf(logfile, "ERROR:" ); va_start(ap, err); vfprintf(logfile, err, ap); va_end(ap); fprintf(logfile, "\n" ); fflush(logfile); } fflush(stderr); } void Log::outErrorDb() { if (m_includeTime) outTime(); fprintf( stderr, "\n" ); if (logfile) { outTimestamp(logfile); fprintf(logfile, "ERROR:\n" ); fflush(logfile); } if (dberLogfile) { outTimestamp(dberLogfile); fprintf(dberLogfile, "\n" ); fflush(dberLogfile); } fflush(stderr); } void Log::outErrorDb( const char * err, ... ) { if (!err) return; if (m_colored) SetColor(false,m_colors[LogError]); if (m_includeTime) outTime(); va_list ap; va_start(ap, err); vutf8printf(stderr, err, &ap); va_end(ap); if (m_colored) ResetColor(false); fprintf( stderr, "\n" ); if (logfile) { outTimestamp(logfile); fprintf(logfile, "ERROR:" ); va_start(ap, err); vfprintf(logfile, err, ap); va_end(ap); fprintf(logfile, "\n" ); fflush(logfile); } if (dberLogfile) { outTimestamp(dberLogfile); va_list ap; va_start(ap, err); vfprintf(dberLogfile, err, ap); va_end(ap); fprintf(dberLogfile, "\n" ); fflush(dberLogfile); } fflush(stderr); } void Log::outBasic( const char * str, ... ) { if (!str) return; if (m_logLevel >= LOG_LVL_BASIC) { if (m_colored) SetColor(true,m_colors[LogDetails]); if (m_includeTime) outTime(); va_list ap; va_start(ap, str); vutf8printf(stdout, str, &ap); va_end(ap); if (m_colored) ResetColor(true); printf( "\n" ); } if (logfile && m_logFileLevel >= LOG_LVL_BASIC) { va_list ap; outTimestamp(logfile); va_start(ap, str); vfprintf(logfile, str, ap); fprintf(logfile, "\n" ); va_end(ap); fflush(logfile); } fflush(stdout); } void Log::outDetail( const char * str, ... ) { if (!str) return; if (m_logLevel >= LOG_LVL_DETAIL) { if (m_colored) SetColor(true,m_colors[LogDetails]); if (m_includeTime) outTime(); va_list ap; va_start(ap, str); vutf8printf(stdout, str, &ap); va_end(ap); if (m_colored) ResetColor(true); printf( "\n" ); } if (logfile && m_logFileLevel >= LOG_LVL_DETAIL) { outTimestamp(logfile); va_list ap; va_start(ap, str); vfprintf(logfile, str, ap); va_end(ap); fprintf(logfile, "\n" ); fflush(logfile); } fflush(stdout); } void Log::outDebug( const char * str, ... ) { if (!str) return; if (m_logLevel >= LOG_LVL_DEBUG) { if (m_colored) SetColor(true,m_colors[LogDebug]); if (m_includeTime) outTime(); va_list ap; va_start(ap, str); vutf8printf(stdout, str, &ap); va_end(ap); if (m_colored) ResetColor(true); printf( "\n" ); } if (logfile && m_logFileLevel >= LOG_LVL_DEBUG) { outTimestamp(logfile); va_list ap; va_start(ap, str); vfprintf(logfile, str, ap); va_end(ap); fprintf(logfile, "\n" ); fflush(logfile); } fflush(stdout); } void Log::outCommand( uint32 account, const char * str, ... ) { if (!str) return; if (m_logLevel >= LOG_LVL_DETAIL) { if (m_colored) SetColor(true,m_colors[LogDetails]); if (m_includeTime) outTime(); va_list ap; va_start(ap, str); vutf8printf(stdout, str, &ap); va_end(ap); if (m_colored) ResetColor(true); printf( "\n" ); } if (logfile && m_logFileLevel >= LOG_LVL_DETAIL) { va_list ap; outTimestamp(logfile); va_start(ap, str); vfprintf(logfile, str, ap); fprintf(logfile, "\n" ); va_end(ap); fflush(logfile); } if (m_gmlog_per_account) { if (FILE* per_file = openGmlogPerAccount (account)) { va_list ap; outTimestamp(per_file); va_start(ap, str); vfprintf(per_file, str, ap); fprintf(per_file, "\n" ); va_end(ap); fclose(per_file); } } else if (gmLogfile) { va_list ap; outTimestamp(gmLogfile); va_start(ap, str); vfprintf(gmLogfile, str, ap); fprintf(gmLogfile, "\n" ); va_end(ap); fflush(gmLogfile); } fflush(stdout); } void Log::outChar(const char * str, ... ) { if (!str) return; if (charLogfile) { va_list ap; outTimestamp(charLogfile); va_start(ap, str); vfprintf(charLogfile, str, ap); fprintf(charLogfile, "\n" ); va_end(ap); fflush(charLogfile); } } void Log::outWorldPacketDump( uint32 socket, uint32 opcode, char const* opcodeName, ByteBuffer const* packet, bool incoming ) { if (!worldLogfile) return; ACE_GUARD(ACE_Thread_Mutex, GuardObj, m_worldLogMtx); outTimestamp(worldLogfile); fprintf(worldLogfile,"\n%s:\nSOCKET: %u\nLENGTH: " SIZEFMTD "\nOPCODE: %s (0x%.4X)\nDATA:\n", incoming ? "CLIENT" : "SERVER", socket, packet->size(), opcodeName, opcode); size_t p = 0; while (p < packet->size()) { for (size_t j = 0; j < 16 && p < packet->size(); ++j) fprintf(worldLogfile, "%.2X ", (*packet)[p++]); fprintf(worldLogfile, "\n"); } fprintf(worldLogfile, "\n\n"); fflush(worldLogfile); } void Log::outCharDump( const char * str, uint32 account_id, uint32 guid, const char * name ) { if (charLogfile) { fprintf(charLogfile, "== START DUMP == (account: %u guid: %u name: %s )\n%s\n== END DUMP ==\n",account_id,guid,name,str ); fflush(charLogfile); } } void Log::outRALog( const char * str, ... ) { if (!str) return; if (raLogfile) { va_list ap; outTimestamp(raLogfile); va_start(ap, str); vfprintf(raLogfile, str, ap); fprintf(raLogfile, "\n" ); va_end(ap); fflush(raLogfile); } fflush(stdout); } void Log::WaitBeforeContinueIfNeed() { int mode = sConfig.GetIntDefault("WaitAtStartupError",0); if (mode < 0) { printf("\nPress <Enter> for continue\n"); std::string line; std::getline (std::cin, line); } else if (mode > 0) { printf("\nWait %u secs for continue.\n",mode); BarGoLink bar(mode); for(int i = 0; i < mode; ++i) { bar.step(); ACE_OS::sleep(1); } } } void outstring_log(const char * str, ...) { if (!str) return; char buf[256]; va_list ap; va_start(ap, str); vsnprintf(buf, 256, str, ap); va_end(ap); sLog.outString("%s", buf); } void detail_log(const char * str, ...) { if (!str) return; char buf[256]; va_list ap; va_start(ap, str); vsnprintf(buf,256, str, ap); va_end(ap); sLog.outDetail("%s", buf); } void debug_log(const char * str, ...) { if (!str) return; char buf[256]; va_list ap; va_start(ap, str); vsnprintf(buf,256, str, ap); va_end(ap); DEBUG_LOG("%s", buf); } void error_log(const char * str, ...) { if (!str) return; char buf[256]; va_list ap; va_start(ap, str); vsnprintf(buf,256, str, ap); va_end(ap); sLog.outError("%s", buf); } void error_db_log(const char * str, ...) { if (!str) return; char buf[256]; va_list ap; va_start(ap, str); vsnprintf(buf,256, str, ap); va_end(ap); sLog.outErrorDb("%s", buf); }
gpl-2.0
camdram/camdram
app/DoctrineMigrations/Version20201210204614.php
961
<?php declare(strict_types=1); namespace Application\Migrations; use Doctrine\DBAL\Schema\Schema; use Doctrine\Migrations\AbstractMigration; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20201210204614 extends AbstractMigration { public function getDescription() : string { return ''; } public function up(Schema $schema) : void { // this up() migration is auto-generated, please modify it to your needs $this->addSql('CREATE TABLE acts_positions (id INT AUTO_INCREMENT NOT NULL, title VARCHAR(255) NOT NULL, slug VARCHAR(255) NOT NULL, wiki_name VARCHAR(255) DEFAULT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB'); } public function down(Schema $schema) : void { // this down() migration is auto-generated, please modify it to your needs $this->addSql('DROP TABLE acts_positions'); } }
gpl-2.0
miguelinux/synergy
src/lib/core/KeyState.cpp
40232
/* * synergy -- mouse and keyboard sharing utility * Copyright (C) 2012-2016 Symless Ltd. * Copyright (C) 2004 Chris Schoeneman * * This package is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * found in the file LICENSE that should have accompanied this file. * * This package is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "core/KeyState.h" #include "base/Log.h" #include <algorithm> #include <cstring> #include <iterator> #include <list> static const KeyButton kButtonMask = static_cast<KeyButton>(IKeyState::kNumButtons - 1); static const KeyID s_decomposeTable[] = { // spacing version of dead keys 0x0060, 0x0300, 0x0020, 0, // grave, dead_grave, space 0x00b4, 0x0301, 0x0020, 0, // acute, dead_acute, space 0x005e, 0x0302, 0x0020, 0, // asciicircum, dead_circumflex, space 0x007e, 0x0303, 0x0020, 0, // asciitilde, dead_tilde, space 0x00a8, 0x0308, 0x0020, 0, // diaeresis, dead_diaeresis, space 0x00b0, 0x030a, 0x0020, 0, // degree, dead_abovering, space 0x00b8, 0x0327, 0x0020, 0, // cedilla, dead_cedilla, space 0x02db, 0x0328, 0x0020, 0, // ogonek, dead_ogonek, space 0x02c7, 0x030c, 0x0020, 0, // caron, dead_caron, space 0x02d9, 0x0307, 0x0020, 0, // abovedot, dead_abovedot, space 0x02dd, 0x030b, 0x0020, 0, // doubleacute, dead_doubleacute, space 0x02d8, 0x0306, 0x0020, 0, // breve, dead_breve, space 0x00af, 0x0304, 0x0020, 0, // macron, dead_macron, space // Latin-1 (ISO 8859-1) 0x00c0, 0x0300, 0x0041, 0, // Agrave, dead_grave, A 0x00c1, 0x0301, 0x0041, 0, // Aacute, dead_acute, A 0x00c2, 0x0302, 0x0041, 0, // Acircumflex, dead_circumflex, A 0x00c3, 0x0303, 0x0041, 0, // Atilde, dead_tilde, A 0x00c4, 0x0308, 0x0041, 0, // Adiaeresis, dead_diaeresis, A 0x00c5, 0x030a, 0x0041, 0, // Aring, dead_abovering, A 0x00c7, 0x0327, 0x0043, 0, // Ccedilla, dead_cedilla, C 0x00c8, 0x0300, 0x0045, 0, // Egrave, dead_grave, E 0x00c9, 0x0301, 0x0045, 0, // Eacute, dead_acute, E 0x00ca, 0x0302, 0x0045, 0, // Ecircumflex, dead_circumflex, E 0x00cb, 0x0308, 0x0045, 0, // Ediaeresis, dead_diaeresis, E 0x00cc, 0x0300, 0x0049, 0, // Igrave, dead_grave, I 0x00cd, 0x0301, 0x0049, 0, // Iacute, dead_acute, I 0x00ce, 0x0302, 0x0049, 0, // Icircumflex, dead_circumflex, I 0x00cf, 0x0308, 0x0049, 0, // Idiaeresis, dead_diaeresis, I 0x00d1, 0x0303, 0x004e, 0, // Ntilde, dead_tilde, N 0x00d2, 0x0300, 0x004f, 0, // Ograve, dead_grave, O 0x00d3, 0x0301, 0x004f, 0, // Oacute, dead_acute, O 0x00d4, 0x0302, 0x004f, 0, // Ocircumflex, dead_circumflex, O 0x00d5, 0x0303, 0x004f, 0, // Otilde, dead_tilde, O 0x00d6, 0x0308, 0x004f, 0, // Odiaeresis, dead_diaeresis, O 0x00d9, 0x0300, 0x0055, 0, // Ugrave, dead_grave, U 0x00da, 0x0301, 0x0055, 0, // Uacute, dead_acute, U 0x00db, 0x0302, 0x0055, 0, // Ucircumflex, dead_circumflex, U 0x00dc, 0x0308, 0x0055, 0, // Udiaeresis, dead_diaeresis, U 0x00dd, 0x0301, 0x0059, 0, // Yacute, dead_acute, Y 0x00e0, 0x0300, 0x0061, 0, // agrave, dead_grave, a 0x00e1, 0x0301, 0x0061, 0, // aacute, dead_acute, a 0x00e2, 0x0302, 0x0061, 0, // acircumflex, dead_circumflex, a 0x00e3, 0x0303, 0x0061, 0, // atilde, dead_tilde, a 0x00e4, 0x0308, 0x0061, 0, // adiaeresis, dead_diaeresis, a 0x00e5, 0x030a, 0x0061, 0, // aring, dead_abovering, a 0x00e7, 0x0327, 0x0063, 0, // ccedilla, dead_cedilla, c 0x00e8, 0x0300, 0x0065, 0, // egrave, dead_grave, e 0x00e9, 0x0301, 0x0065, 0, // eacute, dead_acute, e 0x00ea, 0x0302, 0x0065, 0, // ecircumflex, dead_circumflex, e 0x00eb, 0x0308, 0x0065, 0, // ediaeresis, dead_diaeresis, e 0x00ec, 0x0300, 0x0069, 0, // igrave, dead_grave, i 0x00ed, 0x0301, 0x0069, 0, // iacute, dead_acute, i 0x00ee, 0x0302, 0x0069, 0, // icircumflex, dead_circumflex, i 0x00ef, 0x0308, 0x0069, 0, // idiaeresis, dead_diaeresis, i 0x00f1, 0x0303, 0x006e, 0, // ntilde, dead_tilde, n 0x00f2, 0x0300, 0x006f, 0, // ograve, dead_grave, o 0x00f3, 0x0301, 0x006f, 0, // oacute, dead_acute, o 0x00f4, 0x0302, 0x006f, 0, // ocircumflex, dead_circumflex, o 0x00f5, 0x0303, 0x006f, 0, // otilde, dead_tilde, o 0x00f6, 0x0308, 0x006f, 0, // odiaeresis, dead_diaeresis, o 0x00f9, 0x0300, 0x0075, 0, // ugrave, dead_grave, u 0x00fa, 0x0301, 0x0075, 0, // uacute, dead_acute, u 0x00fb, 0x0302, 0x0075, 0, // ucircumflex, dead_circumflex, u 0x00fc, 0x0308, 0x0075, 0, // udiaeresis, dead_diaeresis, u 0x00fd, 0x0301, 0x0079, 0, // yacute, dead_acute, y 0x00ff, 0x0308, 0x0079, 0, // ydiaeresis, dead_diaeresis, y // Latin-2 (ISO 8859-2) 0x0104, 0x0328, 0x0041, 0, // Aogonek, dead_ogonek, A 0x013d, 0x030c, 0x004c, 0, // Lcaron, dead_caron, L 0x015a, 0x0301, 0x0053, 0, // Sacute, dead_acute, S 0x0160, 0x030c, 0x0053, 0, // Scaron, dead_caron, S 0x015e, 0x0327, 0x0053, 0, // Scedilla, dead_cedilla, S 0x0164, 0x030c, 0x0054, 0, // Tcaron, dead_caron, T 0x0179, 0x0301, 0x005a, 0, // Zacute, dead_acute, Z 0x017d, 0x030c, 0x005a, 0, // Zcaron, dead_caron, Z 0x017b, 0x0307, 0x005a, 0, // Zabovedot, dead_abovedot, Z 0x0105, 0x0328, 0x0061, 0, // aogonek, dead_ogonek, a 0x013e, 0x030c, 0x006c, 0, // lcaron, dead_caron, l 0x015b, 0x0301, 0x0073, 0, // sacute, dead_acute, s 0x0161, 0x030c, 0x0073, 0, // scaron, dead_caron, s 0x015f, 0x0327, 0x0073, 0, // scedilla, dead_cedilla, s 0x0165, 0x030c, 0x0074, 0, // tcaron, dead_caron, t 0x017a, 0x0301, 0x007a, 0, // zacute, dead_acute, z 0x017e, 0x030c, 0x007a, 0, // zcaron, dead_caron, z 0x017c, 0x0307, 0x007a, 0, // zabovedot, dead_abovedot, z 0x0154, 0x0301, 0x0052, 0, // Racute, dead_acute, R 0x0102, 0x0306, 0x0041, 0, // Abreve, dead_breve, A 0x0139, 0x0301, 0x004c, 0, // Lacute, dead_acute, L 0x0106, 0x0301, 0x0043, 0, // Cacute, dead_acute, C 0x010c, 0x030c, 0x0043, 0, // Ccaron, dead_caron, C 0x0118, 0x0328, 0x0045, 0, // Eogonek, dead_ogonek, E 0x011a, 0x030c, 0x0045, 0, // Ecaron, dead_caron, E 0x010e, 0x030c, 0x0044, 0, // Dcaron, dead_caron, D 0x0143, 0x0301, 0x004e, 0, // Nacute, dead_acute, N 0x0147, 0x030c, 0x004e, 0, // Ncaron, dead_caron, N 0x0150, 0x030b, 0x004f, 0, // Odoubleacute, dead_doubleacute, O 0x0158, 0x030c, 0x0052, 0, // Rcaron, dead_caron, R 0x016e, 0x030a, 0x0055, 0, // Uring, dead_abovering, U 0x0170, 0x030b, 0x0055, 0, // Udoubleacute, dead_doubleacute, U 0x0162, 0x0327, 0x0054, 0, // Tcedilla, dead_cedilla, T 0x0155, 0x0301, 0x0072, 0, // racute, dead_acute, r 0x0103, 0x0306, 0x0061, 0, // abreve, dead_breve, a 0x013a, 0x0301, 0x006c, 0, // lacute, dead_acute, l 0x0107, 0x0301, 0x0063, 0, // cacute, dead_acute, c 0x010d, 0x030c, 0x0063, 0, // ccaron, dead_caron, c 0x0119, 0x0328, 0x0065, 0, // eogonek, dead_ogonek, e 0x011b, 0x030c, 0x0065, 0, // ecaron, dead_caron, e 0x010f, 0x030c, 0x0064, 0, // dcaron, dead_caron, d 0x0144, 0x0301, 0x006e, 0, // nacute, dead_acute, n 0x0148, 0x030c, 0x006e, 0, // ncaron, dead_caron, n 0x0151, 0x030b, 0x006f, 0, // odoubleacute, dead_doubleacute, o 0x0159, 0x030c, 0x0072, 0, // rcaron, dead_caron, r 0x016f, 0x030a, 0x0075, 0, // uring, dead_abovering, u 0x0171, 0x030b, 0x0075, 0, // udoubleacute, dead_doubleacute, u 0x0163, 0x0327, 0x0074, 0, // tcedilla, dead_cedilla, t // Latin-3 (ISO 8859-3) 0x0124, 0x0302, 0x0048, 0, // Hcircumflex, dead_circumflex, H 0x0130, 0x0307, 0x0049, 0, // Iabovedot, dead_abovedot, I 0x011e, 0x0306, 0x0047, 0, // Gbreve, dead_breve, G 0x0134, 0x0302, 0x004a, 0, // Jcircumflex, dead_circumflex, J 0x0125, 0x0302, 0x0068, 0, // hcircumflex, dead_circumflex, h 0x011f, 0x0306, 0x0067, 0, // gbreve, dead_breve, g 0x0135, 0x0302, 0x006a, 0, // jcircumflex, dead_circumflex, j 0x010a, 0x0307, 0x0043, 0, // Cabovedot, dead_abovedot, C 0x0108, 0x0302, 0x0043, 0, // Ccircumflex, dead_circumflex, C 0x0120, 0x0307, 0x0047, 0, // Gabovedot, dead_abovedot, G 0x011c, 0x0302, 0x0047, 0, // Gcircumflex, dead_circumflex, G 0x016c, 0x0306, 0x0055, 0, // Ubreve, dead_breve, U 0x015c, 0x0302, 0x0053, 0, // Scircumflex, dead_circumflex, S 0x010b, 0x0307, 0x0063, 0, // cabovedot, dead_abovedot, c 0x0109, 0x0302, 0x0063, 0, // ccircumflex, dead_circumflex, c 0x0121, 0x0307, 0x0067, 0, // gabovedot, dead_abovedot, g 0x011d, 0x0302, 0x0067, 0, // gcircumflex, dead_circumflex, g 0x016d, 0x0306, 0x0075, 0, // ubreve, dead_breve, u 0x015d, 0x0302, 0x0073, 0, // scircumflex, dead_circumflex, s // Latin-4 (ISO 8859-4) 0x0156, 0x0327, 0x0052, 0, // Rcedilla, dead_cedilla, R 0x0128, 0x0303, 0x0049, 0, // Itilde, dead_tilde, I 0x013b, 0x0327, 0x004c, 0, // Lcedilla, dead_cedilla, L 0x0112, 0x0304, 0x0045, 0, // Emacron, dead_macron, E 0x0122, 0x0327, 0x0047, 0, // Gcedilla, dead_cedilla, G 0x0157, 0x0327, 0x0072, 0, // rcedilla, dead_cedilla, r 0x0129, 0x0303, 0x0069, 0, // itilde, dead_tilde, i 0x013c, 0x0327, 0x006c, 0, // lcedilla, dead_cedilla, l 0x0113, 0x0304, 0x0065, 0, // emacron, dead_macron, e 0x0123, 0x0327, 0x0067, 0, // gcedilla, dead_cedilla, g 0x0100, 0x0304, 0x0041, 0, // Amacron, dead_macron, A 0x012e, 0x0328, 0x0049, 0, // Iogonek, dead_ogonek, I 0x0116, 0x0307, 0x0045, 0, // Eabovedot, dead_abovedot, E 0x012a, 0x0304, 0x0049, 0, // Imacron, dead_macron, I 0x0145, 0x0327, 0x004e, 0, // Ncedilla, dead_cedilla, N 0x014c, 0x0304, 0x004f, 0, // Omacron, dead_macron, O 0x0136, 0x0327, 0x004b, 0, // Kcedilla, dead_cedilla, K 0x0172, 0x0328, 0x0055, 0, // Uogonek, dead_ogonek, U 0x0168, 0x0303, 0x0055, 0, // Utilde, dead_tilde, U 0x016a, 0x0304, 0x0055, 0, // Umacron, dead_macron, U 0x0101, 0x0304, 0x0061, 0, // amacron, dead_macron, a 0x012f, 0x0328, 0x0069, 0, // iogonek, dead_ogonek, i 0x0117, 0x0307, 0x0065, 0, // eabovedot, dead_abovedot, e 0x012b, 0x0304, 0x0069, 0, // imacron, dead_macron, i 0x0146, 0x0327, 0x006e, 0, // ncedilla, dead_cedilla, n 0x014d, 0x0304, 0x006f, 0, // omacron, dead_macron, o 0x0137, 0x0327, 0x006b, 0, // kcedilla, dead_cedilla, k 0x0173, 0x0328, 0x0075, 0, // uogonek, dead_ogonek, u 0x0169, 0x0303, 0x0075, 0, // utilde, dead_tilde, u 0x016b, 0x0304, 0x0075, 0, // umacron, dead_macron, u // Latin-8 (ISO 8859-14) 0x1e02, 0x0307, 0x0042, 0, // Babovedot, dead_abovedot, B 0x1e03, 0x0307, 0x0062, 0, // babovedot, dead_abovedot, b 0x1e0a, 0x0307, 0x0044, 0, // Dabovedot, dead_abovedot, D 0x1e80, 0x0300, 0x0057, 0, // Wgrave, dead_grave, W 0x1e82, 0x0301, 0x0057, 0, // Wacute, dead_acute, W 0x1e0b, 0x0307, 0x0064, 0, // dabovedot, dead_abovedot, d 0x1ef2, 0x0300, 0x0059, 0, // Ygrave, dead_grave, Y 0x1e1e, 0x0307, 0x0046, 0, // Fabovedot, dead_abovedot, F 0x1e1f, 0x0307, 0x0066, 0, // fabovedot, dead_abovedot, f 0x1e40, 0x0307, 0x004d, 0, // Mabovedot, dead_abovedot, M 0x1e41, 0x0307, 0x006d, 0, // mabovedot, dead_abovedot, m 0x1e56, 0x0307, 0x0050, 0, // Pabovedot, dead_abovedot, P 0x1e81, 0x0300, 0x0077, 0, // wgrave, dead_grave, w 0x1e57, 0x0307, 0x0070, 0, // pabovedot, dead_abovedot, p 0x1e83, 0x0301, 0x0077, 0, // wacute, dead_acute, w 0x1e60, 0x0307, 0x0053, 0, // Sabovedot, dead_abovedot, S 0x1ef3, 0x0300, 0x0079, 0, // ygrave, dead_grave, y 0x1e84, 0x0308, 0x0057, 0, // Wdiaeresis, dead_diaeresis, W 0x1e85, 0x0308, 0x0077, 0, // wdiaeresis, dead_diaeresis, w 0x1e61, 0x0307, 0x0073, 0, // sabovedot, dead_abovedot, s 0x0174, 0x0302, 0x0057, 0, // Wcircumflex, dead_circumflex, W 0x1e6a, 0x0307, 0x0054, 0, // Tabovedot, dead_abovedot, T 0x0176, 0x0302, 0x0059, 0, // Ycircumflex, dead_circumflex, Y 0x0175, 0x0302, 0x0077, 0, // wcircumflex, dead_circumflex, w 0x1e6b, 0x0307, 0x0074, 0, // tabovedot, dead_abovedot, t 0x0177, 0x0302, 0x0079, 0, // ycircumflex, dead_circumflex, y // Latin-9 (ISO 8859-15) 0x0178, 0x0308, 0x0059, 0, // Ydiaeresis, dead_diaeresis, Y // Compose key sequences 0x00c6, kKeyCompose, 0x0041, 0x0045, 0, // AE, A, E 0x00c1, kKeyCompose, 0x0041, 0x0027, 0, // Aacute, A, apostrophe 0x00c2, kKeyCompose, 0x0041, 0x0053, 0, // Acircumflex, A, asciicircum 0x00c3, kKeyCompose, 0x0041, 0x0022, 0, // Adiaeresis, A, quotedbl 0x00c0, kKeyCompose, 0x0041, 0x0060, 0, // Agrave, A, grave 0x00c5, kKeyCompose, 0x0041, 0x002a, 0, // Aring, A, asterisk 0x00c3, kKeyCompose, 0x0041, 0x007e, 0, // Atilde, A, asciitilde 0x00c7, kKeyCompose, 0x0043, 0x002c, 0, // Ccedilla, C, comma 0x00d0, kKeyCompose, 0x0044, 0x002d, 0, // ETH, D, minus 0x00c9, kKeyCompose, 0x0045, 0x0027, 0, // Eacute, E, apostrophe 0x00ca, kKeyCompose, 0x0045, 0x0053, 0, // Ecircumflex, E, asciicircum 0x00cb, kKeyCompose, 0x0045, 0x0022, 0, // Ediaeresis, E, quotedbl 0x00c8, kKeyCompose, 0x0045, 0x0060, 0, // Egrave, E, grave 0x00cd, kKeyCompose, 0x0049, 0x0027, 0, // Iacute, I, apostrophe 0x00ce, kKeyCompose, 0x0049, 0x0053, 0, // Icircumflex, I, asciicircum 0x00cf, kKeyCompose, 0x0049, 0x0022, 0, // Idiaeresis, I, quotedbl 0x00cc, kKeyCompose, 0x0049, 0x0060, 0, // Igrave, I, grave 0x00d1, kKeyCompose, 0x004e, 0x007e, 0, // Ntilde, N, asciitilde 0x00d3, kKeyCompose, 0x004f, 0x0027, 0, // Oacute, O, apostrophe 0x00d4, kKeyCompose, 0x004f, 0x0053, 0, // Ocircumflex, O, asciicircum 0x00d6, kKeyCompose, 0x004f, 0x0022, 0, // Odiaeresis, O, quotedbl 0x00d2, kKeyCompose, 0x004f, 0x0060, 0, // Ograve, O, grave 0x00d8, kKeyCompose, 0x004f, 0x002f, 0, // Ooblique, O, slash 0x00d5, kKeyCompose, 0x004f, 0x007e, 0, // Otilde, O, asciitilde 0x00de, kKeyCompose, 0x0054, 0x0048, 0, // THORN, T, H 0x00da, kKeyCompose, 0x0055, 0x0027, 0, // Uacute, U, apostrophe 0x00db, kKeyCompose, 0x0055, 0x0053, 0, // Ucircumflex, U, asciicircum 0x00dc, kKeyCompose, 0x0055, 0x0022, 0, // Udiaeresis, U, quotedbl 0x00d9, kKeyCompose, 0x0055, 0x0060, 0, // Ugrave, U, grave 0x00dd, kKeyCompose, 0x0059, 0x0027, 0, // Yacute, Y, apostrophe 0x00e1, kKeyCompose, 0x0061, 0x0027, 0, // aacute, a, apostrophe 0x00e2, kKeyCompose, 0x0061, 0x0053, 0, // acircumflex, a, asciicircum 0x00b4, kKeyCompose, 0x0027, 0x0027, 0, // acute, apostrophe, apostrophe 0x00e4, kKeyCompose, 0x0061, 0x0022, 0, // adiaeresis, a, quotedbl 0x00e6, kKeyCompose, 0x0061, 0x0065, 0, // ae, a, e 0x00e0, kKeyCompose, 0x0061, 0x0060, 0, // agrave, a, grave 0x00e5, kKeyCompose, 0x0061, 0x002a, 0, // aring, a, asterisk 0x0040, kKeyCompose, 0x0041, 0x0054, 0, // at, A, T 0x00e3, kKeyCompose, 0x0061, 0x007e, 0, // atilde, a, asciitilde 0x005c, kKeyCompose, 0x002f, 0x002f, 0, // backslash, slash, slash 0x007c, kKeyCompose, 0x004c, 0x0056, 0, // bar, L, V 0x007b, kKeyCompose, 0x0028, 0x002d, 0, // braceleft, parenleft, minus 0x007d, kKeyCompose, 0x0029, 0x002d, 0, // braceright, parenright, minus 0x005b, kKeyCompose, 0x0028, 0x0028, 0, // bracketleft, parenleft, parenleft 0x005d, kKeyCompose, 0x0029, 0x0029, 0, // bracketright, parenright, parenright 0x00a6, kKeyCompose, 0x0042, 0x0056, 0, // brokenbar, B, V 0x00e7, kKeyCompose, 0x0063, 0x002c, 0, // ccedilla, c, comma 0x00b8, kKeyCompose, 0x002c, 0x002c, 0, // cedilla, comma, comma 0x00a2, kKeyCompose, 0x0063, 0x002f, 0, // cent, c, slash 0x00a9, kKeyCompose, 0x0028, 0x0063, 0, // copyright, parenleft, c 0x00a4, kKeyCompose, 0x006f, 0x0078, 0, // currency, o, x 0x00b0, kKeyCompose, 0x0030, 0x0053, 0, // degree, 0, asciicircum 0x00a8, kKeyCompose, 0x0022, 0x0022, 0, // diaeresis, quotedbl, quotedbl 0x00f7, kKeyCompose, 0x003a, 0x002d, 0, // division, colon, minus 0x00e9, kKeyCompose, 0x0065, 0x0027, 0, // eacute, e, apostrophe 0x00ea, kKeyCompose, 0x0065, 0x0053, 0, // ecircumflex, e, asciicircum 0x00eb, kKeyCompose, 0x0065, 0x0022, 0, // ediaeresis, e, quotedbl 0x00e8, kKeyCompose, 0x0065, 0x0060, 0, // egrave, e, grave 0x00f0, kKeyCompose, 0x0064, 0x002d, 0, // eth, d, minus 0x00a1, kKeyCompose, 0x0021, 0x0021, 0, // exclamdown, exclam, exclam 0x00ab, kKeyCompose, 0x003c, 0x003c, 0, // guillemotleft, less, less 0x00bb, kKeyCompose, 0x003e, 0x003e, 0, // guillemotright, greater, greater 0x0023, kKeyCompose, 0x002b, 0x002b, 0, // numbersign, plus, plus 0x00ad, kKeyCompose, 0x002d, 0x002d, 0, // hyphen, minus, minus 0x00ed, kKeyCompose, 0x0069, 0x0027, 0, // iacute, i, apostrophe 0x00ee, kKeyCompose, 0x0069, 0x0053, 0, // icircumflex, i, asciicircum 0x00ef, kKeyCompose, 0x0069, 0x0022, 0, // idiaeresis, i, quotedbl 0x00ec, kKeyCompose, 0x0069, 0x0060, 0, // igrave, i, grave 0x00af, kKeyCompose, 0x002d, 0x0053, 0, // macron, minus, asciicircum 0x00ba, kKeyCompose, 0x006f, 0x005f, 0, // masculine, o, underscore 0x00b5, kKeyCompose, 0x0075, 0x002f, 0, // mu, u, slash 0x00d7, kKeyCompose, 0x0078, 0x0078, 0, // multiply, x, x 0x00a0, kKeyCompose, 0x0020, 0x0020, 0, // nobreakspace, space, space 0x00ac, kKeyCompose, 0x002c, 0x002d, 0, // notsign, comma, minus 0x00f1, kKeyCompose, 0x006e, 0x007e, 0, // ntilde, n, asciitilde 0x00f3, kKeyCompose, 0x006f, 0x0027, 0, // oacute, o, apostrophe 0x00f4, kKeyCompose, 0x006f, 0x0053, 0, // ocircumflex, o, asciicircum 0x00f6, kKeyCompose, 0x006f, 0x0022, 0, // odiaeresis, o, quotedbl 0x00f2, kKeyCompose, 0x006f, 0x0060, 0, // ograve, o, grave 0x00bd, kKeyCompose, 0x0031, 0x0032, 0, // onehalf, 1, 2 0x00bc, kKeyCompose, 0x0031, 0x0034, 0, // onequarter, 1, 4 0x00b9, kKeyCompose, 0x0031, 0x0053, 0, // onesuperior, 1, asciicircum 0x00aa, kKeyCompose, 0x0061, 0x005f, 0, // ordfeminine, a, underscore 0x00f8, kKeyCompose, 0x006f, 0x002f, 0, // oslash, o, slash 0x00f5, kKeyCompose, 0x006f, 0x007e, 0, // otilde, o, asciitilde 0x00b6, kKeyCompose, 0x0070, 0x0021, 0, // paragraph, p, exclam 0x00b7, kKeyCompose, 0x002e, 0x002e, 0, // periodcentered, period, period 0x00b1, kKeyCompose, 0x002b, 0x002d, 0, // plusminus, plus, minus 0x00bf, kKeyCompose, 0x003f, 0x003f, 0, // questiondown, question, question 0x00ae, kKeyCompose, 0x0028, 0x0072, 0, // registered, parenleft, r 0x00a7, kKeyCompose, 0x0073, 0x006f, 0, // section, s, o 0x00df, kKeyCompose, 0x0073, 0x0073, 0, // ssharp, s, s 0x00a3, kKeyCompose, 0x004c, 0x002d, 0, // sterling, L, minus 0x00fe, kKeyCompose, 0x0074, 0x0068, 0, // thorn, t, h 0x00be, kKeyCompose, 0x0033, 0x0034, 0, // threequarters, 3, 4 0x00b3, kKeyCompose, 0x0033, 0x0053, 0, // threesuperior, 3, asciicircum 0x00b2, kKeyCompose, 0x0032, 0x0053, 0, // twosuperior, 2, asciicircum 0x00fa, kKeyCompose, 0x0075, 0x0027, 0, // uacute, u, apostrophe 0x00fb, kKeyCompose, 0x0075, 0x0053, 0, // ucircumflex, u, asciicircum 0x00fc, kKeyCompose, 0x0075, 0x0022, 0, // udiaeresis, u, quotedbl 0x00f9, kKeyCompose, 0x0075, 0x0060, 0, // ugrave, u, grave 0x00fd, kKeyCompose, 0x0079, 0x0027, 0, // yacute, y, apostrophe 0x00ff, kKeyCompose, 0x0079, 0x0022, 0, // ydiaeresis, y, quotedbl 0x00a5, kKeyCompose, 0x0079, 0x003d, 0, // yen, y, equal // end of table 0 }; static const KeyID s_numpadTable[] = { kKeyKP_Space, 0x0020, kKeyKP_Tab, kKeyTab, kKeyKP_Enter, kKeyReturn, kKeyKP_F1, kKeyF1, kKeyKP_F2, kKeyF2, kKeyKP_F3, kKeyF3, kKeyKP_F4, kKeyF4, kKeyKP_Home, kKeyHome, kKeyKP_Left, kKeyLeft, kKeyKP_Up, kKeyUp, kKeyKP_Right, kKeyRight, kKeyKP_Down, kKeyDown, kKeyKP_PageUp, kKeyPageUp, kKeyKP_PageDown, kKeyPageDown, kKeyKP_End, kKeyEnd, kKeyKP_Begin, kKeyBegin, kKeyKP_Insert, kKeyInsert, kKeyKP_Delete, kKeyDelete, kKeyKP_Equal, 0x003d, kKeyKP_Multiply, 0x002a, kKeyKP_Add, 0x002b, kKeyKP_Separator, 0x002c, kKeyKP_Subtract, 0x002d, kKeyKP_Decimal, 0x002e, kKeyKP_Divide, 0x002f, kKeyKP_0, 0x0030, kKeyKP_1, 0x0031, kKeyKP_2, 0x0032, kKeyKP_3, 0x0033, kKeyKP_4, 0x0034, kKeyKP_5, 0x0035, kKeyKP_6, 0x0036, kKeyKP_7, 0x0037, kKeyKP_8, 0x0038, kKeyKP_9, 0x0039 }; // // KeyState // KeyState::KeyState(IEventQueue* events) : IKeyState(events), m_keyMapPtr(new synergy::KeyMap()), m_keyMap(*m_keyMapPtr), m_mask(0), m_events(events) { init(); } KeyState::KeyState(IEventQueue* events, synergy::KeyMap& keyMap) : IKeyState(events), m_keyMapPtr(nullptr), m_keyMap(keyMap), m_mask(0), m_events(events) { init(); } KeyState::~KeyState() { delete m_keyMapPtr; } void KeyState::init() { memset(&m_keys, 0, sizeof(m_keys)); memset(&m_syntheticKeys, 0, sizeof(m_syntheticKeys)); memset(&m_keyClientData, 0, sizeof(m_keyClientData)); memset(&m_serverKeys, 0, sizeof(m_serverKeys)); } void KeyState::onKey(KeyButton button, bool down, KeyModifierMask newState) { // update modifier state m_mask = newState; LOG((CLOG_DEBUG1 "new mask: 0x%04x", m_mask)); // ignore bogus buttons button &= kButtonMask; if (button == 0) { return; } // update key state if (down) { m_keys[button] = 1; m_syntheticKeys[button] = 1; } else { m_keys[button] = 0; m_syntheticKeys[button] = 0; } } void KeyState::sendKeyEvent( void* target, bool press, bool isAutoRepeat, KeyID key, KeyModifierMask mask, SInt32 count, KeyButton button) { if (m_keyMap.isHalfDuplex(key, button)) { if (isAutoRepeat) { // ignore auto-repeat on half-duplex keys } else { m_events->addEvent(Event(m_events->forIKeyState().keyDown(), target, KeyInfo::alloc(key, mask, button, 1))); m_events->addEvent(Event(m_events->forIKeyState().keyUp(), target, KeyInfo::alloc(key, mask, button, 1))); } } else { if (isAutoRepeat) { m_events->addEvent(Event(m_events->forIKeyState().keyRepeat(), target, KeyInfo::alloc(key, mask, button, count))); } else if (press) { m_events->addEvent(Event(m_events->forIKeyState().keyDown(), target, KeyInfo::alloc(key, mask, button, 1))); } else { m_events->addEvent(Event(m_events->forIKeyState().keyUp(), target, KeyInfo::alloc(key, mask, button, 1))); } } } void KeyState::updateKeyMap() { // get the current keyboard map synergy::KeyMap keyMap; getKeyMap(keyMap); m_keyMap.swap(keyMap); m_keyMap.finish(); // add special keys addCombinationEntries(); addKeypadEntries(); addAliasEntries(); } void KeyState::updateKeyState() { // reset our state memset(&m_keys, 0, sizeof(m_keys)); memset(&m_syntheticKeys, 0, sizeof(m_syntheticKeys)); memset(&m_keyClientData, 0, sizeof(m_keyClientData)); memset(&m_serverKeys, 0, sizeof(m_serverKeys)); m_activeModifiers.clear(); // get the current keyboard state KeyButtonSet keysDown; pollPressedKeys(keysDown); for (unsigned short i : keysDown) { m_keys[i] = 1; } // get the current modifier state m_mask = pollActiveModifiers(); // set active modifiers AddActiveModifierContext addModifierContext(pollActiveGroup(), m_mask, m_activeModifiers); m_keyMap.foreachKey(&KeyState::addActiveModifierCB, &addModifierContext); LOG((CLOG_DEBUG1 "modifiers on update: 0x%04x", m_mask)); } void KeyState::addActiveModifierCB(KeyID /*unused*/, SInt32 group, synergy::KeyMap::KeyItem& keyItem, void* vcontext) { auto* context = static_cast<AddActiveModifierContext*>(vcontext); if (group == context->m_activeGroup && (keyItem.m_generates & context->m_mask) != 0) { context->m_activeModifiers.insert(std::make_pair( keyItem.m_generates, keyItem)); } } void KeyState::setHalfDuplexMask(KeyModifierMask mask) { m_keyMap.clearHalfDuplexModifiers(); if ((mask & KeyModifierCapsLock) != 0) { m_keyMap.addHalfDuplexModifier(kKeyCapsLock); } if ((mask & KeyModifierNumLock) != 0) { m_keyMap.addHalfDuplexModifier(kKeyNumLock); } if ((mask & KeyModifierScrollLock) != 0) { m_keyMap.addHalfDuplexModifier(kKeyScrollLock); } } void KeyState::fakeKeyDown(KeyID id, KeyModifierMask mask, KeyButton serverID) { // if this server key is already down then this is probably a // mis-reported autorepeat. serverID &= kButtonMask; if (m_serverKeys[serverID] != 0) { fakeKeyRepeat(id, mask, 1, serverID); return; } // ignore certain keys if (isIgnoredKey(id, mask)) { LOG((CLOG_DEBUG1 "ignored key %04x %04x", id, mask)); return; } // get keys for key press Keystrokes keys; ModifierToKeys oldActiveModifiers = m_activeModifiers; const synergy::KeyMap::KeyItem* keyItem = m_keyMap.mapKey(keys, id, pollActiveGroup(), m_activeModifiers, getActiveModifiersRValue(), mask, false); if (keyItem == nullptr) { // a media key won't be mapped on mac, so we need to fake it in a // special way if (id == kKeyAudioDown || id == kKeyAudioUp || id == kKeyAudioMute || id == kKeyAudioPlay || id == kKeyAudioPrev || id == kKeyAudioNext || id == kKeyBrightnessDown || id == kKeyBrightnessUp ) { LOG((CLOG_DEBUG1 "emulating media key")); fakeMediaKey(id); } return; } auto localID = static_cast<KeyButton>(keyItem->m_button & kButtonMask); updateModifierKeyState(localID, oldActiveModifiers, m_activeModifiers); if (localID != 0) { // note keys down ++m_keys[localID]; ++m_syntheticKeys[localID]; m_keyClientData[localID] = keyItem->m_client; m_serverKeys[serverID] = localID; } // generate key events fakeKeys(keys, 1); } bool KeyState::fakeKeyRepeat( KeyID id, KeyModifierMask mask, SInt32 count, KeyButton serverID) { serverID &= kButtonMask; // if we haven't seen this button go down then ignore it KeyButton oldLocalID = m_serverKeys[serverID]; if (oldLocalID == 0) { return false; } // get keys for key repeat Keystrokes keys; ModifierToKeys oldActiveModifiers = m_activeModifiers; const synergy::KeyMap::KeyItem* keyItem = m_keyMap.mapKey(keys, id, pollActiveGroup(), m_activeModifiers, getActiveModifiersRValue(), mask, true); if (keyItem == nullptr) { return false; } auto localID = static_cast<KeyButton>(keyItem->m_button & kButtonMask); if (localID == 0) { return false; } // if the KeyButton for the auto-repeat is not the same as for the // initial press then mark the initial key as released and the new // key as pressed. this can happen when we auto-repeat after a // dead key. for example, a dead accent followed by 'a' will // generate an 'a with accent' followed by a repeating 'a'. the // KeyButtons for the two KeyIDs might be different. if (localID != oldLocalID) { // replace key up with previous KeyButton but leave key down // alone so it uses the new KeyButton. for (auto & key : keys) { if (key.m_type == Keystroke::kButton && key.m_data.m_button.m_button == localID) { key.m_data.m_button.m_button = oldLocalID; break; } } // note that old key is now up --m_keys[oldLocalID]; --m_syntheticKeys[oldLocalID]; // note keys down updateModifierKeyState(localID, oldActiveModifiers, m_activeModifiers); ++m_keys[localID]; ++m_syntheticKeys[localID]; m_keyClientData[localID] = keyItem->m_client; m_serverKeys[serverID] = localID; } // generate key events fakeKeys(keys, count); return true; } bool KeyState::fakeKeyUp(KeyButton serverID) { // if we haven't seen this button go down then ignore it KeyButton localID = m_serverKeys[serverID & kButtonMask]; if (localID == 0) { return false; } // get the sequence of keys to simulate key release Keystrokes keys; keys.emplace_back(localID, false, false, m_keyClientData[localID]); // note keys down --m_keys[localID]; --m_syntheticKeys[localID]; m_serverKeys[serverID] = 0; // check if this is a modifier auto i = m_activeModifiers.begin(); while (i != m_activeModifiers.end()) { if (i->second.m_button == localID && !i->second.m_lock) { // modifier is no longer down KeyModifierMask mask = i->first; auto tmp = i; ++i; m_activeModifiers.erase(tmp); if (m_activeModifiers.count(mask) == 0) { // no key for modifier is down so deactivate modifier m_mask &= ~mask; LOG((CLOG_DEBUG1 "new state %04x", m_mask)); } } else { ++i; } } // generate key events fakeKeys(keys, 1); return true; } void KeyState::fakeAllKeysUp() { Keystrokes keys; for (KeyButton i = 0; i < IKeyState::kNumButtons; ++i) { if (m_syntheticKeys[i] > 0) { keys.emplace_back(i, false, false, m_keyClientData[i]); m_keys[i] = 0; m_syntheticKeys[i] = 0; } } fakeKeys(keys, 1); memset(&m_serverKeys, 0, sizeof(m_serverKeys)); m_activeModifiers.clear(); m_mask = pollActiveModifiers(); } bool KeyState::fakeMediaKey(KeyID /*id*/) { return false; } bool KeyState::isKeyDown(KeyButton button) const { return (m_keys[button & kButtonMask] > 0); } KeyModifierMask KeyState::getActiveModifiers() const { return m_mask; } KeyModifierMask& KeyState::getActiveModifiersRValue() { return m_mask; } SInt32 KeyState::getEffectiveGroup(SInt32 group, SInt32 offset) const { return m_keyMap.getEffectiveGroup(group, offset); } bool KeyState::isIgnoredKey(KeyID key, KeyModifierMask /*unused*/) const { switch (key) { case kKeyCapsLock: case kKeyNumLock: case kKeyScrollLock: return true; default: return false; } } KeyButton KeyState::getButton(KeyID id, SInt32 group) const { const synergy::KeyMap::KeyItemList* items = m_keyMap.findCompatibleKey(id, group, 0, 0); if (items == nullptr) { return 0; } return items->back().m_button; } void KeyState::addAliasEntries() { for (SInt32 g = 0, n = m_keyMap.getNumGroups(); g < n; ++g) { // if we can't shift any kKeyTab key in a particular group but we can // shift kKeyLeftTab then add a shifted kKeyTab entry that matches a // shifted kKeyLeftTab entry. m_keyMap.addKeyAliasEntry(kKeyTab, g, KeyModifierShift, KeyModifierShift, kKeyLeftTab, KeyModifierShift, KeyModifierShift); // if we have no kKeyLeftTab but we do have a kKeyTab that can be // shifted then add kKeyLeftTab that matches a kKeyTab. m_keyMap.addKeyAliasEntry(kKeyLeftTab, g, KeyModifierShift, KeyModifierShift, kKeyTab, 0, KeyModifierShift); // map non-breaking space to space m_keyMap.addKeyAliasEntry(0x20, g, 0, 0, 0xa0, 0, 0); } } void KeyState::addKeypadEntries() { // map every numpad key to its equivalent non-numpad key if it's not // on the keyboard. for (SInt32 g = 0, n = m_keyMap.getNumGroups(); g < n; ++g) { for (size_t i = 0; i < sizeof(s_numpadTable) / sizeof(s_numpadTable[0]); i += 2) { m_keyMap.addKeyCombinationEntry(s_numpadTable[i], g, s_numpadTable + i + 1, 1); } } } void KeyState::addCombinationEntries() { for (SInt32 g = 0, n = m_keyMap.getNumGroups(); g < n; ++g) { // add dead and compose key composition sequences for (const KeyID* i = s_decomposeTable; *i != 0; ++i) { // count the decomposed keys for this key UInt32 numKeys = 0; for (const KeyID* j = i; *++j != 0; ) { ++numKeys; } // add an entry for this key m_keyMap.addKeyCombinationEntry(*i, g, i + 1, numKeys); // next key i += numKeys + 1; } } } void KeyState::fakeKeys(const Keystrokes& keys, UInt32 count) { // do nothing if no keys or no repeats if (count == 0 || keys.empty()) { return; } // generate key events LOG((CLOG_DEBUG1 "keystrokes:")); for (auto k = keys.begin(); k != keys.end(); ) { if (k->m_type == Keystroke::kButton && k->m_data.m_button.m_repeat) { // repeat from here up to but not including the next key // with m_repeat == false count times. auto start = k; while (count-- > 0) { // send repeating events for (k = start; k != keys.end() && k->m_type == Keystroke::kButton && k->m_data.m_button.m_repeat; ++k) { fakeKey(*k); } } // note -- k is now on the first non-repeat key after the // repeat keys, exactly where we'd like to continue from. } else { // send event fakeKey(*k); // next key ++k; } } } void KeyState::updateModifierKeyState(KeyButton button, const ModifierToKeys& oldModifiers, const ModifierToKeys& newModifiers) { // get the pressed modifier buttons before and after synergy::KeyMap::ButtonToKeyMap oldKeys, newKeys; for (const auto & oldModifier : oldModifiers) { oldKeys.insert(std::make_pair(oldModifier.second.m_button, &oldModifier.second)); } for (const auto & newModifier : newModifiers) { newKeys.insert(std::make_pair(newModifier.second.m_button, &newModifier.second)); } // get the modifier buttons that were pressed or released synergy::KeyMap::ButtonToKeyMap pressed, released; std::set_difference(oldKeys.begin(), oldKeys.end(), newKeys.begin(), newKeys.end(), std::inserter(released, released.end()), ButtonToKeyLess()); std::set_difference(newKeys.begin(), newKeys.end(), oldKeys.begin(), oldKeys.end(), std::inserter(pressed, pressed.end()), ButtonToKeyLess()); // update state for (synergy::KeyMap::ButtonToKeyMap::const_iterator i = released.begin(); i != released.end(); ++i) { if (i->first != button) { m_keys[i->first] = 0; m_syntheticKeys[i->first] = 0; } } for (synergy::KeyMap::ButtonToKeyMap::const_iterator i = pressed.begin(); i != pressed.end(); ++i) { if (i->first != button) { m_keys[i->first] = 1; m_syntheticKeys[i->first] = 1; m_keyClientData[i->first] = i->second->m_client; } } } // // KeyState::AddActiveModifierContext // KeyState::AddActiveModifierContext::AddActiveModifierContext( SInt32 group, KeyModifierMask mask, ModifierToKeys& activeModifiers) : m_activeGroup(group), m_mask(mask), m_activeModifiers(activeModifiers) { // do nothing }
gpl-2.0
Enturion/WCloud
src/server/scripts/EasternKingdoms/BlackrockSpire/boss_gyth.cpp
7004
/* * Copyright (C) 2010-2011 Project WCloud <http://www.projectwcloud.org/> * Copyright (C) 2008-2011 WCloudCore <http://www.wcloudcore.org/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.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, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "blackrock_spire.h" enum Spells { SPELL_CORROSIVE_ACID = 20667, SPELL_FREEZE = 18763, SPELL_FLAMEBREATH = 20712, SPELL_SELF_ROOT_FOREVER = 33356, }; enum Adds { MODEL_REND_ON_DRAKE = 9723, // TODO: use creature_template 10459 instead of its modelid NPC_RAGE_TALON_FIRE_TONG = 10372, NPC_CHROMATIC_WHELP = 10442, NPC_CHROMATIC_DRAGONSPAWN = 10447, NPC_BLACKHAND_ELITE = 10317, }; enum Events { EVENT_SUMMON_REND = 1, EVENT_AGGRO = 2, EVENT_SUMMON_DRAGON_PACK = 3, EVENT_SUMMON_ORC_PACK = 4, EVENT_CORROSIVE_ACID = 5, EVENT_FREEZE = 6, EVENT_FLAME_BREATH = 7, }; class boss_gyth : public CreatureScript { public: boss_gyth() : CreatureScript("boss_gyth") { } struct boss_gythAI : public BossAI { boss_gythAI(Creature* creature) : BossAI(creature, DATA_GYTH) { DoCast(me, SPELL_SELF_ROOT_FOREVER); } bool SummonedRend; void Reset() { _Reset(); SummonedRend = false; //Invisible for event start me->SetVisible(false); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); } void EnterCombat(Unit* /*who*/) { _EnterCombat(); events.ScheduleEvent(EVENT_SUMMON_DRAGON_PACK, 3*IN_MILLISECONDS); events.ScheduleEvent(EVENT_SUMMON_ORC_PACK, 60*IN_MILLISECONDS); events.ScheduleEvent(EVENT_AGGRO, 60*IN_MILLISECONDS); } void JustDied(Unit* /*who*/) { _JustDied(); } void SummonCreatureWithRandomTarget(uint32 creatureId, uint8 count) { for (uint8 n = 0; n < count; n++) if (Unit* Summoned = me->SummonCreature(creatureId, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), 0, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 240*IN_MILLISECONDS)) if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 50.0f, true)) Summoned->AddThreat(target, 250.0f); } void UpdateAI(uint32 const diff) { if (!UpdateVictim()) return; if (!SummonedRend && HealthBelowPct(11)) { events.ScheduleEvent(EVENT_SUMMON_REND, 8*IN_MILLISECONDS); SummonedRend = true; } events.Update(diff); if (me->HasUnitState(UNIT_STAT_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_SUMMON_REND: // Summon Rend and Change model to normal Gyth // Interrupt any spell casting me->InterruptNonMeleeSpells(false); // Gyth model me->SetDisplayId(me->GetCreatureInfo()->Modelid1); me->SummonCreature(NPC_WARCHIEF_REND_BLACKHAND, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), 0, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 900*IN_MILLISECONDS); events.ScheduleEvent(EVENT_CORROSIVE_ACID, 8*IN_MILLISECONDS); events.ScheduleEvent(EVENT_FREEZE, 11*IN_MILLISECONDS); events.ScheduleEvent(EVENT_FLAME_BREATH, 4*IN_MILLISECONDS); events.CancelEvent(EVENT_SUMMON_REND); break; case EVENT_AGGRO: me->SetVisible(true); me->SetDisplayId(MODEL_REND_ON_DRAKE); me->setFaction(14); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); events.CancelEvent(EVENT_AGGRO); break; // Summon Dragon pack. 2 Dragons and 3 Whelps case EVENT_SUMMON_DRAGON_PACK: for (uint8 i = 0; i < urand(0, 3) + 2; ++i) { SummonCreatureWithRandomTarget(NPC_RAGE_TALON_FIRE_TONG, 2); SummonCreatureWithRandomTarget(NPC_CHROMATIC_WHELP, 3); } events.CancelEvent(EVENT_SUMMON_DRAGON_PACK); break; // Summon Orc pack. 1 Orc Handler 1 Elite Dragonkin and 3 Whelps case EVENT_SUMMON_ORC_PACK: for (uint8 i = 0; i < urand (0, 5) + 2; ++i) { SummonCreatureWithRandomTarget(NPC_CHROMATIC_DRAGONSPAWN, 1); SummonCreatureWithRandomTarget(NPC_BLACKHAND_ELITE, 1); SummonCreatureWithRandomTarget(NPC_CHROMATIC_WHELP, 3); } events.CancelEvent(EVENT_SUMMON_ORC_PACK); break; case EVENT_CORROSIVE_ACID: DoCast(me->getVictim(), SPELL_CORROSIVE_ACID); events.ScheduleEvent(EVENT_CORROSIVE_ACID, 7*IN_MILLISECONDS); break; case EVENT_FREEZE: DoCast(me->getVictim(), SPELL_FREEZE); events.ScheduleEvent(EVENT_FREEZE, 16*IN_MILLISECONDS); break; case EVENT_FLAME_BREATH: DoCast(me->getVictim(), SPELL_FLAMEBREATH); events.ScheduleEvent(EVENT_FLAME_BREATH, 10500); break; } } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const { return new boss_gythAI(creature); } }; void AddSC_boss_gyth() { new boss_gyth(); }
gpl-2.0
Gullanshire/Minecraft_Mod-The_Exorcist
1.7.10/1.7.10_forge/src/main/java/exorcist/Recipes.java
930
package exorcist; import net.minecraft.item.ItemStack; import cpw.mods.fml.common.registry.GameRegistry; import exorcist_blocks.Main_Blocks; import exorcist_items.Main_Items; public class Recipes { public static void Initialize_Recipes(){ ItemStack moonstone1=new ItemStack(Main_Items.moonstone,1); ItemStack moonstone9=new ItemStack(Main_Items.moonstone,9); ItemStack moonstoneBlock1=new ItemStack(Main_Blocks.moonstoneBlock,1); GameRegistry.addRecipe(moonstoneBlock1, "xxx", "xxx", "xxx",'x', moonstone1); GameRegistry.addRecipe(moonstone9, "x",'x', moonstoneBlock1); ItemStack silverIngot1=new ItemStack(Main_Items.silverIngot,1); ItemStack silverIngot9=new ItemStack(Main_Items.silverIngot,9); ItemStack silverBlock1=new ItemStack(Main_Blocks.silverBlock,1); GameRegistry.addRecipe(silverBlock1, "xxx", "xxx", "xxx",'x', silverIngot1); GameRegistry.addRecipe(silverIngot9, "x",'x', silverBlock1); } }
gpl-2.0
BollerTuneZ/App.Server
BTZ.Common/DTO/UserDto.cs
194
using System; namespace BTZ.Common { public class UserDto { public UserDto () { } public string Username{ get; set; } public string Password{ get; set; } } }
gpl-2.0
sbesson/zeroc-ice
java/demo/book/map_filesystem/DirectoryI.java
12313
// ********************************************************************** // // Copyright (c) 2003-2013 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. // // ********************************************************************** import Filesystem.*; import FilesystemDB.*; public class DirectoryI extends _DirectoryDisp { public DirectoryI(Ice.Communicator communicator, String envName) { _communicator = communicator; _envName = envName; Freeze.Connection connection = Freeze.Util.createConnection(_communicator, _envName); try { IdentityDirectoryEntryMap dirDB = new IdentityDirectoryEntryMap(connection, directoriesDB()); // // Create the record for the root directory if necessary. // for(;;) { try { Ice.Identity rootId = new Ice.Identity("RootDir", ""); DirectoryEntry entry = dirDB.get(rootId); if(entry == null) { dirDB.put(rootId, new DirectoryEntry("/", new Ice.Identity("", ""), null)); } break; } catch(Freeze.DeadlockException ex) { continue; } catch(Freeze.DatabaseException ex) { halt(ex); } } } finally { connection.close(); } } public String name(Ice.Current c) { Freeze.Connection connection = Freeze.Util.createConnection(_communicator, _envName); try { IdentityDirectoryEntryMap dirDB = new IdentityDirectoryEntryMap(connection, directoriesDB()); for(;;) { try { DirectoryEntry entry = dirDB.get(c.id); if(entry == null) { throw new Ice.ObjectNotExistException(); } return entry.name; } catch(Freeze.DeadlockException ex) { continue; } catch(Freeze.DatabaseException ex) { halt(ex); } } } finally { connection.close(); } } public NodeDesc[] list(Ice.Current c) { Freeze.Connection connection = Freeze.Util.createConnection(_communicator, _envName); try { IdentityDirectoryEntryMap dirDB = new IdentityDirectoryEntryMap(connection, directoriesDB()); for(;;) { try { DirectoryEntry entry = dirDB.get(c.id); if(entry == null) { throw new Ice.ObjectNotExistException(); } NodeDesc[] result = new NodeDesc[entry.nodes.size()]; java.util.Iterator<NodeDesc> p = entry.nodes.values().iterator(); for(int i = 0; i < entry.nodes.size(); ++i) { result[i] = p.next(); } return result; } catch(Freeze.DeadlockException ex) { continue; } catch(Freeze.DatabaseException ex) { halt(ex); } } } finally { connection.close(); } } public NodeDesc find(String name, Ice.Current c) throws NoSuchName { Freeze.Connection connection = Freeze.Util.createConnection(_communicator, _envName); try { IdentityDirectoryEntryMap dirDB = new IdentityDirectoryEntryMap(connection, directoriesDB()); for(;;) { try { DirectoryEntry entry = dirDB.get(c.id); if(entry == null) { throw new Ice.ObjectNotExistException(); } NodeDesc nd = entry.nodes.get(name); if(nd == null) { throw new NoSuchName(name); } return nd; } catch(Freeze.DeadlockException ex) { continue; } catch(Freeze.DatabaseException ex) { halt(ex); } } } finally { connection.close(); } } public FilePrx createFile(String name, Ice.Current c) throws NameInUse { Freeze.Connection connection = Freeze.Util.createConnection(_communicator, _envName); try { IdentityFileEntryMap fileDB = new IdentityFileEntryMap(connection, FileI.filesDB()); IdentityDirectoryEntryMap dirDB = new IdentityDirectoryEntryMap(connection, directoriesDB()); for(;;) { // // The transaction is necessary since we are altering // two records in one atomic action. // Freeze.Transaction txn = null; try { txn = connection.beginTransaction(); DirectoryEntry entry = dirDB.get(c.id); if(entry == null) { throw new Ice.ObjectNotExistException(); } if(name.length() == 0 || entry.nodes.get(name) != null) { throw new NameInUse(name); } FileEntry newEntry = new FileEntry(name, c.id, null); Ice.Identity id = new Ice.Identity(java.util.UUID.randomUUID().toString(), "file"); FilePrx proxy = FilePrxHelper.uncheckedCast(c.adapter.createProxy(id)); entry.nodes.put(name, new NodeDesc(name, NodeType.FileType, proxy)); dirDB.put(c.id, entry); fileDB.put(id, newEntry); txn.commit(); txn = null; return proxy; } catch(Freeze.DeadlockException ex) { continue; } catch(Freeze.DatabaseException ex) { halt(ex); } finally { if(txn != null) { txn.rollback(); } } } } finally { connection.close(); } } public DirectoryPrx createDirectory(String name, Ice.Current c) throws NameInUse { Freeze.Connection connection = Freeze.Util.createConnection(_communicator, _envName); try { IdentityDirectoryEntryMap dirDB = new IdentityDirectoryEntryMap(connection, directoriesDB()); for(;;) { // // The transaction is necessary since we are altering // two records in one atomic action. // Freeze.Transaction txn = null; try { txn = connection.beginTransaction(); DirectoryEntry entry = dirDB.get(c.id); if(entry == null) { throw new Ice.ObjectNotExistException(); } if(name.length() == 0 || entry.nodes.get(name) != null) { throw new NameInUse(name); } DirectoryEntry newEntry = new DirectoryEntry(name, c.id, null); Ice.Identity id = new Ice.Identity(java.util.UUID.randomUUID().toString(), ""); DirectoryPrx proxy = DirectoryPrxHelper.uncheckedCast(c.adapter.createProxy(id)); entry.nodes.put(name, new NodeDesc(name, NodeType.DirType, proxy)); dirDB.put(c.id, entry); dirDB.put(id, newEntry); txn.commit(); txn = null; return proxy; } catch(Freeze.DeadlockException ex) { continue; } catch(Freeze.DatabaseException ex) { halt(ex); } finally { if(txn != null) { txn.rollback(); } } } } finally { connection.close(); } } public void destroy(Ice.Current c) throws PermissionDenied { Freeze.Connection connection = Freeze.Util.createConnection(_communicator, _envName); try { IdentityDirectoryEntryMap dirDB = new IdentityDirectoryEntryMap(connection, directoriesDB()); for(;;) { // // The transaction is necessary since we are altering // two records in one atomic action. // Freeze.Transaction txn = null; try { txn = connection.beginTransaction(); DirectoryEntry entry = dirDB.get(c.id); if(entry == null) { throw new Ice.ObjectNotExistException(); } if(entry.parent.name.length() == 0) { throw new PermissionDenied("Cannot destroy root directory"); } if(!entry.nodes.isEmpty()) { throw new PermissionDenied("Cannot destroy non-empty directory"); } DirectoryEntry dirEntry = dirDB.get(entry.parent); if(dirEntry == null) { halt(new Freeze.DatabaseException("consistency error: directory without parent")); } dirEntry.nodes.remove(entry.name); dirDB.put(entry.parent, dirEntry); dirDB.remove(c.id); txn.commit(); txn = null; break; } catch(Freeze.DeadlockException ex) { continue; } catch(Freeze.DatabaseException ex) { halt(ex); } finally { if(txn != null) { txn.rollback(); } } } } finally { connection.close(); } } private void halt(Freeze.DatabaseException e) { // // If this is called it's very bad news. We log the error and // then kill the server. // java.io.StringWriter sw = new java.io.StringWriter(); java.io.PrintWriter pw = new java.io.PrintWriter(sw); e.printStackTrace(pw); pw.flush(); _communicator.getLogger().error("fatal database error\n" + sw.toString() + "\n*** Halting JVM ***"); Runtime.getRuntime().halt(1); } public static String directoriesDB() { return "directories"; } private Ice.Communicator _communicator; private String _envName; }
gpl-2.0
seewindcn/tortoisehg
src/ext/dulwich/tests/test_porcelain.py
27560
# test_porcelain.py -- porcelain tests # Copyright (C) 2013 Jelmer Vernooij <[email protected]> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; version 2 # of the License or (at your option) a 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. """Tests for dulwich.porcelain.""" from contextlib import closing from io import BytesIO try: from StringIO import StringIO except ImportError: from io import StringIO import os import shutil import tarfile import tempfile from dulwich import porcelain from dulwich.diff_tree import tree_changes from dulwich.objects import ( Blob, Tag, Tree, ) from dulwich.repo import Repo from dulwich.tests import ( TestCase, ) from dulwich.tests.utils import ( build_commit_graph, make_object, ) class PorcelainTestCase(TestCase): def setUp(self): super(PorcelainTestCase, self).setUp() repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) self.repo = Repo.init(repo_dir) def tearDown(self): super(PorcelainTestCase, self).tearDown() self.repo.close() class ArchiveTests(PorcelainTestCase): """Tests for the archive command.""" def test_simple(self): c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"refs/heads/master"] = c3.id out = BytesIO() err = BytesIO() porcelain.archive(self.repo.path, b"refs/heads/master", outstream=out, errstream=err) self.assertEqual(b"", err.getvalue()) tf = tarfile.TarFile(fileobj=out) self.addCleanup(tf.close) self.assertEqual([], tf.getnames()) class UpdateServerInfoTests(PorcelainTestCase): def test_simple(self): c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"refs/heads/foo"] = c3.id porcelain.update_server_info(self.repo.path) self.assertTrue(os.path.exists(os.path.join(self.repo.controldir(), 'info', 'refs'))) class CommitTests(PorcelainTestCase): def test_custom_author(self): c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"refs/heads/foo"] = c3.id sha = porcelain.commit(self.repo.path, message=b"Some message", author=b"Joe <[email protected]>", committer=b"Bob <[email protected]>") self.assertTrue(isinstance(sha, bytes)) self.assertEqual(len(sha), 40) class CloneTests(PorcelainTestCase): def test_simple_local(self): f1_1 = make_object(Blob, data=b'f1') commit_spec = [[1], [2, 1], [3, 1, 2]] trees = {1: [(b'f1', f1_1), (b'f2', f1_1)], 2: [(b'f1', f1_1), (b'f2', f1_1)], 3: [(b'f1', f1_1), (b'f2', f1_1)], } c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees) self.repo.refs[b"refs/heads/master"] = c3.id target_path = tempfile.mkdtemp() errstream = BytesIO() self.addCleanup(shutil.rmtree, target_path) r = porcelain.clone(self.repo.path, target_path, checkout=False, errstream=errstream) self.assertEqual(r.path, target_path) self.assertEqual(Repo(target_path).head(), c3.id) self.assertTrue(b'f1' not in os.listdir(target_path)) self.assertTrue(b'f2' not in os.listdir(target_path)) def test_simple_local_with_checkout(self): f1_1 = make_object(Blob, data=b'f1') commit_spec = [[1], [2, 1], [3, 1, 2]] trees = {1: [(b'f1', f1_1), (b'f2', f1_1)], 2: [(b'f1', f1_1), (b'f2', f1_1)], 3: [(b'f1', f1_1), (b'f2', f1_1)], } c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees) self.repo.refs[b"refs/heads/master"] = c3.id target_path = tempfile.mkdtemp() errstream = BytesIO() self.addCleanup(shutil.rmtree, target_path) with closing(porcelain.clone(self.repo.path, target_path, checkout=True, errstream=errstream)) as r: self.assertEqual(r.path, target_path) with closing(Repo(target_path)) as r: self.assertEqual(r.head(), c3.id) self.assertTrue('f1' in os.listdir(target_path)) self.assertTrue('f2' in os.listdir(target_path)) def test_bare_local_with_checkout(self): f1_1 = make_object(Blob, data=b'f1') commit_spec = [[1], [2, 1], [3, 1, 2]] trees = {1: [(b'f1', f1_1), (b'f2', f1_1)], 2: [(b'f1', f1_1), (b'f2', f1_1)], 3: [(b'f1', f1_1), (b'f2', f1_1)], } c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees) self.repo.refs[b"refs/heads/master"] = c3.id target_path = tempfile.mkdtemp() errstream = BytesIO() self.addCleanup(shutil.rmtree, target_path) r = porcelain.clone(self.repo.path, target_path, bare=True, errstream=errstream) self.assertEqual(r.path, target_path) self.assertEqual(Repo(target_path).head(), c3.id) self.assertFalse(b'f1' in os.listdir(target_path)) self.assertFalse(b'f2' in os.listdir(target_path)) def test_no_checkout_with_bare(self): f1_1 = make_object(Blob, data=b'f1') commit_spec = [[1]] trees = {1: [(b'f1', f1_1), (b'f2', f1_1)]} (c1, ) = build_commit_graph(self.repo.object_store, commit_spec, trees) self.repo.refs[b"refs/heads/master"] = c1.id target_path = tempfile.mkdtemp() errstream = BytesIO() self.addCleanup(shutil.rmtree, target_path) self.assertRaises(ValueError, porcelain.clone, self.repo.path, target_path, checkout=True, bare=True, errstream=errstream) class InitTests(TestCase): def test_non_bare(self): repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) porcelain.init(repo_dir) def test_bare(self): repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) porcelain.init(repo_dir, bare=True) class AddTests(PorcelainTestCase): def test_add_default_paths(self): # create a file for initial commit with open(os.path.join(self.repo.path, 'blah'), 'w') as f: f.write("\n") porcelain.add(repo=self.repo.path, paths=['blah']) porcelain.commit(repo=self.repo.path, message=b'test', author=b'test', committer=b'test') # Add a second test file and a file in a directory with open(os.path.join(self.repo.path, 'foo'), 'w') as f: f.write("\n") os.mkdir(os.path.join(self.repo.path, 'adir')) with open(os.path.join(self.repo.path, 'adir', 'afile'), 'w') as f: f.write("\n") porcelain.add(self.repo.path) # Check that foo was added and nothing in .git was modified index = self.repo.open_index() self.assertEqual(sorted(index), [b'adir/afile', b'blah', b'foo']) def test_add_file(self): with open(os.path.join(self.repo.path, 'foo'), 'w') as f: f.write("BAR") porcelain.add(self.repo.path, paths=["foo"]) class RemoveTests(PorcelainTestCase): def test_remove_file(self): with open(os.path.join(self.repo.path, 'foo'), 'w') as f: f.write("BAR") porcelain.add(self.repo.path, paths=["foo"]) porcelain.rm(self.repo.path, paths=["foo"]) class LogTests(PorcelainTestCase): def test_simple(self): c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"HEAD"] = c3.id outstream = StringIO() porcelain.log(self.repo.path, outstream=outstream) self.assertEqual(3, outstream.getvalue().count("-" * 50)) def test_max_entries(self): c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"HEAD"] = c3.id outstream = StringIO() porcelain.log(self.repo.path, outstream=outstream, max_entries=1) self.assertEqual(1, outstream.getvalue().count("-" * 50)) class ShowTests(PorcelainTestCase): def test_nolist(self): c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"HEAD"] = c3.id outstream = StringIO() porcelain.show(self.repo.path, objects=c3.id, outstream=outstream) self.assertTrue(outstream.getvalue().startswith("-" * 50)) def test_simple(self): c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"HEAD"] = c3.id outstream = StringIO() porcelain.show(self.repo.path, objects=[c3.id], outstream=outstream) self.assertTrue(outstream.getvalue().startswith("-" * 50)) def test_blob(self): b = Blob.from_string(b"The Foo\n") self.repo.object_store.add_object(b) outstream = StringIO() porcelain.show(self.repo.path, objects=[b.id], outstream=outstream) self.assertEqual(outstream.getvalue(), "The Foo\n") class SymbolicRefTests(PorcelainTestCase): def test_set_wrong_symbolic_ref(self): c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"HEAD"] = c3.id self.assertRaises(ValueError, porcelain.symbolic_ref, self.repo.path, b'foobar') def test_set_force_wrong_symbolic_ref(self): c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"HEAD"] = c3.id porcelain.symbolic_ref(self.repo.path, b'force_foobar', force=True) #test if we actually changed the file with self.repo.get_named_file('HEAD') as f: new_ref = f.read() self.assertEqual(new_ref, b'ref: refs/heads/force_foobar\n') def test_set_symbolic_ref(self): c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"HEAD"] = c3.id porcelain.symbolic_ref(self.repo.path, b'master') def test_set_symbolic_ref_other_than_master(self): c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]], attrs=dict(refs='develop')) self.repo.refs[b"HEAD"] = c3.id self.repo.refs[b"refs/heads/develop"] = c3.id porcelain.symbolic_ref(self.repo.path, b'develop') #test if we actually changed the file with self.repo.get_named_file('HEAD') as f: new_ref = f.read() self.assertEqual(new_ref, b'ref: refs/heads/develop\n') class DiffTreeTests(PorcelainTestCase): def test_empty(self): c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"HEAD"] = c3.id outstream = BytesIO() porcelain.diff_tree(self.repo.path, c2.tree, c3.tree, outstream=outstream) self.assertEqual(outstream.getvalue(), b"") class CommitTreeTests(PorcelainTestCase): def test_simple(self): c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) b = Blob() b.data = b"foo the bar" t = Tree() t.add(b"somename", 0o100644, b.id) self.repo.object_store.add_object(t) self.repo.object_store.add_object(b) sha = porcelain.commit_tree( self.repo.path, t.id, message=b"Withcommit.", author=b"Joe <[email protected]>", committer=b"Jane <[email protected]>") self.assertTrue(isinstance(sha, bytes)) self.assertEqual(len(sha), 40) class RevListTests(PorcelainTestCase): def test_simple(self): c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) outstream = BytesIO() porcelain.rev_list( self.repo.path, [c3.id], outstream=outstream) self.assertEqual( c3.id + b"\n" + c2.id + b"\n" + c1.id + b"\n", outstream.getvalue()) class TagCreateTests(PorcelainTestCase): def test_annotated(self): c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"HEAD"] = c3.id porcelain.tag_create(self.repo.path, b"tryme", b'foo <[email protected]>', b'bar', annotated=True) tags = self.repo.refs.as_dict(b"refs/tags") self.assertEqual(list(tags.keys()), [b"tryme"]) tag = self.repo[b'refs/tags/tryme'] self.assertTrue(isinstance(tag, Tag)) self.assertEqual(b"foo <[email protected]>", tag.tagger) self.assertEqual(b"bar", tag.message) def test_unannotated(self): c1, c2, c3 = build_commit_graph(self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"HEAD"] = c3.id porcelain.tag_create(self.repo.path, b"tryme", annotated=False) tags = self.repo.refs.as_dict(b"refs/tags") self.assertEqual(list(tags.keys()), [b"tryme"]) self.repo[b'refs/tags/tryme'] self.assertEqual(list(tags.values()), [self.repo.head()]) class TagListTests(PorcelainTestCase): def test_empty(self): tags = porcelain.tag_list(self.repo.path) self.assertEqual([], tags) def test_simple(self): self.repo.refs[b"refs/tags/foo"] = b"aa" * 20 self.repo.refs[b"refs/tags/bar/bla"] = b"bb" * 20 tags = porcelain.tag_list(self.repo.path) self.assertEqual([b"bar/bla", b"foo"], tags) class TagDeleteTests(PorcelainTestCase): def test_simple(self): [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo[b"HEAD"] = c1.id porcelain.tag_create(self.repo, b'foo') self.assertTrue(b"foo" in porcelain.tag_list(self.repo)) porcelain.tag_delete(self.repo, b'foo') self.assertFalse(b"foo" in porcelain.tag_list(self.repo)) class ResetTests(PorcelainTestCase): def test_hard_head(self): with open(os.path.join(self.repo.path, 'foo'), 'w') as f: f.write("BAR") porcelain.add(self.repo.path, paths=["foo"]) porcelain.commit(self.repo.path, message=b"Some message", committer=b"Jane <[email protected]>", author=b"John <[email protected]>") with open(os.path.join(self.repo.path, 'foo'), 'wb') as f: f.write(b"OOH") porcelain.reset(self.repo, "hard", b"HEAD") index = self.repo.open_index() changes = list(tree_changes(self.repo, index.commit(self.repo.object_store), self.repo[b'HEAD'].tree)) self.assertEqual([], changes) class PushTests(PorcelainTestCase): def test_simple(self): """ Basic test of porcelain push where self.repo is the remote. First clone the remote, commit a file to the clone, then push the changes back to the remote. """ outstream = BytesIO() errstream = BytesIO() porcelain.commit(repo=self.repo.path, message=b'init', author=b'', committer=b'') # Setup target repo cloned from temp test repo clone_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, clone_path) target_repo = porcelain.clone(self.repo.path, target=clone_path, errstream=errstream) target_repo.close() # create a second file to be pushed back to origin handle, fullpath = tempfile.mkstemp(dir=clone_path) os.close(handle) porcelain.add(repo=clone_path, paths=[os.path.basename(fullpath)]) porcelain.commit(repo=clone_path, message=b'push', author=b'', committer=b'') # Setup a non-checked out branch in the remote refs_path = b"refs/heads/foo" self.repo.refs[refs_path] = self.repo[b'HEAD'].id # Push to the remote porcelain.push(clone_path, self.repo.path, b"HEAD:" + refs_path, outstream=outstream, errstream=errstream) # Check that the target and source with closing(Repo(clone_path)) as r_clone: self.assertEqual(r_clone[b'HEAD'].id, self.repo[refs_path].id) # Get the change in the target repo corresponding to the add # this will be in the foo branch. change = list(tree_changes(self.repo, self.repo[b'HEAD'].tree, self.repo[b'refs/heads/foo'].tree))[0] self.assertEqual(os.path.basename(fullpath), change.new.path.decode('ascii')) class PullTests(PorcelainTestCase): def test_simple(self): outstream = BytesIO() errstream = BytesIO() # create a file for initial commit handle, fullpath = tempfile.mkstemp(dir=self.repo.path) os.close(handle) filename = os.path.basename(fullpath) porcelain.add(repo=self.repo.path, paths=filename) porcelain.commit(repo=self.repo.path, message=b'test', author=b'test', committer=b'test') # Setup target repo target_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, target_path) target_repo = porcelain.clone(self.repo.path, target=target_path, errstream=errstream) target_repo.close() # create a second file to be pushed handle, fullpath = tempfile.mkstemp(dir=self.repo.path) os.close(handle) filename = os.path.basename(fullpath) porcelain.add(repo=self.repo.path, paths=filename) porcelain.commit(repo=self.repo.path, message=b'test2', author=b'test2', committer=b'test2') self.assertTrue(b'refs/heads/master' in self.repo.refs) self.assertTrue(b'refs/heads/master' in target_repo.refs) # Pull changes into the cloned repo porcelain.pull(target_path, self.repo.path, b'refs/heads/master', outstream=outstream, errstream=errstream) # Check the target repo for pushed changes with closing(Repo(target_path)) as r: self.assertEqual(r[b'HEAD'].id, self.repo[b'HEAD'].id) class StatusTests(PorcelainTestCase): def test_status(self): """Integration test for `status` functionality.""" # Commit a dummy file then modify it fullpath = os.path.join(self.repo.path, 'foo') with open(fullpath, 'w') as f: f.write('origstuff') porcelain.add(repo=self.repo.path, paths=['foo']) porcelain.commit(repo=self.repo.path, message=b'test status', author=b'', committer=b'') # modify access and modify time of path os.utime(fullpath, (0, 0)) with open(fullpath, 'wb') as f: f.write(b'stuff') # Make a dummy file and stage it filename_add = 'bar' fullpath = os.path.join(self.repo.path, filename_add) with open(fullpath, 'w') as f: f.write('stuff') porcelain.add(repo=self.repo.path, paths=filename_add) results = porcelain.status(self.repo) self.assertEqual(results.staged['add'][0], filename_add.encode('ascii')) self.assertEqual(results.unstaged, [b'foo']) def test_get_tree_changes_add(self): """Unit test for get_tree_changes add.""" # Make a dummy file, stage filename = 'bar' with open(os.path.join(self.repo.path, filename), 'w') as f: f.write('stuff') porcelain.add(repo=self.repo.path, paths=filename) porcelain.commit(repo=self.repo.path, message=b'test status', author=b'', committer=b'') filename = 'foo' with open(os.path.join(self.repo.path, filename), 'w') as f: f.write('stuff') porcelain.add(repo=self.repo.path, paths=filename) changes = porcelain.get_tree_changes(self.repo.path) self.assertEqual(changes['add'][0], filename.encode('ascii')) self.assertEqual(len(changes['add']), 1) self.assertEqual(len(changes['modify']), 0) self.assertEqual(len(changes['delete']), 0) def test_get_tree_changes_modify(self): """Unit test for get_tree_changes modify.""" # Make a dummy file, stage, commit, modify filename = 'foo' fullpath = os.path.join(self.repo.path, filename) with open(fullpath, 'w') as f: f.write('stuff') porcelain.add(repo=self.repo.path, paths=filename) porcelain.commit(repo=self.repo.path, message=b'test status', author=b'', committer=b'') with open(fullpath, 'w') as f: f.write('otherstuff') porcelain.add(repo=self.repo.path, paths=filename) changes = porcelain.get_tree_changes(self.repo.path) self.assertEqual(changes['modify'][0], filename.encode('ascii')) self.assertEqual(len(changes['add']), 0) self.assertEqual(len(changes['modify']), 1) self.assertEqual(len(changes['delete']), 0) def test_get_tree_changes_delete(self): """Unit test for get_tree_changes delete.""" # Make a dummy file, stage, commit, remove filename = 'foo' with open(os.path.join(self.repo.path, filename), 'w') as f: f.write('stuff') porcelain.add(repo=self.repo.path, paths=filename) porcelain.commit(repo=self.repo.path, message=b'test status', author=b'', committer=b'') porcelain.rm(repo=self.repo.path, paths=[filename]) changes = porcelain.get_tree_changes(self.repo.path) self.assertEqual(changes['delete'][0], filename.encode('ascii')) self.assertEqual(len(changes['add']), 0) self.assertEqual(len(changes['modify']), 0) self.assertEqual(len(changes['delete']), 1) # TODO(jelmer): Add test for dulwich.porcelain.daemon class UploadPackTests(PorcelainTestCase): """Tests for upload_pack.""" def test_upload_pack(self): outf = BytesIO() exitcode = porcelain.upload_pack(self.repo.path, BytesIO(b"0000"), outf) outlines = outf.getvalue().splitlines() self.assertEqual([b"0000"], outlines) self.assertEqual(0, exitcode) class ReceivePackTests(PorcelainTestCase): """Tests for receive_pack.""" def test_receive_pack(self): filename = 'foo' with open(os.path.join(self.repo.path, filename), 'w') as f: f.write('stuff') porcelain.add(repo=self.repo.path, paths=filename) self.repo.do_commit(message=b'test status', author=b'', committer=b'', author_timestamp=1402354300, commit_timestamp=1402354300, author_timezone=0, commit_timezone=0) outf = BytesIO() exitcode = porcelain.receive_pack(self.repo.path, BytesIO(b"0000"), outf) outlines = outf.getvalue().splitlines() self.assertEqual([ b'00739e65bdcf4a22cdd4f3700604a275cd2aaf146b23 HEAD\x00 report-status ' b'delete-refs quiet ofs-delta side-band-64k no-done', b'003f9e65bdcf4a22cdd4f3700604a275cd2aaf146b23 refs/heads/master', b'0000'], outlines) self.assertEqual(0, exitcode) class BranchListTests(PorcelainTestCase): def test_standard(self): self.assertEqual(set([]), set(porcelain.branch_list(self.repo))) def test_new_branch(self): [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo[b"HEAD"] = c1.id porcelain.branch_create(self.repo, b"foo") self.assertEqual( set([b"master", b"foo"]), set(porcelain.branch_list(self.repo))) class BranchCreateTests(PorcelainTestCase): def test_branch_exists(self): [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo[b"HEAD"] = c1.id porcelain.branch_create(self.repo, b"foo") self.assertRaises(KeyError, porcelain.branch_create, self.repo, b"foo") porcelain.branch_create(self.repo, b"foo", force=True) def test_new_branch(self): [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo[b"HEAD"] = c1.id porcelain.branch_create(self.repo, b"foo") self.assertEqual( set([b"master", b"foo"]), set(porcelain.branch_list(self.repo))) class BranchDeleteTests(PorcelainTestCase): def test_simple(self): [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo[b"HEAD"] = c1.id porcelain.branch_create(self.repo, b'foo') self.assertTrue(b"foo" in porcelain.branch_list(self.repo)) porcelain.branch_delete(self.repo, b'foo') self.assertFalse(b"foo" in porcelain.branch_list(self.repo)) class FetchTests(PorcelainTestCase): def test_simple(self): outstream = BytesIO() errstream = BytesIO() # create a file for initial commit handle, fullpath = tempfile.mkstemp(dir=self.repo.path) os.close(handle) filename = os.path.basename(fullpath) porcelain.add(repo=self.repo.path, paths=filename) porcelain.commit(repo=self.repo.path, message=b'test', author=b'test', committer=b'test') # Setup target repo target_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, target_path) target_repo = porcelain.clone(self.repo.path, target=target_path, errstream=errstream) # create a second file to be pushed handle, fullpath = tempfile.mkstemp(dir=self.repo.path) os.close(handle) filename = os.path.basename(fullpath) porcelain.add(repo=self.repo.path, paths=filename) porcelain.commit(repo=self.repo.path, message=b'test2', author=b'test2', committer=b'test2') self.assertFalse(self.repo[b'HEAD'].id in target_repo) target_repo.close() # Fetch changes into the cloned repo porcelain.fetch(target_path, self.repo.path, outstream=outstream, errstream=errstream) # Check the target repo for pushed changes with closing(Repo(target_path)) as r: self.assertTrue(self.repo[b'HEAD'].id in r) class RepackTests(PorcelainTestCase): def test_empty(self): porcelain.repack(self.repo) def test_simple(self): handle, fullpath = tempfile.mkstemp(dir=self.repo.path) os.close(handle) filename = os.path.basename(fullpath) porcelain.add(repo=self.repo.path, paths=filename) porcelain.repack(self.repo)
gpl-2.0
karianna/jdk8_tl
jdk/src/share/classes/sun/text/resources/is/FormatData_is_IS.java
2347
/* * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved * * The original version of this source code and documentation * is copyrighted and owned by Taligent, Inc., a wholly-owned * subsidiary of IBM. These materials are provided under terms * of a License Agreement between Taligent and Sun. This technology * is protected by multiple US and International patents. * * This notice and attribution to Taligent may not be removed. * Taligent is a registered trademark of Taligent, Inc. * */ package sun.text.resources.is; import java.util.ListResourceBundle; public class FormatData_is_IS extends ListResourceBundle { /** * Overrides ListResourceBundle */ protected final Object[][] getContents() { return new Object[][] { { "NumberPatterns", new String[] { "#,##0.###;-#,##0.###", // decimal pattern "#,##0. \u00A4;-#,##0. \u00A4", // currency pattern "#,##0%" // percent pattern } }, }; } }
gpl-2.0
openvsip/openvsip
src/ovxx/opencl/platform.cpp
1384
// // Copyright (c) 2014 Stefan Seefeld // All rights reserved. // // This file is part of OpenVSIP. It is made available under the // license contained in the accompanying LICENSE.BSD file. #include <ovxx/opencl/platform.hpp> #include <cstdlib> namespace ovxx { namespace opencl { // Create a default OpenCL platform. The first one reported is // typically "Default", which ought to work everywhere. However, // a case has been detected where it doesn't, so we allow an // environment variable to override the chosen index. platform default_platform() { size_t idx = 0; char *ovxx_opencl_platform = std::getenv("OVXX_OPENCL_PLATFORM"); if (ovxx_opencl_platform) { std::istringstream iss(ovxx_opencl_platform); iss >> idx; if (!iss) OVXX_DO_THROW(std::runtime_error("Unable to extract index value from OVXX_OPENCL_PLATFORM envvar.")); } cl_uint nplatforms; OVXX_OPENCL_CHECK_RESULT(clGetPlatformIDs, (0, 0, &nplatforms)); if (!nplatforms) OVXX_DO_THROW(std::runtime_error("No OpenCL platform detected.")); else if (idx >= nplatforms) OVXX_DO_THROW(std::invalid_argument("Invalid OpenCL platform index.")); cl_platform_id *ids = new cl_platform_id[nplatforms]; OVXX_OPENCL_CHECK_RESULT(clGetPlatformIDs, (nplatforms, ids, 0)); platform pl(ids[idx]); delete[] ids; return pl; } } // namespace ovxx::opencl } // namespace ovxx
gpl-2.0
JDjimenezdelgado/old-mmexperience
wp-content/plugins/WP_Visual_Chat/assets/js/admin.js
32561
// sent from pPHP : vcht_operatorID,vcht_operator,vcht_operatorAvatar var vcht_checkTimer; var vcht_lastRep = false; var vcht_currentLogID = 0; var vcht_currentDomElement = ''; var vcht_isChatting = false; vcht_operatorID = vcht_operatorID[0]; vcht_operatorAvatar = vcht_operatorAvatar[0]; jQuery(document).ready(function() { // Tooltips jQuery("[data-toggle=tooltip]").tooltip("show"); // Switch jQuery("[data-toggle='switch']").wrap('<div class="switch" />').parent().bootstrapSwitch(); jQuery('#vcht_operatorname').html(vcht_operator); jQuery('#vcht_consolePanelContent').hide(); jQuery('#vcht_onlineCB').change(function() { if (jQuery(this).is(':checked')) { vcht_operatorConnect(); } else { vcht_operatorDisconnect(); } }); }); function vcht_operatorConnect() { jQuery.ajax({ url: ajaxurl, type: 'post', data: { action: 'vcht_operatorConnect', success: function() { vcht_recoverChats(); } } }); } function vcht_operatorDisconnect() { clearTimeout(vcht_checkTimer); jQuery.ajax({ url: ajaxurl, type: 'post', data: { action: 'vcht_operatorDisconnect', success: function() { } } }); } function vcht_checkUsers() { if (jQuery('#usersList li[data-logid]').length == 0) { jQuery('#vcht_btnMinimize').fadeOut(200); if (jQuery('#usersList li').length == 1) { jQuery('#usersList').append('<li class="vcht_nobody">There are no chat currently</li>'); } vcht_minifyChatPanel(); } else { jQuery('#vcht_btnMinimize').fadeIn(200); jQuery('#vcht_btnMinimize').delay(250).css('display', 'block'); jQuery('#usersList .vcht_nobody').remove(); } if (jQuery('#usersList li[data-logid="' + vcht_currentLogID + '"]').length == 0) { vcht_currentLogID = 0; vcht_minifyChatPanel(); } } function vcht_recoverChats() { jQuery.ajax({ url: ajaxurl, type: 'post', data: { action: 'vcht_recoverChats' }, success: function(repS) { var rep = jQuery.parseJSON(repS); jQuery.each(rep, function() { var chat = this; if (chat.id) { var $li = jQuery('<li class="chat" data-logid="' + chat.id + '" data-chatrequest="0" data-userid="' + chat.userID + '" data-username="' + chat.username + '"></li>'); $li.append('<a href="javascript:">' + chat.username + '<span class="navbar-unread">1</span></a>'); jQuery('#usersList').append($li); $li.children('a').click(vcht_clickUserTab); vcht_createChatPanel(chat); jQuery.each(chat.messages, function() { var msg = this; if (msg.isOperator == 1) { vcht_say(msg, chat.id, msg.avatarOperator); } else { if (chat.avatarImg) { vcht_userSay(msg, chat.id, msg.url, chat.avatarImg); } else { vcht_userSay(msg, chat.id, msg.url); } } }); } }); vcht_isChatting = true; vcht_checkOperatorChat(); vcht_checkUsers(); } }); } function vcht_toggleChatPanel() { if (jQuery('#vcht_consolePanelContent').is('.opened')) { vcht_minifyChatPanel(); } else { vcht_openChatPanel(); } } function vcht_minifyChatPanel() { if (jQuery('#vcht_consolePanelContent').is('.opened')) { jQuery('#vcht_btnMinimize span').removeClass('glyphicon-chevron-down'); jQuery('#vcht_btnMinimize span').addClass('glyphicon-chevron-up'); jQuery('#vcht_consolePanelContent').removeClass('opened'); jQuery('#vcht_consolePanelContent').hide('bind'); } } function vcht_openChatPanel() { if (!jQuery('#vcht_consolePanelContent').is('.opened')) { jQuery('#vcht_consolePanelContent > div[data-logid]').each(function() { if (jQuery(this).css('display') != 'none') { vcht_currentLogID = parseInt(jQuery(this).data('logid')); } }); jQuery('#vcht_btnMinimize span').removeClass('glyphicon-chevron-up'); jQuery('#vcht_btnMinimize span').addClass('glyphicon-chevron-down'); jQuery('#vcht_consolePanelContent').addClass('opened'); jQuery('#vcht_consolePanelContent').show('bind'); } } function vcht_getLogs(userID, ip) { vcht_minifyChatPanel(); vcht_currentLogID = 0; if (userID > 0) { jQuery('#vcht_consoleFrame').prop('src', 'admin.php?page=vcht-logsList&userID=' + userID); } else { jQuery('#vcht_consoleFrame').prop('src', 'admin.php?page=vcht-logsList&search=' + ip); } } function vcht_exitChat(logID) { jQuery.ajax({ url: ajaxurl, type: 'post', data: { action: 'vcht_closeChat', logID: logID }, success: function() { jQuery('#usersList li[data-logid=' + logID + ']').fadeOut(250); jQuery('#usersList li[data-logid=' + logID + ']').delay(500).remove(); jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').fadeOut(250); jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').delay(500).remove(); vcht_currentLogID = 0; vcht_checkUsers(); } }); } function vcht_createChatPanel(chat) { var bgImg = ''; if (chat.avatarImg && chat.avatarImg != "") { bgImg = 'style="background-image: none;"'; } else { chat.avatarImg = ''; } var logsBtn = ''; //if (chat.userID > 0) { logsBtn = '<p><a href="javascript:" onclick="vcht_getLogs(' + chat.userID + ',\'' + chat.ip + '\');" class="btn btn-primary"><span class="fui-search"></span>See user logs</a></p>'; // } var panel = jQuery('<div data-logid="' + chat.id + '" data-userid="' + chat.userid + '"></div>'); panel.append('<div class="col-md-2 palette palette-wet-asphalt" id="vcht_userInfos">' + '<div class="vcht_avatarImg" ' + bgImg + '>' + chat.avatarImg + '</div>' + '<p><strong class="vcht_username">' + chat.username + '</strong></p>' + logsBtn + '<p class="vcht_onlineOperatorsNb">Online operators: <strong>1</strong></p>' + '</div>'); jQuery('#vcht_consolePanelContent').append(panel); var historyCt = jQuery('<div class="vcht_chatContent"></div>'); panel.append(historyCt); var history = jQuery('<div class="vcht_chatHistory"></div>'); historyCt.append(history); historyCt.append('<div class="vcht_chatInfos palette palette-primary"><p><span class="glyphicon glyphicon-time"></span><br/><strong class="vcht_timePast">00:00:00</strong></p>' + '<p><div class="dropdown">' + '<div class="btn-group select select-block open"><button class="btn dropdown-toggle clearfix btn-primary" data-toggle="dropdown"><span class="filter-option pull-left">Transfer chat</span>&nbsp;<span class="caret"></span></button><span class="dropdown-arrow dropdown-arrow-inverse"></span><ul data-logid="' + chat.id + '" class="vcht_transferSelect dropdown-menu dropdown-inverse" role="menu" style="max-height: 616px; overflow-y: auto; min-height: 108px;"></ul></div>' + '</div></p>' + '<p><a href="javascript:" onclick="vcht_exitChat(' + chat.id + ');" class="btn btn-danger"><span class="fui-cross"></span>Stop chat</a></p>' + '</div>'); var panelRep = jQuery('<div class="vcht_chatWrite palette palette-clouds container-fluid"></div>'); historyCt.append(panelRep); if (chat.operatorID == 0) { panel.find('.vcht_chatInfos').hide(); panelRep.append('<p class="vcht_chatWrite_newChat"><a href="javascript:" onclick="vcht_acceptChat(' + chat.id + ');" class="btn btn-primary">Accept this chat</a></p>'); } else { panel.find('.vcht_chatInfos').fadeIn(200); vcht_initChatWrite(chat.id); } } function vcht_checkOperatorChat() { if (vcht_isChatting) { vcht_checkTimer = setTimeout(function() { var currentChats = ''; jQuery('#usersList li[data-logid]').each(function() { var li = this; currentChats += jQuery(this).data('logid') + ','; }); if (currentChats.length > 0) { currentChats = currentChats.substr(0, currentChats.length - 1); } jQuery.ajax({ url: ajaxurl, type: 'post', data: { action: 'vcht_check_operator_chat', operatorID: vcht_operatorID, currentChats: currentChats }, success: function(repS) { var rep = jQuery.parseJSON(repS); vcht_lastRep = rep; var requestsArray = new Array(); if (rep.chatRequests.length > 0) { jQuery.each(rep.chatRequests, function() { req = this; requestsArray.push((req.id)); if (jQuery('#usersList li[data-logid=' + req.id + ']').length == 0) { var $li = jQuery('<li class="palette palette-turquoise reqChat" data-logid="' + req.id + '" data-chatrequest="1" data-userid="' + req.userID + '" data-username="' + req.username + '"></li>'); $li.append('<a href="javascript:">' + req.username + '</a>'); jQuery('#usersList').append($li); $li.children('a').click(vcht_clickUserTab); if (jQuery('#vcht_audioMsg').data('enable') != 'false') { jQuery('#vcht_audioMsg').get(0).play(); } if (req.id != vcht_currentLogID && jQuery('#usersList li[data-logid=' + req.id + '] a span').length == 0) { jQuery('#usersList li[data-logid=' + req.id + '] a').append('<span class="navbar-unread">1</span>'); } } }); } // remove chats requests past jQuery('#usersList li[data-logid][data-chatrequest="1"]').not('.vcht_accepted').each(function() { var li = this; var chk = false; jQuery.each(rep.chatRequests, function() { req = this; if (parseInt(req.id) == parseInt(jQuery(li).data('logid'))) { chk = true; } }); if (!chk) { jQuery(this).remove(); } }); jQuery.each(rep.chats, function() { var chat = this; var hours = Math.floor(chat.timePast / (60 * 60)); var divisor_for_minutes = chat.timePast % (60 * 60); var minutes = Math.floor(divisor_for_minutes / 60); var divisor_for_seconds = divisor_for_minutes % 60; var seconds = Math.ceil(divisor_for_seconds); jQuery('#vcht_consolePanelContent > div[data-logid=' + chat.id + '] .vcht_timePast').html(hours.toString().replace(/^(\d)$/, '0$1') + ':' + minutes.toString().replace(/^(\d)$/, '0$1') + ':' + seconds.toString().replace(/^(\d)$/, '0$1')); jQuery.each(chat.messages, function() { var msg = this; vcht_userSay(msg, chat.id, msg.url); if (vcht_currentLogID == chat.id && msg.url != jQuery('#vcht_consoleFrame').prop('src')) { jQuery('#vcht_consoleFrame').prop('src', msg.url); } if (chat.id != vcht_currentLogID) { jQuery('#usersList li[data-logid=' + chat.id + '] a > span.navbar-unread').fadeIn(100); if (jQuery('#vcht_audioMsg').data('enable') != 'false') { jQuery('#vcht_audioMsg').get(0).play(); } } }); }); jQuery.each(rep.chatsClosed, function() { var chatClosed = this; if (jQuery('#usersList li[data-logid=' + chatClosed + ']').length > 0) { if (jQuery('#usersList li[data-logid=' + chatClosed + ']').is('.palette-turquoise')) { vcht_exitChat(chatClosed); } else { jQuery('#usersList li[data-logid=' + chatClosed + ']').addClass('palette palette-concrete'); jQuery('#vcht_consolePanelContent > div[data-logid=' + chatClosed + '] .vcht_chatHistory').append('<div class="userAction palette palette-clouds"><div class="avatarImg bubble_photo"></div> User disconnects.</div>'); jQuery('#vcht_consolePanelContent > div[data-logid=' + chatClosed + '] .vcht_chatHistory .userAction:last-child').fadeIn(250); jQuery('#vcht_consolePanelContent > div[data-logid=' + chatClosed + '] .vcht_chatWrite').fadeOut(200); } } }); // transfers jQuery.each(rep.transfers, function() { var chat = this; vcht_createChatPanel(chat); jQuery('#vcht_consolePanelContent > div[data-logid=' + chat.id + '] .vcht_chatInfos').fadeIn(250); jQuery.each(chat.messages, function() { var msg = this; if (msg.isOperator == '1') { vcht_say(msg, chat.id); } else { vcht_userSay(msg, chat.id, msg.url); } }); jQuery('#vcht_consolePanelContent > div[data-logid=' + chat.id + '] .vcht_chatHistory').append('<div class="userAction palette palette-clouds"><div class="avatarImg bubble_photo"></div> This discussion was transferred to you</div>'); jQuery('#vcht_consolePanelContent > div[data-logid=' + chat.id + '] .vcht_chatHistory .userAction:last-child').fadeIn(250); var $li = jQuery('<li class="palette palette-turquoise reqChat" data-logid="' + chat.id + '" data-chatrequest="0" data-userid="' + chat.userID + '" data-username="' + chat.username + '"></li>'); $li.append('<a href="javascript:">' + chat.username + '</a>'); jQuery('#usersList').append($li); $li.children('a').click(vcht_clickUserTab); jQuery('#vcht_consolePanelContent > div[data-logid=' + chat.id + ']').find('.vcht_chatContent').scrollTop(jQuery('#vcht_consolePanelContent > div[data-logid=' + chat.id + ']').find('.vcht_chatContent')[0].scrollHeight); }); // operators if (rep.operators.length > 1) { jQuery('ul.vcht_transferSelect').html('<li rel="0" class=""><a tabindex="-1" href="#" class="active"><span class="pull-left">Choose operator</span></a></li>'); } else { jQuery('ul.vcht_transferSelect').html('<li rel="0" class=""><a tabindex="-1" href="#" class="active"><span class="pull-left">No operators </<span></a></li>'); } jQuery.each(rep.operators, function(i) { var operator = this; if (operator.userID != vcht_operatorID) { var $li = jQuery('<li data-userid="' + operator.userID + '" rel="' + (i + 1) + '" class=""><a tabindex="-1" href="#" class="active"><span class="pull-left">' + operator.username + '</span></a></li>'); jQuery('ul.vcht_transferSelect').append($li); $li.click(function() { var logID = jQuery(this).parent('ul').data('logid'); var operatorID = jQuery(this).data('userid'); jQuery.ajax({ url: ajaxurl, type: 'post', data: { action: 'vcht_transferChat', logID: logID, operatorID: operatorID }, success: function() { jQuery('#usersList li[data-logid=' + logID + ']').fadeOut(250); jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').fadeOut(250); setTimeout(function() { jQuery('#usersList li[data-logid=' + logID + ']').remove(); jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').remove(); }, 500); } }); }); } }); jQuery('.vcht_onlineOperatorsNb strong').html(rep.operators.length); vcht_checkUsers(); setTimeout(function() { vcht_checkOperatorChat(); },1500); } }); }, 1000); } } function vcht_getChat(userID, username, isRequest) { var rep = false; if (vcht_lastRep) { if (isRequest) { jQuery.each(vcht_lastRep.chatRequests, function() { var req = this; if (userID > 0 && req.userID == userID) { rep = req; } else if (userID == 0 && req.username == username) { rep = req; } }); } else { jQuery.each(vcht_lastRep.chats, function() { var req = this; if (userID > 0 && req.userID == userID) { rep = req; } else if (userID == 0 && req.username == username) { rep = req; } }); } } return rep; } function vcht_clickUserTab() { jQuery(this).find('span.navbar-unread').fadeOut(100); if (jQuery(this).is('palette-turquoise') && jQuery(this).data('chatrequest') == '0') { jQuery(this).removeClass('palette-turquoise'); } vcht_loadChatPanel(jQuery(this).parent().data('logid')); vcht_currentLogID = jQuery(this).parent().data('logid'); vcht_openChatPanel(); } function vcht_isIframe() { try { return window.self !== window.top; } catch (e) { return true; } } function vcht_declineChat(logID) { jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').hide(); jQuery('#usersList li[data-logid=' + logID + ']').hide(); } function vcht_acceptChat(logID) { jQuery('#usersList li[data-logid=' + logID + ']').addClass('vcht_accepted'); jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').fadeOut(250); jQuery('#vcht_loader').delay(300).fadeIn(100); jQuery.ajax({ url: ajaxurl, type: 'post', data: { action: 'vcht_acceptChat', logID: logID }, success: function(rep) { if (rep == '1') { jQuery('#usersList li[data-logid=' + logID + ']').removeClass('palette'); jQuery('#usersList li[data-logid=' + logID + ']').removeClass('palette-turquoise').data('chatrequest', '0'); vcht_initChatWrite(logID); jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + '] .vcht_chatHistory').html(''); jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').delay(1500).fadeIn(250); jQuery('#vcht_loader').delay(1400).fadeOut(100); jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').delay(300).find('.vcht_chatInfos').fadeIn(200); } } }); } function vcht_initChatWrite(logID) { jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + '] .vcht_chatWrite').html('<div class="col-md-7"><div class="form-group"><textarea data-logid="' + logID + '" data-url="" data-domelement="" class="form-control" rows="3" placeholder="Write your message here"></textarea></div></div>'); jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + '] .vcht_chatWrite').append('<div class="col-md-3"><p>Element selected : <strong class="vcht_hasElementSelected">No</strong></p><p><a href="javascript:" class="btn btn-primary" onclick="vcht_startSelectDomElement();"><span class="fui-eye"></span> Select an element</a></p></div>'); jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + '] .vcht_chatWrite').append('<div class="col-md-2"><a href="javascript:" onclick="vcht_sendMessage(' + logID + ')" class="btn btn-lg btn-primary btn-block vcht_sendBtn"><span class="fui-chat"></span></a></div>'); jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + '] .vcht_chatWrite textarea').keypress(function(e) { if (e.which == 13 && !e.shiftKey) { e.preventDefault(); vcht_sendMessage(jQuery(this).data('logid')); } }); } function vcht_startSelectDomElement() { vcht_minifyChatPanel(); jQuery('#vcht_consolePanel').delay(500).fadeOut(250); jQuery('#vcht_infosPanel > .container > .col-md-12').html('<p>Navigate to the desired page and click on "Select an element" button.</p>'); jQuery('#vcht_infosPanel > .container > .col-md-12').append('<p><a href="javascript:" class="btn btn-primary" onclick="vcht_targetDomElement();">Select an element</a><a href="javascript:" class="btn btn-warning" onclick="vcht_stopSelectDomElement();">Cancel</a></p>'); jQuery('#vcht_infosPanel').delay(850).fadeIn(250); } function vcht_targetDomElement() { jQuery('#vcht_infosPanel > .container > .col-md-12').html('<p>Click on the desired item</p>'); jQuery('#vcht_consoleFrame').get(0).contentWindow.vcht_startSelection(); } function vcht_stopSelectDomElement() { jQuery('#vcht_infosPanel').fadeOut(250); jQuery('#vcht_consolePanel').delay(300).fadeIn(250); setTimeout(function() { vcht_openChatPanel(); }, 600); } function vcht_selectDomElement(el) { vcht_currentDomElement = el; jQuery('#vcht_infosPanel > .container > .col-md-12').html('<p>Do you want to show this item to the user?</p>'); jQuery('#vcht_infosPanel > .container > .col-md-12').append('<p><a href="javascript:" class="btn btn-primary" onclick="vcht_confirmDomElement();">Yes</a><a href="javascript:" class="btn btn-warning" onclick="vcht_targetDomElement();">No</a></p>'); } function vcht_confirmDomElement(el) { var path = vcht_getPath(vcht_currentDomElement); jQuery('#vcht_consolePanelContent > div[data-logid=' + vcht_currentLogID + '] .vcht_chatWrite .vcht_hasElementSelected').html('Yes'); jQuery('#vcht_consolePanelContent > div[data-logid=' + vcht_currentLogID + '] .vcht_chatWrite textarea').data('domelement', path); jQuery('#vcht_consolePanelContent > div[data-logid=' + vcht_currentLogID + '] .vcht_chatWrite textarea').data('url', jQuery('#vcht_consoleFrame').get(0).contentWindow.document.location.href); vcht_stopSelectDomElement(); } function vcht_getPath(el) { var path = ''; if (jQuery(el).length > 0 && typeof (jQuery(el).prop('tagName')) != "undefined") { if (!jQuery(el).attr('id')) { path = '>' + jQuery(el).prop('tagName') + ':nth-child(' + (jQuery(el).index() + 1) + ')' + path; path = vcht_getPath(jQuery(el).parent()) + path; } else { path += '#' + jQuery(el).attr('id'); } } return path; } function vcht_sendMessage(logID) { jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').find('.vcht_chatWrite textarea').parent().removeClass('has-error'); var msg = jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').find('.vcht_chatWrite textarea').val(); if (msg == "") { jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').find('.vcht_chatWrite textarea').parent().addClass('has-error'); } else { var today = new Date(); var dd = today.getDate(); var mm = today.getMonth() + 1; var yyyy = today.getFullYear(); var h = today.getHours(); var m = today.getMinutes(); var s = today.getSeconds(); if (dd < 10) { dd = '0' + dd; } if (mm < 10) { mm = '0' + mm; } if (h < 10) { h = '0' + h; } if (m < 10) { m = '0' + m; } if (s < 10) { s = '0' + s; } var date = yyyy + '-' + mm + '-' + dd + ' ' + h + ':' + m + ':' + s; msg = msg.replace(/\n/g, '<br/>'); vcht_say({content: msg, date: date}, logID); jQuery.ajax({ url: ajaxurl, type: 'post', data: { action: 'vcht_operatorSay', logID: logID, msg: msg, domElement: jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').find('.vcht_chatWrite textarea').data('domelement'), url: jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').find('.vcht_chatWrite textarea').data('url') }, success: function(repS) { jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + '] .vcht_chatWrite .vcht_hasElementSelected').html('No'); jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').find('.vcht_chatWrite textarea').val(''); jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').find('.vcht_chatWrite textarea').data('domelement', ''); jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').find('.vcht_chatWrite textarea').data('url', ''); } }); } } function vcht_userSay(msg, logID, url, avatarImg) { var bubble = jQuery('<div class="bubble_left palette palette-clouds" data-url="' + url + '"></div>'); bubble.append('<div class="bubble_arrow"></div>'); bubble.append(msg.content); var username = jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + '] .vcht_username').html(); var hour = msg.date.substr(msg.date.indexOf(' ') + 1); bubble.append('<div class="bubble_meta">' + hour + ' - ' + username + '</div>'); if (avatarImg && avatarImg != "") { bubble.append('<div class="avatarImg bubble_photo" style="background-image: none;">' + avatarImg + '</div>'); } else { bubble.append('<div class="avatarImg bubble_photo"></div>'); } jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').find('.vcht_chatHistory').append(bubble); bubble.fadeIn(250); jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').find('.vcht_chatContent').scrollTop(jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').find('.vcht_chatContent')[0].scrollHeight); } function vcht_say(msg, logID, avatarOperator) { var bubble = jQuery('<div class="bubble_right palette palette-turquoise"></div>'); bubble.append(msg.content); var username = jQuery('#vcht_operatorname').html(); if (msg.username && msg.username != "") { username = msg.username; } var hour = msg.date.substr(msg.date.indexOf(' ') + 1); bubble.append('<div class="bubble_meta">' + hour + ' - ' + username + '</div>'); bubble.append('<div class="bubble_arrow"></div>'); if (avatarOperator) { bubble.append('<div class="avatarImg bubble_photo" style="background-image: none;">' + avatarOperator + '</div>'); } else { bubble.append('<div class="avatarImg bubble_photo" style="background-image: none;">' + vcht_operatorAvatar + '</div>'); } jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').find('.vcht_chatHistory').append(bubble); bubble.fadeIn(250); jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').find('.vcht_chatContent').scrollTop(jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').find('.vcht_chatContent')[0].scrollHeight); } function vcht_loadChatPanel(logID) { if (jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').length > 0) { jQuery('#vcht_consolePanelContent > div').fadeOut(250); jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').delay(300).fadeIn(250); setTimeout(function() { jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').find('.vcht_chatContent').scrollTop(jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').find('.vcht_chatContent')[0].scrollHeight); }, 800); var userUrl = ''; userUrl = jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + '] .vcht_chatHistory .bubble_left:last-child').data('url'); jQuery('#vcht_consoleFrame').prop('src', userUrl); } else { jQuery('#vcht_loader').fadeIn(100); jQuery.ajax({ url: ajaxurl, type: 'post', data: { action: 'vcht_getLogChat', logID: logID }, success: function(repS) { var rep = jQuery.parseJSON(repS); jQuery('#vcht_consolePanelContent > div').fadeOut(500); vcht_createChatPanel(rep); var userURL = ''; jQuery.each(rep.messages, function() { var msg = this; if (msg.isOperator == 1) { var bubble = jQuery('<div class="bubble_right palette palette-turquoise"></div>'); bubble.append(msg.content); bubble.append('<div class="bubble_arrow"></div>'); } else { var bubble = jQuery('<div class="bubble_left palette palette-clouds" data-url="' + msg.url + '"></div>'); bubble.append('<div class="bubble_arrow"></div>'); bubble.append(msg.content); userURL = msg.url; } bubble.append('<div class="avatarImg bubble_photo"></div>'); var panel = jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']'); panel.find('.vcht_chatHistory').append(bubble); bubble.fadeIn(250); panel.find('.vcht_chatContent').delay(500).scrollTop(panel.find('.vcht_chatContent')[0].scrollHeight); }); jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').delay(1000).fadeIn(500); jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').find('.vcht_chatContent').delay(1500).scrollTop(jQuery('#vcht_consolePanelContent > div[data-logid=' + logID + ']').find('.vcht_chatContent')[0].scrollHeight); jQuery('#vcht_consoleFrame').prop('src', userURL); jQuery('#vcht_loader').fadeOut(100); } }); } }
gpl-2.0
CnCNet/cncnet-ladder-api
cncnet-api/database/migrations/2017_11_09_204327_add_pings_to_game_reports.php
681
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddPingsToGameReports extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('game_reports', function(Blueprint $table) { // $table->integer("pings_sent")->default(0); $table->integer("pings_received")->default(0); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('game_reports', function(Blueprint $table) { // $table->dropColumn("pings_sent"); $table->dropColumn("pings_received"); }); } }
gpl-2.0
Honeybunch/BrickwareGraphics
include/BrickwareGraphics/dxerr.hpp
3268
//-------------------------------------------------------------------------------------- // File: DXErr.h // // DirectX Error Library // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- // This version only supports UNICODE. #ifdef D3D_SUPPORT #include "BrickwareGraphics/BrickwareGraphicsDLL.hpp" #ifdef _MSC_VER #pragma once #endif #include <windows.h> #include <sal.h> #ifdef __cplusplus extern "C" { #endif //-------------------------------------------------------------------------------------- // DXGetErrorString //-------------------------------------------------------------------------------------- const BRICKWARE_GRAPHICS_API WCHAR* WINAPI DXGetErrorStringW(_In_ HRESULT hr); #define DXGetErrorString DXGetErrorStringW //-------------------------------------------------------------------------------------- // DXGetErrorDescription has to be modified to return a copy in a buffer rather than // the original static string. //-------------------------------------------------------------------------------------- BRICKWARE_GRAPHICS_API void WINAPI DXGetErrorDescriptionW(_In_ HRESULT hr, _Out_cap_(count) WCHAR* desc, _In_ size_t count); #define DXGetErrorDescription DXGetErrorDescriptionW //-------------------------------------------------------------------------------------- // DXTrace // // Desc: Outputs a formatted error message to the debug stream // // Args: WCHAR* strFile The current file, typically passed in using the // __FILEW__ macro. // DWORD dwLine The current line number, typically passed in using the // __LINE__ macro. // HRESULT hr An HRESULT that will be traced to the debug stream. // CHAR* strMsg A string that will be traced to the debug stream (may be nullptr) // BOOL bPopMsgBox If TRUE, then a message box will popup also containing the passed info. // // Return: The hr that was passed in. //-------------------------------------------------------------------------------------- BRICKWARE_GRAPHICS_API HRESULT WINAPI DXTraceW(_In_z_ const WCHAR* strFile, _In_ DWORD dwLine, _In_ HRESULT hr, _In_opt_ const WCHAR* strMsg, _In_ bool bPopMsgBox); #define DXTrace DXTraceW //-------------------------------------------------------------------------------------- // // Helper macros // //-------------------------------------------------------------------------------------- #if defined(DEBUG) || defined(_DEBUG) #define DXTRACE_MSG(str) DXTrace( __FILEW__, (DWORD)__LINE__, 0, str, false ) #define DXTRACE_ERR(str,hr) DXTrace( __FILEW__, (DWORD)__LINE__, hr, str, false ) #define DXTRACE_ERR_MSGBOX(str,hr) DXTrace( __FILEW__, (DWORD)__LINE__, hr, str, true ) #else #define DXTRACE_MSG(str) (0L) #define DXTRACE_ERR(str,hr) (hr) #define DXTRACE_ERR_MSGBOX(str,hr) (hr) #endif #ifdef __cplusplus } #endif //__cplusplus #endif;
gpl-2.0
DrBenton/talk-talk
app/core-plugins/ajax-navigation/assets/js/modules/components/ajax-navigation.js
3635
/** * This is just a single entry point for our other Ajax navigation components */ define(function (require, exports, module) { "use strict"; var defineComponent = require("flight").component; var withUrlNormalization = require("app-modules/utils/mixins/data/with-url-normalization"); var withHttpStatusManagement = require("app-modules/utils/mixins/data/with-http-status-management"); var varsRegistry = require("app-modules/core/vars-registry"); var logger = require("logger"); // Sub components var ajaxLinksHandler = require("./ui/ajax-links-handler"); var ajaxFormsHandler = require("./ui/ajax-forms-handler"); var ajaxContentUpdater = require("./ui/ajax-page-content-updater"); var ajaxBreadcrumbHandler = require("./ui/ajax-breadcrumb-handler"); var ajaxContentLoader = require("./data/ajax-content-loader"); var ajaxHistory = require("./data/ajax-history"); var ajaxContentLoadingDisplay = require("./ui/ajax-content-loading-display"); var myDebug = false; // Exports: component definition module.exports = defineComponent(ajaxNavigation, withUrlNormalization, withHttpStatusManagement); myDebug && logger.debug(module.id, "Component on the bridge, captain!"); function ajaxNavigation() { this.createSubComponents = function() { // The "Ajax links handler" will track "a.ajax-link" user clicks in the site container, // and will request content updates for the site main content container. ajaxLinksHandler.attachTo(varsRegistry.$siteContainer, { targetContentContainerSelector: this.mainContentContainerSelector }); // The "Ajax forms handler" will track "form.ajax-form" user submissions in the site container, // and will request content updates for the site main content container too. ajaxFormsHandler.attachTo(varsRegistry.$siteContainer, { targetContentContainerSelector: this.mainContentContainerSelector }); // The "Ajax breadcrumb handler" will just update the breadcrumb when it is requested. ajaxBreadcrumbHandler.attachTo(varsRegistry.$breadcrumb); // The "Ajax content updater" is "node agnostic", so we attach it to the document. // It will update page content parts following the events "target" instructions. ajaxContentUpdater.attachTo(varsRegistry.$document); // Idem for "Ajax content loader"... ajaxContentLoader.attachTo(varsRegistry.$document); // The "Ajax content updater" is "node agnostic", so we attach it to the document. // It will update page History only when the updated content part will be the main content container. ajaxHistory.attachTo(varsRegistry.$document, { contentContainerToListenSelector: this.mainContentContainerSelector }); // The "Ajax content loading display" "node agnostic" too. ajaxContentLoadingDisplay.attachTo(varsRegistry.$document); }; this.handleInitialMainContent = function() { myDebug && logger.debug(module.id, "Let's check if the initial content has cache information..."); if (this.isCurrentPageAnError()) { // Don't handle anything if the current page is a error page return; } this.trigger("uiNeedsContentAjaxInstructionsCheck", { url: this.normalizeUrl(document.location), target: this.mainContentContainerSelector }); }; // Component initialization this.after("initialize", function() { this.mainContentContainerSelector = "#" + varsRegistry.$mainContent.attr("id"); this.createSubComponents(); this.handleInitialMainContent(); }); } });
gpl-2.0
unioslo/cerebrum
contrib/list_password_change_dates.py
2284
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2015 University of Oslo, Norway # # This file is part of Cerebrum. # # Cerebrum 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. # # Cerebrum 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 Cerebrum; if not, write to the Free Software Foundation, # Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. u"""Takes a file with account names, lists password change timestamps.""" import cereconf from Cerebrum import Errors from Cerebrum.Utils import Factory from Cerebrum.modules.pwcheck.history import PasswordHistory def print_change_dates(accounts): db = Factory.get('Database')() ac = Factory.get('Account')(db) logger = Factory.get_logger('console') ph = PasswordHistory(db) for account_name in accounts: ac.clear() try: ac.find_by_name(account_name) except Errors.NotFoundError: logger.error("No such account {!r}".format(account_name)) continue history = ph.get_history(ac.entity_id) if history: history = sorted(history, key=lambda x: x['set_at']) last = dict(history[-1]) print "{}\t{}".format(account_name, str(last['set_at'])) else: print "{}\t{}".format(account_name, 'NEVER') def main(): """ Script invocation. """ import argparse parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-a', '--account-file', dest='account_file', help='text file with newline separated account names', required=True) args = parser.parse_args() with open(args.account_file) as af: accounts = filter(None, (line.rstrip() for line in af)) print_change_dates(accounts) if __name__ == '__main__': main()
gpl-2.0
trK54Ylmz/elasticsearch-php-thrift
src/Elasticsearch/Namespaces/Thrift/Protocol/TProtocolDecorator.php
7404
<?php /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 thrift.protocol */ namespace Thrift\Protocol; use Thrift\Exception\TException; /** * <code>TProtocolDecorator</code> forwards all requests to an enclosed * <code>TProtocol</code> instance, providing a way to author concise * concrete decorator subclasses. While it has no abstract methods, it * is marked abstract as a reminder that by itself, it does not modify * the behaviour of the enclosed <code>TProtocol</code>. * * @package Thrift\Protocol */ abstract class TProtocolDecorator extends TProtocol { /** * Instance of protocol, to which all operations will be forwarded. * * @var TProtocol */ private $concreteProtocol_; /** * Constructor of <code>TProtocolDecorator</code> class. * Encloses the specified protocol. * * @param TProtocol $protocol All operations will be forward to this instance. Must be non-null. */ protected function __construct(TProtocol $protocol) { parent::__construct($protocol->getTransport()); $this->concreteProtocol_ = $protocol; } /** * Writes the message header. * * @param string $name Function name * @param int $type message type TMessageType::CALL or TMessageType::REPLY * @param int $seqid The sequence id of this message */ public function writeMessageBegin($name, $type, $seqid) { return $this->concreteProtocol_->writeMessageBegin($name, $type, $seqid); } /** * Closes the message. */ public function writeMessageEnd() { return $this->concreteProtocol_->writeMessageEnd(); } /** * Writes a struct header. * * @param string $name Struct name * * @throws TException on write error * @return int How many bytes written */ public function writeStructBegin($name) { return $this->concreteProtocol_->writeStructBegin($name); } /** * Close a struct. * * @throws TException on write error * @return int How many bytes written */ public function writeStructEnd() { return $this->concreteProtocol_->writeStructEnd(); } public function writeFieldBegin($fieldName, $fieldType, $fieldId) { return $this->concreteProtocol_->writeFieldBegin($fieldName, $fieldType, $fieldId); } public function writeFieldEnd() { return $this->concreteProtocol_->writeFieldEnd(); } public function writeFieldStop() { return $this->concreteProtocol_->writeFieldStop(); } public function writeMapBegin($keyType, $valType, $size) { return $this->concreteProtocol_->writeMapBegin($keyType, $valType, $size); } public function writeMapEnd() { return $this->concreteProtocol_->writeMapEnd(); } public function writeListBegin($elemType, $size) { return $this->concreteProtocol_->writeListBegin($elemType, $size); } public function writeListEnd() { return $this->concreteProtocol_->writeListEnd(); } public function writeSetBegin($elemType, $size) { return $this->concreteProtocol_->writeSetBegin($elemType, $size); } public function writeSetEnd() { return $this->concreteProtocol_->writeSetEnd(); } public function writeBool($bool) { return $this->concreteProtocol_->writeBool($bool); } public function writeByte($byte) { return $this->concreteProtocol_->writeByte($byte); } public function writeI16($i16) { return $this->concreteProtocol_->writeI16($i16); } public function writeI32($i32) { return $this->concreteProtocol_->writeI32($i32); } public function writeI64($i64) { return $this->concreteProtocol_->writeI64($i64); } public function writeDouble($dub) { return $this->concreteProtocol_->writeDouble($dub); } public function writeString($str) { return $this->concreteProtocol_->writeString($str); } /** * Reads the message header * * @param string $name Function name * @param int $type message type TMessageType::CALL or TMessageType::REPLY * @param int $seqid The sequence id of this message */ public function readMessageBegin(&$name, &$type, &$seqid) { return $this->concreteProtocol_->readMessageBegin($name, $type, $seqid); } /** * Read the close of message */ public function readMessageEnd() { return $this->concreteProtocol_->readMessageEnd(); } public function readStructBegin(&$name) { return $this->concreteProtocol_->readStructBegin($name); } public function readStructEnd() { return $this->concreteProtocol_->readStructEnd(); } public function readFieldBegin(&$name, &$fieldType, &$fieldId) { return $this->concreteProtocol_->readFieldBegin($name, $fieldType, $fieldId); } public function readFieldEnd() { return $this->concreteProtocol_->readFieldEnd(); } public function readMapBegin(&$keyType, &$valType, &$size) { $this->concreteProtocol_->readFieldEnd($keyType, $valType, $size); } public function readMapEnd() { return $this->concreteProtocol_->readMapEnd(); } public function readListBegin(&$elemType, &$size) { $this->concreteProtocol_->readListBegin($elemType, $size); } public function readListEnd() { return $this->concreteProtocol_->readListEnd(); } public function readSetBegin(&$elemType, &$size) { return $this->concreteProtocol_->readSetBegin($elemType, $size); } public function readSetEnd() { return $this->concreteProtocol_->readSetEnd(); } public function readBool(&$bool) { return $this->concreteProtocol_->readBool($bool); } public function readByte(&$byte) { return $this->concreteProtocol_->readByte($byte); } public function readI16(&$i16) { return $this->concreteProtocol_->readI16($i16); } public function readI32(&$i32) { return $this->concreteProtocol_->readI32($i32); } public function readI64(&$i64) { return $this->concreteProtocol_->readI64($i64); } public function readDouble(&$dub) { return $this->concreteProtocol_->readDouble($dub); } public function readString(&$str) { return $this->concreteProtocol_->readString($str); } }
gpl-2.0
destyjustc/mandy_real
wp-content/themes/zippy/js/zippy.js
2571
jQuery(document).ready(function(){ jQuery('.nav_menu ul li').hover(function(){ jQuery(this).find('ul:first').slideDown(100); jQuery(this).addClass("hover"); },function(){ jQuery(this).find('ul').css('display','none'); jQuery(this).removeClass("hover"); }); jQuery('.nav_menu li ul li:has(ul)').find("a:first").append(" <span class='menu_more'>»</span> "); var menu_width = 0; jQuery('.nav_menu ul:first > li').each(function(){ menu_width = jQuery(this).outerWidth()+menu_width; if(menu_width > jQuery(this).parents("ul").innerWidth()){ jQuery(this).prev().addClass("menu_last_item"); menu_width = jQuery(this).outerWidth(); } }); /*! /* Mobile Menu */ (function($) { var current = $('#nav .nav_menu li.current-menu-item a').html(); if( $('span').hasClass('custom-mobile-menu-title') ) { current = $('span.custom-mobile-menu-title').html(); } else if( typeof current == 'undefined' || current === null ) { if( $('body').hasClass('home') ) { if( $('.logo span').hasClass('site-name') ) { current = $('.logo .site-name').html(); } else { current = $('.logo .logo_pic img').attr('alt'); } } else{ if( $('body').hasClass('woocommerce') ) { current = $('h1.page-title').html(); } else if( $('body').hasClass('archive') ) { current = $('h6.title-archive').html(); } else if( $('body').hasClass('search-results') ) { current = $('h6.title-search-results').html(); } else if( $('body').hasClass('page-template-blog-excerpt-php') ) { current = $('.current_page_item').text(); } else if( $('body').hasClass('page-template-blog-php') ) { current = $('.current_page_item').text(); } else { current = $('h1.post-title').html(); } } }; if(typeof current == 'undefined' || current === null){current = "GO TO";} $('#nav .nav_menu').append('<a id="responsive_menu_button"></a>'); $('#nav .nav_menu').prepend('<div id="responsive_current_menu_item">' + current + '</div>'); $('a#responsive_menu_button, #responsive_current_menu_item').click(function(){ $('body #nav .nav_menu ul').slideToggle( function() { if( $(this).is(':visible') ) { $('a#responsive_menu_button').addClass('responsive-toggle-open'); } else { $('a#responsive_menu_button').removeClass('responsive-toggle-open'); $('body #nav .nav_menu ul').removeAttr('style'); } }); }); })(jQuery); });
gpl-2.0
woutervs/DirectoryTreeView
DirectoryTree/Converters/ObjectNullToVisibilityConverter.cs
1263
using System; using System.Globalization; using System.Windows; using System.Windows.Data; namespace DirectoryTree.Converters { public class ObjectNullToVisibilityConverter : IValueConverter { /// <summary> /// Converts a null object to a Hidden|Collapsed state. /// </summary> /// <param name="value">Object that is or is not null.</param> /// <param name="targetType"></param> /// <param name="parameter">String parameter defining whether the return is Hidden|Collapsed (Hidden being the default.)</param> /// <param name="culture"></param> /// <returns>value == null ? Hidden|Collapsed : Visible</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var hiddenType = parameter.ToString().ToLowerInvariant() == "collapsed" ? Visibility.Collapsed : Visibility.Hidden; return value == null ? hiddenType : Visibility.Visible; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException("Cannot convert back from visibility to object."); } } }
gpl-2.0
Planigle/planigle
src/app/main/models/story-attribute.ts
5230
import { StoryAttributeValue } from './story-attribute-value'; import { StoryValue } from './story-value'; import { ChooseStatusComponent } from '../components/choose-status/choose-status.component'; export class StoryAttribute { public id: number; public project_id: number; public name: string; public value_type: number; public is_custom: boolean; public width: number; public ordering: number; public show: boolean; public storyAttributeValues: StoryAttributeValue[] = []; private mappings: any = { 'Id': 'id', 'Epic': 'epic_name', 'Name': 'name', 'Description': 'description', 'Acceptance Criteria': 'acceptance_criteria_string', 'Release': 'release_name', 'Iteration': 'iteration_name', 'Team': 'team_name', 'Project': 'project_id', 'Owner': 'individual_name', 'Public': 'is_public', 'Rank': 'rank', 'User Rank': 'user_rank', 'Lead Time': 'lead_time', 'Cycle Time': 'cycle_time', 'Estimate': 'estimate', 'Actual': 'actual', 'To Do': 'toDo', 'Size': 'size' }; constructor(values: any) { this.id = values.id; this.project_id = values.project_id; this.name = values.name; this.value_type = values.value_type; this.is_custom = values.is_custom; this.width = values.width; this.ordering = parseFloat(values.ordering); this.show = values.show; let attributeValues = values.story_attribute_values ? values.story_attribute_values : values.storyAttributeValues; if (attributeValues) { attributeValues.forEach((storyAttributeValue) => { this.storyAttributeValues.push(new StoryAttributeValue(storyAttributeValue)); }); this.storyAttributeValues.sort((v1: StoryAttributeValue, v2: StoryAttributeValue) => { if (v1.value < v2.value) { return -1; } if (v2.value < v1.value) { return 1; } return 0; }); } } getFieldName(): string { let fieldName: string = this.mappings[this.name]; return fieldName == null ? '' : fieldName; } getter(): any { if (this.is_custom || this.storyAttributeValues.length > 0) { return this.getValue; } switch (this.name) { case 'Status': return this.getStatus; default: return null; } } getStatus(params: any): string { switch (params.data.status_code) { case 0: return 'Not Started'; case 1: return 'In Progress'; case 2: return 'Blocked'; case 3: return 'Done'; } } getSize(params: any): number { let object: any = params.data; return object.getSize(); } getToDo(params: any): number { let object: any = params.data; return object.getToDo(); } getValue(params: any): string { let object: any = params.data; let storyAttribute = params.colDef.storyAttribute; let result = null; if (object.story_values) { if (storyAttribute.storyAttributeValues.length > 0) { storyAttribute.storyAttributeValues.forEach((value: StoryAttributeValue) => { object.story_values.forEach((storyValue: StoryValue) => { if (storyValue.story_attribute_id === storyAttribute.id && parseFloat(storyValue.value) === value.id) { result = value.value; } }); }); } else { object.story_values.forEach((storyValue: StoryValue) => { if (storyValue.story_attribute_id === storyAttribute.id) { result = storyValue.value; } }); } } return result; } getTooltip(): string { switch (this.name) { case 'Name': return 'description'; case 'Description': return 'description'; case 'Acceptance Criteria': return 'acceptance_criteria_string'; default: return null; } } getCellRenderer(): any { switch (this.name) { case 'Status': return ChooseStatusComponent; default: return null; } } getValuesForRelease(release_id: number): StoryAttributeValue[] { let values: StoryAttributeValue[] = []; this.storyAttributeValues.forEach((storyAttributeValue: StoryAttributeValue) => { if (storyAttributeValue.release_id === release_id) { values.push(storyAttributeValue); } }); return values; } getValuesStringsForRelease(release_id: number): String[] { let strings = []; this.getValuesForRelease(release_id).forEach((storyAttributeValue: StoryAttributeValue) => { strings.push(storyAttributeValue.id + ''); }); return strings; } values(): string { let values: string[] = []; this.storyAttributeValues.forEach((value: StoryAttributeValue) => { if (value.release_id) { values.push(value.release_id + '@' + value.value); } else if (value.id) { values.push('@' + value.id + '@' + value.value); } else { values.push(value.value); } }); return values.join(','); } hasReleaseList(): boolean { return this.value_type === 4; } hasList(): boolean { return this.value_type === 3 || this.value_type === 4; } isNumber(): boolean { return this.value_type === 2; } }
gpl-2.0
epireve/joomla
components/com_xipt/libraries/setup/rule/jsfields.php
3474
<?php /** * @Copyright Ready Bytes Software Labs Pvt. Ltd. (C) 2010- author-Team Joomlaxi * @license GNU/GPL http://www.gnu.org/copyleft/gpl.html **/ // no direct access if(!defined('_JEXEC')) die('Restricted access'); class XiptSetupRuleJsfields extends XiptSetupBase { function isRequired() { $fields = self::_checkExistance(); if(!$fields || count($fields)!= 2) return true; $tmpField = $fields[TEMPLATE_CUSTOM_FIELD_CODE]; $ptField = $fields[PROFILETYPE_CUSTOM_FIELD_CODE]; return (!($tmpField->published && $ptField->published)); } function doApply() { if(self::isRequired()== false) return XiptText::_("CUSTOM_FIELD_ALREADY_CREATED_AND_ENABLED_SUCCESSFULLY"); $fields = self::_checkExistance(); $tFieldCreated = true; if(isset($fields[TEMPLATE_CUSTOM_FIELD_CODE])===false) $tFieldCreated = self::createCustomField(TEMPLATE_CUSTOM_FIELD_CODE); $pFieldCreated = true; if(isset($fields[PROFILETYPE_CUSTOM_FIELD_CODE])===false) $pFieldCreated = self::createCustomField(PROFILETYPE_CUSTOM_FIELD_CODE); $fieldEnabled = self::_switchFieldState(1); if($pFieldCreated && $tFieldCreated && $fieldEnabled) return XiptText::_("CUSTOM_FIELD_CREATED_AND_ENABLED_SUCCESSFULLY"); return XiptText::_("CUSTOM_FIELDS_ARE_NOT_CREATED_OR_ENABLED"); } function doRevert() { return self::_switchFieldState(0); } //check existance of custom fields profiletype and template function _checkExistance() { $query = new XiptQuery(); return $query->select('*') ->from('#__community_fields') ->where(" fieldcode = '".PROFILETYPE_CUSTOM_FIELD_CODE."' ", 'OR') ->where(" fieldcode = '".TEMPLATE_CUSTOM_FIELD_CODE."' ") ->dbLoadQuery() ->loadObjectList('fieldcode'); } //create custome field function createCustomField($what) { // Load the JTable Object. JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_community'.DS.'tables'); $row = JTable::getInstance( 'profiles' , 'CommunityTable' ); $row->load(0); switch($what) { case PROFILETYPE_CUSTOM_FIELD_CODE: $data['type'] = PROFILETYPE_FIELD_TYPE_NAME; $data['name'] = 'Profiletype'; $data['tips'] = 'Profiletype Of User'; break; case TEMPLATE_CUSTOM_FIELD_CODE: $data['type'] = TEMPLATE_FIELD_TYPE_NAME; $data['name'] = 'Template'; $data['tips'] = 'Template Of User'; break; default : XiptError::assert(0); break; } $data['published'] = 1; $data['fieldcode'] = $what; return $row->bind($data) && $row->store(); } //enable template & profiletype fields in community_fields table function _switchFieldState($state) { $query = new XiptQuery(); return $query->update('#__community_fields') ->set(" published = '$state' ") ->where(" type = 'profiletypes' ", 'OR') ->where(" type = 'templates' ") ->dbLoadQuery() ->query(); } function getMessage() { $requiredSetup = array(); if(self::isRequired()) { $link = XiptRoute::_("index.php?option=com_xipt&view=setup&task=doApply&name=jsfields",false); $requiredSetup['message'] = '<a href="'.$link.'">'.XiptText::_("PLEASE_CLICK_HERE_TO_CREATE_AND_ENABLE_CUSTOM_FIELDS").'</a>'; $requiredSetup['done'] = false; } else { $requiredSetup['message'] = XiptText::_("CUSTOM_FIELDS_EXIST"); $requiredSetup['done'] = true; } return $requiredSetup; } }
gpl-2.0
meyerjp3/jmetrik
src/main/java/com/itemanalysis/jmetrik/stats/irt/linking/IrtLinkingThetaDialog.java
19266
/* * Copyright (c) 2012 Patrick Meyer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.itemanalysis.jmetrik.stats.irt.linking; import com.itemanalysis.jmetrik.dao.DatabaseAccessObject; import com.itemanalysis.jmetrik.model.SortedListModel; import com.itemanalysis.jmetrik.model.VariableListFilter; import com.itemanalysis.jmetrik.model.VariableListModel; import com.itemanalysis.jmetrik.sql.DataTableName; import com.itemanalysis.jmetrik.sql.VariableTableName; import com.itemanalysis.psychometrics.data.DataType; import com.itemanalysis.psychometrics.data.ItemType; import com.itemanalysis.psychometrics.data.VariableAttributes; import org.apache.log4j.Logger; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; public class IrtLinkingThetaDialog extends JDialog{ // Variables declaration - do not modify private JButton cancelButton; private JList variableList; private JButton okButton; private JList tableList; private JScrollPane tableScrollPane; private JButton thetaButton; private JLabel thetaLabel; private JTextField thetaTextField1; private JScrollPane variableScrollPane; private JButton weightButton; private JLabel weightLabel; private JTextField weightTextField; // End of variables declaration private String formName = ""; private Connection conn = null; private DatabaseAccessObject dao = null; private DataTableName currentTable = null; private SortedListModel<DataTableName> tableListModel = null; private VariableListModel variableListModel = null; private boolean canRun = false; private boolean selectTheta = true; private boolean selectWeight = true; private VariableAttributes thetaVariable = null; private VariableAttributes weightVariable = null; static Logger logger = Logger.getLogger("jmetrik-logger"); /** Creates new form IrtEquatingThetaDialog */ public IrtLinkingThetaDialog(JDialog parent, Connection conn, DatabaseAccessObject dao, SortedListModel<DataTableName> tableListModel, String formName) { super(parent, formName+" Person Parameters", true); this.conn = conn; this.dao = dao; this.tableListModel = tableListModel; initComponents(); setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE); setLocationRelativeTo(parent); setResizable(false); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { tableScrollPane = new JScrollPane(); tableList = new JList(); tableList.setName("tableList"); tableList.setModel(tableListModel); tableList.addListSelectionListener(new TableSelectionListener()); variableScrollPane = new JScrollPane(); variableList = new JList(); variableList.setName("unselectedVariableList"); variableList.addFocusListener(new ListFocusListener()); thetaLabel = new JLabel(); weightTextField = new JTextField(); weightTextField.setName("selectedWeightList"); weightTextField.addFocusListener(new ListFocusListener()); thetaButton = new JButton(); weightLabel = new JLabel(); thetaTextField1 = new JTextField(); thetaTextField1.setName("selectedThetaList"); thetaTextField1.addFocusListener(new ListFocusListener()); weightButton = new JButton(); okButton = new JButton(); cancelButton = new JButton(); tableScrollPane.setMinimumSize(new Dimension(150, 300)); tableScrollPane.setPreferredSize(new Dimension(150, 300)); tableScrollPane.setViewportView(tableList); variableScrollPane.setMinimumSize(new Dimension(150, 300)); variableScrollPane.setPreferredSize(new Dimension(150, 300)); //filter out items and strings // VariableListFilter listFilter = new VariableListFilter(); // listFilter.addFilteredType(new VariableType(VariableType.BINARY_ITEM, VariableType.STRING)); // listFilter.addFilteredType(new VariableType(VariableType.BINARY_ITEM, VariableType.DOUBLE)); // listFilter.addFilteredType(new VariableType(VariableType.POLYTOMOUS_ITEM, VariableType.STRING)); // listFilter.addFilteredType(new VariableType(VariableType.POLYTOMOUS_ITEM, VariableType.DOUBLE)); // listFilter.addFilteredType(new VariableType(VariableType.CONTINUOUS_ITEM, VariableType.STRING)); // listFilter.addFilteredType(new VariableType(VariableType.CONTINUOUS_ITEM, VariableType.DOUBLE)); // listFilter.addFilteredType(new VariableType(VariableType.NOT_ITEM, VariableType.STRING)); //filter out items and strings VariableListFilter listFilter = new VariableListFilter(); listFilter.addFilteredItemType(ItemType.BINARY_ITEM); listFilter.addFilteredItemType(ItemType.POLYTOMOUS_ITEM); listFilter.addFilteredItemType(ItemType.CONTINUOUS_ITEM); listFilter.addFilteredDataType(DataType.STRING); variableListModel = new VariableListModel(listFilter); variableList.setModel(variableListModel); variableScrollPane.setViewportView(variableList); thetaLabel.setText("Theta"); weightTextField.setMinimumSize(new Dimension(150, 25)); weightTextField.setPreferredSize(new Dimension(150, 25)); thetaButton.setText(">"); thetaButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(selectTheta){ //move selected variable to selectedList int selected = variableList.getSelectedIndex(); thetaVariable = variableListModel.getElementAt(selected); thetaTextField1.setText(thetaVariable.getName().toString()); variableListModel.removeElement(thetaVariable); variableList.clearSelection(); }else{ if(thetaVariable!=null){ variableListModel.addElement(thetaVariable); thetaVariable=null; thetaTextField1.setText(""); } } } }); thetaButton.setMaximumSize(new Dimension(49, 25)); thetaButton.setMinimumSize(new Dimension(49, 25)); thetaButton.setPreferredSize(new Dimension(49, 25)); weightLabel.setText("Weight"); thetaTextField1.setMinimumSize(new Dimension(150, 25)); thetaTextField1.setPreferredSize(new Dimension(150, 25)); weightButton.setText(">"); weightButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(selectWeight){ //move selected variable to selectedList int selected = variableList.getSelectedIndex(); weightVariable = variableListModel.getElementAt(selected); weightTextField.setText(weightVariable.getName().toString()); variableListModel.removeElement(weightVariable); variableList.clearSelection(); }else{ if(weightVariable!=null){ variableListModel.addElement(weightVariable); weightVariable=null; weightTextField.setText(""); } } } }); weightButton.setMaximumSize(new Dimension(49, 25)); weightButton.setMinimumSize(new Dimension(49, 25)); weightButton.setPreferredSize(new Dimension(49, 25)); okButton.setText("OK"); okButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setVisible(false); } }); okButton.setMaximumSize(new Dimension(69, 25)); okButton.setMinimumSize(new Dimension(69, 25)); okButton.setPreferredSize(new Dimension(69, 25)); cancelButton.setText("Cancel"); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setVisible(false); } }); cancelButton.setMaximumSize(new Dimension(69, 25)); cancelButton.setMinimumSize(new Dimension(69, 25)); cancelButton.setPreferredSize(new Dimension(69, 25)); GroupLayout layout = new GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(tableScrollPane, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(variableScrollPane, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING) .addComponent(thetaButton, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(weightButton, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addComponent(thetaLabel) .addComponent(weightLabel) .addComponent(weightTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(thetaTextField1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))) .addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(okButton, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(cancelButton, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGap(12, 12, 12))) .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addComponent(variableScrollPane, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(tableScrollPane, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(thetaLabel) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(thetaButton, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(thetaTextField1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGap(33, 33, 33) .addComponent(weightLabel) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(weightTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(weightButton, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 146, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(okButton, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(cancelButton, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGap(19, 19, 19)))) ); pack(); }// </editor-fold> private void reset(){ thetaButton.setEnabled(true); thetaButton.setText(">"); thetaButton.setToolTipText("Select variable"); weightButton.setEnabled(true); weightButton.setText(">"); weightButton.setToolTipText("SelectVariable"); variableList.clearSelection(); thetaTextField1.setText(""); thetaVariable = null; weightTextField.setText(""); weightVariable = null; } private void setVariables(ArrayList<VariableAttributes> variables){ reset(); variableListModel.clear(); for(VariableAttributes v : variables){ variableListModel.addElement(v); } } private void openTable(DataTableName tableName){ try{ if(currentTable!=null && currentTable.equals(tableName)) return; VariableTableName variableTableName = new VariableTableName(tableName.toString()); ArrayList<VariableAttributes> v = dao.getAllVariables(conn, variableTableName); setVariables(v); currentTable = tableName; }catch(SQLException ex){ logger.fatal(ex.getMessage(), ex); JOptionPane.showMessageDialog(IrtLinkingThetaDialog.this, "Table could not be opened.", "SQL Exception", JOptionPane.ERROR_MESSAGE); } } public DataTableName getTableName(){ return currentTable; } public boolean canRun(){ return thetaVariable!=null; } public VariableAttributes getTheta(){ return thetaVariable; } public VariableAttributes getWeight(){ return weightVariable; } public boolean hasTheta(){ return thetaVariable!=null; } public boolean hasWeight(){ return weightVariable!=null; } public class TableSelectionListener implements ListSelectionListener { public void valueChanged(ListSelectionEvent e){ DataTableName tableName = (DataTableName)tableList.getSelectedValue(); if(tableName!=null){ openTable(tableName); } } } public class ListFocusListener implements FocusListener { public void focusGained(FocusEvent e){ String compName = e.getComponent().getName(); if(compName!=null){ if("unselectedVariableList".equals(compName)){ if(thetaVariable!=null) thetaButton.setEnabled(true); if(weightVariable!=null) weightButton.setEnabled(true); thetaButton.setText(">"); thetaButton.setToolTipText("Select variable"); selectTheta = true; weightButton.setText(">"); weightButton.setToolTipText("SelectVariable"); selectWeight = true; } if("selectedThetaList".equals(compName)){ thetaButton.setText("<"); thetaButton.setEnabled(true); thetaButton.setToolTipText("Unselect variable"); selectTheta = false; } if("selectedWeightList".equals(compName)){ weightButton.setText("<"); weightButton.setEnabled(true); weightButton.setToolTipText("Unselect variable"); selectWeight = false; } } } public void focusLost(FocusEvent e){ //do nothing } } }
gpl-2.0
ChaosPaladin/TERA_atlascore
java/game/tera/gameserver/model/SellableItem.java
3811
package tera.gameserver.model; import rlib.util.pools.Foldable; import rlib.util.pools.FoldablePool; import rlib.util.pools.Pools; import tera.Config; import tera.gameserver.model.inventory.Cell; import tera.gameserver.model.inventory.Inventory; import tera.gameserver.model.items.ItemInstance; /** * Модель покупаемого итема. * * @author Ronn */ public final class SellableItem implements Foldable { /** пул не используемых итемов */ private static final FoldablePool<SellableItem> pool = Pools.newConcurrentFoldablePool(SellableItem.class); /** * Создание нового экземпляра оболочки продаваемого итема. * * @param item продаваемый итем. * @param inventory инвентапь. * @param count кол-во продаваемых итемов. * @return новая оболочка. */ public static final SellableItem newInstance(ItemInstance item, Inventory inventory, long count) { SellableItem sell = pool.take(); if(sell == null) sell = new SellableItem(item, inventory, count); else { sell.item = item; sell.inventory = inventory; sell.count = count; } return sell; } /** покупаемый итем */ private ItemInstance item; /** инвентарь */ private Inventory inventory; /** кол-во */ private long count; /** * @param item покупаемый итем. * @param inventory инвентарь. * @param count кол-во покупаемого итема. */ private SellableItem(ItemInstance item, Inventory inventory, long count) { this.item = item; this.inventory = inventory; this.count = count; } /** * @param count добавленное кол-во итемов. */ public void addCount(long count) { this.count += count; } /** * @return все ли хорошо с этим итемом. */ public boolean check() { return inventory != null && inventory.getCellForObjectId(item.getObjectId()) != null; } /** * @return удаляет продаваемые итемы */ public void deleteItem() { inventory.lock(); try { Cell cell = inventory.getCellForObjectId(item.getObjectId()); inventory.removeItemFromIndex(count, cell.getIndex()); } finally { inventory.unlock(); } } @Override public boolean equals(Object object) { if(this == object || item == object) return true; return false; } @Override public void finalyze() { inventory = null; item = null; count = 0; } /** * Положить в пул. */ public void fold() { pool.put(this); } /** * @return кол-во продаваемых итемов. */ public long getCount() { return count; } /** * @return продаваемый итем. */ public ItemInstance getItem() { return item; } /** * @return ид продаваемого итема. */ public int getItemId() { return item.getItemId(); } /** * @return уникальный ид итема. */ public int getObjectId() { return item.getObjectId(); } /** * @return итоговая цена на итемы */ public long getSellPrice() { return (long) (count * item.getSellPrice() * Config.WORLD_SHOP_PRICE_MOD); } @Override public void reinit(){} /** * @param count кол-во продаваемых итемов. */ public void setCount(int count) { this.count = count; } /** * @param item продаваемый итем. */ public void setItem(ItemInstance item) { this.item = item; } /** * @param count кол-во на которое нужно уменьшить продаваемых итемов. */ public void subCount(int count) { this.count -= count; } }
gpl-2.0
garvitdelhi/emulate
Packages/Framework/TYPO3.Flow/Tests/Unit/Validation/Validator/DateTimeValidatorTest.php
3604
<?php namespace TYPO3\Flow\Tests\Unit\Validation\Validator; /* * * This script belongs to the TYPO3 Flow framework. * * * * It is free software; you can redistribute it and/or modify it under * * the terms of the GNU Lesser General Public License, either version 3 * * of the License, or (at your option) any later version. * * * * The TYPO3 project - inspiring people to share! * * */ require_once('AbstractValidatorTestcase.php'); /** * Testcase for the DateTime validator * */ class DateTimeValidatorTest extends \TYPO3\Flow\Tests\Unit\Validation\Validator\AbstractValidatorTestcase { protected $validatorClassName = 'TYPO3\Flow\Validation\Validator\DateTimeValidator'; /** * @var \TYPO3\Flow\I18n\Locale */ protected $sampleLocale; protected $mockDatetimeParser; /** * @return void */ public function setUp() { parent::setUp(); $this->sampleLocale = new \TYPO3\Flow\I18n\Locale('en_GB'); $this->mockObjectManagerReturnValues['TYPO3\Flow\I18n\Locale'] = $this->sampleLocale; $this->mockDatetimeParser = $this->getMock('TYPO3\Flow\I18n\Parser\DatetimeParser'); } /** * @test */ public function validateReturnsNoErrorIfTheGivenValueIsNull() { $this->validatorOptions(array()); $this->inject($this->validator, 'datetimeParser', $this->mockDatetimeParser); $this->assertFalse($this->validator->validate(NULL)->hasErrors()); } /** * @test */ public function validateReturnsNoErrorIfTheGivenValueIsAnEmptyString() { $this->validatorOptions(array()); $this->inject($this->validator, 'datetimeParser', $this->mockDatetimeParser); $this->assertFalse($this->validator->validate('')->hasErrors()); } /** * @test */ public function validateReturnsNoErrorIfTheGivenValueIsOfTypeDateTime() { $this->validatorOptions(array()); $this->inject($this->validator, 'datetimeParser', $this->mockDatetimeParser); $this->assertFalse($this->validator->validate(new \DateTime())->hasErrors()); } /** * @test */ public function returnsErrorsOnIncorrectValues() { $sampleInvalidTime = 'this is not a time string'; $this->mockDatetimeParser->expects($this->once())->method('parseTime', $sampleInvalidTime)->will($this->returnValue(FALSE)); $this->validatorOptions(array('locale' => 'en_GB', 'formatLength' => \TYPO3\Flow\I18n\Cldr\Reader\DatesReader::FORMAT_LENGTH_DEFAULT, 'formatType' => \TYPO3\Flow\I18n\Cldr\Reader\DatesReader::FORMAT_TYPE_TIME)); $this->inject($this->validator, 'datetimeParser', $this->mockDatetimeParser); $this->assertTrue($this->validator->validate($sampleInvalidTime)->hasErrors()); } /** * @test */ public function returnsTrueForCorrectValues() { $sampleValidDateTime = '10.08.2010, 18:00 CEST'; $this->mockDatetimeParser->expects($this->once())->method('parseDateAndTime', $sampleValidDateTime)->will($this->returnValue(array('parsed datetime'))); $this->validatorOptions(array('locale' => 'en_GB', 'formatLength' => \TYPO3\Flow\I18n\Cldr\Reader\DatesReader::FORMAT_LENGTH_FULL, 'formatType' => \TYPO3\Flow\I18n\Cldr\Reader\DatesReader::FORMAT_TYPE_DATETIME)); $this->inject($this->validator, 'datetimeParser', $this->mockDatetimeParser); $this->assertFalse($this->validator->validate($sampleValidDateTime)->hasErrors()); } }
gpl-2.0
NallelyFlores89/cronica-ambiental
wp-content/plugins/facebook-like-send-button/class-frontend.php
4217
<?php //ADD XFBML add_filter('language_attributes', 'fbls_schema'); function fbls_schema($attr) { $options = get_option('fbls'); if (!isset($options['fbns'])) {$options['fbns'] = "";} if (!isset($options['opengraph'])) {$options['opengraph'] = "";} if ($options['opengraph'] == 'on') {$attr .= "\n xmlns:og=\"http://ogp.me/ns#\"";} if ($options['fbns'] == 'on') {$attr .= "\n xmlns:fb=\"http://ogp.me/ns/fb#\"";} return $attr; } //ADD OPEN GRAPH META function fblsgraphinfo() { $options = get_option('fbls'); ?> <meta property="fb:app_id" content="<?php echo $options['appID']; ?>"/> <meta property="fb:admins" content="<?php echo $options['mods']; ?>"/> <?php } add_action('wp_head', 'fblsgraphinfo'); function fbmllssetup() { $options = get_option('fbls'); if (!isset($options['fbml'])) {$options['fbml'] = "";} if ($options['fbml'] == 'on') { ?> <!-- Facebook Like & Share Button: http://peadig.com/wordpress-plugins/facebook-like-share-button/ --> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/<?php echo $options['language']; ?>/sdk.js#xfbml=1&appId=<?php echo $options['appID']; ?>&version=v2.3"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <?php }} add_action('wp_footer', 'fbmllssetup', 100); //COMMENT BOX function fbls_button($content) { $options = get_option('fbls'); if (!isset($options['html5'])) {$options['html5'] = "off";} if (!isset($options['linklove'])) {$options['linklove'] = "off";} if (!isset($options['posts'])) {$options['posts'] = "off";} if (!isset($options['pages'])) {$options['pages'] = "off";} if (!isset($options['homepage'])) {$options['homepage'] = "off";} if ( (is_single() && $options['posts'] == 'on') || (is_page() && $options['pages'] == 'on') || ((is_home() || is_front_page()) && $options['homepage'] == 'on')) { $content .= "<!-- Facebook Like & Share Button: http://peadig.com/wordpress-plugins/facebook-like-share-button/ -->"; if ($options['html5'] == 'on') { $content .= '<div class="fb-like" data-href="'.get_permalink().'" data-layout="'.$options['layout'].'" data-action="'.$options['verb'].'" data-show-faces="'.$options['faces'].'" data-share="'.$options['share'].'"></div>'; } else { $content .= '<fb:like href="'.get_permalink().'" layout="'.$options['layout'].'" action="'.$options['verb'].'" show_faces="'.$options['faces'].'" share="'.$options['share'].'"></fb:like>'; } if ($options['linklove'] != 'no') { if ($options['linklove'] != 'off') { if (empty($fbls[linklove])) { $content .= '<p>Powered by <a href="http://peadig.com/wordpress-plugins/facebook-like-share-button/">Facebook Like</a></p>'; }}} } return $content; } add_filter ('the_content', 'fbls_button', 100); function fbls_shortcode($fbatts) { extract(shortcode_atts(array( "options" => get_option('fbls'), "url" => get_permalink(), ), $fbatts)); if (!empty($fbatts)) { foreach ($fbatts as $key => $option) $fbls[$key] = $option; } $fbls_sc = "<!-- Facebook Like & Share Button: http://peadig.com/wordpress-plugins/facebook-like-share-button/ -->"; if ($fbls[html5] == 'on') { $fbls_sc .= '<div class="fb-like" data-href="'.$url.'" data-layout="'.$options['layout'].'" data-action="'.$options['verb'].'" data-show-faces="'.$options['faces'].'" data-share="'.$options['share'].'"></div>'; "<div class=\"fb-comments\" data-href=\"".$url."\" data-num-posts=\"".$fbls[num]."\" data-width=\"".$fbls[width]."\" data-colorscheme=\"".$fbls[scheme]."\"></div>"; } else { $fbls_sc .= '<fb:like href="'.$url.'" layout="'.$options['layout'].'" action="'.$options['verb'].'" show_faces="'.$options['faces'].'" share="'.$options['share'].'"></fb:like>'; } if (!empty($fbls[linklove])) { $fbls_sc .= '<p>Powered by <a href="http://peadig.com/wordpress-plugins/facebook-like-share-button/">Facebook Like</a></p>'; } return $fbls_sc; } add_filter('widget_text', 'do_shortcode'); add_shortcode('fbls', 'fbls_shortcode'); ?>
gpl-2.0
actility/ong
gscl/m2m/src/main/java/com/actility/m2m/m2m/impl/M2MContextImpl.java
17255
/* * Copyright Actility, SA. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 only, as published by the Free Software Foundation. * * 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 version 2 for more details (a copy is * included at /legal/license.txt). * * You should have received a copy of the GNU General Public License * version 2 along with this work; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * * Please contact Actility, SA., 4, rue Ampere 22300 LANNION FRANCE * or visit www.actility.com if you need additional * information or have any questions. * * id $Id: M2MContextImpl.java 8761 2014-05-21 15:31:37Z JReich $ * author $Author: JReich $ * version $Revision: 8761 $ * lastrevision $Date: 2014-05-21 17:31:37 +0200 (Wed, 21 May 2014) $ * modifiedby $LastChangedBy: JReich $ * lastmodified $LastChangedDate: 2014-05-21 17:31:37 +0200 (Wed, 21 May 2014) $ */ package com.actility.m2m.m2m.impl; import java.io.IOException; import java.io.Serializable; import java.net.URI; import javax.servlet.ServletContext; import javax.servlet.ServletException; import org.apache.log4j.Logger; import com.actility.m2m.m2m.M2MConstants; import com.actility.m2m.m2m.M2MContext; import com.actility.m2m.m2m.M2MEventHandler; import com.actility.m2m.m2m.M2MException; import com.actility.m2m.m2m.M2MProxyHandler; import com.actility.m2m.m2m.M2MSession; import com.actility.m2m.m2m.M2MUtils; import com.actility.m2m.m2m.Request; import com.actility.m2m.m2m.StatusCode; import com.actility.m2m.m2m.log.BundleLogger; import com.actility.m2m.servlet.ApplicationSession; import com.actility.m2m.servlet.ApplicationSessionEvent; import com.actility.m2m.servlet.ApplicationSessionListener; import com.actility.m2m.servlet.ServletTimer; import com.actility.m2m.servlet.TimerListener; import com.actility.m2m.servlet.TimerService; import com.actility.m2m.servlet.song.LongPollURIs; import com.actility.m2m.servlet.song.SongDynamicRouter; import com.actility.m2m.servlet.song.SongFactory; import com.actility.m2m.servlet.song.SongServlet; import com.actility.m2m.servlet.song.SongServletMessage; import com.actility.m2m.servlet.song.SongServletRequest; import com.actility.m2m.servlet.song.SongServletResponse; import com.actility.m2m.servlet.song.SongURI; import com.actility.m2m.util.log.OSGiLogger; import com.actility.m2m.xo.XoException; import com.actility.m2m.xo.XoObject; import com.actility.m2m.xo.XoService; public final class M2MContextImpl extends SongServlet implements M2MContext, TimerListener, ApplicationSessionListener { private static final Logger LOG = OSGiLogger.getLogger(M2MContextImpl.class, BundleLogger.getStaticLogger()); public static final String M2M_PREFIX = "m2m:"; public static final String M2M_TIMER_PREFIX = M2M_PREFIX + "timer/"; public static final String AT_REMOTE_RESOURCE = M2M_PREFIX + "RemoteResource"; public static final String AT_INDICATION = M2M_PREFIX + "Indication"; public static final String AT_REQUEST = M2M_PREFIX + "Request"; private static final String AT_M2M_SESSION = M2M_PREFIX + "M2MSession"; private ApplicationSession appSession; private final XoService xoService; private final M2MUtils m2mUtils; private final M2MProxyHandler proxyHandler; private final M2MEventHandler eventHandler; private final URI sclUri; private SongURI songSclUri; private SongFactory songFactory; private SongDynamicRouter songDynamicRouter; private TimerService timerService; private volatile int[] backtrackableErrorCodes; public M2MContextImpl(URI sclUri, M2MProxyHandler proxyHandler, M2MEventHandler eventHandler, XoService xoService, M2MUtils m2mUtils) { this.sclUri = sclUri; this.proxyHandler = proxyHandler; this.eventHandler = eventHandler; this.xoService = xoService; this.m2mUtils = m2mUtils; this.backtrackableErrorCodes = new int[0]; } private void sendUnsuccessResponse(IndicationImpl indication, StatusCode statusCode, String message) throws IOException, ServletException { if (!indication.isCommitted()) { String mediaType = null; StatusCode realStatusCode = statusCode; String realMessage = message; try { mediaType = m2mUtils.getAcceptedXoMediaType(indication.getHeader(SongServletMessage.HD_ACCEPT)); } catch (M2MException e) { LOG.error(e.getMessage(), e); realStatusCode = e.getStatusCode(); realMessage = e.getMessage(); } ResponseImpl response = (ResponseImpl) indication.createUnsuccessResponse(realStatusCode); XoObject errorInfo = null; try { if (statusCode == realStatusCode) { errorInfo = xoService.newXmlXoObject(M2MConstants.TAG_M2M_ERROR_INFO); errorInfo.setNameSpace(M2MConstants.PREFIX_M2M); errorInfo.setStringAttribute(M2MConstants.TAG_M2M_STATUS_CODE, realStatusCode.name()); errorInfo.setStringAttribute(M2MConstants.TAG_M2M_ADDITIONAL_INFO, realMessage); if (M2MConstants.MT_APPLICATION_EXI.equals(mediaType)) { response.getSongResponse().setContent(errorInfo.saveExi(), M2MConstants.MT_APPLICATION_EXI); } else { response.getSongResponse().setContent(errorInfo.saveXml(), M2MConstants.CT_APPLICATION_XML_UTF8); } } response.send(); } catch (XoException e) { throw new ServletException(message, e); } finally { if (errorInfo != null) { errorInfo.free(true); } } } else { throw new ServletException(message); } } public void init() { ServletContext servletContext = getServletContext(); this.songFactory = (SongFactory) servletContext.getAttribute(SONG_FACTORY); this.songDynamicRouter = (SongDynamicRouter) servletContext.getAttribute(SONG_DYNAMIC_ROUTER); this.timerService = (TimerService) servletContext.getAttribute(TIMER_SERVICE); appSession = songFactory.createApplicationSession(); appSession.setExpires(0); appSession.setInvalidateWhenReady(false); if (sclUri != null) { songSclUri = songFactory.createURI(sclUri); } } public void destroy() { if (appSession.isValid()) { appSession.invalidate(); } } public M2MEventHandler getM2MHandler() { return eventHandler; } public String getApplicationName() { return getServletContext().getServletContextName(); } public String getApplicationPath() { return getServletContext().getContextPath(); } public int[] getBacktrackableErrorCodes() { return backtrackableErrorCodes; } public void setBacktrackableErrorCodes(int[] backtrackableErrors) { this.backtrackableErrorCodes = backtrackableErrors; } public Object getAttribute(String name) { if (name.startsWith(M2MContextImpl.M2M_PREFIX)) { return null; } return getServletContext().getAttribute(name); } public void setAttribute(String name, Object attribute) { if (name.startsWith(M2MContextImpl.M2M_PREFIX)) { throw new IllegalArgumentException( "m2m: prefix is reserved for M2M Layer internal attributes. Cannot set an attribute with this prefix: " + name); } getServletContext().setAttribute(name, attribute); } public void removeAttribute(String name) { if (name.startsWith(M2MContextImpl.M2M_PREFIX)) { throw new IllegalArgumentException( "m2m: prefix is reserved for M2M Layer internal attributes. Cannot remove an attribute with this prefix: " + name); } getServletContext().removeAttribute(name); } public void cancelTimer(String timerId) { ServletTimer timer = appSession.getTimer(timerId); if (timer != null) { timer.cancel(); appSession.removeAttribute(timerId); } } public URI createLocalUri(URI reference, String path) throws M2MException { try { return songFactory.createLocalURIFrom(reference, path).toURI(); } catch (ServletException e) { throw new M2MException("Cannot compute the local URI from " + reference.toString(), StatusCode.STATUS_INTERNAL_SERVER_ERROR, e); } } public boolean canBeServer(URI reference) throws M2MException { try { return songDynamicRouter.canBeServerFrom(songFactory.createURI(reference)); } catch (ServletException e) { throw new M2MException("Cannot determine if application can be server from " + reference.toString(), StatusCode.STATUS_INTERNAL_SERVER_ERROR, e); } } public URI[] createServerLongPoll(URI remoteTarget) throws M2MException { try { LongPollURIs uris = songDynamicRouter.createServerLongPoll(songFactory.createURI(remoteTarget)); return new URI[] { uris.getContactURI().toURI(), uris.getLongPollURI().toURI() }; } catch (ServletException e) { throw new M2MException("Cannot create a server long poll connection", StatusCode.STATUS_INTERNAL_SERVER_ERROR, e); } } public void createServerLongPoll(URI contactUri, URI longPollUri) throws M2MException { try { songDynamicRouter.createServerLongPoll(songFactory.createURI(contactUri), songFactory.createURI(longPollUri)); } catch (ServletException e) { throw new M2MException("Cannot create a server long poll connection", StatusCode.STATUS_INTERNAL_SERVER_ERROR, e); } } public void deleteServerLongPoll(URI contactUri, URI longPollUri) { songDynamicRouter.deleteServerLongPoll(songFactory.createURI(contactUri), songFactory.createURI(longPollUri)); } public void createClientLongPoll(URI contactUri, URI longPollUri) throws M2MException { try { songDynamicRouter.createClientLongPoll(songFactory.createURI(contactUri), songFactory.createURI(longPollUri)); } catch (ServletException e) { throw new M2MException("Cannot create a client long poll connection", StatusCode.STATUS_INTERNAL_SERVER_ERROR, e); } } public void deleteClientLongPoll(URI contactUri, URI longPollUri) { songDynamicRouter.deleteClientLongPoll(songFactory.createURI(contactUri), songFactory.createURI(longPollUri)); } public String startTimer(long timeout, Serializable info) { ServletTimer timer = timerService.createTimer(appSession, timeout, false, info); return timer.getId(); } public M2MSession createSession(int timeout) { ApplicationSession appSession = songFactory.createApplicationSession(); M2MSession m2mSession = new M2MSessionImpl(timerService, appSession, timeout); appSession.setAttribute(AT_M2M_SESSION, m2mSession); return m2mSession; } public void doCreate(SongServletRequest request) throws IOException, ServletException { IndicationImpl indication = new IndicationImpl(songFactory, xoService, m2mUtils, request); StatusCode statusCode = null; String message = null; try { if (request.isProxy()) { proxyHandler.doProxyCreateIndication(indication); } else { eventHandler.doCreateIndication(indication); } } catch (M2MException e) { statusCode = e.getStatusCode(); message = e.getMessage(); } if (statusCode != null) { sendUnsuccessResponse(indication, statusCode, message); } } public void doRetrieve(SongServletRequest request) throws IOException, ServletException { IndicationImpl indication = new IndicationImpl(songFactory, xoService, m2mUtils, request); StatusCode statusCode = null; String message = null; try { if (request.isProxy()) { proxyHandler.doProxyRetrieveIndication(indication); } else { eventHandler.doRetrieveIndication(indication); } } catch (M2MException e) { statusCode = e.getStatusCode(); message = e.getMessage(); } if (statusCode != null) { sendUnsuccessResponse(indication, statusCode, message); } } public void doUpdate(SongServletRequest request) throws IOException, ServletException { IndicationImpl indication = new IndicationImpl(songFactory, xoService, m2mUtils, request); StatusCode statusCode = null; String message = null; try { if (request.isProxy()) { proxyHandler.doProxyUpdateIndication(indication); } else { eventHandler.doUpdateIndication(indication); } } catch (M2MException e) { statusCode = e.getStatusCode(); message = e.getMessage(); } if (statusCode != null) { sendUnsuccessResponse(indication, statusCode, message); } } public void doDelete(SongServletRequest request) throws IOException, ServletException { IndicationImpl indication = new IndicationImpl(songFactory, xoService, m2mUtils, request); StatusCode statusCode = null; String message = null; try { if (request.isProxy()) { proxyHandler.doProxyDeleteIndication(indication); } else { eventHandler.doDeleteIndication(indication); } } catch (M2MException e) { statusCode = e.getStatusCode(); message = e.getMessage(); } if (statusCode != null) { sendUnsuccessResponse(indication, statusCode, message); } } public void doSuccessResponse(SongServletResponse response) throws IOException { ConfirmImpl confirm = new ConfirmImpl(xoService, response); try { eventHandler.doSuccessConfirm(confirm); } catch (M2MException e) { LOG.error("ResourceException while calling doSuccessResponseConfirm for request on " + response.getRequest().getTargetID().absoluteURI(), e); } } public void doErrorResponse(SongServletResponse response) throws IOException { ConfirmImpl confirm = new ConfirmImpl(xoService, response); try { eventHandler.doUnsuccessConfirm(confirm); } catch (M2MException e) { LOG.error("ResourceException while calling doSuccessResponseConfirm for request on " + response.getRequest().getTargetID().absoluteURI(), e); } } public void timeout(ServletTimer timer) { M2MSession session = (M2MSession) timer.getApplicationSession().getAttribute(M2M_TIMER_PREFIX + timer.getId()); try { eventHandler.timeout(timer.getId(), session, timer.getInfo()); } catch (IOException e) { LOG.error("IOException while calling timeout", e); } catch (M2MException e) { LOG.error("ResoruceException while calling timeout", e); } } public void sessionCreated(ApplicationSessionEvent ev) { // Ignore } public void sessionDestroyed(ApplicationSessionEvent ev) { // Ignore } public void sessionExpired(ApplicationSessionEvent ev) { M2MSession session = (M2MSession) ev.getApplicationSession().getAttribute(AT_M2M_SESSION); if (session != null) { try { eventHandler.sessionExpired(session); } catch (IOException e) { LOG.error("IOException while calling sessionExpired", e); } catch (M2MException e) { LOG.error("ResourceException while calling sessionExpired", e); } } } public void sessionReadyToInvalidate(ApplicationSessionEvent ev) { // Ignore } public Request createRequest(String method, URI requestingEntity, URI targetID) { SongServletRequest request = songFactory.createRequest(method, requestingEntity, targetID); if (songSclUri != null) { request.getProxy().setProxyTo(songSclUri); } return new RequestImpl(songFactory, request); } public M2MUtils getM2MUtils() { return m2mUtils; } }
gpl-2.0
mailsystem/community
src/Mailsystem/Bundle/LetterBundle/Tests/Unit/Entity/LetterTest.php
1936
<?php namespace Mailsystem\Bundle\LetterBundle\Tests\Unit\Entity; use Mailsystem\Bundle\LetterBundle\Entity\Letter; class LetterTest extends \PHPUnit_Framework_TestCase { /** * @dataProvider getSetDataProvider */ public function testGetSet($property, $value, $expected) { $obj = new Letter(); call_user_func_array([$obj, 'set' . ucfirst($property)], [$value]); $this->assertEquals($expected, call_user_func_array([$obj, 'get' . ucfirst($property)], [])); } public function getSetDataProvider() { $now = new \DateTime('now'); $owner = $this->getMockBuilder('Oro\Bundle\UserBundle\Entity\User') ->disableOriginalConstructor() ->getMock(); $organization = $this->getMockBuilder('Oro\Bundle\OrganizationBundle\Entity\Organization') ->disableOriginalConstructor() ->getMock(); return [ 'owner' => ['owner', $owner, $owner], 'organization' => ['organization', $organization, $organization], 'subject' => ['subject', 'subject', 'subject'], 'body' => ['body', 'body', 'body'], 'createdAt' => ['createdAt', $now, $now], 'updatedAt' => ['updatedAt', $now, $now], ]; } public function testBeforeSave() { $obj = new Letter(); $this->assertNull($obj->getCreatedAt()); $this->assertNull($obj->getUpdatedAt()); $obj->prePersist(); $this->assertInstanceOf('\DateTime', $obj->getCreatedAt()); $this->assertNull($obj->getUpdatedAt()); } public function testBeforeUpdate() { $obj = new Letter(); $this->assertNull($obj->getCreatedAt()); $this->assertNull($obj->getUpdatedAt()); $obj->preUpdate(); $this->assertInstanceOf('\DateTime', $obj->getUpdatedAt()); $this->assertNull($obj->getCreatedAt()); } }
gpl-2.0
usv-public/nubomedia-autonomous-installer
credentials.py
2162
# Copyright 2016 Universitatea Stefan cel Mare Suceava # Copyright 2016 NUBOMEDIA # 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. import os from images_configurations import * def get_keystone_creds(): d = {} env = os.environ.get('OS_USERNAME') if env is None: d['username'] = username d['password'] = password d['auth_url'] = auth_url d['tenant_name'] = tenant_name else: d['username'] = os.environ['OS_USERNAME'] d['password'] = os.environ['OS_PASSWORD'] d['auth_url'] = os.environ['OS_AUTH_URL'] d['tenant_name'] = os.environ['OS_TENANT_NAME'] return d def get_nova_creds(): d = {} env = os.environ.get('OS_USERNAME') if env is None: d['username'] = username d['api_key'] = password d['auth_url'] = auth_url d['project_id'] = tenant_name else: d['username'] = os.environ['OS_USERNAME'] d['api_key'] = os.environ['OS_PASSWORD'] d['auth_url'] = os.environ['OS_AUTH_URL'] d['project_id'] = os.environ['OS_TENANT_NAME'] return d def get_glance_creds(): env = os.environ.get('GLANCE_ENDPOINT') if env is None: d = glance_endpoint else: d = os.environ['GLANCE_ENDPOINT'] return d def get_master_creds(): d = {} d['username'] = master_user if master_pass is None: d['key_filename'] = master_key else: d['password'] = master_pass return d def get_master_ip(): return master_ip def get_env_vars(): d = {} d['floating_ip_pool'] = floating_ip_pool return d
gpl-2.0
arafathnihar/nifras
plugins/system/hikashopsocial/hikashopsocial.php
19713
<?php /** * @package HikaShop for Joomla! * @version 2.3.4 * @author hikashop.com * @copyright (C) 2010-2014 HIKARI SOFTWARE. All rights reserved. * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ defined('_JEXEC') or die('Restricted access'); ?><?php jimport( 'joomla.plugin.plugin' ); class plgSystemHikashopsocial extends JPlugin { var $meta=array(); function plgSystemHikashopsocial( &$subject, $params ) { parent::__construct( $subject, $params ); if ( (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https') ) { $this->https = 's'; } else { $this->https = ''; } } function onAfterRender(){ $app = Jfactory::getApplication(); if(!$app->isAdmin() && (JRequest::getVar('option')=='com_hikashop' || JRequest::getVar('option')=='') && (JRequest::getVar('ctrl')=='product' || JRequest::getVar('ctrl')=='category') && (JRequest::getVar('task')=='show' || JRequest::getVar('task')=='listing')){ $body = JResponse::getBody(); if(strpos($body,'{hikashop_social}')){ $pluginsClass = hikashop_get('class.plugins'); $plugin = $pluginsClass->getByName('system','hikashopsocial'); if(!isset($plugin->params['position'])){ $plugin->params['position'] = 0; $plugin->params['display_twitter'] = 1; $plugin->params['display_fb'] = 1; $plugin->params['display_google'] = 1; $plugin->params['fb_style'] = 0; $plugin->params['fb_faces'] = 1; $plugin->params['fb_verb'] = 0; $plugin->params['fb_theme'] = 0; $plugin->params['fb_font'] = 0; $plugin->params['fb_type'] = 0; $plugin->params['twitter_count'] = 0; $plugin->params['google_size']=2; $plugin->params['google_count']=1; } if(!isset($plugin->params['fb_send'])){ $plugin->params['fb_send']=0; } if(!isset($plugin->params['fb_tag'])){ $plugin->params['fb_tag']="iframe"; } if($plugin->params['position']==0) $html='<div id="hikashop_social" style="text-align:left;">'; else if($plugin->params['position']==1 && $plugin->params['width']!=0) $html='<div id="hikashop_social" style="text-align:right; width:'.$plugin->params['width'].'px">'; else{ $html='<div id="hikashop_social" style="text-align:right; width:100%">'; } if($plugin->params['display_twitter']) $html.=$this->_addTwitterButton( $plugin); if(@$plugin->params['display_pinterest']) $html.=$this->_addPinterestButton( $plugin); if(@$plugin->params['display_google']) $html.=$this->_addGoogleButton( $plugin); if(@$plugin->params['display_addThis']) $html.=$this->_addAddThisButton( $plugin); if($plugin->params['display_fb']) $html.=$this->_addFacebookButton( $plugin); $html.='</div>'; $body = str_replace('{hikashop_social}',$html,$body); if(@$plugin->params['display_google']){ $mainLang = JFactory::getLanguage(); $tag = $mainLang->get('tag'); if(!in_array($tag,array('zh-CN','zh-TW','en-GB','en-US','pt-BR','pt-PT'))) $tag=strtolower(substr($tag,0,2)); $lang = '{"lang": "'.$tag.'"}'; $body=str_replace('</head>', '<script type="text/javascript" src="https://apis.google.com/js/plusone.js">'.$lang.'</script></head>', $body); } if($plugin->params['display_fb']){ $body=str_replace('<html ', '<html xmlns:fb="https://www.facebook.com/2008/fbml" xmlns:og="http://ogp.me/ns# " xmlns:fb="http://ogp.me/ns/fb#" ', $body); if($plugin->params['fb_tag']=="xfbml"){ $mainLang = JFactory::getLanguage(); $tag = str_replace('-','_',$mainLang->get('tag')); $fb='<div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/'.$tag.'/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, \'script\', \'facebook-jssdk\')); </script>'; $body = preg_replace('#<body.*>#Us','$0'.$fb,$body); } } if(@$plugin->params['display_pinterest']){ $body=str_replace('</head>', '<script type="text/javascript" src="http'.$this->https.'://assets.pinterest.com/js/pinit.js"></script></head>', $body); } if(@$plugin->params['display_addThis']){ $var=array(); $vars=''; if(!empty($plugin->params['services_exclude'])){ $var[]='services_exclude: "'.$plugin->params['services_exclude'].'"';} if(!empty($var)){ $vars='<script type="text/javascript">var addthis_config = { '.implode(';',$var).' }</script>'; } $body=str_replace('</head>', '<script type="text/javascript" src="http'.$this->https.'://s7.addthis.com/js/250/addthis_widget.js"></script>'.$vars.'</head>', $body); } if(!empty($this->meta)){ foreach($this->meta as $k => $v){ if(!strpos($body,$k)){ $body=str_replace('</head>', $v.'</head>', $body); } } } JResponse::setBody($body); } } } function _addAddThisButton(&$plugin){ $atClass=''; $class=''; $divClass=''; $endDiv=''; if($plugin->params['addThis_display']==0){ $atClass='addthis_button_compact'; } if($plugin->params['addThis_display']==1){ $atClass='addthis_button_compact'; $divClass='<div class="addthis_default_style addthis_toolbox addthis_32x32_style">'; $endDiv='</div>';} if($plugin->params['addThis_display']==2){ $atClass='addthis_counter';} if($plugin->params['position']==0){ $class='hikashop_social_addThis'; } else{ $class='hikashop_social_addThis_right'; } $html='<span class="'.$class.'" >'.$divClass.'<a class="'.$atClass.'"></a>'.$endDiv.'</span>'; return $html; } function _addGoogleButton(&$plugin){ if($plugin->params['google_count']==1){ $count='count="true"'; } else{ $count='count="false"'; } $div='<span>'; if($plugin->params['position']==0){ if($plugin->params['google_size']==0){ $size='size="standard"'; $div="<span class='hikashop_social_google'>"; } if($plugin->params['google_size']==1){ $size='size="small"'; $div="<span class='hikashop_social_google'>";} if($plugin->params['google_size']==2){ $size='size="medium"'; $div="<span class='hikashop_social_google'>";} if($plugin->params['google_size']==3){ $size='size="tall"'; $div="<span class='hikashop_social_google'>";} }else{ if($plugin->params['google_size']==0){ $size='size="standard"'; $div="<span class='hikashop_social_google_right'>"; } if($plugin->params['google_size']==1){ $size='size="small"'; $div="<span class='hikashop_social_google_right'>";} if($plugin->params['google_size']==2){ $size='size="medium"'; $div="<span class='hikashop_social_google_right'>";} if($plugin->params['google_size']==3){ $size='size="tall"'; $div="<span class='hikashop_social_google_right'>";} } $html=$div.'<g:plusone '.$size.' '.$count.'></g:plusone></span>'; return $html; } function _addPinterestButton(&$plugin){ $product = $this->_getProductInfo(); $imageUrl = $this->_getImageURL($product->product_id); if($plugin->params['position']==0){ if($plugin->params['pinterest_display']==0){ $count='horizontal'; $div="<span class='hikashop_social_pinterest'>";} if($plugin->params['pinterest_display']==1){ $count='vertical'; $div="<span class='hikashop_social_pinterest'>";} if($plugin->params['pinterest_display']==2){ $count='none'; $div="<span class='hikashop_social_pinterest'>";} }else{ if($plugin->params['pinterest_display']==0){ $count='horizontal'; $div="<span class='hikashop_social_pinterest_right'>";} if($plugin->params['pinterest_display']==1){ $count='vertical'; $div="<span class='hikashop_social_pinterest_right'>";} if($plugin->params['pinterest_display']==2){ $count='none'; $div="<span class='hikashop_social_pinterest_right'>";} } if(isset($product->product_canonical) && !empty($product->product_canonical)){ $url = hikashop_cleanURL($product->product_canonical); }else{ $url=hikashop_currentURL('',false); } $html=$div.'<a href="http'.$this->https.'://pinterest.com/pin/create/button/?url='.urlencode($url).'&media='.urlencode($imageUrl).'&description='.htmlspecialchars(strip_tags($product->product_description), ENT_COMPAT,'UTF-8').'" class="pin-it-button" count-layout="'.$count.'"><img border="0" src="http://assets.pinterest.com/images/PinExt.png" title="Pin It" /></a></span>'; return $html; } function _addTwitterButton(&$plugin){ $product = $this->_getProductInfo(); if($plugin->params['position']==0){ if($plugin->params['twitter_count']==0){ $count='horizontal'; $div="<span class='hikashop_social_tw_horizontal'>"; } if($plugin->params['twitter_count']==1){ $count='vertical'; $div="<span class='hikashop_social_tw'>"; } if($plugin->params['twitter_count']==2){ $count='none'; $div="<span class='hikashop_social_tw'>"; } }else{ if($plugin->params['twitter_count']==0){ $count='horizontal'; $div="<span class='hikashop_social_tw_horizontal_right'>"; } if($plugin->params['twitter_count']==1){ $count='vertical'; $div="<span class='hikashop_social_tw_right'>"; } if($plugin->params['twitter_count']==2){ $count='none'; $div="<span class='hikashop_social_tw_right'>"; } } $message=''; if(!empty($plugin->params['twitter_text'])){ $message='data-text="'.$plugin->params['twitter_text'].'"'; } $mention=''; if(!empty($plugin->params['twitter_mention'])){ $mention='data-via="'.$plugin->params['twitter_mention'].'"'; } $mainLang = JFactory::getLanguage(); $locale=strtolower(substr($mainLang->get('tag'),0,2)); if($locale=='en') $lang=''; else if($locale=='fr') $lang='data-lang="fr"'; else if($locale=='de') $lang='data-lang="de"'; else if($locale=='es') $lang='data-lang="es"'; else if($locale=='it') $lang='data-lang="it"'; else if($locale=='ja') $lang='data-lang="ja"'; else if($locale=='ru') $lang='data-lang="ru"'; else if($locale=='tr') $lang='data-lang="tr"'; else if($locale=='ko') $lang='data-lang="ko"'; else $lang=''; if (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) { $this->meta['hikashop_twitter_js_code']='<script type="text/javascript"> function twitterPop(str) { mywindow = window.open(\'http://twitter.com/share?url=\'+str,"Tweet_widow","channelmode=no,directories=no,location=no,menubar=no,scrollbars=no,toolbar=no,status=no,width=500,height=375,left=300,top=200"); mywindow.focus(); } </script>'; $html=$div; if(isset($product->product_canonical) && !empty($product->product_canonical)){ $url = hikashop_cleanURL($product->product_canonical); }else{ $url=hikashop_currentURL('',false); } $html.='<a href="javascript:twitterPop(\''.$url.'\')"><img src="'.HIKASHOP_IMAGES.'icons/tweet_button.jpg"></a></span>'; return $html; } if(!isset($div)) $div='<span>'; $html=$div; $html.='<a href="http'.$this->https.'://twitter.com/share" class="twitter-share-button" '.$message.' data-count="'.$count.'" '.$mention.' '.$lang.'>Tweet</a> <script type="text/javascript" src="http'.$this->https.'://platform.twitter.com/widgets.js"></script></span>'; return $html; } function _addFacebookButton( &$plugin){ $product=$this->_getProductInfo(); $options=''; $xfbml_options= ''; if($plugin->params['fb_style']==0){ $options='layout=standard&amp;'; $options.='width=400&amp;';} if($plugin->params['fb_style']==1){ $options='layout=button_count&amp;'; $options.='width=115&amp;'; $xfbml_options.='data-layout="button_count" ';} if($plugin->params['fb_style']==2){ $options='layout=box_count&amp;'; $options.='width=115&amp;'; $xfbml_options.='data-layout="box_count" ';} if($plugin->params['fb_faces']==0){ $options.='show_faces=false&amp;'; $xfbml_options.='data-show-faces="false" ';} else{ $options.='show_faces=true&amp;'; $xfbml_options.='data-show-faces="false" '; } if($plugin->params['fb_verb']==0){ $options.='action=like&amp;'; } else{ $options.='action=recommend&amp;'; $xfbml_options.='data-action="recommend" ';} if($plugin->params['fb_theme']==0){ $options.='colorscheme=light&amp;'; } else{ $options.='colorscheme=dark&amp;'; $xfbml_options.='data-colorscheme="dark" ';} if($plugin->params['fb_font']==0){ $options.='font=arial&amp;'; $xfbml_options.='data-font="arial" '; } if($plugin->params['fb_font']==1){ $options.='font=lucida%20grande&amp;'; $xfbml_options.='data-font="lucida%20grande" '; } if($plugin->params['fb_font']==2){ $options.='font=segoe%20ui&amp;'; $xfbml_options.='data-font="segoe%20ui" ';} if($plugin->params['fb_font']==3){ $options.='font=tahoma&amp;'; $xfbml_options.='data-font="tahoma" '; } if($plugin->params['fb_font']==4){ $options.='font=trebuchet%2Bms&amp;'; $xfbml_options.='data-font="trebuchet%20ms" '; } if($plugin->params['fb_font']==5){ $options.='font=verdana&amp;'; $xfbml_options.='data-font="verdana" '; } if($plugin->params['fb_send']==1){ $xfbml_options.='data-send="true"" ';} if(isset($product->product_canonical) && !empty($product->product_canonical)){ $url = hikashop_cleanURL($product->product_canonical); }else{ $url=hikashop_currentURL('',false); } if($plugin->params['position']==0){ if($plugin->params['fb_style']==0){ $sizes='class="hikashop_social_fb_standard"'; $div='<span class="hikashop_social_fb" >';} if($plugin->params['fb_style']==1){ $sizes='class="hikashop_social_fb_button_count"'; $div='<span class="hikashop_social_fb" >';} if($plugin->params['fb_style']==2){ $sizes='class="hikashop_social_fb_box_count"'; $div='<span class="hikashop_social_fb" >';} }else{ if($plugin->params['fb_style']==0){ $sizes='class="hikashop_social_fb_standard"'; $div='<span class="hikashop_social_fb_right" >';} if($plugin->params['fb_style']==1){ $sizes='class="hikashop_social_fb_button_count"'; $div='<span class="hikashop_social_fb_right" >';} if($plugin->params['fb_style']==2){ $sizes='class="hikashop_social_fb_box_count"'; $div='<span class="hikashop_social_fb_right" >';} } if(isset($div)){ $html=$div; } else{ $html='';} if($plugin->params['fb_tag']=="iframe"){ $html.='<iframe src="http'.$this->https.'://www.facebook.com/plugins/like.php?href='.urlencode($url).'&amp;send=false&amp;'.$options.'height=30" scrolling="no" frameborder="0" style="border:none; overflow:hidden;" '.$sizes.' allowTransparency="true"> </iframe>'; }else{ $html.='<div class="fb-like" data-href="'.$url.'" '.$xfbml_options.'></div>'; } if(isset($div)) $html.='</span>'; $this->meta['property="og:title"']='<meta property="og:title" content="'.htmlspecialchars($product->product_name, ENT_COMPAT,'UTF-8').'"/> '; if($plugin->params['fb_type']==0){ $this->meta['property="og:type"']='<meta property="og:type" content="product"/> '; } if($plugin->params['fb_type']==1){ $this->meta['property="og:type"']='<meta property="og:type" content="album"/> '; } if($plugin->params['fb_type']==2){ $this->meta['property="og:type"']='<meta property="og:type" content="book"/> '; } if($plugin->params['fb_type']==3){ $this->meta['property="og:type"']='<meta property="og:type" content="company"/> '; } if($plugin->params['fb_type']==4){ $this->meta['property="og:type"']='<meta property="og:type" content="drink"/> '; } if($plugin->params['fb_type']==5){ $this->meta['property="og:type"']='<meta property="og:type" content="game"/> '; } if($plugin->params['fb_type']==6){ $this->meta['property="og:type"']='<meta property="og:type" content="movie"/> '; } if($plugin->params['fb_type']==7){ $this->meta['property="og:type"']='<meta property="og:type" content="song"/> '; } $config =& hikashop_config(); $uploadFolder = ltrim(JPath::clean(html_entity_decode($config->get('uploadfolder','media/com_hikashop/upload/'))),DS); $uploadFolder = rtrim($uploadFolder,DS).DS; $this->uploadFolder_url = str_replace(DS,'/',$uploadFolder); $this->uploadFolder = JPATH_ROOT.DS.$uploadFolder; $this->thumbnail = $config->get('thumbnail',1); $this->thumbnail_y = $config->get('product_image_y',$config->get('thumbnail_y')); $this->thumbnail_x = $config->get('product_image_x',$config->get('thumbnail_x')); $this->main_thumbnail_x=$this->thumbnail_x; $this->main_thumbnail_y=$this->thumbnail_y; $this->main_uploadFolder_url = $this->uploadFolder_url; $this->main_uploadFolder = $this->uploadFolder; $imageUrl = $this->_getImageURL($product->product_id); if(!empty($imageUrl)){ $this->meta['property="og:image"']='<meta property="og:image" content="'.$imageUrl.'" /> '; } $this->meta['property="og:url"']='<meta property="og:url" content="'.$url.'" />'; $conf = JFactory::getConfig(); if(HIKASHOP_J30){ $siteName=$conf->get('sitename'); }else{ $siteName=$conf->getValue('config.sitename'); } $this->meta['property="og:description"']='<meta property="og:description" content="'.htmlspecialchars(strip_tags($product->product_description), ENT_COMPAT,'UTF-8').'"/> '; $this->meta['property="og:site_name"']='<meta property="og:site_name" content="'.htmlspecialchars($siteName, ENT_COMPAT,'UTF-8').'"/> '; if(!empty($plugin->params['admin'])){ $this->meta['property="fb:admins"']='<meta property="fb:admins" content="'.htmlspecialchars($plugin->params['admin'], ENT_COMPAT,'UTF-8').'" />'; } return $html; } function _getProductInfo(){ static $product = null; if(empty($product)){ $app = Jfactory::getApplication(); $product_id = (int)hikashop_getCID('product_id'); $menus = $app->getMenu(); $menu = $menus->getActive(); if(empty($menu)){ if(!empty($Itemid)){ $menus->setActive($Itemid); $menu = $menus->getItem($Itemid); } } if(empty($product_id)){ if (is_object( $menu )) { jimport('joomla.html.parameter'); $category_params = new JParameter( $menu->params ); $product_id = $category_params->get('product_id'); } } if(!empty($product_id)){ $productClass = hikashop_get('class.product'); $product = $productClass->get($product_id); if($product->product_type=='variant'){ $product = $productClass->get($product->product_parent_id); } } } return $product; } function _getImageURL($product_id){ $config =& hikashop_config(); $uploadFolder = ltrim(JPath::clean(html_entity_decode($config->get('uploadfolder','media/com_hikashop/upload/'))),DS); $uploadFolder = rtrim($uploadFolder,DS).DS; $this->uploadFolder_url = str_replace(DS,'/',$uploadFolder); $this->main_uploadFolder_url = $this->uploadFolder_url; $db = JFactory::getDBO(); $queryImage = 'SELECT * FROM '.hikashop_table('file').' WHERE file_ref_id='.$product_id.' AND file_type=\'product\' ORDER BY file_ordering ASC, file_id ASC'; $db->setQuery($queryImage); $image = $db->loadObject(); $imageUrl = ''; if(empty($image)){ $queryImage = 'SELECT * FROM '.hikashop_table('file').' as a LEFT JOIN '.hikashop_table('product').' as b ON a.file_ref_id=b.product_id WHERE product_parent_id='.$product_id.' AND file_type=\'product\' ORDER BY file_ordering ASC, file_id ASC'; $db->setQuery($queryImage); $image = $db->loadObject(); } if(!empty($image)){ $imageUrl=JURI::base().$this->main_uploadFolder_url.$image->file_path; } return $imageUrl; } }
gpl-2.0
ricker75/Global-Server
data/actions/scripts/pits of inferno quest/pitsOfInfernoQuestMirror.lua
967
function onUse(cid, item, fromPosition, itemEx, toPosition) local tapestry = 6434 local mirror = 1847 local blue_tapestry_pos_create = { x=32739, y=32392, z=14, stackpos=2} local blue_tapestry_pos = { x=32739, y=32393, z=14, stackpos=2} local remove_blue_tapestry = getThingfromPos(blue_tapestry_pos) if itemEx.actionid == 39511 and itemEx.itemid == tapestry then doRemoveItem(remove_blue_tapestry.uid,1) doCreateItem(6434,1,blue_tapestry_pos_create) end local cbtp = { x=32739, y=32393, z=14, stackpos=2} local rbtp = { x=32739, y=32392, z=14, stackpos=2} local rbt = getThingfromPos(rbtp) local pos = {x=32739, y=32392, z=13} if itemEx.actionid == 39512 and itemEx.itemid == mirror then local ek = doCreateItem(6434,1,cbtp) doSetItemActionId(ek, 10088) doRemoveItem(rbt.uid,1) doTeleportThing(cid, pos) doSendMagicEffect(getCreaturePosition(cid),10) doCreatureSay(cid, "Beauty has to be rewarded! Muahahaha!", TALKTYPE_ORANGE_1) end end
gpl-2.0