code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class FileLogger extends MyLoggerImpl { private String fileName; public FileLogger(String fileName) { super(); this.fileName = fileName; } @Override public void log(int level, String message) throws ErrorIntegerLevelException { super.log(level, message); try { File file = new File(fileName); FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); BufferedWriter bw = new BufferedWriter(fw); if(file.length() > 0) { bw.write("\n"+ getLogMessage()); } else { bw.write(getLogMessage()); } bw.close(); } catch (IOException e) { System.err.println("This file doesn`t exist!"); } } public static void main(String[] argv) { MyLogger consoleLogger = new FileLogger("test.txt"); try { consoleLogger.log(1, "Hello world!"); consoleLogger.log(2, "The application`s digital signature has error!"); consoleLogger.log(3, "Checking file system on C!"); consoleLogger.log(4, "Error level!"); } catch (ErrorIntegerLevelException e) { System.err.println("Error level! It must be 1, 2 or 3"); } } }
irin4eto/HackBulgaria_JavaScript
Candidacy/SimpleLogger/src/FileLogger.java
Java
gpl-2.0
1,200
/** * Created by Paul on 24/01/2015. */ var install_url = $("#install_url").val(); $("#updateCase").click(function () { var case_id = $('#case_id').val(); var case_priority = $('#case_priority').val(); var case_status = $('#case_status').val(); var case_type = $('#case_type').val(); var assignedTo = $('#assignedTo').val(); var case_subject = $('#case_subject').val(); var case_description = $('#case_description').val(); var case_resolution = $('#case_resolution').val(); $.ajax({ url: install_url + '/web/front.php/tickets/update_case_ajax', type: 'POST', data: "id=" + case_id + "&case_priority=" + case_priority + "&case_status=" + case_status + "&case_type=" + case_type + "&assignedTo=" + assignedTo + "&case_subject=" + case_subject + "&case_description=" + case_description + "&case_resolution=" + case_resolution, dataType: 'json', success: function (data) { if (data.error == "no") { toastr.options = { "closeButton": true, "showDuration": 3 }; toastr['success']('MyCRM', "Case updated"); } else { toastr.options = { "closeButton": true, "showDuration": 3 }; toastr['error']('MyCRM', "Error while updating case"); } }, error: function (data) { toastr.options = { "closeButton": true, "showDuration": 3 }; toastr['error']('MyCRM', "Error while updating case : " + data); } }); });
paulcoiffier/Mobissime-Liberta
src/MyCrm/Modules/LibertaTickets/Js/edit_case.js
JavaScript
gpl-2.0
1,698
<?php /* Smarty version 2.6.14, created on 2010-01-28 11:39:35 compiled from CRM/Contact/Form/Search.tpl */ ?> <?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php'); smarty_core_load_plugins(array('plugins' => array(array('block', 'ts', 'CRM/Contact/Form/Search.tpl', 19, false),)), $this); ?> <?php $_smarty_tpl_vars = $this->_tpl_vars; $this->_smarty_include(array('smarty_include_tpl_file' => "CRM/Contact/Form/Search/Intro.tpl", 'smarty_include_vars' => array())); $this->_tpl_vars = $_smarty_tpl_vars; unset($_smarty_tpl_vars); ?> <?php if ($this->_tpl_vars['context'] == 'smog'): ?> <?php if ($this->_tpl_vars['rowsEmpty']): ?> <?php $this->assign('showBlock', ""); ?> <?php $this->assign('hideBlock', "'searchForm','searchForm_show'"); ?> <?php else: ?> <?php $this->assign('showBlock', "'searchForm_show'"); ?> <?php $this->assign('hideBlock', "'searchForm'"); ?> <?php endif; else: ?> <?php $this->assign('showBlock', "'searchForm'"); ?> <?php $this->assign('hideBlock', "'searchForm_show'"); endif; ?> <div id="searchForm_show" class="form-item"> <a href="#" onclick="hide('searchForm_show'); show('searchForm'); return false;"><img src="<?php echo $this->_tpl_vars['config']->resourceBase; ?> i/TreePlus.gif" class="action-icon" alt="<?php $this->_tag_stack[] = array('ts', array()); $_block_repeat=true;smarty_block_ts($this->_tag_stack[count($this->_tag_stack)-1][1], null, $this, $_block_repeat);while ($_block_repeat) { ob_start(); ?>open section<?php $_block_content = ob_get_contents(); ob_end_clean(); $_block_repeat=false;echo smarty_block_ts($this->_tag_stack[count($this->_tag_stack)-1][1], $_block_content, $this, $_block_repeat); } array_pop($this->_tag_stack); ?>" /></a> <label> <?php if ($this->_tpl_vars['context'] == 'smog'): $this->_tag_stack[] = array('ts', array()); $_block_repeat=true;smarty_block_ts($this->_tag_stack[count($this->_tag_stack)-1][1], null, $this, $_block_repeat);while ($_block_repeat) { ob_start(); ?>Find Members within this Group<?php $_block_content = ob_get_contents(); ob_end_clean(); $_block_repeat=false;echo smarty_block_ts($this->_tag_stack[count($this->_tag_stack)-1][1], $_block_content, $this, $_block_repeat); } array_pop($this->_tag_stack); ?> <?php elseif ($this->_tpl_vars['context'] == 'amtg'): $this->_tag_stack[] = array('ts', array()); $_block_repeat=true;smarty_block_ts($this->_tag_stack[count($this->_tag_stack)-1][1], null, $this, $_block_repeat);while ($_block_repeat) { ob_start(); ?>Find Contacts to Add to this Group<?php $_block_content = ob_get_contents(); ob_end_clean(); $_block_repeat=false;echo smarty_block_ts($this->_tag_stack[count($this->_tag_stack)-1][1], $_block_content, $this, $_block_repeat); } array_pop($this->_tag_stack); ?> <?php else: $this->_tag_stack[] = array('ts', array()); $_block_repeat=true;smarty_block_ts($this->_tag_stack[count($this->_tag_stack)-1][1], null, $this, $_block_repeat);while ($_block_repeat) { ob_start(); ?>Search Criteria<?php $_block_content = ob_get_contents(); ob_end_clean(); $_block_repeat=false;echo smarty_block_ts($this->_tag_stack[count($this->_tag_stack)-1][1], $_block_content, $this, $_block_repeat); } array_pop($this->_tag_stack); endif; ?> </label> </div> <div id="searchForm"> <?php $_smarty_tpl_vars = $this->_tpl_vars; $this->_smarty_include(array('smarty_include_tpl_file' => "CRM/Contact/Form/Search/BasicCriteria.tpl", 'smarty_include_vars' => array())); $this->_tpl_vars = $_smarty_tpl_vars; unset($_smarty_tpl_vars); ?> </div> <?php if ($this->_tpl_vars['rowsEmpty']): ?> <?php $_smarty_tpl_vars = $this->_tpl_vars; $this->_smarty_include(array('smarty_include_tpl_file' => "CRM/Contact/Form/Search/EmptyResults.tpl", 'smarty_include_vars' => array())); $this->_tpl_vars = $_smarty_tpl_vars; unset($_smarty_tpl_vars); endif; ?> <?php if ($this->_tpl_vars['rows']): ?> <fieldset> <?php $_smarty_tpl_vars = $this->_tpl_vars; $this->_smarty_include(array('smarty_include_tpl_file' => "CRM/Contact/Form/Search/ResultTasks.tpl", 'smarty_include_vars' => array())); $this->_tpl_vars = $_smarty_tpl_vars; unset($_smarty_tpl_vars); ?> <p></p> <?php $_smarty_tpl_vars = $this->_tpl_vars; $this->_smarty_include(array('smarty_include_tpl_file' => "CRM/Contact/Form/Selector.tpl", 'smarty_include_vars' => array())); $this->_tpl_vars = $_smarty_tpl_vars; unset($_smarty_tpl_vars); ?> </fieldset> <?php endif; ?> <script type="text/javascript"> var showBlock = new Array(<?php echo $this->_tpl_vars['showBlock']; ?> ); var hideBlock = new Array(<?php echo $this->_tpl_vars['hideBlock']; ?> ); on_load_init_blocks( showBlock, hideBlock ); </script>
zakiya/Peoples-History
files/civicrm/templates_c/en_US/%%70^70A^70AFFDD6%%Search.tpl.php
PHP
gpl-2.0
4,792
/** * 项目名: java-code-tutorials-tools * 包名: net.fantesy84.common.util * 文件名: IPUtils.java * Copy Right © 2015 Andronicus Ge * 时间: 2015年11月9日 */ package net.fantesy84.common.util; import java.net.InetAddress; import java.net.UnknownHostException; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Andronicus * @since 2015年11月9日 */ public abstract class IPUtils { private static final Logger logger = LoggerFactory.getLogger(IPUtils.class); private static String LOCALHOST_NAME; static { try { LOCALHOST_NAME = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { logger.error(e.getMessage(), new IllegalStateException(e)); } } /** * 获取本地网络适配器IP地址 * <P>有多个网卡时会有多个IP,一一对应 * @return 网卡地址列表 */ public static String getLocalIPv4Address(){ String ip = null; try { InetAddress[] addresses = InetAddress.getAllByName(LOCALHOST_NAME); if (!ArrayUtils.isEmpty(addresses)) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < addresses.length; i++) { if (addresses[i].getHostAddress().matches(RegularExpressions.IP_V4_REGEX)){ builder.append(",").append(addresses[i].getHostAddress()); } } ip = builder.toString().replaceFirst(",", ""); } } catch (UnknownHostException e) { logger.error(e.getMessage(), new IllegalStateException(e)); } return ip; } /** * 获取远程访问者IP地址 * <P> 关于代理请求,通过代理过滤进行查询.有多层代理时,第一个IP地址即为真实地址. * @param request 网络请求 * @return 远程访问者IP地址 */ public static String getRemoteIP(HttpServletRequest request, String regex){ String ip = null; ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) { ip = getLocalIPv4Address(); } if (ip != null && ip.length() > 15) { if (!StringUtils.isBlank(regex)) { StringBuilder builder = new StringBuilder(); String[] addrs = ip.split(","); for (String addr : addrs) { if (addr.matches(regex)) { builder.append(",").append(addr); } } ip = builder.toString().replaceFirst(",", ""); } if (ip.indexOf(",") > 0) { ip = ip.substring(0, ip.indexOf(",")); } } if (ip == null) { logger.error("未获取到任何IP地址!请检查网络配置!", new IllegalStateException()); } return ip; } }
fantesy84/java-code-tutorials
java-code-tutorials-tools/src/main/java/net/fantesy84/common/util/IPUtils.java
Java
gpl-2.0
2,924
<?php /** * @package jCart * @copyright Copyright (C) 2009 - 2012 softPHP,http://www.soft-php.com * @license GNU/GPL http://www.gnu.org/copyleft/gpl.html */ // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ); $_['text_sub_total'] = 'Sub-Total'; ?>
jiangfanglu/grart
components/com_opencart/catalog/language/english/total/sub_total.php
PHP
gpl-2.0
272
/** Copyright 2011 Red Hat, Inc. This software is licensed to you under the GNU General Public License as published by the Free Software Foundation; either version 2 of the License (GPLv2) or (at your option) any later version. There is NO WARRANTY for this software, express or implied, including the implied warranties of MERCHANTABILITY, NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 along with this software; if not, see http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. */ KT.panel.list.registerPage('gpg_keys', { create : 'new_gpg_key', extra_create_data : function(){ return { 'gpg_key[name]' : $('#gpg_key_name').val() }; } }); $(document).ready(function(){ $('#upload_gpg_key').live('click', function(event){ KT.gpg_key.upload(); }); $('#upload_new_gpg_key').live('submit', function(e){ e.preventDefault(); KT.gpg_key.upload(); }); $('#update_upload_gpg_key').live('click', function(event){ KT.gpg_key.upload_update(); }); $('#gpg_key_content').live('input keyup paste', function(){ if( $(this).val() !== '' ){ $('#gpg_key_content_upload').attr('disabled', 'disabled'); $('#upload_gpg_key').attr('disabled', 'disabled'); $('#clear_gpg_key').removeAttr('disabled'); } else { $('#gpg_key_content_upload').removeAttr('disabled'); $('#upload_gpg_key').removeAttr('disabled'); $('#clear_gpg_key').attr('disabled', 'disabled'); } }); $('#gpg_key_content_upload').live('change', function(){ if( $(this).val() !== '' ){ $('#gpg_key_content').attr('disabled', 'disabled'); $('#save_gpg_key').attr('disabled', 'disabled'); $('#clear_upload_gpg_key').removeAttr('disabled'); } else { $('#gpg_key_content').removeAttr('disabled'); $('#save_gpg_key').removeAttr('disabled'); $('#clear_upload_gpg_key').attr('disabled', 'disabled'); } }); $('#clear_upload_gpg_key').live('click', function(){ $('#gpg_key_content_upload').val(''); $('#gpg_key_content').removeAttr('disabled'); $('#save_gpg_key').removeAttr('disabled'); $('#clear_upload_gpg_key').attr('disabled', 'disabled'); $('#clear_gpg_key').attr('disabled', 'disabled'); }); $('#clear_gpg_key').live('click', function(){ $('#gpg_key_content').val(''); $('#gpg_key_content_upload').removeAttr('disabled'); $('#upload_gpg_key').removeAttr('disabled'); $('#clear_upload_gpg_key').attr('disabled', 'disabled'); $('#clear_gpg_key').attr('disabled', 'disabled'); }); $('#gpg_key_content_upload_update').live('change', function(){ if( $(this).val() !== '' ){ $('#update_upload_gpg_key').removeAttr('disabled'); $('#clear_upload_gpg_key').removeAttr('disabled'); } else { $('#update_upload_gpg_key').attr('disabled', 'disabled'); $('#clear_upload_gpg_key').attr('disabled', 'disabled'); } }); $('#clear_upload_gpg_key').live('click', function(){ $('#update_upload_gpg_key').attr('disabled', 'disabled'); $('#clear_upload_gpg_key').attr('disabled', 'disabled'); $('#gpg_key_content_upload_update').val(''); }); }); KT.gpg_key = (function($){ var self = this, get_buttons = function(){ return { 'gpg_key_save' : $('#save_gpg_key'), 'gpg_key_upload': $('#upload_gpg_key') } }, enable_buttons = function(){ var buttons = get_buttons(); buttons.gpg_key_save.removeAttr('disabled'); buttons.gpg_key_upload.removeAttr('disabled'); }, disable_buttons = function(){ var buttons = get_buttons(); buttons.gpg_key_save.attr('disabled', 'disabled'); buttons.gpg_key_upload.attr('disabled', 'disabled'); }; self.upload = function(){ var submit_data = { 'gpg_key[name]' : $('#gpg_key_name').val() }; disable_buttons(); $('#upload_new_gpg_key').ajaxSubmit({ url : KT.routes['gpg_keys_path'](), type : 'POST', data : submit_data, iframe : true, success : function(data, status, xhr){ var parsed_data = $(data); if( parsed_data.get(0).tagName === 'PRE' ){ notices.displayNotice('error', parsed_data.html()); } else { KT.panel.list.createSuccess(data); } enable_buttons(); }, error : function(){ enable_buttons(); notices.checkNotices(); } }); }; self.upload_update = function(){ $('#update_upload_gpg_key').attr('disabled', 'disabled'); $('#clear_upload_gpg_key').attr('disabled', 'disabled'); $('#upload_gpg_key').ajaxSubmit({ url : $(this).data('url'), type : 'POST', iframe : true, success : function(data, status, xhr){ if( !data.match(/notices/) ){ $('#gpg_key_content').html(data); $('#upload_gpg_key').val(''); } notices.checkNotices(); $('#update_upload_gpg_key').removeAttr('disabled'); $('#clear_upload_gpg_key').removeAttr('disabled'); }, error : function(){ $('#update_upload_gpg_key').removeAttr('disabled'); $('#clear_upload_gpg_key').removeAttr('disabled'); notices.checkNotices(); } }); }; return self; })(jQuery);
iNecas/katello
src/public/javascripts/gpg_key.js
JavaScript
gpl-2.0
5,150
/* UnknownTypeException.java -- Thrown by an unknown type. Copyright (C) 2012 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 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 GNU General Public License cover the whole combination. As a special 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 this 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 javax.lang.model.type; /** * Thrown when an unknown type is encountered, * usually by a {@link TypeVisitor}. * * @author Andrew John Hughes (gnu_andrew@member.fsf.org) * @since 1.6 * @see TypeVisitor#visitUnknown(TypeMirror,P) */ public class UnknownTypeException extends RuntimeException { private static final long serialVersionUID = 269L; /** * The unknown type. */ private TypeMirror type; /** * The additional parameter. */ private Object param; /** * Constructs a new {@code UnknownTypeException} * for the specified type. An additional * object may also be passed to give further context as * to where the exception occurred, such as the additional parameter * used by visitor classes. * * @param type the unknown type or {@code null}. * @param param the additional parameter or {@code null}. */ public UnknownTypeException(TypeMirror type, Object param) { this.type = type; this.param = param; } /** * Returns the additional parameter or {@code null} if * unavailable. * * @return the additional parameter. */ public Object getArgument() { return param; } /** * Returns the unknown type or {@code null} * if unavailable. The type may be {@code null} if * the value is not {@link java.io.Serializable} but the * exception has been serialized and read back in. * * @return the unknown type. */ public TypeMirror getUnknownType() { return type; } }
penberg/classpath
javax/lang/model/type/UnknownTypeException.java
Java
gpl-2.0
3,277
/*---------------------------------------------------------------------------*\ ## #### ###### | ## ## ## | Copyright: ICE Stroemungsfoschungs GmbH ## ## #### | ## ## ## | http://www.ice-sf.at ## #### ###### | ------------------------------------------------------------------------------- ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 1991-2008 OpenCFD Ltd. \\/ M anipulation | ------------------------------------------------------------------------------- License This file is based on OpenFOAM. OpenFOAM is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Class Foam::fvcSpreadFunctionPlugin Description SourceFiles fvcSpreadPluginfunction.C Contributors/Copyright: 2015-2017 Bernhard F.W. Gschaider <bgschaid@hfd-research.com> SWAK Revision: $Id$ \*---------------------------------------------------------------------------*/ #ifndef fvcSpreadPluginfunction_H #define fvcSpreadPluginfunction_H #include "FieldValuePluginFunction.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { /*---------------------------------------------------------------------------*\ Class fvcSpreadPluginFunction Declaration \*---------------------------------------------------------------------------*/ class fvcSpreadPluginFunction : public FieldValuePluginFunction { //- Disallow default bitwise assignment void operator=(const fvcSpreadPluginFunction &); fvcSpreadPluginFunction(const fvcSpreadPluginFunction &); //- number of layers label nLayers_; //- difference of alpha scalar alphaDiff_; //- maximum of alpha scalar alphaMax_; //- minimum of alpha scalar alphaMin_; //- the field to be spreaded autoPtr<volScalarField> field_; //- the field to be spreaded with autoPtr<volScalarField> alpha_; public: fvcSpreadPluginFunction( const FieldValueExpressionDriver &parentDriver, const word &name ); virtual ~fvcSpreadPluginFunction() {} TypeName("fvcSpreadPluginFunction"); void doEvaluation(); void setArgument( label index, const string &content, const CommonValueExpressionDriver &driver ); void setArgument(label index,const scalar &); void setArgument(label index,const label &); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
Unofficial-Extend-Project-Mirror/openfoam-extend-Breeder2.0-libraries-swak4Foam
Libraries/functionPlugins/swakFvcSchemesFunctionPlugin/fvcSpreadPluginFunction.H
C++
gpl-2.0
3,532
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Shoot__n_Loot.Scenes; namespace Shoot__n_Loot { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { public static Point ScreenSize { get { return new Point(1200, 750); } } public static Random random; public static bool exit; GraphicsDeviceManager graphics; SpriteBatch spriteBatch; public Game1() { Window.Title = "Escape from Zombie Island"; graphics = new GraphicsDeviceManager(this); graphics.PreferredBackBufferWidth = ScreenSize.X; graphics.PreferredBackBufferHeight = ScreenSize.Y; Content.RootDirectory = "Content"; IsMouseVisible = true; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { Input.Initialize(); Camera.FollowSpeed = .3f; Camera.Scale = 1; Camera.Origin = new Vector2(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height) / (2 * Camera.Scale); random = new Random(); Music music = new Music(Content.Load<Song>("track1")); music.Initialize(); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); TextureManager.Load(Content); SoundManager.Load(Content); SceneManager.LoadAll(); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { if (exit) Exit(); Input.Update(); SceneManager.CurrentScene.Update(); base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(new Color(0, 3, 73)); spriteBatch.Begin(SpriteSortMode.BackToFront, null, null, null, null, null, Camera.Transform); SceneManager.CurrentScene.Draw(spriteBatch); spriteBatch.End(); base.Draw(gameTime); } } }
ShootnLootProgramerare/Shoot_n_Loot
Shoot 'n Loot/Shoot 'n Loot/Shoot 'n Loot/Game1.cs
C#
gpl-2.0
3,815
package com.citypark.api.task; import com.citypark.api.parser.CityParkStartPaymentParser; import android.content.Context; import android.os.AsyncTask; import android.text.format.Time; public class StopPaymentTask extends AsyncTask<Void, Void, Boolean> { private Context context; private String sessionId; private String paymentProviderName; private double latitude; private double longitude; private String operationStatus; public StopPaymentTask(Context context, String sessionId, String paymentProviderName, double latitude, double longitude, String operationStatus) { super(); this.context = context; this.sessionId = sessionId; this.paymentProviderName = paymentProviderName; this.latitude = latitude; this.longitude = longitude; this.operationStatus = operationStatus; } @Override protected Boolean doInBackground(Void... params) { //update citypark through API on success or failure CityParkStartPaymentParser parser = new CityParkStartPaymentParser(context, sessionId, paymentProviderName, latitude, longitude, operationStatus); parser.parse(); return true; } }
kruzel/citypark-android
src/com/citypark/api/task/StopPaymentTask.java
Java
gpl-2.0
1,144
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "graphics/fontman.h" #include "backends/platform/tizen/form.h" #include "backends/platform/tizen/system.h" #include "backends/platform/tizen/graphics.h" // // TizenGraphicsManager // TizenGraphicsManager::TizenGraphicsManager(TizenAppForm *appForm) : _appForm(appForm), _eglDisplay(EGL_DEFAULT_DISPLAY), _eglSurface(EGL_NO_SURFACE), _eglConfig(NULL), _eglContext(EGL_NO_CONTEXT), _initState(true) { assert(appForm != NULL); _videoMode.fullscreen = true; } TizenGraphicsManager::~TizenGraphicsManager() { logEntered(); if (_eglDisplay != EGL_NO_DISPLAY) { eglMakeCurrent(_eglDisplay, NULL, NULL, NULL); if (_eglContext != EGL_NO_CONTEXT) { eglDestroyContext(_eglDisplay, _eglContext); } } } const Graphics::Font *TizenGraphicsManager::getFontOSD() { return FontMan.getFontByUsage(Graphics::FontManager::kBigGUIFont); } bool TizenGraphicsManager::moveMouse(int16 &x, int16 &y) { int16 currentX = _cursorState.x; int16 currentY = _cursorState.y; // save the current hardware coordinates _cursorState.x = x; _cursorState.y = y; // return x/y as game coordinates adjustMousePosition(x, y); // convert current x/y to game coordinates adjustMousePosition(currentX, currentY); // return whether game coordinates have changed return (currentX != x || currentY != y); } Common::List<Graphics::PixelFormat> TizenGraphicsManager::getSupportedFormats() const { logEntered(); Common::List<Graphics::PixelFormat> res; res.push_back(Graphics::PixelFormat(2, 4, 4, 4, 4, 12, 8, 4, 0)); res.push_back(Graphics::PixelFormat(2, 5, 6, 5, 0, 11, 5, 0, 0)); res.push_back(Graphics::PixelFormat(2, 5, 5, 5, 1, 11, 6, 1, 0)); res.push_back(Graphics::PixelFormat::createFormatCLUT8()); return res; } bool TizenGraphicsManager::hasFeature(OSystem::Feature f) { bool result = (f == OSystem::kFeatureFullscreenMode || f == OSystem::kFeatureVirtualKeyboard || OpenGLGraphicsManager::hasFeature(f)); return result; } void TizenGraphicsManager::setFeatureState(OSystem::Feature f, bool enable) { if (f == OSystem::kFeatureVirtualKeyboard && enable) { _appForm->showKeypad(); } else { OpenGLGraphicsManager::setFeatureState(f, enable); } } void TizenGraphicsManager::setReady() { _initState = false; } void TizenGraphicsManager::updateScreen() { if (_transactionMode == kTransactionNone) { internUpdateScreen(); } } bool TizenGraphicsManager::loadEgl() { logEntered(); EGLint numConfigs = 1; EGLint eglConfigList[] = { EGL_RED_SIZE, 5, EGL_GREEN_SIZE, 6, EGL_BLUE_SIZE, 5, EGL_ALPHA_SIZE, 0, EGL_DEPTH_SIZE, 8, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES_BIT, EGL_NONE }; EGLint eglContextList[] = { EGL_CONTEXT_CLIENT_VERSION, 1, EGL_NONE }; eglBindAPI(EGL_OPENGL_ES_API); if (_eglDisplay) { unloadGFXMode(); } _eglDisplay = eglGetDisplay((EGLNativeDisplayType) EGL_DEFAULT_DISPLAY); if (EGL_NO_DISPLAY == _eglDisplay) { systemError("eglGetDisplay() failed"); return false; } if (EGL_FALSE == eglInitialize(_eglDisplay, NULL, NULL) || EGL_SUCCESS != eglGetError()) { systemError("eglInitialize() failed"); return false; } if (EGL_FALSE == eglChooseConfig(_eglDisplay, eglConfigList, &_eglConfig, 1, &numConfigs) || EGL_SUCCESS != eglGetError()) { systemError("eglChooseConfig() failed"); return false; } if (!numConfigs) { systemError("eglChooseConfig() failed. Matching config does not exist \n"); return false; } _eglSurface = eglCreateWindowSurface(_eglDisplay, _eglConfig, (EGLNativeWindowType)_appForm, NULL); if (EGL_NO_SURFACE == _eglSurface || EGL_SUCCESS != eglGetError()) { systemError("eglCreateWindowSurface() failed. EGL_NO_SURFACE"); return false; } _eglContext = eglCreateContext(_eglDisplay, _eglConfig, EGL_NO_CONTEXT, eglContextList); if (EGL_NO_CONTEXT == _eglContext || EGL_SUCCESS != eglGetError()) { systemError("eglCreateContext() failed"); return false; } if (false == eglMakeCurrent(_eglDisplay, _eglSurface, _eglSurface, _eglContext) || EGL_SUCCESS != eglGetError()) { systemError("eglMakeCurrent() failed"); return false; } logLeaving(); return true; } bool TizenGraphicsManager::loadGFXMode() { logEntered(); if (!loadEgl()) { unloadGFXMode(); return false; } int x, y, width, height; _appForm->GetBounds(x, y, width, height); _videoMode.overlayWidth = _videoMode.hardwareWidth = width; _videoMode.overlayHeight = _videoMode.hardwareHeight = height; _videoMode.scaleFactor = 4; // for proportional sized cursor in the launcher AppLog("screen size: %dx%d", _videoMode.hardwareWidth, _videoMode.hardwareHeight); return OpenGLGraphicsManager::loadGFXMode(); } void TizenGraphicsManager::loadTextures() { logEntered(); OpenGLGraphicsManager::loadTextures(); } void TizenGraphicsManager::internUpdateScreen() { if (!_initState) { OpenGLGraphicsManager::internUpdateScreen(); eglSwapBuffers(_eglDisplay, _eglSurface); } } void TizenGraphicsManager::unloadGFXMode() { logEntered(); if (_eglDisplay != EGL_NO_DISPLAY) { eglMakeCurrent(_eglDisplay, NULL, NULL, NULL); if (_eglContext != EGL_NO_CONTEXT) { eglDestroyContext(_eglDisplay, _eglContext); _eglContext = EGL_NO_CONTEXT; } if (_eglSurface != EGL_NO_SURFACE) { eglDestroySurface(_eglDisplay, _eglSurface); _eglSurface = EGL_NO_SURFACE; } eglTerminate(_eglDisplay); _eglDisplay = EGL_NO_DISPLAY; } _eglConfig = NULL; OpenGLGraphicsManager::unloadGFXMode(); logLeaving(); }
nemomobile-apps/scummvm
backends/platform/tizen/graphics.cpp
C++
gpl-2.0
6,444
# -*- coding: utf-8 -*- """ *************************************************************************** SplitRGBBands.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot 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. * * * *************************************************************************** """ from processing.tools.system import * from processing.tools import dataobjects from processing.saga.SagaUtils import SagaUtils __author__ = 'Victor Olaya' __date__ = 'August 2012' __copyright__ = '(C) 2012, Victor Olaya' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' from PyQt4 import QtGui from processing.core.GeoAlgorithm import GeoAlgorithm from processing.parameters.ParameterRaster import ParameterRaster from processing.outputs.OutputRaster import OutputRaster import os class SplitRGBBands(GeoAlgorithm): INPUT = "INPUT" R = "R" G = "G" B = "B" def getIcon(self): return QtGui.QIcon(os.path.dirname(__file__) + "/../images/saga.png") def defineCharacteristics(self): self.name = "Split RGB bands" self.group = "Grid - Tools" self.addParameter(ParameterRaster(SplitRGBBands.INPUT, "Input layer", False)) self.addOutput(OutputRaster(SplitRGBBands.R, "Output R band layer")) self.addOutput(OutputRaster(SplitRGBBands.G, "Output G band layer")) self.addOutput(OutputRaster(SplitRGBBands.B, "Output B band layer")) def processAlgorithm(self, progress): #TODO:check correct num of bands input = self.getParameterValue(SplitRGBBands.INPUT) temp = getTempFilename(None).replace('.',''); basename = os.path.basename(temp) validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" safeBasename = ''.join(c for c in basename if c in validChars) temp = os.path.join(os.path.dirname(temp), safeBasename) r = self.getOutputValue(SplitRGBBands.R) g = self.getOutputValue(SplitRGBBands.G) b = self.getOutputValue(SplitRGBBands.B) commands = [] if isWindows(): commands.append("io_gdal 0 -GRIDS \"" + temp + "\" -FILES \"" + input+"\"") commands.append("io_gdal 1 -GRIDS \"" + temp + "_0001.sgrd\" -FORMAT 1 -TYPE 0 -FILE \"" + r + "\""); commands.append("io_gdal 1 -GRIDS \"" + temp + "_0002.sgrd\" -FORMAT 1 -TYPE 0 -FILE \"" + g + "\""); commands.append("io_gdal 1 -GRIDS \"" + temp + "_0003.sgrd\" -FORMAT 1 -TYPE 0 -FILE \"" + b + "\""); else: commands.append("libio_gdal 0 -GRIDS \"" + temp + "\" -FILES \"" + input + "\"") commands.append("libio_gdal 1 -GRIDS \"" + temp + "_0001.sgrd\" -FORMAT 1 -TYPE 0 -FILE \"" + r + "\""); commands.append("libio_gdal 1 -GRIDS \"" + temp + "_0002.sgrd\" -FORMAT 1 -TYPE 0 -FILE \"" + g + "\""); commands.append("libio_gdal 1 -GRIDS \"" + temp + "_0003.sgrd\" -FORMAT 1 -TYPE 0 -FILE \"" + b + "\""); SagaUtils.createSagaBatchJobFileFromSagaCommands(commands) SagaUtils.executeSaga(progress);
camptocamp/QGIS
python/plugins/processing/saga/SplitRGBBands.py
Python
gpl-2.0
3,715
/*************************************************************************** FluxIntegral.cpp - Integrates Lx dx L (x1, x2) = int^x2_x1 dx Lx ------------------- begin : December 2006 copyright : (C) 2006 by Maurice Leutenegger email : maurice@astro.columbia.edu ***************************************************************************/ /* 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 "FluxIntegral.h" #include <iostream> using namespace std; FluxIntegral::FluxIntegral (Lx* lx) : Integral (), itsLx (lx), itsXKink (itsLx->getXKink ()), itsXOcc (itsLx->getXOcc ()) { return; } FluxIntegral::~FluxIntegral () { return; } double FluxIntegral::integrand (double x) { return itsLx->getLx (x); } /* Integrates Lx over [y,x]. Will mostly be called with y < x, but if not, it swaps them. Note: is there code somewhere else to deal with an unresolved profile? (The code below only deals with the case where it's known to be completely unresolved in advance.) */ Real FluxIntegral::getFlux (Real x, Real y) { if (compare (y, x) == 1) { Real temp = x; x = y; y = temp; } bool xInRange = (compare (fabs(x), 1.) == -1); bool yInRange = (compare (fabs(y), 1.) == -1); if (!xInRange && !yInRange) return 0.; if (!xInRange) x = 1.; if (!yInRange) y = -1.; if ((compare (itsXKink, y) == 1) && (compare (itsXKink, x) == -1)) { return (qag (y, itsXKink) + qag (itsXKink, x)); } if ((compare (itsXOcc, y) == 1) && (compare (itsXOcc, x) == -1)) { return (qag (y, itsXOcc) + qag (itsXOcc, x)); } return qag (y, x); /* The kink coordinate gives the point at which many profiles have a kink at negative x on the blue side of the profile. This kink occurs at the x where the cutoff u0 starts to become important. (At zero optical depth, the profile becomes flat at this point). The "occ" coordinate gives the point in x where occultation begins to become important. I choose to place this not at p = 1 but at p = 1 + e, to avoid edge effects. */ /* if (xInRange && yInRange) { return qag (y, x); } else if (xInRange && !yInRange) { return qag (-1., x); } else if (!xInRange && yInRange) { return qag (y, 1.); } else { return 0.; } */ } // Integrate on x in [-1:1] Real FluxIntegral::getFlux () { return (qag (-1., itsXKink) + qag (itsXKink, itsXOcc) + qag (itsXOcc, 1.)); }
mauriceleutenegger/windprofile
FluxIntegral.cpp
C++
gpl-2.0
3,166
<?php session_start(); ?> <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <title>Somali Taekwondo - About us</title> <?php include('inc/metatags.inc') ?> </head> <body> <!--[if lt IE 7]> <p class="chromeframe">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a> to improve your experience.</p> <![endif]--> <header> <div class="navbar-wrapper"> <!-- Wrap the .navbar in .container to center it within the absolutely positioned parent. --> <div class="container"> <div class="navbar navbar-inverse"> <div class="navbar-inner"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="/home"><img src="img/logo.png" alt="gotkd" width="150" /></a> <?php include('inc/nav.inc') ?> </div> </div> </div> </div> </header> <section id="container" class="container aboutus"> <br /> <br /> <br /> <div class="page-header"> <h1>About us</h1> </div> <div class="row-fluid media"> <div class="span7"> <p>Having its headquarters in Switzerland, Somali Taekwondo was established in 2012 and is responsible for all aspects of Somali National Team around the world helping athletes achieve their full potential, and preparing them for major competition, as well as selecting athlete to compete at African Championship, World Championships, and of course the Olympic Games.</p> <p>After emerging from decades of civil war and social upheaval, Somali Taekwondo use the sport to promote a better image of Somali and helping the country climb out of poverty.</p> <p>Somali Taekwondo use funds provided from donations of people from all around the world to promote Somali image, giving an assistance to the sport, focusing on improving opportunities for the somalian athletes participate in many tournament, giving a hope for the country.</p> <p>Every donation will be indented for the developing of each somalian athlete giving the oportunity to participate to every tournement recognized by the World Taekwondo Federation and the Somali Olympic Committee. Donations that will be more than needed will be given to an ONG that helps against the somali poverty.</p> </div> <div class="span5 thumbnail"> <img src="https://fbcdn-sphotos-a-a.akamaihd.net/hphotos-ak-ash3/942859_162735743901850_517590466_n.jpg" alt="" /> </div> </div> <?php include('inc/footer.inc') ?> </section> <!-- /container --> <?php include('inc/js.inc') ?> </body> </html>
somalitaekwondo/site
novo/about-us.php
PHP
gpl-2.0
3,667
<?php namespace Drush\Boot; use Consolidation\AnnotatedCommand\AnnotationData; use Drush\Log\DrushLog; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Drupal\Core\DrupalKernel; use Drush\Drush; use Drush\Drupal\DrushServiceModifier; use Drush\Log\LogLevel; class DrupalBoot8 extends DrupalBoot implements AutoloaderAwareInterface { use AutoloaderAwareTrait; /** * @var \Drupal\Core\DrupalKernelInterface */ protected $kernel; /** * @var \Symfony\Component\HttpFoundation\Request */ protected $request; /** * @return \Symfony\Component\HttpFoundation\Request */ public function getRequest() { return $this->request; } /** * @param \Symfony\Component\HttpFoundation\Request $request */ public function setRequest($request) { $this->request = $request; } /** * @return \Drupal\Core\DrupalKernelInterface */ public function getKernel() { return $this->kernel; } public function validRoot($path) { if (!empty($path) && is_dir($path) && file_exists($path . '/autoload.php')) { // Additional check for the presence of core/composer.json to // grant it is not a Drupal 7 site with a base folder named "core". $candidate = 'core/includes/common.inc'; if (file_exists($path . '/' . $candidate) && file_exists($path . '/core/core.services.yml')) { if (file_exists($path . '/core/misc/drupal.js') || file_exists($path . '/core/assets/js/drupal.js')) { return $candidate; } } } } public function getVersion($drupal_root) { // Are the class constants available? if (!$this->hasAutoloader()) { throw new \Exception('Cannot access Drupal 8 class constants - Drupal autoloader not loaded yet.'); } // Drush depends on bootstrap being loaded at this point. require_once $drupal_root .'/core/includes/bootstrap.inc'; if (defined('\Drupal::VERSION')) { return \Drupal::VERSION; } } public function confPath($require_settings = true, $reset = false) { if (\Drupal::hasService('kernel')) { $site_path = \Drupal::service('kernel')->getSitePath(); } if (!isset($site_path) || empty($site_path)) { $site_path = DrupalKernel::findSitePath($this->getRequest(), $require_settings); } return $site_path; } public function addLogger() { // Provide a logger which sends // output to drush_log(). This should catch every message logged through every // channel. $container = \Drupal::getContainer(); $parser = $container->get('logger.log_message_parser'); $drushLogger = Drush::logger(); $logger = new DrushLog($parser, $drushLogger); $container->get('logger.factory')->addLogger($logger); } public function bootstrapDrupalCore($drupal_root) { $core = DRUPAL_ROOT . '/core'; return $core; } public function bootstrapDrupalSiteValidate() { parent::bootstrapDrupalSiteValidate(); // Normalize URI. $uri = rtrim($this->uri, '/') . '/'; $parsed_url = parse_url($uri); // Account for users who omit the http:// prefix. if (empty($parsed_url['scheme'])) { $this->uri = 'http://' . $this->uri; $parsed_url = parse_url($this->uri); } $server = [ 'SCRIPT_FILENAME' => getcwd() . '/index.php', 'SCRIPT_NAME' => isset($parsed_url['path']) ? $parsed_url['path'] . 'index.php' : '/index.php', ]; $request = Request::create($this->uri, 'GET', [], [], [], $server); $this->setRequest($request); $confPath = drush_bootstrap_value('confPath', $this->confPath(true, true)); drush_bootstrap_value('site', $request->getHttpHost()); return true; } public function bootstrapDrupalConfigurationValidate() { $conf_file = $this->confPath() . '/settings.php'; if (!file_exists($conf_file)) { $msg = dt("Could not find a Drupal settings.php file at !file.", ['!file' => $conf_file]); $this->logger->debug($msg); // Cant do this because site:install deliberately bootstraps to configure without a settings.php file. // return drush_set_error($msg); } return true; } public function bootstrapDrupalDatabaseValidate() { return parent::bootstrapDrupalDatabaseValidate() && $this->bootstrapDrupalDatabaseHasTable('key_value'); } public function bootstrapDrupalDatabase() { // D8 omits this bootstrap level as nothing special needs to be done. parent::bootstrapDrupalDatabase(); } public function bootstrapDrupalConfiguration(AnnotationData $annotationData = null) { // Default to the standard kernel. $kernel = Kernels::DRUPAL; if (!empty($annotationData)) { $kernel = $annotationData->get('kernel', Kernels::DRUPAL); } $classloader = $this->autoloader(); $request = $this->getRequest(); $kernel_factory = Kernels::getKernelFactory($kernel); $allow_dumping = $kernel !== Kernels::UPDATE; /** @var \Drupal\Core\DrupalKernelInterface kernel */ $this->kernel = $kernel_factory($request, $classloader, 'prod', $allow_dumping); // Include Drush services in the container. // @see Drush\Drupal\DrupalKernel::addServiceModifier() $this->kernel->addServiceModifier(new DrushServiceModifier()); // Unset drupal error handler and restore Drush's one. restore_error_handler(); // Disable automated cron if the module is enabled. $GLOBALS['config']['automated_cron.settings']['interval'] = 0; parent::bootstrapDrupalConfiguration(); } public function bootstrapDrupalFull() { $this->logger->debug(dt('Start bootstrap of the Drupal Kernel.')); $this->kernel->boot(); $this->kernel->prepareLegacyRequest($this->getRequest()); $this->logger->debug(dt('Finished bootstrap of the Drupal Kernel.')); parent::bootstrapDrupalFull(); $this->addLogger(); // Get a list of the modules to ignore $ignored_modules = drush_get_option_list('ignored-modules', []); $application = Drush::getApplication(); $runner = Drush::runner(); // We have to get the service command list from the container, because // it is constructed in an indirect way during the container initialization. // The upshot is that the list of console commands is not available // until after $kernel->boot() is called. $container = \Drupal::getContainer(); // Set the command info alterers. if ($container->has(DrushServiceModifier::DRUSH_COMMAND_INFO_ALTERER_SERVICES)) { $serviceCommandInfoAltererlist = $container->get(DrushServiceModifier::DRUSH_COMMAND_INFO_ALTERER_SERVICES); $commandFactory = Drush::commandFactory(); foreach ($serviceCommandInfoAltererlist->getCommandList() as $altererHandler) { $commandFactory->addCommandInfoAlterer($altererHandler); $this->logger->debug(dt('Commands are potentially altered in !class.', ['!class' => get_class($altererHandler)])); } } $serviceCommandlist = $container->get(DrushServiceModifier::DRUSH_CONSOLE_SERVICES); if ($container->has(DrushServiceModifier::DRUSH_CONSOLE_SERVICES)) { foreach ($serviceCommandlist->getCommandList() as $command) { if (!$this->commandIgnored($command, $ignored_modules)) { $this->inflect($command); $this->logger->log(LogLevel::DEBUG_NOTIFY, dt('Add a command: !name', ['!name' => $command->getName()])); $application->add($command); } } } // Do the same thing with the annotation commands. if ($container->has(DrushServiceModifier::DRUSH_COMMAND_SERVICES)) { $serviceCommandlist = $container->get(DrushServiceModifier::DRUSH_COMMAND_SERVICES); foreach ($serviceCommandlist->getCommandList() as $commandHandler) { if (!$this->commandIgnored($commandHandler, $ignored_modules)) { $this->inflect($commandHandler); $this->logger->log(LogLevel::DEBUG_NOTIFY, dt('Add a commandfile class: !name', ['!name' => get_class($commandHandler)])); $runner->registerCommandClass($application, $commandHandler); } } } } public function commandIgnored($command, $ignored_modules) { if (empty($ignored_modules)) { return false; } $ignored_regex = '#\\\\(' . implode('|', $ignored_modules) . ')\\\\#'; $class = new \ReflectionClass($command); $commandNamespace = $class->getNamespaceName(); return preg_match($ignored_regex, $commandNamespace); } /** * {@inheritdoc} */ public function terminate() { parent::terminate(); if ($this->kernel) { $response = Response::create(''); $this->kernel->terminate($this->getRequest(), $response); } } }
eigentor/tommiblog
vendor/drush/drush/src/Boot/DrupalBoot8.php
PHP
gpl-2.0
9,577
// _________ __ __ // / _____// |_____________ _/ |______ ____ __ __ ______ // \_____ \\ __\_ __ \__ \\ __\__ \ / ___\| | \/ ___/ // / \| | | | \// __ \| | / __ \_/ /_/ > | /\___ | // /_______ /|__| |__| (____ /__| (____ /\___ /|____//____ > // \/ \/ \//_____/ \/ // ______________________ ______________________ // T H E W A R B E G I N S // Stratagus - A free fantasy real time strategy game engine // /**@name mainscr.cpp - The main screen. */ // // (c) Copyright 1998-2007 by Lutz Sammer, Valery Shchedrin, and // Jimmy Salmon // // 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; only version 2 of the License. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU 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. // //@{ /*---------------------------------------------------------------------------- -- Includes ----------------------------------------------------------------------------*/ #include "stratagus.h" #include "action/action_built.h" #include "action/action_research.h" #include "action/action_train.h" #include "action/action_upgradeto.h" #include "font.h" #include "icons.h" #include "interface.h" #include "map.h" #include "menus.h" #include "network.h" #include "player.h" #include "settings.h" #include "sound.h" #include "spells.h" #include "translate.h" #include "trigger.h" #include "ui/contenttype.h" #include "ui.h" #include "unit.h" #include "unitsound.h" #include "unittype.h" #include "upgrade.h" #include "video.h" #ifdef DEBUG #include "../ai/ai_local.h" #endif #include <sstream> /*---------------------------------------------------------------------------- -- UI BUTTONS ----------------------------------------------------------------------------*/ static void DrawMenuButtonArea_noNetwork() { if (UI.MenuButton.X != -1) { DrawUIButton(UI.MenuButton.Style, (ButtonAreaUnderCursor == ButtonAreaMenu && ButtonUnderCursor == ButtonUnderMenu ? MI_FLAGS_ACTIVE : 0) | (GameMenuButtonClicked ? MI_FLAGS_CLICKED : 0), UI.MenuButton.X, UI.MenuButton.Y, UI.MenuButton.Text); } } static void DrawMenuButtonArea_Network() { if (UI.NetworkMenuButton.X != -1) { DrawUIButton(UI.NetworkMenuButton.Style, (ButtonAreaUnderCursor == ButtonAreaMenu && ButtonUnderCursor == ButtonUnderNetworkMenu ? MI_FLAGS_ACTIVE : 0) | (GameMenuButtonClicked ? MI_FLAGS_CLICKED : 0), UI.NetworkMenuButton.X, UI.NetworkMenuButton.Y, UI.NetworkMenuButton.Text); } if (UI.NetworkDiplomacyButton.X != -1) { DrawUIButton(UI.NetworkDiplomacyButton.Style, (ButtonAreaUnderCursor == ButtonAreaMenu && ButtonUnderCursor == ButtonUnderNetworkDiplomacy ? MI_FLAGS_ACTIVE : 0) | (GameDiplomacyButtonClicked ? MI_FLAGS_CLICKED : 0), UI.NetworkDiplomacyButton.X, UI.NetworkDiplomacyButton.Y, UI.NetworkDiplomacyButton.Text); } } /** ** Draw menu button area. */ void DrawMenuButtonArea() { if (!IsNetworkGame()) { DrawMenuButtonArea_noNetwork(); } else { DrawMenuButtonArea_Network(); } } void DrawUserDefinedButtons() { for (size_t i = 0; i < UI.UserButtons.size(); ++i) { const CUIUserButton &button = UI.UserButtons[i]; if (button.Button.X != -1) { DrawUIButton(button.Button.Style, (ButtonAreaUnderCursor == ButtonAreaUser && size_t(ButtonUnderCursor) == i ? MI_FLAGS_ACTIVE : 0) | (button.Clicked ? MI_FLAGS_CLICKED : 0), button.Button.X, button.Button.Y, button.Button.Text); } } } /*---------------------------------------------------------------------------- -- Icons ----------------------------------------------------------------------------*/ /** ** Draw life bar of a unit at x,y. ** Placed under icons on top-panel. ** ** @param unit Pointer to unit. ** @param x Screen X position of icon ** @param y Screen Y position of icon */ static void UiDrawLifeBar(const CUnit &unit, int x, int y) { // FIXME: add icon borders int hBar, hAll; if (Preference.IconsShift) { hBar = 6; hAll = 10; } else { hBar = 5; hAll = 7; } y += unit.Type->Icon.Icon->G->Height; Video.FillRectangleClip(ColorBlack, x - 4, y + 2, unit.Type->Icon.Icon->G->Width + 8, hAll); if (unit.Variable[HP_INDEX].Value) { Uint32 color; int f = (100 * unit.Variable[HP_INDEX].Value) / unit.Variable[HP_INDEX].Max; if (f > 75) { color = ColorDarkGreen; } else if (f > 50) { color = ColorYellow; } else if (f > 25) { color = ColorOrange; } else { color = ColorRed; } f = (f * (unit.Type->Icon.Icon->G->Width + 6)) / 100; Video.FillRectangleClip(color, x - 2, y + 4, f > 1 ? f - 2 : 0, hBar); } } /** ** Draw mana bar of a unit at x,y. ** Placed under icons on top-panel. ** ** @param unit Pointer to unit. ** @param x Screen X position of icon ** @param y Screen Y position of icon */ static void UiDrawManaBar(const CUnit &unit, int x, int y) { // FIXME: add icon borders y += unit.Type->Icon.Icon->G->Height; Video.FillRectangleClip(ColorBlack, x, y + 3, unit.Type->Icon.Icon->G->Width, 4); if (unit.Stats->Variables[MANA_INDEX].Max) { int f = (100 * unit.Variable[MANA_INDEX].Value) / unit.Variable[MANA_INDEX].Max; f = (f * (unit.Type->Icon.Icon->G->Width)) / 100; Video.FillRectangleClip(ColorBlue, x + 1, y + 3 + 1, f, 2); } } /** ** Tell if we can show the content. ** verify each sub condition for that. ** ** @param condition condition to verify. ** @param unit unit that certain condition can refer. ** ** @return 0 if we can't show the content, else 1. */ static bool CanShowContent(const ConditionPanel *condition, const CUnit &unit) { if (!condition) { return true; } if ((condition->ShowOnlySelected && !unit.Selected) || (unit.Player->Type == PlayerNeutral && condition->HideNeutral) || (ThisPlayer->IsEnemy(unit) && !condition->ShowOpponent) || (ThisPlayer->IsAllied(unit) && (unit.Player != ThisPlayer) && condition->HideAllied)) { return false; } if (condition->BoolFlags && !unit.Type->CheckUserBoolFlags(condition->BoolFlags)) { return false; } if (condition->Variables) { for (unsigned int i = 0; i < UnitTypeVar.GetNumberVariable(); ++i) { if (condition->Variables[i] != CONDITION_TRUE) { if ((condition->Variables[i] == CONDITION_ONLY) ^ unit.Variable[i].Enable) { return false; } } } } return true; } enum UStrIntType { USTRINT_STR, USTRINT_INT }; struct UStrInt { union {const char *s; int i;}; UStrIntType type; }; /** ** Return the value corresponding. ** ** @param unit Unit. ** @param index Index of the variable. ** @param e Component of the variable. ** @param t Which var use (0:unit, 1:Type, 2:Stats) ** ** @return Value corresponding */ UStrInt GetComponent(const CUnit &unit, int index, EnumVariable e, int t) { UStrInt val; CVariable *var; Assert((unsigned int) index < UnitTypeVar.GetNumberVariable()); switch (t) { case 0: // Unit: var = &unit.Variable[index]; break; case 1: // Type: var = &unit.Type->DefaultStat.Variables[index]; break; case 2: // Stats: var = &unit.Stats->Variables[index]; break; default: DebugPrint("Bad value for GetComponent: t = %d" _C_ t); var = &unit.Variable[index]; break; } switch (e) { case VariableValue: val.type = USTRINT_INT; val.i = var->Value; break; case VariableMax: val.type = USTRINT_INT; val.i = var->Max; break; case VariableIncrease: val.type = USTRINT_INT; val.i = var->Increase; break; case VariableDiff: val.type = USTRINT_INT; val.i = var->Max - var->Value; break; case VariablePercent: Assert(unit.Variable[index].Max != 0); val.type = USTRINT_INT; val.i = 100 * var->Value / var->Max; break; case VariableName: if (index == GIVERESOURCE_INDEX) { val.type = USTRINT_STR; val.i = unit.Type->GivesResource; val.s = DefaultResourceNames[unit.Type->GivesResource].c_str(); } else if (index == CARRYRESOURCE_INDEX) { val.type = USTRINT_STR; val.i = unit.CurrentResource; val.s = DefaultResourceNames[unit.CurrentResource].c_str(); } else { val.type = USTRINT_STR; val.i = index; val.s = UnitTypeVar.VariableNameLookup[index]; } break; } return val; } UStrInt GetComponent(const CUnitType &type, int index, EnumVariable e, int t) { UStrInt val; CVariable *var; Assert((unsigned int) index < UnitTypeVar.GetNumberVariable()); switch (t) { case 0: // Unit: var = &type.Stats[ThisPlayer->Index].Variables[index];; break; case 1: // Type: var = &type.DefaultStat.Variables[index]; break; case 2: // Stats: var = &type.Stats[ThisPlayer->Index].Variables[index]; break; default: DebugPrint("Bad value for GetComponent: t = %d" _C_ t); var = &type.Stats[ThisPlayer->Index].Variables[index]; break; } switch (e) { case VariableValue: val.type = USTRINT_INT; val.i = var->Value; break; case VariableMax: val.type = USTRINT_INT; val.i = var->Max; break; case VariableIncrease: val.type = USTRINT_INT; val.i = var->Increase; break; case VariableDiff: val.type = USTRINT_INT; val.i = var->Max - var->Value; break; case VariablePercent: Assert(type.Stats[ThisPlayer->Index].Variables[index].Max != 0); val.type = USTRINT_INT; val.i = 100 * var->Value / var->Max; break; case VariableName: if (index == GIVERESOURCE_INDEX) { val.type = USTRINT_STR; val.i = type.GivesResource; val.s = DefaultResourceNames[type.GivesResource].c_str(); } else { val.type = USTRINT_STR; val.i = index; val.s = UnitTypeVar.VariableNameLookup[index]; } break; } return val; } static void DrawUnitInfo_Training(const CUnit &unit) { if (unit.Orders.size() == 1 || unit.Orders[1]->Action != UnitActionTrain) { if (!UI.SingleTrainingText.empty()) { CLabel label(*UI.SingleTrainingFont); label.Draw(UI.SingleTrainingTextX, UI.SingleTrainingTextY, UI.SingleTrainingText); } if (UI.SingleTrainingButton) { const COrder_Train &order = *static_cast<COrder_Train *>(unit.CurrentOrder()); CIcon &icon = *order.GetUnitType().Icon.Icon; const unsigned int flags = (ButtonAreaUnderCursor == ButtonAreaTraining && ButtonUnderCursor == 0) ? (IconActive | (MouseButtons & LeftButton)) : 0; const PixelPos pos(UI.SingleTrainingButton->X, UI.SingleTrainingButton->Y); icon.DrawUnitIcon(*UI.SingleTrainingButton->Style, flags, pos, "", unit.RescuedFrom ? GameSettings.Presets[unit.RescuedFrom->Index].PlayerColor : GameSettings.Presets[unit.Player->Index].PlayerColor); } } else { if (!UI.TrainingText.empty()) { CLabel label(*UI.TrainingFont); label.Draw(UI.TrainingTextX, UI.TrainingTextY, UI.TrainingText); } if (!UI.TrainingButtons.empty()) { for (size_t i = 0; i < unit.Orders.size() && i < UI.TrainingButtons.size(); ++i) { if (unit.Orders[i]->Action == UnitActionTrain) { const COrder_Train &order = *static_cast<COrder_Train *>(unit.Orders[i]); CIcon &icon = *order.GetUnitType().Icon.Icon; const int flag = (ButtonAreaUnderCursor == ButtonAreaTraining && static_cast<size_t>(ButtonUnderCursor) == i) ? (IconActive | (MouseButtons & LeftButton)) : 0; const PixelPos pos(UI.TrainingButtons[i].X, UI.TrainingButtons[i].Y); icon.DrawUnitIcon(*UI.TrainingButtons[i].Style, flag, pos, "", unit.RescuedFrom ? GameSettings.Presets[unit.RescuedFrom->Index].PlayerColor : GameSettings.Presets[unit.Player->Index].PlayerColor); } } } } } static void DrawUnitInfo_portrait(const CUnit &unit) { const CUnitType &type = *unit.Type; #ifdef USE_MNG if (type.Portrait.Num) { type.Portrait.Mngs[type.Portrait.CurrMng]->Draw( UI.SingleSelectedButton->X, UI.SingleSelectedButton->Y); if (type.Portrait.Mngs[type.Portrait.CurrMng]->iteration == type.Portrait.NumIterations) { type.Portrait.Mngs[type.Portrait.CurrMng]->Reset(); // FIXME: should be configurable if (type.Portrait.CurrMng == 0) { type.Portrait.CurrMng = (SyncRand() % (type.Portrait.Num - 1)) + 1; type.Portrait.NumIterations = 1; } else { type.Portrait.CurrMng = 0; type.Portrait.NumIterations = SyncRand() % 16 + 1; } } return; } #endif if (UI.SingleSelectedButton) { const PixelPos pos(UI.SingleSelectedButton->X, UI.SingleSelectedButton->Y); const int flag = (ButtonAreaUnderCursor == ButtonAreaSelected && ButtonUnderCursor == 0) ? (IconActive | (MouseButtons & LeftButton)) : 0; type.Icon.Icon->DrawUnitIcon(*UI.SingleSelectedButton->Style, flag, pos, "", unit.RescuedFrom ? GameSettings.Presets[unit.RescuedFrom->Index].PlayerColor : GameSettings.Presets[unit.Player->Index].PlayerColor); } } static bool DrawUnitInfo_single_selection(const CUnit &unit) { switch (unit.CurrentAction()) { case UnitActionTrain: { // Building training units. DrawUnitInfo_Training(unit); return true; } case UnitActionUpgradeTo: { // Building upgrading to better type. if (UI.UpgradingButton) { const COrder_UpgradeTo &order = *static_cast<COrder_UpgradeTo *>(unit.CurrentOrder()); CIcon &icon = *order.GetUnitType().Icon.Icon; unsigned int flag = (ButtonAreaUnderCursor == ButtonAreaUpgrading && ButtonUnderCursor == 0) ? (IconActive | (MouseButtons & LeftButton)) : 0; const PixelPos pos(UI.UpgradingButton->X, UI.UpgradingButton->Y); icon.DrawUnitIcon(*UI.UpgradingButton->Style, flag, pos, "", unit.RescuedFrom ? GameSettings.Presets[unit.RescuedFrom->Index].PlayerColor : GameSettings.Presets[unit.Player->Index].PlayerColor); } return true; } case UnitActionResearch: { // Building research new technology. if (UI.ResearchingButton) { COrder_Research &order = *static_cast<COrder_Research *>(unit.CurrentOrder()); CIcon &icon = *order.GetUpgrade().Icon; int flag = (ButtonAreaUnderCursor == ButtonAreaResearching && ButtonUnderCursor == 0) ? (IconActive | (MouseButtons & LeftButton)) : 0; PixelPos pos(UI.ResearchingButton->X, UI.ResearchingButton->Y); icon.DrawUnitIcon(*UI.ResearchingButton->Style, flag, pos, "", unit.RescuedFrom ? GameSettings.Presets[unit.RescuedFrom->Index].PlayerColor : GameSettings.Presets[unit.Player->Index].PlayerColor); } return true; } default: return false; } } static void DrawUnitInfo_transporter(CUnit &unit) { CUnit *uins = unit.UnitInside; size_t j = 0; for (int i = 0; i < unit.InsideCount; ++i, uins = uins->NextContained) { if (!uins->Boarded || j >= UI.TransportingButtons.size()) { continue; } CIcon &icon = *uins->Type->Icon.Icon; int flag = (ButtonAreaUnderCursor == ButtonAreaTransporting && static_cast<size_t>(ButtonUnderCursor) == j) ? (IconActive | (MouseButtons & LeftButton)) : 0; const PixelPos pos(UI.TransportingButtons[j].X, UI.TransportingButtons[j].Y); icon.DrawUnitIcon(*UI.TransportingButtons[j].Style, flag, pos, "", unit.RescuedFrom ? GameSettings.Presets[unit.RescuedFrom->Index].PlayerColor : GameSettings.Presets[unit.Player->Index].PlayerColor); UiDrawLifeBar(*uins, pos.x, pos.y); if (uins->Type->CanCastSpell && uins->Variable[MANA_INDEX].Max) { UiDrawManaBar(*uins, pos.x, pos.y); } if (ButtonAreaUnderCursor == ButtonAreaTransporting && static_cast<size_t>(ButtonUnderCursor) == j) { UI.StatusLine.Set(uins->Type->Name); } ++j; } } /** ** Draw the unit info into top-panel. ** ** @param unit Pointer to unit. */ static void DrawUnitInfo(CUnit &unit) { UpdateUnitVariables(unit); for (size_t i = 0; i != UI.InfoPanelContents.size(); ++i) { if (CanShowContent(UI.InfoPanelContents[i]->Condition, unit)) { for (std::vector<CContentType *>::const_iterator content = UI.InfoPanelContents[i]->Contents.begin(); content != UI.InfoPanelContents[i]->Contents.end(); ++content) { if (CanShowContent((*content)->Condition, unit)) { (*content)->Draw(unit, UI.InfoPanelContents[i]->DefaultFont); } } } } const CUnitType &type = *unit.Type; Assert(&type); // Draw IconUnit DrawUnitInfo_portrait(unit); if (unit.Player != ThisPlayer && !ThisPlayer->IsAllied(*unit.Player)) { return; } // Show progress if they are selected. if (IsOnlySelected(unit)) { if (DrawUnitInfo_single_selection(unit)) { return; } } // Transporting units. if (type.CanTransport() && unit.BoardCount && CurrentButtonLevel == unit.Type->ButtonLevelForTransporter) { DrawUnitInfo_transporter(unit); return; } } /*---------------------------------------------------------------------------- -- RESOURCES ----------------------------------------------------------------------------*/ /** ** Draw the player resource in top line. ** ** @todo FIXME : make DrawResources more configurable (format, font). */ void DrawResources() { CLabel label(GetGameFont()); // Draw all icons of resource. for (int i = 0; i <= FreeWorkersCount; ++i) { if (UI.Resources[i].G) { UI.Resources[i].G->DrawFrameClip(UI.Resources[i].IconFrame, UI.Resources[i].IconX, UI.Resources[i].IconY); } } for (int i = 0; i < MaxCosts; ++i) { if (UI.Resources[i].TextX != -1) { const int resourceAmount = ThisPlayer->Resources[i]; if (ThisPlayer->MaxResources[i] != -1) { const int resAmount = ThisPlayer->StoredResources[i] + ThisPlayer->Resources[i]; char tmp[256]; snprintf(tmp, sizeof(tmp), "%d (%d)", resAmount, ThisPlayer->MaxResources[i] - ThisPlayer->StoredResources[i]); label.SetFont(GetSmallFont()); label.Draw(UI.Resources[i].TextX, UI.Resources[i].TextY + 3, tmp); } else { label.SetFont(resourceAmount > 99999 ? GetSmallFont() : GetGameFont()); label.Draw(UI.Resources[i].TextX, UI.Resources[i].TextY + (resourceAmount > 99999) * 3, resourceAmount); } } } if (UI.Resources[FoodCost].TextX != -1) { char tmp[256]; snprintf(tmp, sizeof(tmp), "%d/%d", ThisPlayer->Demand, ThisPlayer->Supply); label.SetFont(GetGameFont()); if (ThisPlayer->Supply < ThisPlayer->Demand) { label.DrawReverse(UI.Resources[FoodCost].TextX, UI.Resources[FoodCost].TextY, tmp); } else { label.Draw(UI.Resources[FoodCost].TextX, UI.Resources[FoodCost].TextY, tmp); } } if (UI.Resources[ScoreCost].TextX != -1) { const int score = ThisPlayer->Score; label.SetFont(score > 99999 ? GetSmallFont() : GetGameFont()); label.Draw(UI.Resources[ScoreCost].TextX, UI.Resources[ScoreCost].TextY + (score > 99999) * 3, score); } if (UI.Resources[FreeWorkersCount].TextX != -1) { const int workers = ThisPlayer->FreeWorkers.size(); label.SetFont(GetGameFont()); label.Draw(UI.Resources[FreeWorkersCount].TextX, UI.Resources[FreeWorkersCount].TextY, workers); } } /*---------------------------------------------------------------------------- -- MESSAGE ----------------------------------------------------------------------------*/ #define MESSAGES_MAX 10 /// How many can be displayed static char MessagesEvent[MESSAGES_MAX][256]; /// Array of event messages static Vec2i MessagesEventPos[MESSAGES_MAX]; /// coordinate of event static int MessagesEventCount; /// Number of event messages static int MessagesEventIndex; /// FIXME: docu class MessagesDisplay { public: MessagesDisplay() : show(true) { #ifdef DEBUG showBuilList = false; #endif CleanMessages(); } void UpdateMessages(); void AddUniqueMessage(const char *s); void DrawMessages(); void CleanMessages(); void ToggleShowMessages() { show = !show; } #ifdef DEBUG void ToggleShowBuilListMessages() { showBuilList = !showBuilList; } #endif protected: void ShiftMessages(); void AddMessage(const char *msg); bool CheckRepeatMessage(const char *msg); private: char Messages[MESSAGES_MAX][256]; /// Array of messages int MessagesCount; /// Number of messages int MessagesSameCount; /// Counts same message repeats int MessagesScrollY; unsigned long MessagesFrameTimeout; /// Frame to expire message bool show; #ifdef DEBUG bool showBuilList; #endif }; /** ** Shift messages array by one. */ void MessagesDisplay::ShiftMessages() { if (MessagesCount) { --MessagesCount; for (int z = 0; z < MessagesCount; ++z) { strcpy_s(Messages[z], sizeof(Messages[z]), Messages[z + 1]); } } } /** ** Update messages ** ** @todo FIXME: make scroll speed configurable. */ void MessagesDisplay::UpdateMessages() { if (!MessagesCount) { return; } // Scroll/remove old message line const unsigned long ticks = GetTicks(); if (MessagesFrameTimeout < ticks) { ++MessagesScrollY; if (MessagesScrollY == UI.MessageFont->Height() + 1) { MessagesFrameTimeout = ticks + UI.MessageScrollSpeed * 1000; MessagesScrollY = 0; ShiftMessages(); } } } /** ** Draw message(s). ** ** @todo FIXME: make message font configurable. */ void MessagesDisplay::DrawMessages() { if (show && Preference.ShowMessages) { CLabel label(*UI.MessageFont); #ifdef DEBUG if (showBuilList && ThisPlayer->Ai) { char buffer[256]; int count = ThisPlayer->Ai->UnitTypeBuilt.size(); // Draw message line(s) for (int z = 0; z < count; ++z) { if (z == 0) { PushClipping(); SetClipping(UI.MapArea.X + 8, UI.MapArea.Y + 8, Video.Width - 1, Video.Height - 1); } snprintf(buffer, 256, "%s (%d/%d) Wait %lu [%d,%d]", ThisPlayer->Ai->UnitTypeBuilt[z].Type->Name.c_str(), ThisPlayer->Ai->UnitTypeBuilt[z].Made, ThisPlayer->Ai->UnitTypeBuilt[z].Want, ThisPlayer->Ai->UnitTypeBuilt[z].Wait, ThisPlayer->Ai->UnitTypeBuilt[z].Pos.x, ThisPlayer->Ai->UnitTypeBuilt[z].Pos.y); label.DrawClip(UI.MapArea.X + 8, UI.MapArea.Y + 8 + z * (UI.MessageFont->Height() + 1), buffer); if (z == 0) { PopClipping(); } } } else { #endif // background so the text is easier to read if (MessagesCount) { int textHeight = MessagesCount * (UI.MessageFont->Height() + 1); Uint32 color = Video.MapRGB(TheScreen->format, 38, 38, 78); Video.FillTransRectangleClip(color, UI.MapArea.X + 7, UI.MapArea.Y + 7, UI.MapArea.EndX - UI.MapArea.X - 16, textHeight - MessagesScrollY + 1, 0x80); Video.DrawRectangle(color, UI.MapArea.X + 6, UI.MapArea.Y + 6, UI.MapArea.EndX - UI.MapArea.X - 15, textHeight - MessagesScrollY + 2); } // Draw message line(s) for (int z = 0; z < MessagesCount; ++z) { if (z == 0) { PushClipping(); SetClipping(UI.MapArea.X + 8, UI.MapArea.Y + 8, Video.Width - 1, Video.Height - 1); } /* * Due parallel drawing we have to force message copy due temp * std::string(Messages[z]) creation because * char * pointer may change during text drawing. */ label.DrawClip(UI.MapArea.X + 8, UI.MapArea.Y + 8 + z * (UI.MessageFont->Height() + 1) - MessagesScrollY, std::string(Messages[z])); if (z == 0) { PopClipping(); } } if (MessagesCount < 1) { MessagesSameCount = 0; } #ifdef DEBUG } #endif } } /** ** Adds message to the stack ** ** @param msg Message to add. */ void MessagesDisplay::AddMessage(const char *msg) { unsigned long ticks = GetTicks(); if (!MessagesCount) { MessagesFrameTimeout = ticks + UI.MessageScrollSpeed * 1000; } if (MessagesCount == MESSAGES_MAX) { // Out of space to store messages, can't scroll smoothly ShiftMessages(); MessagesFrameTimeout = ticks + UI.MessageScrollSpeed * 1000; MessagesScrollY = 0; } char *ptr; char *next; char *message = Messages[MessagesCount]; // Split long message into lines if (strlen(msg) >= sizeof(Messages[0])) { strncpy(message, msg, sizeof(Messages[0]) - 1); ptr = message + sizeof(Messages[0]) - 1; *ptr-- = '\0'; next = ptr + 1; while (ptr >= message) { if (*ptr == ' ') { *ptr = '\0'; next = ptr + 1; break; } --ptr; } if (ptr < message) { ptr = next - 1; } } else { strcpy_s(message, sizeof(Messages[MessagesCount]), msg); next = ptr = message + strlen(message); } while (UI.MessageFont->Width(message) + 8 >= UI.MapArea.EndX - UI.MapArea.X) { while (1) { --ptr; if (*ptr == ' ') { *ptr = '\0'; next = ptr + 1; break; } else if (ptr == message) { break; } } // No space found, wrap in the middle of a word if (ptr == message) { ptr = next - 1; while (UI.MessageFont->Width(message) + 8 >= UI.MapArea.EndX - UI.MapArea.X) { *--ptr = '\0'; } next = ptr + 1; break; } } ++MessagesCount; if (strlen(msg) != (size_t)(ptr - message)) { AddMessage(msg + (next - message)); } } /** ** Check if this message repeats ** ** @param msg Message to check. ** ** @return true to skip this message */ bool MessagesDisplay::CheckRepeatMessage(const char *msg) { if (MessagesCount < 1) { return false; } if (!strcmp(msg, Messages[MessagesCount - 1])) { ++MessagesSameCount; return true; } if (MessagesSameCount > 0) { char temp[256]; int n = MessagesSameCount; MessagesSameCount = 0; // NOTE: vladi: yep it's a tricky one, but should work fine prbably :) snprintf(temp, sizeof(temp), _("Last message repeated ~<%d~> times"), n + 1); AddMessage(temp); } return false; } /** ** Add a new message to display only if it differs from the preceding one. */ void MessagesDisplay::AddUniqueMessage(const char *s) { if (!CheckRepeatMessage(s)) { AddMessage(s); } } /** ** Clean up messages. */ void MessagesDisplay::CleanMessages() { MessagesCount = 0; MessagesSameCount = 0; MessagesScrollY = 0; MessagesFrameTimeout = 0; MessagesEventCount = 0; MessagesEventIndex = 0; } static MessagesDisplay allmessages; /** ** Update messages */ void UpdateMessages() { allmessages.UpdateMessages(); } /** ** Clean messages */ void CleanMessages() { allmessages.CleanMessages(); } /** ** Draw messages */ void DrawMessages() { allmessages.DrawMessages(); } /** ** Set message to display. ** ** @param fmt To be displayed in text overlay. */ void SetMessage(const char *fmt, ...) { char temp[512]; va_list va; va_start(va, fmt); vsnprintf(temp, sizeof(temp) - 1, fmt, va); temp[sizeof(temp) - 1] = '\0'; va_end(va); allmessages.AddUniqueMessage(temp); } /** ** Shift messages events array by one. */ void ShiftMessagesEvent() { if (MessagesEventCount) { --MessagesEventCount; for (int z = 0; z < MessagesEventCount; ++z) { MessagesEventPos[z] = MessagesEventPos[z + 1]; strcpy_s(MessagesEvent[z], sizeof(MessagesEvent[z]), MessagesEvent[z + 1]); } } } /** ** Set message to display. ** ** @param pos Message pos map origin. ** @param fmt To be displayed in text overlay. ** ** @note FIXME: vladi: I know this can be just separated func w/o msg but ** it is handy to stick all in one call, someone? */ void SetMessageEvent(const Vec2i &pos, const char *fmt, ...) { Assert(Map.Info.IsPointOnMap(pos)); char temp[256]; va_list va; va_start(va, fmt); vsnprintf(temp, sizeof(temp) - 1, fmt, va); temp[sizeof(temp) - 1] = '\0'; va_end(va); allmessages.AddUniqueMessage(temp); if (MessagesEventCount == MESSAGES_MAX) { ShiftMessagesEvent(); } strcpy_s(MessagesEvent[MessagesEventCount], sizeof(MessagesEvent[MessagesEventCount]), temp); MessagesEventPos[MessagesEventCount] = pos; MessagesEventIndex = MessagesEventCount; ++MessagesEventCount; } /** ** Goto message origin. */ void CenterOnMessage() { if (MessagesEventIndex >= MessagesEventCount) { MessagesEventIndex = 0; } if (MessagesEventCount == 0) { return; } const Vec2i &pos(MessagesEventPos[MessagesEventIndex]); UI.SelectedViewport->Center(Map.TilePosToMapPixelPos_Center(pos)); SetMessage(_("~<Event: %s~>"), MessagesEvent[MessagesEventIndex]); ++MessagesEventIndex; } void ToggleShowMessages() { allmessages.ToggleShowMessages(); } #ifdef DEBUG void ToggleShowBuilListMessages() { allmessages.ToggleShowBuilListMessages(); } #endif /*---------------------------------------------------------------------------- -- INFO PANEL ----------------------------------------------------------------------------*/ /** ** Draw info panel background. ** ** @param frame frame nr. of the info panel background. */ static void DrawInfoPanelBackground(unsigned frame) { if (UI.InfoPanel.G) { UI.InfoPanel.G->DrawFrame(frame, UI.InfoPanel.X, UI.InfoPanel.Y); } } static void InfoPanel_draw_no_selection() { DrawInfoPanelBackground(0); if (UnitUnderCursor && UnitUnderCursor->IsVisible(*ThisPlayer) && !UnitUnderCursor->Type->BoolFlag[ISNOTSELECTABLE_INDEX].value) { // FIXME: not correct for enemies units DrawUnitInfo(*UnitUnderCursor); } else { // FIXME: need some cool ideas for this. int x = UI.InfoPanel.X + 16; int y = UI.InfoPanel.Y + 8; CLabel label(GetGameFont()); label.Draw(x, y, "Stratagus"); y += 16; label.Draw(x, y, _("Cycle:")); label.Draw(x + 48, y, GameCycle); label.Draw(x + 110, y, CYCLES_PER_SECOND * VideoSyncSpeed / 100); y += 20; std::string nc; std::string rc; GetDefaultTextColors(nc, rc); for (int i = 0; i < PlayerMax - 1; ++i) { if (Players[i].Type != PlayerNobody) { if (ThisPlayer->IsAllied(Players[i])) { label.SetNormalColor(FontGreen); } else if (ThisPlayer->IsEnemy(Players[i])) { label.SetNormalColor(FontRed); } else { label.SetNormalColor(nc); } label.Draw(x + 15, y, i); Video.DrawRectangleClip(ColorWhite, x, y, 12, 12); Video.FillRectangleClip(PlayerColors[GameSettings.Presets[i].PlayerColor][0], x + 1, y + 1, 10, 10); label.Draw(x + 27, y, Players[i].Name); label.Draw(x + 117, y, Players[i].Score); y += 14; } } } } static void InfoPanel_draw_single_selection(CUnit *selUnit) { CUnit &unit = (selUnit ? *selUnit : *Selected[0]); int panelIndex; // FIXME: not correct for enemy's units if (unit.Player == ThisPlayer || ThisPlayer->IsTeamed(unit) || ThisPlayer->IsAllied(unit) || ReplayRevealMap) { if (unit.Orders[0]->Action == UnitActionBuilt || unit.Orders[0]->Action == UnitActionResearch || unit.Orders[0]->Action == UnitActionUpgradeTo || unit.Orders[0]->Action == UnitActionTrain) { panelIndex = 3; } else if (unit.Stats->Variables[MANA_INDEX].Max) { panelIndex = 2; } else { panelIndex = 1; } } else { panelIndex = 0; } DrawInfoPanelBackground(panelIndex); DrawUnitInfo(unit); if (ButtonAreaUnderCursor == ButtonAreaSelected && ButtonUnderCursor == 0) { UI.StatusLine.Set(unit.Type->Name); } } static void InfoPanel_draw_multiple_selection() { // If there are more units selected draw their pictures and a health bar DrawInfoPanelBackground(0); for (size_t i = 0; i != std::min(Selected.size(), UI.SelectedButtons.size()); ++i) { const CIcon &icon = *Selected[i]->Type->Icon.Icon; const PixelPos pos(UI.SelectedButtons[i].X, UI.SelectedButtons[i].Y); icon.DrawUnitIcon(*UI.SelectedButtons[i].Style, (ButtonAreaUnderCursor == ButtonAreaSelected && ButtonUnderCursor == (int)i) ? (IconActive | (MouseButtons & LeftButton)) : 0, pos, "", Selected[i]->RescuedFrom ? GameSettings.Presets[Selected[i]->RescuedFrom->Index].PlayerColor : GameSettings.Presets[Selected[i]->Player->Index].PlayerColor); UiDrawLifeBar(*Selected[i], UI.SelectedButtons[i].X, UI.SelectedButtons[i].Y); if (ButtonAreaUnderCursor == ButtonAreaSelected && ButtonUnderCursor == (int) i) { UI.StatusLine.Set(Selected[i]->Type->Name); } } if (Selected.size() > UI.SelectedButtons.size()) { char buf[5]; sprintf(buf, "+%lu", (long unsigned int)(Selected.size() - UI.SelectedButtons.size())); CLabel(*UI.MaxSelectedFont).Draw(UI.MaxSelectedTextX, UI.MaxSelectedTextY, buf); } } /** ** Draw info panel. ** ** Panel: ** neutral - neutral or opponent ** normal - not 1,3,4 ** magic unit - magic units ** construction - under construction */ void CInfoPanel::Draw() { if (UnitUnderCursor && Selected.empty() && !UnitUnderCursor->Type->IsNotSelectable && (ReplayRevealMap || UnitUnderCursor->IsVisible(*ThisPlayer))) { InfoPanel_draw_single_selection(UnitUnderCursor); } else { switch (Selected.size()) { case 0: { InfoPanel_draw_no_selection(); break; } case 1: { InfoPanel_draw_single_selection(NULL); break; } default: { InfoPanel_draw_multiple_selection(); break; } } } } /*---------------------------------------------------------------------------- -- TIMER ----------------------------------------------------------------------------*/ /** ** Draw the timer ** ** @todo FIXME : make DrawTimer more configurable (Pos, format). */ void DrawTimer() { if (!GameTimer.Init) { return; } int sec = GameTimer.Cycles / CYCLES_PER_SECOND; UI.Timer.Draw(sec); } /** ** Update the timer */ void UpdateTimer() { if (GameTimer.Running) { if (GameTimer.Increasing) { GameTimer.Cycles += GameCycle - GameTimer.LastUpdate; } else { GameTimer.Cycles -= GameCycle - GameTimer.LastUpdate; GameTimer.Cycles = std::max(GameTimer.Cycles, 0l); } GameTimer.LastUpdate = GameCycle; } } //@}
Stratagus/Stratagus
src/ui/mainscr.cpp
C++
gpl-2.0
33,991
function isPrime(n) { if (n === 2) { return true; } if (n % 2 === 0 || n === 1) { return false; } for (var i = 3; i <= Math.sqrt(n); i += 2) { if (n % i === 0) { return false; } } return true; } function nthPrimeNumber(n) { if (n <= 0) { throw new Error('Must be an integer >= 1'); } var numPrime = 1; var i = 1; if (n === 1) { return 2; } while (numPrime < n) { i += 2; if (isPrime(i)) { numPrime++; } } return i; } console.log(nthPrimeNumber(10001));
pbjr23/project-euler-js
pr7.js
JavaScript
gpl-2.0
536
<?php /** * glFusion CMS * * UTF-8 Language File for Calendar Plugin * * @license GNU General Public License version 2 or later * http://www.opensource.org/licenses/gpl-license.php * * Copyright (C) 2008-2018 by the following authors: * Mark R. Evans mark AT glfusion DOT org * * Based on prior work Copyright (C) 2001-2005 by the following authors: * Tony Bibbs - tony AT tonybibbs DOT com * Trinity Bays - trinity93 AT gmail DOT com * */ if (!defined ('GVERSION')) { die ('This file cannot be used on its own.'); } global $LANG32; ############################################################################### # Array Format: # $LANGXX[YY]: $LANG - variable name # XX - file id number # YY - phrase id number ############################################################################### # index.php $LANG_CAL_1 = array( 1 => 'Tapahtumakalenteri', 2 => 'Ei tapahtumia.', 3 => 'Milloin', 4 => 'Juuri', 5 => 'Kuvaus', 6 => 'Lisää tapahtuma', 7 => 'Tulevat tapahtumat', 8 => 'Lisäämällä tämän taphtuman kalenteriisi, näet nopeasti ne tapahtumat jotka sinua kiinnostaa klikkaamalla "Oma Kalenteri" käyttäjän toiminnot alueella.', 9 => 'Lisää minun jalenteriin', 10 => 'Poista minun kalenterista', 11 => 'Lisätään tapahtuma %s\'s Kalenteriin', 12 => 'Tapahtuma', 13 => 'Alkaa', 14 => 'Loppuu', 15 => 'Takaisin kalenteriin', 16 => 'Kalenteri', 17 => 'Aloitusp&auml;iv&auml;', 18 => 'Lopetusp&auml;iv&auml;', 19 => 'kalenteriin lähetetyt', 20 => 'Otsikko', 21 => 'Alkamis päivä', 22 => 'URL', 23 => 'Sinun tapahtumat', 24 => 'Sivuston tapahtumat', 25 => 'Ei tulevia tapahtumia', 26 => 'Lähetä tapahtuma', 27 => "Lähetetään tapahtuma {$_CONF['site_name']} laitaa tapahtuman pääkalenteriin josta käyttäjät voi lisätä heidän omaan kalenteriin. Tämä toiminto <b>EI</b> ole tarkoitettu henkilökohtaisiin tapahtumiin kuten syntymäpäivät yms tapahtumat.<br><br>Kun olet lähettänyt tapahtumasi, se lähetetään ylläpitoon ja jos se hyväksytään, tapahtumasai ilmestyy pääkalenteriin.", 28 => 'Otsikko', 29 => 'Päättymis aika', 30 => 'Alamis aika', 31 => 'Kokopäivän tapahtuma', 32 => 'Osoiterivi 1', 33 => 'Osoiterivi 2', 34 => 'Kaupunki', 35 => 'Osavaltio', 36 => 'Postinumero', 37 => 'Tapahtuman tyyppi', 38 => 'Muokkaa tapahtuma tyyppejä', 39 => 'Sijainti', 40 => 'Lisää tapahtuma kohteeseen', 41 => 'Pääkalenteri', 42 => 'Henkilökohtainen kalenteri', 43 => 'Linkki', 44 => 'HTML koodit eiv&auml;t ole sallittu', 45 => 'Lähetä', 46 => 'Tapahtumat systeemissä', 47 => 'Top kymmenen tapahtumat', 48 => 'Lukukertoja', 49 => 'Näyttää siltä että tällä sivustolla ei ole tapahtumia, tai kukaan ei ole klikannut niitä.', 50 => 'Tapahtumat', 51 => 'Poista', 52 => 'L&auml;hetti', 53 => 'Calendar View', ); $_LANG_CAL_SEARCH = array( 'results' => 'Kalenteri tulokset', 'title' => 'Otsikko', 'date_time' => 'Päivä & Aika', 'location' => 'Sijainti', 'description' => 'Kuvaus' ); ############################################################################### # calendar.php ($LANG30) $LANG_CAL_2 = array( 8 => 'Lisää oma tapahtuma', 9 => '%s Tapahtuma', 10 => 'Tapahtumat ', 11 => 'Pääkalenteri', 12 => 'Oma kalenteri', 25 => 'Takaisin ', 26 => 'Koko p&auml;iv&auml;n', 27 => 'Viikko', 28 => 'Oma kalenteri kohteelle', 29 => ' Julkinen kalenteri', 30 => 'poista tapahtuma', 31 => 'Lis&auml;&auml;', 32 => 'Tapahtuma', 33 => 'Päivä', 34 => 'Aika', 35 => 'Nopea lisäys', 36 => 'Lähetä', 37 => 'Oma kalenteri toiminto ei ole käytössä', 38 => 'Oma tapahtuma muokkaus', 39 => 'Päivä', 40 => 'Viikko', 41 => 'Kuukausi', 42 => 'Lisää päätapahtuma', 43 => 'Lähetetyt tapahtumat' ); ############################################################################### # admin/plugins/calendar/index.php, formerly admin/event.php ($LANG22) $LANG_CAL_ADMIN = array( 1 => 'Tapahtuma Muokkaus', 2 => 'Virhe', 3 => 'Viestin muoto', 4 => 'Tapahtuman URL', 5 => 'Tapahtuman alkamispäivä', 6 => 'Tapahtuman päättymispäivä', 7 => 'Tapahtuman sijainti', 8 => 'Kuvaus tapahtumasta', 9 => '(mukaanlukien http://)', 10 => 'Sinun täytyy antaa päivä/aika, tapahtuman otsikko, ja kuvaus tapahtumasta', 11 => 'Kalenteri hallinta', 12 => 'Muokataksesi tai poistaaksesi tapahtuman, klikkaa tapahtuman edit ikonia alhaalla. Uuden tapahtuman luodaksesi klikkaa "Luo uusi" ylhäältä. Klikkaa kopioi ikonia kopioidaksesi olemassaolevan tapahtuman.', 13 => 'Omistaja', 14 => 'Alkamispäivä', 15 => 'Päättymispäivä', 16 => '', 17 => "Yrität päästä tapahtumaan johon sinulla ei ole pääsy oikeutta. Tämä yrtitys kirjattiin. <a href=\"{$_CONF['site_admin_url']}/plugins/calendar/index.php\">mene takaisin tapahtuman hallintaan</a>.", 18 => '', 19 => '', 20 => 'tallenna', 21 => 'peruuta', 22 => 'poista', 23 => 'Epäkelpo Alkamis Päivä.', 24 => 'Epäkelpo päättymis Päivä.', 25 => 'Päättymispäivä On Aikaisemmin Kuin Alkamispäivä.', 26 => 'Batch Event Manager', 27 => 'Tässä ovat kaikki tapahtumat jotka ovat vanhempia kuin ', 28 => ' kuukautta. Päivitä aikaväli halutuksi, ja klikkaa Päivitä Lista. valitse yksi tai useampia tapahtumia tuloksista, ja klikkaa poista Ikonia alla poistaaksesi nämä tapahtumat. Vain tapahtumat jotka näkyy tällä sivulla ja on listattu, poistetaan.', 29 => '', 30 => 'P&auml;ivit&auml; Lista', 31 => 'Oletko varma että haluat poistaa kaikki valitut käyttäjät?', 32 => 'Listaa kaikki', 33 => 'Yhtään tapahtumaa ei valittu poistettavaksi', 34 => 'Tapahtuman ID', 35 => 'ei voitu poistaa', 36 => 'Poistettu', 37 => 'Moderoi Tapahtumaa', 38 => 'Batch tapahtuma Admin', 39 => 'Tapahtuman Admin', 40 => 'Event List', 41 => 'This screen allows you to edit / create events. Edit the fields below and save.', ); $LANG_CAL_AUTOTAG = array( 'desc_calendar' => 'Link: to a Calendar event on this site; link_text defaults to event title: [calendar:<i>event_id</i> {link_text}]', ); $LANG_CAL_MESSAGE = array( 'save' => 'tapahtuma Tallennettu.', 'delete' => 'Tapahtuma Poistettu.', 'private' => 'Tapahtuma Tallennettu Kalenteriisi', 'login' => 'Kalenteriasi ei voi avata ennenkuin olet kirjautunut', 'removed' => 'tapahtuma poistettu kalenteristasi', 'noprivate' => 'Valitamme, mutta henkilökohtaiset kalenterit ei ole sallittu tällä hetkellä', 'unauth' => 'Sinulla ei ole oikeuksia tapahtuman ylläpito sivulle. Kaikki yritykset kirjataan', 'delete_confirm' => 'Oletko varma että haluat poistaa tämän tapahtuman?' ); $PLG_calendar_MESSAGE4 = "Kiitos lähettämistä tapahtuman {$_CONF['site_name']}. On toimitettu henkilökuntamme hyväksyttäväksi. Jos hyväksytään, tapahtuma nähdään täällä, meidän <a href=\"{$_CONF['site_url']}/calendar/index.php\">kalenteri</a> jaksossa."; $PLG_calendar_MESSAGE17 = 'Tapahtuma Tallennettu.'; $PLG_calendar_MESSAGE18 = 'Tapahtuma Poistettu.'; $PLG_calendar_MESSAGE24 = 'Tapahtuma Tallennettu Kalenteriisi.'; $PLG_calendar_MESSAGE26 = 'Tapahtuma Poistettu.'; // Messages for the plugin upgrade $PLG_calendar_MESSAGE3001 = 'Plugin päivitys ei tueta.'; $PLG_calendar_MESSAGE3002 = $LANG32[9]; // Localization of the Admin Configuration UI $LANG_configsections['calendar'] = array( 'label' => 'Kalenteri', 'title' => 'Kalenteri Asetukset' ); $LANG_confignames['calendar'] = array( 'calendarloginrequired' => 'Kalenteri Kirjautuminen Vaaditaan', 'hidecalendarmenu' => 'Piiloita Kalenteri Valikossa', 'personalcalendars' => 'Salli Henkilökohtaiset Kalenterit', 'eventsubmission' => 'Ota Käyttöön Lähetys Jono', 'showupcomingevents' => 'Näytä Tulevat Tapahtumat', 'upcomingeventsrange' => 'Tulevien Tapahtumien Aikaväli', 'event_types' => 'Tapahtuma Tyypit', 'hour_mode' => 'Tunti Moodi', 'notification' => 'Sähköposti Ilmoitus', 'delete_event' => 'Poista Tapahtumalta Omistaja', 'aftersave' => 'Tapahtuman Tallennuksen Jälkeen', 'default_permissions' => 'Tapahtuman Oletus Oikeudet', 'only_admin_submit' => 'Salli Vain Admineitten Lähettää', 'displayblocks' => 'Näytä glFusion Lohkot', ); $LANG_configsubgroups['calendar'] = array( 'sg_main' => 'Pää Asetukset' ); $LANG_fs['calendar'] = array( 'fs_main' => 'Yleiset Kalenteri Asetukset', 'fs_permissions' => 'Oletus Oikeudet' ); $LANG_configSelect['calendar'] = array( 0 => array(1=> 'True', 0 => 'False'), 1 => array(true => 'True', false => 'False'), 6 => array(12 => '12', 24 => '24'), 9 => array('item'=>'Forward to Event', 'list'=>'Display Admin List', 'plugin'=>'Display Calendar', 'home'=>'Display Home', 'admin'=>'Display Admin'), 12 => array(0=>'No access', 2=>'Vain luku', 3=>'Read-Write'), 13 => array(0=>'Left Blocks', 1=>'Right Blocks', 2=>'Left & Right Blocks', 3=>'Ei yht&auml;&auml;n') ); ?>
glFusion/glfusion
private/plugins/calendar/language/finnish_utf-8.php
PHP
gpl-2.0
9,331
/* * Copyright 2001-2009 Sun Microsystems, Inc. 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. * * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. * */ // Sparse remembered set for a heap region (the "owning" region). Maps // indices of other regions to short sequences of cards in the other region // that might contain pointers into the owner region. // These tables only expand while they are accessed in parallel -- // deletions may be done in single-threaded code. This allows us to allow // unsynchronized reads/iterations, as long as expansions caused by // insertions only enqueue old versions for deletions, but do not delete // old versions synchronously. class SparsePRTEntry: public CHeapObj { public: enum SomePublicConstants { CardsPerEntry = 4, NullEntry = -1 }; private: RegionIdx_t _region_ind; int _next_index; CardIdx_t _cards[CardsPerEntry]; public: // Set the region_ind to the given value, and delete all cards. inline void init(RegionIdx_t region_ind); RegionIdx_t r_ind() const { return _region_ind; } bool valid_entry() const { return r_ind() >= 0; } void set_r_ind(RegionIdx_t rind) { _region_ind = rind; } int next_index() const { return _next_index; } int* next_index_addr() { return &_next_index; } void set_next_index(int ni) { _next_index = ni; } // Returns "true" iff the entry contains the given card index. inline bool contains_card(CardIdx_t card_index) const; // Returns the number of non-NULL card entries. inline int num_valid_cards() const; // Requires that the entry not contain the given card index. If there is // space available, add the given card index to the entry and return // "true"; otherwise, return "false" to indicate that the entry is full. enum AddCardResult { overflow, found, added }; inline AddCardResult add_card(CardIdx_t card_index); // Copy the current entry's cards into "cards". inline void copy_cards(CardIdx_t* cards) const; // Copy the current entry's cards into the "_card" array of "e." inline void copy_cards(SparsePRTEntry* e) const; inline CardIdx_t card(int i) const { return _cards[i]; } }; class RSHashTable : public CHeapObj { friend class RSHashTableIter; enum SomePrivateConstants { NullEntry = -1 }; size_t _capacity; size_t _capacity_mask; size_t _occupied_entries; size_t _occupied_cards; SparsePRTEntry* _entries; int* _buckets; int _free_region; int _free_list; // Requires that the caller hold a lock preventing parallel modifying // operations, and that the the table be less than completely full. If // an entry for "region_ind" is already in the table, finds it and // returns its address; otherwise returns "NULL." SparsePRTEntry* entry_for_region_ind(RegionIdx_t region_ind) const; // Requires that the caller hold a lock preventing parallel modifying // operations, and that the the table be less than completely full. If // an entry for "region_ind" is already in the table, finds it and // returns its address; otherwise allocates, initializes, inserts and // returns a new entry for "region_ind". SparsePRTEntry* entry_for_region_ind_create(RegionIdx_t region_ind); // Returns the index of the next free entry in "_entries". int alloc_entry(); // Declares the entry "fi" to be free. (It must have already been // deleted from any bucket lists. void free_entry(int fi); public: RSHashTable(size_t capacity); ~RSHashTable(); // Attempts to ensure that the given card_index in the given region is in // the sparse table. If successful (because the card was already // present, or because it was successfullly added) returns "true". // Otherwise, returns "false" to indicate that the addition would // overflow the entry for the region. The caller must transfer these // entries to a larger-capacity representation. bool add_card(RegionIdx_t region_id, CardIdx_t card_index); bool get_cards(RegionIdx_t region_id, CardIdx_t* cards); bool delete_entry(RegionIdx_t region_id); bool contains_card(RegionIdx_t region_id, CardIdx_t card_index) const; void add_entry(SparsePRTEntry* e); void clear(); size_t capacity() const { return _capacity; } size_t capacity_mask() const { return _capacity_mask; } size_t occupied_entries() const { return _occupied_entries; } size_t occupied_cards() const { return _occupied_cards; } size_t mem_size() const; SparsePRTEntry* entry(int i) const { return &_entries[i]; } void print(); }; // ValueObj because will be embedded in HRRS iterator. class RSHashTableIter VALUE_OBJ_CLASS_SPEC { int _tbl_ind; // [-1, 0.._rsht->_capacity) int _bl_ind; // [-1, 0.._rsht->_capacity) short _card_ind; // [0..CardsPerEntry) RSHashTable* _rsht; size_t _heap_bot_card_ind; // If the bucket list pointed to by _bl_ind contains a card, sets // _bl_ind to the index of that entry, and returns the card. // Otherwise, returns SparseEntry::NullEntry. CardIdx_t find_first_card_in_list(); // Computes the proper card index for the card whose offset in the // current region (as indicated by _bl_ind) is "ci". // This is subject to errors when there is iteration concurrent with // modification, but these errors should be benign. size_t compute_card_ind(CardIdx_t ci); public: RSHashTableIter(size_t heap_bot_card_ind) : _tbl_ind(RSHashTable::NullEntry), _bl_ind(RSHashTable::NullEntry), _card_ind((SparsePRTEntry::CardsPerEntry-1)), _rsht(NULL), _heap_bot_card_ind(heap_bot_card_ind) {} void init(RSHashTable* rsht) { _rsht = rsht; _tbl_ind = -1; // So that first increment gets to 0. _bl_ind = RSHashTable::NullEntry; _card_ind = (SparsePRTEntry::CardsPerEntry-1); } bool has_next(size_t& card_index); }; // Concurrent accesss to a SparsePRT must be serialized by some external // mutex. class SparsePRTIter; class SparsePRT VALUE_OBJ_CLASS_SPEC { // Iterations are done on the _cur hash table, since they only need to // see entries visible at the start of a collection pause. // All other operations are done using the _next hash table. RSHashTable* _cur; RSHashTable* _next; HeapRegion* _hr; enum SomeAdditionalPrivateConstants { InitialCapacity = 16 }; void expand(); bool _expanded; bool expanded() { return _expanded; } void set_expanded(bool b) { _expanded = b; } SparsePRT* _next_expanded; SparsePRT* next_expanded() { return _next_expanded; } void set_next_expanded(SparsePRT* nxt) { _next_expanded = nxt; } static SparsePRT* _head_expanded_list; public: SparsePRT(HeapRegion* hr); ~SparsePRT(); size_t occupied() const { return _next->occupied_cards(); } size_t mem_size() const; // Attempts to ensure that the given card_index in the given region is in // the sparse table. If successful (because the card was already // present, or because it was successfullly added) returns "true". // Otherwise, returns "false" to indicate that the addition would // overflow the entry for the region. The caller must transfer these // entries to a larger-capacity representation. bool add_card(RegionIdx_t region_id, CardIdx_t card_index); // If the table hold an entry for "region_ind", Copies its // cards into "cards", which must be an array of length at least // "CardsPerEntry", and returns "true"; otherwise, returns "false". bool get_cards(RegionIdx_t region_ind, CardIdx_t* cards); // If there is an entry for "region_ind", removes it and return "true"; // otherwise returns "false." bool delete_entry(RegionIdx_t region_ind); // Clear the table, and reinitialize to initial capacity. void clear(); // Ensure that "_cur" and "_next" point to the same table. void cleanup(); // Clean up all tables on the expanded list. Called single threaded. static void cleanup_all(); RSHashTable* cur() const { return _cur; } void init_iterator(SparsePRTIter* sprt_iter); static void add_to_expanded_list(SparsePRT* sprt); static SparsePRT* get_from_expanded_list(); bool contains_card(RegionIdx_t region_id, CardIdx_t card_index) const { return _next->contains_card(region_id, card_index); } #if 0 void verify_is_cleared(); void print(); #endif }; class SparsePRTIter: public /* RSHashTable:: */RSHashTableIter { public: SparsePRTIter(size_t heap_bot_card_ind) : /* RSHashTable:: */RSHashTableIter(heap_bot_card_ind) {} void init(const SparsePRT* sprt) { RSHashTableIter::init(sprt->cur()); } bool has_next(size_t& card_index) { return RSHashTableIter::has_next(card_index); } };
TheTypoMaster/Scaper
openjdk/hotspot/src/share/vm/gc_implementation/g1/sparsePRT.hpp
C++
gpl-2.0
9,597
<?php $widget = $vars["entity"]; // get widget settings $count = (int) $widget->wire_count; $filter = $widget->filter; if ($count < 1) { $count = 8; } $options = array( "type" => "object", "subtype" => "thewire", "limit" => $count, "full_view" => false, "pagination" => false, "view_type_toggle" => false ); if (!empty($filter)) { $filters = string_to_tag_array($filter); $filters = array_map("sanitise_string", $filters); $options["joins"] = array("JOIN " . elgg_get_config("dbprefix") . "objects_entity oe ON oe.guid = e.guid"); $options["wheres"] = array("(oe.description LIKE '%" . implode("%' OR oe.description LIKE '%", $filters) . "%')"); } $content = elgg_list_entities($options); if (!empty($content)) { echo $content; echo "<span class='elgg-widget-more'>" . elgg_view("output/url", array("href" => "thewire/all","text" => elgg_echo("thewire:moreposts"))) . "</span>"; } else { echo elgg_echo("thewire_tools:no_result"); }
3lywa/gcconnex
mod/thewire_tools/views/default/widgets/index_thewire/content.php
PHP
gpl-2.0
955
<?php /* * Template Name: Blog */ get_header(); ?> <?php while ( have_posts() ) : the_post(); ?> <div id="blog"> <?php get_template_part( 'content', 'introtext' ); ?> <section class="features"> <div class="container" role="main"> <div class="row"> <div class="span9"> <?php get_template_part( 'content', get_post_format() ); ?> </div> <div class="span3 sidebar"> <div class="blognav"> <?php get_sidebar(); ?> </div> </div> </div> </div> </section> </div> <?php endwhile; // end of the loop. ?> <?php get_footer(); ?>
thinkluke/retailexpress
wp-content/themes/retailexpress/single.php
PHP
gpl-2.0
677
<?php function uwpf_delete_plugin() { delete_option('uwpf_options'); } function uwpf_init(){ register_setting( 'uwpf_plugin_options', 'uwpf_options', 'uwpf_validate' ); } function requires_wordpress_version() { global $wp_version; $plugin = plugin_basename( __FILE__ ); $plugin_data = get_plugin_data( __FILE__, false ); if ( version_compare($wp_version, "2.9", "<" ) ) { if( is_plugin_active($plugin) ) { deactivate_plugins( $plugin ); wp_die( "'".$plugin_data['Name']."' requires WordPress 2.9 or higher, and has been deactivated! Please upgrade WordPress and try again.<br /><br />Back to <a href='".admin_url()."'>WordPress admin</a>." ); } } } ?>
maewna/food-sawasdee
wp-content/plugins/ultimate-wp-filter/uwpf_functions.php
PHP
gpl-2.0
714
<?php if ( !class_exists( 'RWMB_Field ' ) ) { class RWMB_Field { /** * Add actions * * @return void */ static function add_actions() {} /** * Enqueue scripts and styles * * @return void */ static function admin_enqueue_scripts() {} /** * Show field HTML * * @param array $field * @param bool $saved * * @return string */ static function show( $field, $saved ) { global $post; $field_class = RW_Meta_Box::get_class_name( $field ); $meta = call_user_func( array( $field_class, 'meta' ), $post->ID, $saved, $field ); $group = ''; // Empty the clone-group field $type = $field['type']; $id = $field['id']; $begin = call_user_func( array( $field_class, 'begin_html' ), $meta, $field ); // Apply filter to field begin HTML // 1st filter applies to all fields // 2nd filter applies to all fields with the same type // 3rd filter applies to current field only $begin = apply_filters( 'rwmb_begin_html', $begin, $field, $meta ); $begin = apply_filters( "rwmb_{$type}_begin_html", $begin, $field, $meta ); $begin = apply_filters( "rwmb_{$id}_begin_html", $begin, $field, $meta ); // Separate code for cloneable and non-cloneable fields to make easy to maintain // Cloneable fields if ( $field['clone'] ) { if ( isset( $field['clone-group'] ) ) $group = " clone-group='{$field['clone-group']}'"; $meta = (array) $meta; $field_html = ''; foreach ( $meta as $index => $sub_meta ) { $sub_field = $field; $sub_field['field_name'] = $field['field_name'] . "[{$index}]"; if ($index>0) { if (isset( $sub_field['address_field'] )) $sub_field['address_field'] = $field['address_field'] . "_{$index}"; $sub_field['id'] = $field['id'] . "_{$index}"; } if ( $field['multiple'] ) $sub_field['field_name'] .= '[]'; // Wrap field HTML in a div with class="rwmb-clone" if needed $input_html = '<div class="rwmb-clone">'; // Call separated methods for displaying each type of field //$input_html .= call_user_func( array( $field_class, 'html' ), $sub_meta, $sub_field ); // Apply filter to field HTML // 1st filter applies to all fields with the same type // 2nd filter applies to current field only $input_html = apply_filters( "rwmb_{$type}_html", $input_html, $field, $sub_meta ); $input_html = apply_filters( "rwmb_{$id}_html", $input_html, $field, $sub_meta ); // Add clone button $input_html .= self::clone_button(); $input_html .= '</div>'; $field_html .= $input_html; } } // Non-cloneable fields else { // Call separated methods for displaying each type of field $field_html = call_user_func( array( $field_class, 'html' ), $meta, $field ); // Apply filter to field HTML // 1st filter applies to all fields with the same type // 2nd filter applies to current field only $field_html = apply_filters( "rwmb_{$type}_html", $field_html, $field, $meta ); $field_html = apply_filters( "rwmb_{$id}_html", $field_html, $field, $meta ); } $end = call_user_func( array( $field_class, 'end_html' ), $meta, $field ); // Apply filter to field end HTML // 1st filter applies to all fields // 2nd filter applies to all fields with the same type // 3rd filter applies to current field only $end = apply_filters( 'rwmb_end_html', $end, $field, $meta ); $end = apply_filters( "rwmb_{$type}_end_html", $end, $field, $meta ); $end = apply_filters( "rwmb_{$id}_end_html", $end, $field, $meta ); // Apply filter to field wrapper // This allow users to change whole HTML markup of the field wrapper (i.e. table row) // 1st filter applies to all fields with the same type // 2nd filter applies to current field only //$html = apply_filters( "rwmb_{$type}_wrapper_html", "{$begin}{$field_html}{$end}", $field, $meta ); $html = apply_filters( "rwmb_{$type}_wrapper_html", "{$field_html}", $field, $meta ); $html = apply_filters( "rwmb_{$id}_wrapper_html", $html, $field, $meta ); // Display label and input in DIV and allow user-defined classes to be appended $classes = array( 'rwmb-field', "rwmb-{$type}-wrapper" ); if ( 'hidden' === $field['type'] ) $classes[] = 'hidden'; if ( !empty( $field['required'] ) ) $classes[] = 'required'; if ( !empty( $field['class'] ) ) $classes[] = $field['class']; printf( $field['before'] . '<div class="%s"%s>%s</div>' . $field['after'], implode( ' ', $classes ), $group, $html ); } /** * Get field HTML * * @param mixed $meta * @param array $field * * @return string */ static function html( $meta, $field ) { return ''; } /** * Show begin HTML markup for fields * * @param mixed $meta * @param array $field * * @return string */ static function begin_html( $meta, $field ) { if ( empty( $field['name'] ) ) return '<div class="rwmb-input">'; return sprintf( '<div class="rwmb-label"> <label for="%s">%s</label> </div> <div class="rwmb-input">', $field['id'], $field['name'] ); } /** * Show end HTML markup for fields * * @param mixed $meta * @param array $field * * @return string */ static function end_html( $meta, $field ) { $id = $field['id']; $button = ''; if ( $field['clone'] ) $button = '<a href="#" class="rwmb-button button-primary add-clone">' . __( '+', 'rwmb' ) . '</a>'; $desc = !empty( $field['desc'] ) ? "<p id='{$id}_description' class='description'>{$field['desc']}</p>" : ''; // Closes the container $html = "{$button}{$desc}</div>"; return $html; } /** * Add clone button * * @return string $html */ static function clone_button() { return '<a href="#" class="rwmb-button button remove-clone">' . __( '&#8211;', 'rwmb' ) . '</a>'; } /** * Get meta value * * @param int $post_id * @param bool $saved * @param array $field * * @return mixed */ static function meta( $post_id, $saved, $field ) { $meta = get_post_meta( $post_id, $field['id'], !$field['multiple'] ); // Use $field['std'] only when the meta box hasn't been saved (i.e. the first time we run) $meta = ( !$saved && '' === $meta || array() === $meta ) ? $field['std'] : $meta; // Escape attributes for non-wysiwyg fields if ( 'wysiwyg' !== $field['type'] ) $meta = is_array( $meta ) ? array_map( 'esc_attr', $meta ) : esc_attr( $meta ); $meta = apply_filters( "rwmb_{$field['type']}_meta", $meta ); $meta = apply_filters( "rwmb_{$field['id']}_meta", $meta ); return $meta; } /** * Set value of meta before saving into database * * @param mixed $new * @param mixed $old * @param int $post_id * @param array $field * * @return int */ static function value( $new, $old, $post_id, $field ) { return $new; } /** * Save meta value * * @param $new * @param $old * @param $post_id * @param $field */ static function save( $new, $old, $post_id, $field ) { $name = $field['id']; if ( '' === $new || array() === $new ) { delete_post_meta( $post_id, $name ); return; } if ( $field['multiple'] ) { foreach ( $new as $new_value ) { if ( !in_array( $new_value, $old ) ) add_post_meta( $post_id, $name, $new_value, false ); } foreach ( $old as $old_value ) { if ( !in_array( $old_value, $new ) ) delete_post_meta( $post_id, $name, $old_value ); } } else { if ( $field['clone'] ) { $new = (array) $new; foreach ( $new as $k => $v ) { if ( '' === $v ) unset( $new[$k] ); } } update_post_meta( $post_id, $name, $new ); } } /** * Normalize parameters for field * * @param array $field * * @return array */ static function normalize_field( $field ) { return $field; } } }
marcosalm/digiwall
public/wp-content/plugins/meta-box-master/inc/field.php
PHP
gpl-2.0
8,037
/*************************************************************************** ofxdump.cpp ------------------- copyright : (C) 2002 by Benoit Grégoire email : bock@step.polymtl.ca ***************************************************************************/ /**@file * \brief Code for ofxdump utility. C++ example code * * ofxdump prints to stdout, in human readable form, everything the library understands about a particular ofx response file, and sends errors to stderr. To know exactly what the library understands about of a particular ofx response file, just call ofxdump on that file. * * ofxdump is meant as both a C++ code example and a developper/debuging tool. It uses every function and every structure of the LibOFX API. By default, WARNING, INFO, ERROR and STATUS messages are enabled. You can change these defaults at the top of ofxdump.cpp * * usage: ofxdump path_to_ofx_file/ofx_filename */ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include <iostream> #include <iomanip> #include <string> #include "libofx.h" #include <stdio.h> /* for printf() */ #include <config.h> /* Include config constants, e.g., VERSION TF */ #include <errno.h> #include "cmdline.h" /* Gengetopt generated parser */ using namespace std; int ofx_proc_security_cb(struct OfxSecurityData data, void * security_data) { char dest_string[255]; cout<<"ofx_proc_security():\n"; if(data.unique_id_valid==true){ cout<<" Unique ID of the security being traded: "<<data.unique_id<<"\n"; } if(data.unique_id_type_valid==true){ cout<<" Format of the Unique ID: "<<data.unique_id_type<<"\n"; } if(data.secname_valid==true){ cout<<" Name of the security: "<<data.secname<<"\n"; } if(data.ticker_valid==true){ cout<<" Ticker symbol: "<<data.ticker<<"\n"; } if(data.unitprice_valid==true){ cout<<" Price of each unit of the security: "<<data.unitprice<<"\n"; } if(data.date_unitprice_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.date_unitprice))); cout<<" Date as of which the unitprice is valid: "<<dest_string<<"\n"; } if(data.currency_valid==true){ cout<<" Currency of the unitprice: "<<data.currency<<"\n"; } if(data.memo_valid==true){ cout<<" Extra transaction information (memo): "<<data.memo<<"\n"; } cout<<"\n"; return 0; } int ofx_proc_transaction_cb(struct OfxTransactionData data, void * transaction_data) { char dest_string[255]; cout<<"ofx_proc_transaction():\n"; if(data.account_id_valid==true){ cout<<" Account ID : "<<data.account_id<<"\n"; } if(data.transactiontype_valid==true) { if(data.transactiontype==OFX_CREDIT) strncpy(dest_string, "CREDIT: Generic credit", sizeof(dest_string)); else if (data.transactiontype==OFX_DEBIT) strncpy(dest_string, "DEBIT: Generic debit", sizeof(dest_string)); else if (data.transactiontype==OFX_INT) strncpy(dest_string, "INT: Interest earned or paid (Note: Depends on signage of amount)", sizeof(dest_string)); else if (data.transactiontype==OFX_DIV) strncpy(dest_string, "DIV: Dividend", sizeof(dest_string)); else if (data.transactiontype==OFX_FEE) strncpy(dest_string, "FEE: FI fee", sizeof(dest_string)); else if (data.transactiontype==OFX_SRVCHG) strncpy(dest_string, "SRVCHG: Service charge", sizeof(dest_string)); else if (data.transactiontype==OFX_DEP) strncpy(dest_string, "DEP: Deposit", sizeof(dest_string)); else if (data.transactiontype==OFX_ATM) strncpy(dest_string, "ATM: ATM debit or credit (Note: Depends on signage of amount)", sizeof(dest_string)); else if (data.transactiontype==OFX_POS) strncpy(dest_string, "POS: Point of sale debit or credit (Note: Depends on signage of amount)", sizeof(dest_string)); else if (data.transactiontype==OFX_XFER) strncpy(dest_string, "XFER: Transfer", sizeof(dest_string)); else if (data.transactiontype==OFX_CHECK) strncpy(dest_string, "CHECK: Check", sizeof(dest_string)); else if (data.transactiontype==OFX_PAYMENT) strncpy(dest_string, "PAYMENT: Electronic payment", sizeof(dest_string)); else if (data.transactiontype==OFX_CASH) strncpy(dest_string, "CASH: Cash withdrawal", sizeof(dest_string)); else if (data.transactiontype==OFX_DIRECTDEP) strncpy(dest_string, "DIRECTDEP: Direct deposit", sizeof(dest_string)); else if (data.transactiontype==OFX_DIRECTDEBIT) strncpy(dest_string, "DIRECTDEBIT: Merchant initiated debit", sizeof(dest_string)); else if (data.transactiontype==OFX_REPEATPMT) strncpy(dest_string, "REPEATPMT: Repeating payment/standing order", sizeof(dest_string)); else if (data.transactiontype==OFX_OTHER) strncpy(dest_string, "OTHER: Other", sizeof(dest_string)); else strncpy(dest_string, "Unknown transaction type", sizeof(dest_string)); cout<<" Transaction type: "<<dest_string<<"\n"; } if(data.date_initiated_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.date_initiated))); cout<<" Date initiated: "<<dest_string<<"\n"; } if(data.date_posted_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.date_posted))); cout<<" Date posted: "<<dest_string<<"\n"; } if(data.date_funds_available_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.date_funds_available))); cout<<" Date funds are available: "<<dest_string<<"\n"; } if(data.amount_valid==true){ cout<<" Total money amount: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.amount<<"\n"; } if(data.units_valid==true){ cout<<" # of units: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.units<<"\n"; } if(data.oldunits_valid==true){ cout<<" # of units before split: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.oldunits<<"\n"; } if(data.newunits_valid==true){ cout<<" # of units after split: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.newunits<<"\n"; } if(data.unitprice_valid==true){ cout<<" Unit price: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.unitprice<<"\n"; } if(data.fees_valid==true){ cout<<" Fees: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.fees<<"\n"; } if(data.commission_valid==true){ cout<<" Commission: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.commission<<"\n"; } if(data.fi_id_valid==true){ cout<<" Financial institution's ID for this transaction: "<<data.fi_id<<"\n"; } if(data.fi_id_corrected_valid==true){ cout<<" Financial institution ID replaced or corrected by this transaction: "<<data.fi_id_corrected<<"\n"; } if(data.fi_id_correction_action_valid==true){ cout<<" Action to take on the corrected transaction: "; if (data.fi_id_correction_action==DELETE) cout<<"DELETE\n"; else if (data.fi_id_correction_action==REPLACE) cout<<"REPLACE\n"; else cout<<"ofx_proc_transaction(): This should not happen!\n"; } if(data.invtransactiontype_valid==true){ cout<<" Investment transaction type: "; if (data.invtransactiontype==OFX_BUYDEBT) strncpy(dest_string, "BUYDEBT (Buy debt security)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_BUYMF) strncpy(dest_string, "BUYMF (Buy mutual fund)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_BUYOPT) strncpy(dest_string, "BUYOPT (Buy option)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_BUYOTHER) strncpy(dest_string, "BUYOTHER (Buy other security type)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_BUYSTOCK) strncpy(dest_string, "BUYSTOCK (Buy stock))", sizeof(dest_string)); else if (data.invtransactiontype==OFX_CLOSUREOPT) strncpy(dest_string, "CLOSUREOPT (Close a position for an option)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_INCOME) strncpy(dest_string, "INCOME (Investment income is realized as cash into the investment account)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_INVEXPENSE) strncpy(dest_string, "INVEXPENSE (Misc investment expense that is associated with a specific security)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_JRNLFUND) strncpy(dest_string, "JRNLFUND (Journaling cash holdings between subaccounts within the same investment account)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_MARGININTEREST) strncpy(dest_string, "MARGININTEREST (Margin interest expense)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_REINVEST) strncpy(dest_string, "REINVEST (Reinvestment of income)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_RETOFCAP) strncpy(dest_string, "RETOFCAP (Return of capital)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_SELLDEBT) strncpy(dest_string, "SELLDEBT (Sell debt security. Used when debt is sold, called, or reached maturity)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_SELLMF) strncpy(dest_string, "SELLMF (Sell mutual fund)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_SELLOPT) strncpy(dest_string, "SELLOPT (Sell option)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_SELLOTHER) strncpy(dest_string, "SELLOTHER (Sell other type of security)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_SELLSTOCK) strncpy(dest_string, "SELLSTOCK (Sell stock)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_SPLIT) strncpy(dest_string, "SPLIT (Stock or mutial fund split)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_TRANSFER) strncpy(dest_string, "TRANSFER (Transfer holdings in and out of the investment account)", sizeof(dest_string)); else strncpy(dest_string, "ERROR, this investment transaction type is unknown. This is a bug in ofxdump", sizeof(dest_string)); cout<<dest_string<<"\n"; } if(data.unique_id_valid==true){ cout<<" Unique ID of the security being traded: "<<data.unique_id<<"\n"; } if(data.unique_id_type_valid==true){ cout<<" Format of the Unique ID: "<<data.unique_id_type<<"\n"; } if(data.security_data_valid==true){ ofx_proc_security_cb(*(data.security_data_ptr), NULL ); } if(data.server_transaction_id_valid==true){ cout<<" Server's transaction ID (confirmation number): "<<data.server_transaction_id<<"\n"; } if(data.check_number_valid==true){ cout<<" Check number: "<<data.check_number<<"\n"; } if(data.reference_number_valid==true){ cout<<" Reference number: "<<data.reference_number<<"\n"; } if(data.standard_industrial_code_valid==true){ cout<<" Standard Industrial Code: "<<data.standard_industrial_code<<"\n"; } if(data.payee_id_valid==true){ cout<<" Payee_id: "<<data.payee_id<<"\n"; } if(data.name_valid==true){ cout<<" Name of payee or transaction description: "<<data.name<<"\n"; } if(data.memo_valid==true){ cout<<" Extra transaction information (memo): "<<data.memo<<"\n"; } cout<<"\n"; return 0; }//end ofx_proc_transaction() int ofx_proc_statement_cb(struct OfxStatementData data, void * statement_data) { char dest_string[255]; cout<<"ofx_proc_statement():\n"; if(data.currency_valid==true){ cout<<" Currency: "<<data.currency<<"\n"; } if(data.account_id_valid==true){ cout<<" Account ID: "<<data.account_id<<"\n"; } if(data.date_start_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.date_start))); cout<<" Start date of this statement: "<<dest_string<<"\n"; } if(data.date_end_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.date_end))); cout<<" End date of this statement: "<<dest_string<<"\n"; } if(data.ledger_balance_valid==true){ cout<<" Ledger balance: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.ledger_balance<<"\n"; } if(data.ledger_balance_date_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.ledger_balance_date))); cout<<" Ledger balance date: "<<dest_string<<"\n"; } if(data.available_balance_valid==true){ cout<<" Available balance: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.available_balance<<"\n"; } if(data.available_balance_date_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.available_balance_date))); cout<<" Ledger balance date: "<<dest_string<<"\n"; } if(data.marketing_info_valid==true){ cout<<" Marketing information: "<<data.marketing_info<<"\n"; } cout<<"\n"; return 0; }//end ofx_proc_statement() int ofx_proc_account_cb(struct OfxAccountData data, void * account_data) { cout<<"ofx_proc_account():\n"; if(data.account_id_valid==true){ cout<<" Account ID: "<<data.account_id<<"\n"; cout<<" Account name: "<<data.account_name<<"\n"; } if(data.account_type_valid==true){ cout<<" Account type: "; switch(data.account_type){ case OfxAccountData::OFX_CHECKING : cout<<"CHECKING\n"; break; case OfxAccountData::OFX_SAVINGS : cout<<"SAVINGS\n"; break; case OfxAccountData::OFX_MONEYMRKT : cout<<"MONEYMRKT\n"; break; case OfxAccountData::OFX_CREDITLINE : cout<<"CREDITLINE\n"; break; case OfxAccountData::OFX_CMA : cout<<"CMA\n"; break; case OfxAccountData::OFX_CREDITCARD : cout<<"CREDITCARD\n"; break; case OfxAccountData::OFX_INVESTMENT : cout<<"INVESTMENT\n"; break; default: cout<<"ofx_proc_account() WRITEME: This is an unknown account type!"; } } if(data.currency_valid==true){ cout<<" Currency: "<<data.currency<<"\n"; } if (data.bank_id_valid) cout<<" Bank ID: "<<data.bank_id << endl;; if (data.branch_id_valid) cout<<" Branch ID: "<<data.branch_id << endl; if (data.account_number_valid) cout<<" Account #: "<<data.account_number << endl; cout<<"\n"; return 0; }//end ofx_proc_account() int ofx_proc_status_cb(struct OfxStatusData data, void * status_data) { cout<<"ofx_proc_status():\n"; if(data.ofx_element_name_valid==true){ cout<<" Ofx entity this status is relevent to: "<< data.ofx_element_name<<" \n"; } if(data.severity_valid==true){ cout<<" Severity: "; switch(data.severity){ case OfxStatusData::INFO : cout<<"INFO\n"; break; case OfxStatusData::WARN : cout<<"WARN\n"; break; case OfxStatusData::ERROR : cout<<"ERROR\n"; break; default: cout<<"WRITEME: Unknown status severity!\n"; } } if(data.code_valid==true){ cout<<" Code: "<<data.code<<", name: "<<data.name<<"\n Description: "<<data.description<<"\n"; } if(data.server_message_valid==true){ cout<<" Server Message: "<<data.server_message<<"\n"; } cout<<"\n"; return 0; } int main (int argc, char *argv[]) { /** Tell ofxdump what you want it to send to stderr. See messages.cpp for more details */ extern int ofx_PARSER_msg; extern int ofx_DEBUG_msg; extern int ofx_WARNING_msg; extern int ofx_ERROR_msg; extern int ofx_INFO_msg; extern int ofx_STATUS_msg; gengetopt_args_info args_info; /* let's call our cmdline parser */ if (cmdline_parser (argc, argv, &args_info) != 0) exit(1) ; // if (args_info.msg_parser_given) // cout << "The msg_parser option was given!" << endl; // cout << "The flag is " << ( args_info.msg_parser_flag ? "on" : "off" ) << // "." << endl ; args_info.msg_parser_flag ? ofx_PARSER_msg = true : ofx_PARSER_msg = false; args_info.msg_debug_flag ? ofx_DEBUG_msg = true : ofx_DEBUG_msg = false; args_info.msg_warning_flag ? ofx_WARNING_msg = true : ofx_WARNING_msg = false; args_info.msg_error_flag ? ofx_ERROR_msg = true : ofx_ERROR_msg = false; args_info.msg_info_flag ? ofx_INFO_msg = true : ofx_INFO_msg = false; args_info.msg_status_flag ? ofx_STATUS_msg = true : ofx_STATUS_msg; bool skiphelp = false; if(args_info.list_import_formats_given) { skiphelp = true; cout <<"The supported file formats for the 'input-file-format' argument are:"<<endl; for(int i=0; LibofxImportFormatList[i].format!=LAST; i++) { cout <<" "<<LibofxImportFormatList[i].description<<endl; } } LibofxContextPtr libofx_context = libofx_get_new_context(); //char **inputs ; /* unamed options */ //unsigned inputs_num ; /* unamed options number */ if (args_info.inputs_num > 0) { const char* filename = args_info.inputs[0]; ofx_set_statement_cb(libofx_context, ofx_proc_statement_cb, 0); ofx_set_account_cb(libofx_context, ofx_proc_account_cb, 0); ofx_set_transaction_cb(libofx_context, ofx_proc_transaction_cb, 0); ofx_set_security_cb(libofx_context, ofx_proc_security_cb, 0); ofx_set_status_cb(libofx_context, ofx_proc_status_cb, 0); enum LibofxFileFormat file_format = libofx_get_file_format_from_str(LibofxImportFormatList, args_info.import_format_arg); /** @todo currently, only the first file is processed as the library can't deal with more right now.*/ if(args_info.inputs_num > 1) { cout << "Sorry, currently, only the first file is processed as the library can't deal with more right now. The following files were ignored:"<<endl; for ( unsigned i = 1 ; i < args_info.inputs_num ; ++i ) { cout << "file: " << args_info.inputs[i] << endl ; } } libofx_proc_file(libofx_context, args_info.inputs[0], file_format); } else { if ( !skiphelp ) cmdline_parser_print_help(); } return 0; }
tectronics/cashbox
libofx/libofx-0.8.2/ofxdump/ofxdump.cpp
C++
gpl-2.0
18,771
<?php namespace Drupal\dct_user\EventSubscriber; use Drupal\Core\Routing\RouteMatchInterface; use Drupal\Core\Session\AccountInterface; use Drupal\Core\Url; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpKernel\Event\GetResponseEvent; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\HttpKernel\KernelEvents; /** * Class NotAuthenticatedEventSubscriber. * * @package Drupal\dct_user\EventSubscriber */ class NotAuthenticatedEventSubscriber implements EventSubscriberInterface { /** * The current user. * * @var \Drupal\Core\Session\AccountInterface */ protected $currentUser; /** * The current request. * * @var \Symfony\Component\HttpFoundation\Request */ protected $request; /** * The current route match. * * @var \Drupal\Core\Routing\RouteMatchInterface */ protected $routeMatch; /** * The routes this subscriber should act on. */ const ROUTES = [ 'dct_commerce.ticket_redemption_code', 'entity.commerce_product.canonical', ]; /** * Constructs a new event subscriber. * * @param \Drupal\Core\Session\AccountInterface $current_user * The current user. * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack * The current request stack. * @param \Drupal\Core\Routing\RouteMatchInterface $routeMatch * The current routeMatch. */ public function __construct(AccountInterface $current_user, RequestStack $requestStack, RouteMatchInterface $routeMatch) { $this->request = $requestStack->getCurrentRequest(); $this->currentUser = $current_user; $this->routeMatch = $routeMatch; } /** * {@inheritdoc} */ public static function getSubscribedEvents() { $events[KernelEvents::EXCEPTION][] = ['onKernelException']; return $events; } /** * Redirects on 403 Access Denied kernel exceptions. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The Event to process. */ public function onKernelException(GetResponseEvent $event) { $exception = $event->getException(); if ($exception instanceof AccessDeniedHttpException && $this->currentUser->isAnonymous() && in_array($this->routeMatch->getRouteName(), static::ROUTES)) { $destination = []; if (!empty($this->request->getRequestUri())) { $destination = ['destination' => $this->request->getRequestUri()]; } $url = Url::fromRoute('dct_user.error_page', $destination); $response = new RedirectResponse($url->toString(TRUE)->getGeneratedUrl()); $event->setResponse($response); } } }
drupaltransylvania/drupal-camp
docroot/modules/custom/dct_user/src/EventSubscriber/NotAuthenticatedEventSubscriber.php
PHP
gpl-2.0
2,780
using System; using Server.Engines.Craft; namespace Server.Items { [Alterable(typeof(DefBlacksmithy), typeof(DualShortAxes))] [FlipableAttribute(0x1443, 0x1442)] public class TwoHandedAxe : BaseAxe { [Constructable] public TwoHandedAxe() : base(0x1443) { this.Weight = 8.0; } public TwoHandedAxe(Serial serial) : base(serial) { } public override WeaponAbility PrimaryAbility { get { return WeaponAbility.DoubleStrike; } } public override WeaponAbility SecondaryAbility { get { return WeaponAbility.ShadowStrike; } } public override int AosStrengthReq { get { return 40; } } public override int AosMinDamage { get { return 16; } } public override int AosMaxDamage { get { return 19; } } public override int AosSpeed { get { return 31; } } public override float MlSpeed { get { return 3.50f; } } public override int InitMinHits { get { return 31; } } public override int InitMaxHits { get { return 90; } } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); // version } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } }
kevin-10/ServUO
Scripts/Items/Equipment/Weapons/TwoHandedAxe.cs
C#
gpl-2.0
2,045
class ChangeRoleForUsers < ActiveRecord::Migration def change remove_column :users, :role, :string add_column :users, :role, :string, :default=>'user' end end
cronon/fanfiction
db/migrate/20130831030543_change_role_for_users.rb
Ruby
gpl-2.0
169
<?php /* Template Name: Full Width */ ?> <?php get_header(); ?> <div class="row"> <div class="sixteen columns"> <div class="single-page" role="main"> <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <article <?php post_class(); ?>> <?php /*if(!is_front_page()) { WE DONT WANT THIS ?> <h1 id="post-<?php the_ID(); ?>" class="article-title"> <?php the_title(); ?> </h1> <?php } */?> <section class="post-content"> <?php the_content(); ?> </section><!-- .post-content --> </article> <?php endwhile; ?> <?php comments_template(); ?> <?php else : ?> <h2 class="center"><?php esc_attr_e('Nothing is Here - Page Not Found', ''); ?></h2> <div class="entry-content"> <p><?php esc_attr_e( 'Sorry, but we couldn\'t find what you we\'re looking for.', '' ); ?></p> </div><!-- .entry-content --> <?php endif; ?> </div><!--End Single Article--> </div> </div> <?php get_footer(); ?>
RPI-Sage-Hillel/Website
wp-content/themes/bartleby-child/fullwidth-page.php
PHP
gpl-2.0
916
#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def run(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v) else: generate = True if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: return True context.graph.clear() # Generate a complete graph k_n(context, N) res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True def k_n(C, n): """ k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v: # add an edge between u and v G.addEdge((u, v)) def moment(C, compact=False): """ Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) break else: # We did not find a divisor # print "%d is a prime!" % p break else: # Can't happen! raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n) # Position each vertex if compact: for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10) else: for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i)) return
ulethHCI/GLuskap
plugins/moment_curve.py
Python
gpl-2.0
3,644
<?php namespace Thru\ActiveRecord\Test\Models; use Thru\ActiveRecord\ActiveRecord; /** * Class TestModel * @var $test_model_id integer * @var $integer_field integer * @var $text_field text * @var $date_field date */ class TestModel extends ActiveRecord { protected $_table = "test_models"; public $test_model_id; public $integer_field; public $text_field; public $date_field; }
Thruio/ActiveRecord
tests/Models/TestModel.php
PHP
gpl-2.0
409
package newpackage; public class DaneWejsciowe { float wartosc; String argument; public DaneWejsciowe( String argument,float wartosc) { this.wartosc = wartosc; this.argument = argument; } }
Zajcew/SystemEkspertowy
System Ekspertowy/src/newpackage/DaneWejsciowe.java
Java
gpl-2.0
213
<?php /** * Template to display the main page for the new forum * @access public */ $this->setLayoutTemplate('poll_layout_tpl.php'); echo $display.'<br />'; ?>
chisimba/modules
poll/templates/content/home_tpl.php
PHP
gpl-2.0
171
/* * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> * * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "Common.h" #include "WorldPacket.h" #include "Opcodes.h" #include "Log.h" #include "ObjectMgr.h" #include "SpellMgr.h" #include "Player.h" #include "Unit.h" #include "Spell.h" #include "SpellAuraEffects.h" #include "DynamicObject.h" #include "ObjectAccessor.h" #include "Util.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "CellImpl.h" AuraApplication::AuraApplication(Unit * target, Unit * caster, Aura * aura, uint8 effMask) : m_target(target), m_base(aura), m_slot(MAX_AURAS), m_flags(AFLAG_NONE), m_needClientUpdate(false) , m_removeMode(AURA_REMOVE_NONE), m_effectsToApply(effMask) { assert(GetTarget() && GetBase()); if (GetBase()->IsVisible()) { // Try find slot for aura uint8 slot = MAX_AURAS; // Lookup for auras already applied from spell if (AuraApplication * foundAura = m_target->GetAuraApplication(m_base->GetId(), m_base->GetCasterGUID())) { // allow use single slot only by auras from same caster slot = foundAura->GetSlot(); } else { Unit::VisibleAuraMap const * visibleAuras = m_target->GetVisibleAuras(); // lookup for free slots in units visibleAuras Unit::VisibleAuraMap::const_iterator itr = visibleAuras->find(0); for (uint32 freeSlot = 0; freeSlot < MAX_AURAS; ++itr , ++freeSlot) { if (itr == visibleAuras->end() || itr->first != freeSlot) { slot = freeSlot; break; } } } // Register Visible Aura if (slot < MAX_AURAS) { m_slot = slot; m_target->SetVisibleAura(slot, this); SetNeedClientUpdate(); sLog.outDebug("Aura: %u Effect: %d put to unit visible auras slot: %u", GetBase()->GetId(), GetEffectMask(), slot); } else sLog.outDebug("Aura: %u Effect: %d could not find empty unit visible slot", GetBase()->GetId(), GetEffectMask()); } m_flags |= (_CheckPositive(caster) ? AFLAG_POSITIVE : AFLAG_NEGATIVE) | (GetBase()->GetCasterGUID() == GetTarget()->GetGUID() ? AFLAG_CASTER : AFLAG_NONE); m_isNeedManyNegativeEffects = false; if (GetBase()->GetCasterGUID() == GetTarget()->GetGUID()) // caster == target - 1 negative effect is enough for aura to be negative m_isNeedManyNegativeEffects = false; else if (caster) m_isNeedManyNegativeEffects = caster->IsFriendlyTo(m_target); } void AuraApplication::_Remove() { uint8 slot = GetSlot(); if (slot >= MAX_AURAS) return; if (AuraApplication * foundAura = m_target->GetAuraApplication(GetBase()->GetId(), GetBase()->GetCasterGUID())) { // Reuse visible aura slot by aura which is still applied - prevent storing dead pointers if (slot == foundAura->GetSlot()) { if (GetTarget()->GetVisibleAura(slot) == this) { GetTarget()->SetVisibleAura(slot, foundAura); foundAura->SetNeedClientUpdate(); } // set not valid slot for aura - prevent removing other visible aura slot = MAX_AURAS; } } // update for out of range group members if (slot < MAX_AURAS) { GetTarget()->RemoveVisibleAura(slot); ClientUpdate(true); } } bool AuraApplication::_CheckPositive(Unit * caster) const { // Aura is positive when it is casted by friend and at least one aura is positive // or when it is casted by enemy and at least one aura is negative for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if ((1<<i & GetEffectMask())) { if (m_isNeedManyNegativeEffects == IsPositiveEffect(GetBase()->GetId(), i)) return m_isNeedManyNegativeEffects; } } return !m_isNeedManyNegativeEffects; } void AuraApplication::_HandleEffect(uint8 effIndex, bool apply) { AuraEffect * aurEff = GetBase()->GetEffect(effIndex); assert(aurEff); assert(HasEffect(effIndex) == (!apply)); assert((1<<effIndex) & m_effectsToApply); sLog.outDebug("AuraApplication::_HandleEffect: %u, apply: %u: amount: %u", aurEff->GetAuraType(), apply, aurEff->GetAmount()); Unit * caster = GetBase()->GetCaster(); m_flags &= ~(AFLAG_POSITIVE | AFLAG_NEGATIVE); if (apply) { m_flags |= 1<<effIndex; m_flags |=_CheckPositive(caster) ? AFLAG_POSITIVE : AFLAG_NEGATIVE; GetTarget()->_HandleAuraEffect(aurEff, true); aurEff->HandleEffect(this, AURA_EFFECT_HANDLE_REAL, true); } else { m_flags &= ~(1<<effIndex); m_flags |=_CheckPositive(caster) ? AFLAG_POSITIVE : AFLAG_NEGATIVE; // remove from list before mods removing (prevent cyclic calls, mods added before including to aura list - use reverse order) GetTarget()->_HandleAuraEffect(aurEff, false); aurEff->HandleEffect(this, AURA_EFFECT_HANDLE_REAL, false); // Remove all triggered by aura spells vs unlimited duration aurEff->CleanupTriggeredSpells(GetTarget()); } SetNeedClientUpdate(); } void AuraApplication::ClientUpdate(bool remove) { m_needClientUpdate = false; WorldPacket data(SMSG_AURA_UPDATE); data.append(GetTarget()->GetPackGUID()); data << uint8(m_slot); if (remove) { assert(!m_target->GetVisibleAura(m_slot)); data << uint32(0); sLog.outDebug("Aura %u removed slot %u",GetBase()->GetId(), m_slot); m_target->SendMessageToSet(&data, true); return; } assert(m_target->GetVisibleAura(m_slot)); Aura const * aura = GetBase(); data << uint32(aura->GetId()); uint32 flags = m_flags; if (aura->GetMaxDuration() > 0) flags |= AFLAG_DURATION; data << uint8(flags); data << uint8(aura->GetCasterLevel()); data << uint8(aura->GetStackAmount() > 1 ? aura->GetStackAmount() : (aura->GetCharges()) ? aura->GetCharges() : 1); if (!(flags & AFLAG_CASTER)) data.appendPackGUID(aura->GetCasterGUID()); if (flags & AFLAG_DURATION) { data << uint32(aura->GetMaxDuration()); data << uint32(aura->GetDuration()); } m_target->SendMessageToSet(&data, true); } Aura * Aura::TryCreate(SpellEntry const* spellproto, uint8 tryEffMask, WorldObject * owner, Unit * caster, int32 *baseAmount, Item * castItem, uint64 casterGUID) { assert(spellproto); assert(owner); assert(caster || casterGUID); assert(tryEffMask <= MAX_EFFECT_MASK); uint8 effMask = 0; switch(owner->GetTypeId()) { case TYPEID_UNIT: case TYPEID_PLAYER: for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i) { if (IsUnitOwnedAuraEffect(spellproto->Effect[i])) effMask |= 1 << i; } break; case TYPEID_DYNAMICOBJECT: for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i) { if (spellproto->Effect[i] == SPELL_EFFECT_PERSISTENT_AREA_AURA) effMask |= 1 << i; } break; } if (uint8 realMask = effMask & tryEffMask) return Create(spellproto,realMask,owner,caster,baseAmount,castItem,casterGUID); return NULL; } Aura * Aura::TryCreate(SpellEntry const* spellproto, WorldObject * owner, Unit * caster, int32 *baseAmount, Item * castItem, uint64 casterGUID) { assert(spellproto); assert(owner); assert(caster || casterGUID); uint8 effMask = 0; switch(owner->GetTypeId()) { case TYPEID_UNIT: case TYPEID_PLAYER: for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i) { if (IsUnitOwnedAuraEffect(spellproto->Effect[i])) effMask |= 1 << i; } break; case TYPEID_DYNAMICOBJECT: for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i) { if (spellproto->Effect[i] == SPELL_EFFECT_PERSISTENT_AREA_AURA) effMask |= 1 << i; } break; } if (effMask) return Create(spellproto,effMask,owner,caster,baseAmount,castItem,casterGUID); return NULL; } Aura * Aura::Create(SpellEntry const* spellproto, uint8 effMask, WorldObject * owner, Unit * caster, int32 *baseAmount, Item * castItem, uint64 casterGUID) { assert(effMask); assert(spellproto); assert(owner); assert(caster || casterGUID); assert(effMask <= MAX_EFFECT_MASK); // try to get caster of aura if (casterGUID) { if (owner->GetGUID() == casterGUID) caster = (Unit *)owner; else caster = ObjectAccessor::GetUnit(*owner, casterGUID); } Aura * aura = NULL; switch(owner->GetTypeId()) { case TYPEID_UNIT: case TYPEID_PLAYER: aura = new UnitAura(spellproto,effMask,owner,caster,baseAmount,castItem, casterGUID); break; case TYPEID_DYNAMICOBJECT: aura = new DynObjAura(spellproto,effMask,owner,caster,baseAmount,castItem, casterGUID); break; default: assert(false); return NULL; } // aura can be removed in Unit::_AddAura call if (aura->IsRemoved()) return NULL; return aura; } Aura::Aura(SpellEntry const* spellproto, uint8 effMask, WorldObject * owner, Unit * caster, int32 *baseAmount, Item * castItem, uint64 casterGUID) : m_spellProto(spellproto), m_owner(owner), m_casterGuid(casterGUID ? casterGUID : caster->GetGUID()), m_castItemGuid(castItem ? castItem->GetGUID() : 0), m_applyTime(time(NULL)), m_timeCla(0), m_isSingleTarget(false), m_updateTargetMapInterval(0), m_procCharges(0), m_stackAmount(1), m_isRemoved(false), m_casterLevel(caster ? caster->getLevel() : m_spellProto->spellLevel) { if (m_spellProto->manaPerSecond || m_spellProto->manaPerSecondPerLevel) m_timeCla = 1 * IN_MILISECONDS; Player* modOwner = NULL; if (caster) { modOwner = caster->GetSpellModOwner(); m_maxDuration = caster->CalcSpellDuration(m_spellProto); } else m_maxDuration = GetSpellDuration(m_spellProto); if (IsPassive() && m_spellProto->DurationIndex == 0) m_maxDuration = -1; if (!IsPermanent() && modOwner) modOwner->ApplySpellMod(GetId(), SPELLMOD_DURATION, m_maxDuration); m_duration = m_maxDuration; m_procCharges = m_spellProto->procCharges; if (modOwner) modOwner->ApplySpellMod(GetId(), SPELLMOD_CHARGES, m_procCharges); for (uint8 i=0 ; i<MAX_SPELL_EFFECTS; ++i) { if (effMask & (uint8(1) << i)) m_effects[i] = new AuraEffect(this, i, baseAmount ? baseAmount + i : NULL, caster); else m_effects[i] = NULL; } } Aura::~Aura() { // free effects memory for (uint8 i = 0 ; i < MAX_SPELL_EFFECTS; ++i) if (m_effects[i]) delete m_effects[i]; assert(m_applications.empty()); _DeleteRemovedApplications(); } Unit* Aura::GetCaster() const { if (GetOwner()->GetGUID() == GetCasterGUID()) return GetUnitOwner(); if (AuraApplication const * aurApp = GetApplicationOfTarget(GetCasterGUID())) return aurApp->GetTarget(); return ObjectAccessor::GetUnit(*GetOwner(), GetCasterGUID()); } AuraObjectType Aura::GetType() const { return (m_owner->GetTypeId() == TYPEID_DYNAMICOBJECT) ? DYNOBJ_AURA_TYPE : UNIT_AURA_TYPE; } void Aura::_ApplyForTarget(Unit * target, Unit * caster, AuraApplication * auraApp) { assert(target); assert(auraApp); // aura mustn't be already applied assert (m_applications.find(target->GetGUID()) == m_applications.end()); m_applications[target->GetGUID()] = auraApp; // set infinity cooldown state for spells if (caster && caster->GetTypeId() == TYPEID_PLAYER) { if (m_spellProto->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) { Item* castItem = m_castItemGuid ? caster->ToPlayer()->GetItemByGuid(m_castItemGuid) : NULL; caster->ToPlayer()->AddSpellAndCategoryCooldowns(m_spellProto,castItem ? castItem->GetEntry() : 0, NULL,true); } } } void Aura::_UnapplyForTarget(Unit * target, Unit * caster, AuraApplication * auraApp) { assert(target); assert(auraApp->GetRemoveMode()); assert(auraApp); ApplicationMap::iterator itr = m_applications.find(target->GetGUID()); // aura has to be already applied assert(itr->second == auraApp); m_applications.erase(itr); m_removedApplications.push_back(auraApp); // reset cooldown state for spells if (caster && caster->GetTypeId() == TYPEID_PLAYER) { if (GetSpellProto()->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases) caster->ToPlayer()->SendCooldownEvent(GetSpellProto()); } } // removes aura from all targets // and marks aura as removed void Aura::_Remove(AuraRemoveMode removeMode) { assert (!m_isRemoved); m_isRemoved = true; ApplicationMap::iterator appItr = m_applications.begin(); while (!m_applications.empty()) { AuraApplication * aurApp = appItr->second; Unit * target = aurApp->GetTarget(); target->_UnapplyAura(aurApp, removeMode); appItr = m_applications.begin(); } } void Aura::UpdateTargetMap(Unit * caster, bool apply) { if (IsRemoved()) return; m_updateTargetMapInterval = UPDATE_TARGET_MAP_INTERVAL; // fill up to date target list // target, effMask std::map<Unit *, uint8> targets; FillTargetMap(targets, caster); UnitList targetsToRemove; // mark all auras as ready to remove for (ApplicationMap::iterator appIter = m_applications.begin(); appIter != m_applications.end();++appIter) { std::map<Unit *, uint8>::iterator existing = targets.find(appIter->second->GetTarget()); // not found in current area - remove the aura if (existing == targets.end()) targetsToRemove.push_back(appIter->second->GetTarget()); else { // needs readding - remove now, will be applied in next update cycle // (dbcs do not have auras which apply on same type of targets but have different radius, so this is not really needed) if (appIter->second->GetEffectMask() != existing->second) targetsToRemove.push_back(appIter->second->GetTarget()); // nothing todo - aura already applied // remove from auras to register list targets.erase(existing); } } // register auras for units for (std::map<Unit *, uint8>::iterator itr = targets.begin(); itr!= targets.end();) { bool addUnit = true; // check target immunities if (itr->first->IsImmunedToSpell(GetSpellProto())) addUnit = false; if (addUnit) { // persistent area aura does not hit flying targets if (GetType() == DYNOBJ_AURA_TYPE) { if (itr->first->isInFlight()) addUnit = false; } // unit auras can not stack with each other else // (GetType() == UNIT_AURA_TYPE) { // Allow to remove by stack when aura is going to be applied on owner if (itr->first != GetOwner()) { // check if not stacking aura already on target // this one prevents unwanted usefull buff loss because of stacking and prevents overriding auras periodicaly by 2 near area aura owners for (Unit::AuraApplicationMap::iterator iter = itr->first->GetAppliedAuras().begin(); iter != itr->first->GetAppliedAuras().end(); ++iter) { Aura const * aura = iter->second->GetBase(); if (!spellmgr.CanAurasStack(GetSpellProto(), aura->GetSpellProto(), aura->GetCasterGUID() == GetCasterGUID())) { addUnit = false; break; } } } } } if (!addUnit) targets.erase(itr++); else { // owner has to be in world, or effect has to be applied to self assert((!GetOwner()->IsInWorld() && GetOwner() == itr->first) || GetOwner()->IsInMap(itr->first)); itr->first->_CreateAuraApplication(this, itr->second); ++itr; } } // remove auras from units no longer needing them for (UnitList::iterator itr = targetsToRemove.begin(); itr != targetsToRemove.end();++itr) { if (AuraApplication * aurApp = GetApplicationOfTarget((*itr)->GetGUID())) (*itr)->_UnapplyAura(aurApp, AURA_REMOVE_BY_DEFAULT); } if (!apply) return; // apply aura effects for units for (std::map<Unit *, uint8>::iterator itr = targets.begin(); itr!= targets.end();++itr) { if (AuraApplication * aurApp = GetApplicationOfTarget(itr->first->GetGUID())) { // owner has to be in world, or effect has to be applied to self assert((!GetOwner()->IsInWorld() && GetOwner() == itr->first) || GetOwner()->IsInMap(itr->first)); itr->first->_ApplyAura(aurApp, itr->second); } } } // targets have to be registered and not have effect applied yet to use this function void Aura::_ApplyEffectForTargets(uint8 effIndex) { Unit * caster = GetCaster(); // prepare list of aura targets UnitList targetList; for (ApplicationMap::iterator appIter = m_applications.begin(); appIter != m_applications.end(); ++appIter) { if ((appIter->second->GetEffectsToApply() & (1<<effIndex)) && CheckTarget(appIter->second->GetTarget()) && !appIter->second->HasEffect(effIndex)) targetList.push_back(appIter->second->GetTarget()); } // apply effect to targets for (UnitList::iterator itr = targetList.begin(); itr != targetList.end(); ++itr) { if (GetApplicationOfTarget((*itr)->GetGUID())) { // owner has to be in world, or effect has to be applied to self assert((!GetOwner()->IsInWorld() && GetOwner() == *itr) || GetOwner()->IsInMap(*itr)); (*itr)->_ApplyAuraEffect(this, effIndex); } } } void Aura::UpdateOwner(uint32 diff, WorldObject * owner) { assert(owner == m_owner); Unit * caster = GetCaster(); // Apply spellmods for channeled auras // used for example when triggered spell of spell:10 is modded Spell * modSpell = NULL; Player * modOwner = NULL; if (caster) if ((modOwner = caster->GetSpellModOwner()) && (modSpell = modOwner->FindCurrentSpellBySpellId(GetId()))) modOwner->SetSpellModTakingSpell(modSpell, true); Update(diff, caster); if (m_updateTargetMapInterval <= diff) UpdateTargetMap(caster); else m_updateTargetMapInterval -= diff; // update aura effects for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (m_effects[i]) m_effects[i]->Update(diff, caster); // remove spellmods after effects update if (modSpell) modOwner->SetSpellModTakingSpell(modSpell, false); _DeleteRemovedApplications(); } void Aura::Update(uint32 diff, Unit * caster) { if (m_duration > 0) { m_duration -= diff; if (m_duration < 0) m_duration = 0; // handle manaPerSecond/manaPerSecondPerLevel if (m_timeCla) { if (m_timeCla > diff) m_timeCla -= diff; else if (caster) { if (int32 manaPerSecond = m_spellProto->manaPerSecond + m_spellProto->manaPerSecondPerLevel * caster->getLevel()) { m_timeCla += 1000 - diff; Powers powertype = Powers(m_spellProto->powerType); if (powertype == POWER_HEALTH) { if (caster->GetHealth() > manaPerSecond) caster->ModifyHealth(-manaPerSecond); else { Remove(); return; } } else { if (caster->GetPower(powertype) >= manaPerSecond) caster->ModifyPower(powertype, -manaPerSecond); else { Remove(); return; } } } } } } } bool Aura::CheckTarget(Unit *target) { // some special cases switch(GetId()) { case 45828: // AV Marshal's HP/DMG auras case 45829: case 45830: case 45821: case 45822: // AV Warmaster's HP/DMG auras case 45823: case 45824: case 45826: switch(target->GetEntry()) { // alliance case 14762: // Dun Baldar North Marshal case 14763: // Dun Baldar South Marshal case 14764: // Icewing Marshal case 14765: // Stonehearth Marshal case 11948: // Vandar Stormspike // horde case 14772: // East Frostwolf Warmaster case 14776: // Tower Point Warmaster case 14773: // Iceblood Warmaster case 14777: // West Frostwolf Warmaster case 11946: // Drek'thar return true; default: return false; break; } break; default: return true; break; } } void Aura::SetDuration(int32 duration, bool withMods) { if (withMods) { if (Unit * caster = GetCaster()) if (Player * modOwner = caster->GetSpellModOwner()) modOwner->ApplySpellMod(GetId(), SPELLMOD_DURATION, duration); } m_duration = duration; SetNeedClientUpdateForTargets(); } void Aura::RefreshDuration() { SetDuration(GetMaxDuration()); for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (m_effects[i]) m_effects[i]->ResetPeriodic(); if (m_spellProto->manaPerSecond || m_spellProto->manaPerSecondPerLevel) m_timeCla = 1 * IN_MILISECONDS; } void Aura::SetCharges(uint8 charges) { if (m_procCharges == charges) return; m_procCharges = charges; SetNeedClientUpdateForTargets(); } bool Aura::DropCharge() { if (m_procCharges) //auras without charges always have charge = 0 { if (--m_procCharges) // Send charge change SetNeedClientUpdateForTargets(); else // Last charge dropped { Remove(AURA_REMOVE_BY_EXPIRE); return true; } } return false; } void Aura::SetStackAmount(uint8 stackAmount, bool applied) { if (stackAmount != m_stackAmount) { m_stackAmount = stackAmount; RecalculateAmountOfEffects(); } SetNeedClientUpdateForTargets(); } bool Aura::ModStackAmount(int32 num) { // Can`t mod if (!m_spellProto->StackAmount || !GetStackAmount()) return true; // Modify stack but limit it int32 stackAmount = m_stackAmount + num; if (stackAmount > m_spellProto->StackAmount) stackAmount = m_spellProto->StackAmount; else if (stackAmount <= 0) // Last aura from stack removed { m_stackAmount = 0; return true; // need remove aura } bool refresh = stackAmount >= GetStackAmount(); // Update stack amount SetStackAmount(stackAmount); if (refresh) RefreshDuration(); SetNeedClientUpdateForTargets(); return false; } bool Aura::IsPassive() const { return IsPassiveSpell(GetSpellProto()); } bool Aura::IsDeathPersistent() const { return IsDeathPersistentSpell(GetSpellProto()); } bool Aura::CanBeSaved() const { if (IsPassive()) return false; if (GetCasterGUID() != GetOwner()->GetGUID()) if (IsSingleTargetSpell(GetSpellProto())) return false; // Can't be saved - aura handler relies on calculated amount and changes it if (HasEffectType(SPELL_AURA_CONVERT_RUNE)) return false; return true; } bool Aura::HasEffectType(AuraType type) const { for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (m_effects[i] && m_effects[i]->GetAuraType() == type) return true; } return false; } void Aura::RecalculateAmountOfEffects() { assert (!IsRemoved()); Unit * caster = GetCaster(); for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (m_effects[i]) m_effects[i]->RecalculateAmount(caster); } void Aura::HandleAllEffects(AuraApplication const * aurApp, uint8 mode, bool apply) { assert (!IsRemoved()); for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (m_effects[i] && !IsRemoved()) m_effects[i]->HandleEffect(aurApp, mode, apply); } bool Aura::IsVisible() const { // Is this blizzlike? show totem passive auras if (GetOwner()->GetTypeId() == TYPEID_UNIT && m_owner->ToCreature()->isTotem() && IsPassive()) return true; return !IsPassive() || HasEffectType(SPELL_AURA_ABILITY_IGNORE_AURASTATE); } void Aura::UnregisterSingleTarget() { assert(m_isSingleTarget); Unit * caster = GetCaster(); caster->GetSingleCastAuras().remove(this); SetIsSingleTarget(false); } void Aura::SetLoadedState(int32 maxduration, int32 duration, int32 charges, uint8 stackamount, uint8 recalculateMask, int32 * amount) { m_maxDuration = maxduration; m_duration = duration; m_procCharges = charges; m_stackAmount = stackamount; Unit * caster = GetCaster(); for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (m_effects[i]) { m_effects[i]->SetAmount(amount[i]); m_effects[i]->SetCanBeRecalculated(recalculateMask & (1<<i)); m_effects[i]->CalculatePeriodic(caster); m_effects[i]->CalculateSpellMod(); m_effects[i]->RecalculateAmount(caster); } } // trigger effects on real aura apply/remove void Aura::HandleAuraSpecificMods(AuraApplication const * aurApp, Unit * caster, bool apply) { Unit * target = aurApp->GetTarget(); AuraRemoveMode removeMode = aurApp->GetRemoveMode(); // spell_area table SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAuraMapBounds(GetId()); if (saBounds.first != saBounds.second) { uint32 zone, area; target->GetZoneAndAreaId(zone,area); for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr) { // some auras remove at aura remove if (!itr->second->IsFitToRequirements((Player*)target,zone,area)) target->RemoveAurasDueToSpell(itr->second->spellId); // some auras applied at aura apply else if (itr->second->autocast) { if (!target->HasAura(itr->second->spellId)) target->CastSpell(target,itr->second->spellId,true); } } } // mods at aura apply if (apply) { // Apply linked auras (On first aura apply) if (spellmgr.GetSpellCustomAttr(GetId()) & SPELL_ATTR_CU_LINK_AURA) { if (const std::vector<int32> *spell_triggered = spellmgr.GetSpellLinked(GetId() + SPELL_LINK_AURA)) for (std::vector<int32>::const_iterator itr = spell_triggered->begin(); itr != spell_triggered->end(); ++itr) { if (*itr < 0) target->ApplySpellImmune(GetId(), IMMUNITY_ID, -(*itr), true); else if (caster) caster->AddAura(*itr, target); } } switch (GetSpellProto()->SpellFamilyName) { case SPELLFAMILY_GENERIC: switch(GetId()) { case 32474: // Buffeting Winds of Susurrus if (target->GetTypeId() == TYPEID_PLAYER) target->ToPlayer()->ActivateTaxiPathTo(506, GetId()); break; case 33572: // Gronn Lord's Grasp, becomes stoned if (GetStackAmount() >= 5 && !target->HasAura(33652)) target->CastSpell(target, 33652, true); break; case 60970: // Heroic Fury (remove Intercept cooldown) if (target->GetTypeId() == TYPEID_PLAYER) target->ToPlayer()->RemoveSpellCooldown(20252, true); break; } break; case SPELLFAMILY_MAGE: if (!caster) break; if (GetSpellProto()->SpellFamilyFlags[0] & 0x00000001 && GetSpellProto()->SpellFamilyFlags[2] & 0x00000008) { // Glyph of Fireball if (caster->HasAura(56368)) SetDuration(0); } else if (GetSpellProto()->SpellFamilyFlags[0] & 0x00000020 && GetSpellProto()->SpellVisual[0] == 13) { // Glyph of Frostbolt if (caster->HasAura(56370)) SetDuration(0); } // Todo: This should be moved to similar function in spell::hit else if (GetSpellProto()->SpellFamilyFlags[0] & 0x01000000) { // Polymorph Sound - Sheep && Penguin if (GetSpellProto()->SpellIconID == 82 && GetSpellProto()->SpellVisual[0] == 12978) { // Glyph of the Penguin if (caster->HasAura(52648)) caster->CastSpell(target,61635,true); else caster->CastSpell(target,61634,true); } } switch(GetId()) { case 12536: // Clearcasting case 12043: // Presence of Mind // Arcane Potency if (AuraEffect const * aurEff = caster->GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_MAGE, 2120, 0)) { if (roll_chance_i(aurEff->GetAmount())) { uint32 spellId = 0; switch (aurEff->GetId()) { case 31571: spellId = 57529; break; case 31572: spellId = 57531; break; default: sLog.outError("Aura::HandleAuraSpecificMods: Unknown rank of Arcane Potency (%d) found", aurEff->GetId()); } if (spellId) caster->CastSpell(caster, spellId, true); } } break; } break; case SPELLFAMILY_WARLOCK: switch(GetId()) { case 48020: // Demonic Circle if (target->GetTypeId() == TYPEID_PLAYER) if (GameObject* obj = target->GetGameObject(48018)) { target->ToPlayer()->TeleportTo(obj->GetMapId(),obj->GetPositionX(),obj->GetPositionY(),obj->GetPositionZ(),obj->GetOrientation()); target->ToPlayer()->RemoveMovementImpairingAuras(); } break; } break; case SPELLFAMILY_PRIEST: if (!caster) break; // Devouring Plague if (GetSpellProto()->SpellFamilyFlags[0] & 0x02000000 && GetEffect(0)) { // Improved Devouring Plague if (AuraEffect const * aurEff = caster->GetDummyAuraEffect(SPELLFAMILY_PRIEST, 3790, 1)) { int32 basepoints0 = aurEff->GetAmount() * GetEffect(0)->GetTotalTicks() * GetEffect(0)->GetAmount() / 100; caster->CastCustomSpell(target, 63675, &basepoints0, NULL, NULL, true, NULL, GetEffect(0)); } } // Renew else if (GetSpellProto()->SpellFamilyFlags[0] & 0x00000040 && GetEffect(0)) { // Empowered Renew if (AuraEffect const * aurEff = caster->GetDummyAuraEffect(SPELLFAMILY_PRIEST, 3021, 1)) { int32 basepoints0 = aurEff->GetAmount() * GetEffect(0)->GetTotalTicks() * caster->SpellHealingBonus(target, GetSpellProto(), GetEffect(0)->GetAmount(), HEAL) / 100; caster->CastCustomSpell(target, 63544, &basepoints0, NULL, NULL, true, NULL, GetEffect(0)); } } // Power Word: Shield else if (m_spellProto->SpellFamilyFlags[0] & 0x1 && m_spellProto->SpellFamilyFlags[2] & 0x400 && GetEffect(0)) { // Glyph of Power Word: Shield if (AuraEffect* glyph = caster->GetAuraEffect(55672,0)) { // instantly heal m_amount% of the absorb-value int32 heal = glyph->GetAmount() * GetEffect(0)->GetAmount()/100; caster->CastCustomSpell(GetUnitOwner(), 56160, &heal, NULL, NULL, true, 0, GetEffect(0)); } } break; case SPELLFAMILY_ROGUE: // Sprint (skip non player casted spells by category) if (GetSpellProto()->SpellFamilyFlags[0] & 0x40 && GetSpellProto()->Category == 44) // in official maybe there is only one icon? if (target->HasAura(58039)) // Glyph of Blurred Speed target->CastSpell(target, 61922, true); // Sprint (waterwalk) break; case SPELLFAMILY_DEATHKNIGHT: if (!caster) break; // Frost Fever and Blood Plague if (GetSpellProto()->SpellFamilyFlags[2] & 0x2) { // Can't proc on self if (GetCasterGUID() == target->GetGUID()) break; AuraEffect * aurEff = NULL; // Ebon Plaguebringer / Crypt Fever Unit::AuraEffectList const& TalentAuras = caster->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); for (Unit::AuraEffectList::const_iterator itr = TalentAuras.begin(); itr != TalentAuras.end(); ++itr) { if ((*itr)->GetMiscValue() == 7282) { aurEff = *itr; // Ebon Plaguebringer - end search if found if ((*itr)->GetSpellProto()->SpellIconID == 1766) break; } } if (aurEff) { uint32 spellId = 0; switch (aurEff->GetId()) { // Ebon Plague case 51161: spellId = 51735; break; case 51160: spellId = 51734; break; case 51099: spellId = 51726; break; // Crypt Fever case 49632: spellId = 50510; break; case 49631: spellId = 50509; break; case 49032: spellId = 50508; break; default: sLog.outError("Aura::HandleAuraSpecificMods: Unknown rank of Crypt Fever/Ebon Plague (%d) found", aurEff->GetId()); } caster->CastSpell(target, spellId, true, 0, GetEffect(0)); } } break; } } // mods at aura remove else { // Remove Linked Auras if (removeMode != AURA_REMOVE_BY_STACK && removeMode != AURA_REMOVE_BY_DEATH) { if (uint32 customAttr = spellmgr.GetSpellCustomAttr(GetId())) { if (customAttr & SPELL_ATTR_CU_LINK_REMOVE) { if (const std::vector<int32> *spell_triggered = spellmgr.GetSpellLinked(-(int32)GetId())) for (std::vector<int32>::const_iterator itr = spell_triggered->begin(); itr != spell_triggered->end(); ++itr) { if (*itr < 0) target->RemoveAurasDueToSpell(-(*itr)); else if (removeMode != AURA_REMOVE_BY_DEFAULT) target->CastSpell(target, *itr, true, 0, 0, GetCasterGUID()); } } if (customAttr & SPELL_ATTR_CU_LINK_AURA) { if (const std::vector<int32> *spell_triggered = spellmgr.GetSpellLinked(GetId() + SPELL_LINK_AURA)) for (std::vector<int32>::const_iterator itr = spell_triggered->begin(); itr != spell_triggered->end(); ++itr) { if (*itr < 0) target->ApplySpellImmune(GetId(), IMMUNITY_ID, -(*itr), false); else target->RemoveAurasDueToSpell(*itr); } } } } switch(GetSpellProto()->SpellFamilyName) { case SPELLFAMILY_GENERIC: // Remove the immunity shield marker on Avenging Wrath removal if Forbearance is not present if (GetId() == 61987 && target->HasAura(61988) && !target->HasAura(25771)) target->RemoveAura(61988); break; case SPELLFAMILY_MAGE: switch(GetId()) { case 66: // Invisibility if (removeMode != AURA_REMOVE_BY_EXPIRE) break; target->CastSpell(target, 32612, true, NULL, GetEffect(1)); break; } if (!caster) break; // Ice barrier - dispel/absorb remove if (removeMode == AURA_REMOVE_BY_ENEMY_SPELL && GetSpellProto()->SpellFamilyFlags[1] & 0x1) { // Shattered Barrier if (caster->GetDummyAuraEffect(SPELLFAMILY_MAGE, 2945, 0)) caster->CastSpell(target, 55080, true, NULL, GetEffect(0)); } break; case SPELLFAMILY_WARRIOR: if (!caster) break; // Spell Reflection if (GetSpellProto()->SpellFamilyFlags[1] & 0x2) { if (removeMode != AURA_REMOVE_BY_DEFAULT) { // Improved Spell Reflection if (caster->GetDummyAuraEffect(SPELLFAMILY_WARRIOR,1935, 1)) { // aura remove - remove auras from all party members std::list<Unit*> PartyMembers; target->GetPartyMembers(PartyMembers); for (std::list<Unit*>::iterator itr = PartyMembers.begin(); itr != PartyMembers.end(); ++itr) { if ((*itr)!= target) (*itr)->RemoveAurasWithFamily(SPELLFAMILY_WARRIOR, 0, 0x2, 0, GetCasterGUID()); } } } } break; case SPELLFAMILY_WARLOCK: if (!caster) break; // Curse of Doom if (GetSpellProto()->SpellFamilyFlags[1] & 0x02) { if (removeMode == AURA_REMOVE_BY_DEATH) { if (caster->GetTypeId() == TYPEID_PLAYER && caster->ToPlayer()->isHonorOrXPTarget(target)) caster->CastSpell(target, 18662, true, NULL, GetEffect(0)); } } // Improved Fear else if (GetSpellProto()->SpellFamilyFlags[1] & 0x00000400) { if (AuraEffect* aurEff = caster->GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_WARLOCK, 98, 0)) { uint32 spellId = 0; switch (aurEff->GetId()) { case 53759: spellId = 60947; break; case 53754: spellId = 60946; break; default: sLog.outError("Aura::HandleAuraSpecificMods: Unknown rank of Improved Fear (%d) found", aurEff->GetId()); } if (spellId) caster->CastSpell(target, spellId, true); } } switch(GetId()) { case 48018: // Demonic Circle // Do not remove GO when aura is removed by stack // to prevent remove GO added by new spell // old one is already removed if (removeMode != AURA_REMOVE_BY_STACK) target->RemoveGameObject(GetId(), true); target->RemoveAura(62388); break; } break; case SPELLFAMILY_PRIEST: if (!caster) break; // Shadow word: Pain // Vampiric Touch if (removeMode == AURA_REMOVE_BY_ENEMY_SPELL && (GetSpellProto()->SpellFamilyFlags[0] & 0x00008000 || GetSpellProto()->SpellFamilyFlags[1] & 0x00000400)) { // Shadow Affinity if (AuraEffect const * aurEff = caster->GetDummyAuraEffect(SPELLFAMILY_PRIEST, 178, 1)) { int32 basepoints0 = aurEff->GetAmount() * caster->GetCreateMana() / 100; caster->CastCustomSpell(caster, 64103, &basepoints0, NULL, NULL, true, NULL, GetEffect(0)); } } // Power word: shield else if (removeMode == AURA_REMOVE_BY_ENEMY_SPELL && GetSpellProto()->SpellFamilyFlags[0] & 0x00000001) { // Rapture if (Aura const * aura = caster->GetAuraOfRankedSpell(47535)) { // check cooldown if (caster->GetTypeId() == TYPEID_PLAYER) { if (caster->ToPlayer()->HasSpellCooldown(aura->GetId())) break; // and add if needed caster->ToPlayer()->AddSpellCooldown(aura->GetId(), 0, uint32(time(NULL) + 12)); } // effect on caster if (AuraEffect const * aurEff = aura->GetEffect(0)) { float multiplier = aurEff->GetAmount(); if (aurEff->GetId() == 47535) multiplier -= 0.5f; else if (aurEff->GetId() == 47537) multiplier += 0.5f; int32 basepoints0 = (multiplier * caster->GetMaxPower(POWER_MANA) / 100); caster->CastCustomSpell(caster, 47755, &basepoints0, NULL, NULL, true); } // effect on aura target if (AuraEffect const * aurEff = aura->GetEffect(1)) { if (!roll_chance_i(aurEff->GetAmount())) break; int32 triggeredSpellId = 0; switch(target->getPowerType()) { case POWER_MANA: { int32 basepoints0 = 2 * (target->GetMaxPower(POWER_MANA) / 100); caster->CastCustomSpell(target, 63654, &basepoints0, NULL, NULL, true); break; } case POWER_RAGE: triggeredSpellId = 63653; break; case POWER_ENERGY: triggeredSpellId = 63655; break; case POWER_RUNIC_POWER: triggeredSpellId = 63652; break; } if (triggeredSpellId) caster->CastSpell(target, triggeredSpellId, true); } } } switch(GetId()) { case 47788: // Guardian Spirit if (removeMode != AURA_REMOVE_BY_EXPIRE) break; if (caster->GetTypeId() != TYPEID_PLAYER) break; Player *player = caster->ToPlayer(); // Glyph of Guardian Spirit if (AuraEffect * aurEff = player->GetAuraEffect(63231, 0)) { if (!player->HasSpellCooldown(47788)) break; player->RemoveSpellCooldown(GetSpellProto()->Id, true); player->AddSpellCooldown(GetSpellProto()->Id, 0, uint32(time(NULL) + aurEff->GetAmount())); WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4+4); data << uint64(player->GetGUID()); data << uint8(0x0); // flags (0x1, 0x2) data << uint32(GetSpellProto()->Id); data << uint32(aurEff->GetAmount()*IN_MILISECONDS); player->SendDirectMessage(&data); } break; } break; case SPELLFAMILY_PALADIN: // Remove the immunity shield marker on Forbearance removal if AW marker is not present if (GetId() == 25771 && target->HasAura(61988) && !target->HasAura(61987)) target->RemoveAura(61988); break; case SPELLFAMILY_DEATHKNIGHT: // Blood of the North // Reaping // Death Rune Mastery if (GetSpellProto()->SpellIconID == 3041 || GetSpellProto()->SpellIconID == 22 || GetSpellProto()->SpellIconID == 2622) { if (!GetEffect(0) || GetEffect(0)->GetAuraType() != SPELL_AURA_PERIODIC_DUMMY) break; if (target->GetTypeId() != TYPEID_PLAYER) break; if (target->ToPlayer()->getClass() != CLASS_DEATH_KNIGHT) break; // aura removed - remove death runes target->ToPlayer()->RemoveRunesByAuraEffect(GetEffect(0)); } switch(GetId()) { case 50514: // Summon Gargoyle if (removeMode != AURA_REMOVE_BY_EXPIRE) break; target->CastSpell(target, GetEffect(0)->GetAmount(), true, NULL, GetEffect(0)); break; } break; } } // mods at aura apply or remove switch (GetSpellProto()->SpellFamilyName) { case SPELLFAMILY_ROGUE: // Stealth if (GetSpellProto()->SpellFamilyFlags[0] & 0x00400000) { // Master of subtlety if (AuraEffect const * aurEff = target->GetAuraEffectOfRankedSpell(31221, 0)) { if (!apply) target->CastSpell(target,31666,true); else { int32 basepoints0 = aurEff->GetAmount(); target->CastCustomSpell(target,31665, &basepoints0, NULL, NULL ,true); } } // Overkill if (target->HasAura(58426)) { if (!apply) target->CastSpell(target,58428,true); else target->CastSpell(target,58427,true); } break; } break; case SPELLFAMILY_HUNTER: switch(GetId()) { case 19574: // Bestial Wrath // The Beast Within cast on owner if talent present if (Unit* owner = target->GetOwner()) { // Search talent if (owner->HasAura(34692)) { if (apply) owner->CastSpell(owner, 34471, true, 0, GetEffect(0)); else owner->RemoveAurasDueToSpell(34471); } } break; } break; case SPELLFAMILY_PALADIN: switch(GetId()) { case 19746: case 31821: // Aura Mastery Triggered Spell Handler // If apply Concentration Aura -> trigger -> apply Aura Mastery Immunity // If remove Concentration Aura -> trigger -> remove Aura Mastery Immunity // If remove Aura Mastery -> trigger -> remove Aura Mastery Immunity // Do effects only on aura owner if (GetCasterGUID() != target->GetGUID()) break; if (apply) { if ((GetSpellProto()->Id == 31821 && target->HasAura(19746, GetCasterGUID())) || (GetSpellProto()->Id == 19746 && target->HasAura(31821))) target->CastSpell(target,64364,true); } else target->RemoveAurasDueToSpell(64364, GetCasterGUID()); break; } break; case SPELLFAMILY_DEATHKNIGHT: if (GetSpellSpecific(GetSpellProto()) == SPELL_SPECIFIC_PRESENCE) { AuraEffect *bloodPresenceAura=0; // healing by damage done AuraEffect *frostPresenceAura=0; // increased health AuraEffect *unholyPresenceAura=0; // increased movement speed, faster rune recovery // Improved Presences Unit::AuraEffectList const& vDummyAuras = target->GetAuraEffectsByType(SPELL_AURA_DUMMY); for (Unit::AuraEffectList::const_iterator itr = vDummyAuras.begin(); itr != vDummyAuras.end(); ++itr) { switch((*itr)->GetId()) { // Improved Blood Presence case 50365: case 50371: { bloodPresenceAura = (*itr); break; } // Improved Frost Presence case 50384: case 50385: { frostPresenceAura = (*itr); break; } // Improved Unholy Presence case 50391: case 50392: { unholyPresenceAura = (*itr); break; } } } uint32 presence=GetId(); if (apply) { // Blood Presence bonus if (presence == 48266) target->CastSpell(target, 63611, true); else if (bloodPresenceAura) { int32 basePoints1=bloodPresenceAura->GetAmount(); target->CastCustomSpell(target,63611,NULL,&basePoints1,NULL,true,0,bloodPresenceAura); } // Frost Presence bonus if (presence == 48263) target->CastSpell(target, 61261, true); else if (frostPresenceAura) { int32 basePoints0=frostPresenceAura->GetAmount(); target->CastCustomSpell(target,61261,&basePoints0,NULL,NULL,true,0,frostPresenceAura); } // Unholy Presence bonus if (presence == 48265) { if (unholyPresenceAura) { // Not listed as any effect, only base points set int32 basePoints0 = unholyPresenceAura->GetSpellProto()->EffectBasePoints[1]; target->CastCustomSpell(target,63622,&basePoints0 ,&basePoints0,&basePoints0,true,0,unholyPresenceAura); target->CastCustomSpell(target,65095,&basePoints0 ,NULL,NULL,true,0,unholyPresenceAura); } target->CastSpell(target,49772, true); } else if (unholyPresenceAura) { int32 basePoints0=unholyPresenceAura->GetAmount(); target->CastCustomSpell(target,49772,&basePoints0,NULL,NULL,true,0,unholyPresenceAura); } } else { // Remove passive auras if (presence == 48266 || bloodPresenceAura) target->RemoveAurasDueToSpell(63611); if (presence == 48263 || frostPresenceAura) target->RemoveAurasDueToSpell(61261); if (presence == 48265 || unholyPresenceAura) { if (presence == 48265 && unholyPresenceAura) { target->RemoveAurasDueToSpell(63622); target->RemoveAurasDueToSpell(65095); } target->RemoveAurasDueToSpell(49772); } } } break; case SPELLFAMILY_WARLOCK: // Drain Soul - If the target is at or below 25% health, Drain Soul causes four times the normal damage if (GetSpellProto()->SpellFamilyFlags[0] & 0x00004000) { if (!caster) break; if (apply) { if (target != caster && target->GetHealth() <= target->GetMaxHealth() / 4) caster->CastSpell(caster, 200000, true); } else { if (target != caster) caster->RemoveAurasDueToSpell(GetId()); else caster->RemoveAurasDueToSpell(200000); } } break; } } void Aura::SetNeedClientUpdateForTargets() const { for (ApplicationMap::const_iterator appIter = m_applications.begin(); appIter != m_applications.end(); ++appIter) appIter->second->SetNeedClientUpdate(); } void Aura::_DeleteRemovedApplications() { while (!m_removedApplications.empty()) { delete m_removedApplications.front(); m_removedApplications.pop_front(); } } UnitAura::UnitAura(SpellEntry const* spellproto, uint8 effMask, WorldObject * owner, Unit * caster, int32 *baseAmount, Item * castItem, uint64 casterGUID) : Aura(spellproto, effMask, owner, caster, baseAmount, castItem, casterGUID) { m_AuraDRGroup = DIMINISHING_NONE; GetUnitOwner()->_AddAura(this, caster); }; void UnitAura::_ApplyForTarget(Unit * target, Unit * caster, AuraApplication * aurApp) { Aura::_ApplyForTarget(target, caster, aurApp); // register aura diminishing on apply if (DiminishingGroup group = GetDiminishGroup()) target->ApplyDiminishingAura(group,true); } void UnitAura::_UnapplyForTarget(Unit * target, Unit * caster, AuraApplication * aurApp) { Aura::_UnapplyForTarget(target, caster, aurApp); // unregister aura diminishing (and store last time) if (DiminishingGroup group = GetDiminishGroup()) target->ApplyDiminishingAura(group,false); } void UnitAura::Remove(AuraRemoveMode removeMode) { if (IsRemoved()) return; GetUnitOwner()->RemoveOwnedAura(this, removeMode); } void UnitAura::FillTargetMap(std::map<Unit *, uint8> & targets, Unit * caster) { Player * modOwner = NULL; if (caster) modOwner = caster->GetSpellModOwner(); for (uint8 effIndex = 0; effIndex < MAX_SPELL_EFFECTS ; ++effIndex) { if (!HasEffect(effIndex)) continue; UnitList targetList; // non-area aura if (GetSpellProto()->Effect[effIndex] == SPELL_EFFECT_APPLY_AURA) { targetList.push_back(GetUnitOwner()); } else { float radius; if (GetSpellProto()->Effect[effIndex] == SPELL_EFFECT_APPLY_AREA_AURA_ENEMY) radius = GetSpellRadiusForHostile(sSpellRadiusStore.LookupEntry(GetSpellProto()->EffectRadiusIndex[effIndex])); else radius = GetSpellRadiusForFriend(sSpellRadiusStore.LookupEntry(GetSpellProto()->EffectRadiusIndex[effIndex])); if (modOwner) modOwner->ApplySpellMod(GetId(), SPELLMOD_RADIUS, radius); if (!GetUnitOwner()->hasUnitState(UNIT_STAT_ISOLATED)) { switch(GetSpellProto()->Effect[effIndex]) { case SPELL_EFFECT_APPLY_AREA_AURA_PARTY: targetList.push_back(GetUnitOwner()); GetUnitOwner()->GetPartyMemberInDist(targetList, radius); break; case SPELL_EFFECT_APPLY_AREA_AURA_RAID: targetList.push_back(GetUnitOwner()); GetUnitOwner()->GetRaidMember(targetList, radius); break; case SPELL_EFFECT_APPLY_AREA_AURA_FRIEND: { targetList.push_back(GetUnitOwner()); Trinity::AnyFriendlyUnitInObjectRangeCheck u_check(GetUnitOwner(), GetUnitOwner(), radius); Trinity::UnitListSearcher<Trinity::AnyFriendlyUnitInObjectRangeCheck> searcher(GetUnitOwner(), targetList, u_check); GetUnitOwner()->VisitNearbyObject(radius, searcher); break; } case SPELL_EFFECT_APPLY_AREA_AURA_ENEMY: { Trinity::AnyAoETargetUnitInObjectRangeCheck u_check(GetUnitOwner(), GetUnitOwner(), radius); // No GetCharmer in searcher Trinity::UnitListSearcher<Trinity::AnyAoETargetUnitInObjectRangeCheck> searcher(GetUnitOwner(), targetList, u_check); GetUnitOwner()->VisitNearbyObject(radius, searcher); break; } case SPELL_EFFECT_APPLY_AREA_AURA_PET: targetList.push_back(GetUnitOwner()); case SPELL_EFFECT_APPLY_AREA_AURA_OWNER: { if (Unit *owner = GetUnitOwner()->GetCharmerOrOwner()) if (GetUnitOwner()->IsWithinDistInMap(owner, radius)) targetList.push_back(owner); break; } } } } for (UnitList::iterator itr = targetList.begin(); itr!= targetList.end();++itr) { std::map<Unit *, uint8>::iterator existing = targets.find(*itr); if (existing != targets.end()) existing->second |= 1<<effIndex; else targets[*itr] = 1<<effIndex; } } } DynObjAura::DynObjAura(SpellEntry const* spellproto, uint8 effMask, WorldObject * owner, Unit * caster, int32 *baseAmount, Item * castItem, uint64 casterGUID) : Aura(spellproto, effMask, owner, caster, baseAmount, castItem, casterGUID) { GetDynobjOwner()->SetAura(this); } void DynObjAura::Remove(AuraRemoveMode removeMode) { if (IsRemoved()) return; _Remove(removeMode); } void DynObjAura::FillTargetMap(std::map<Unit *, uint8> & targets, Unit * caster) { Unit * dynObjOwnerCaster = GetDynobjOwner()->GetCaster(); float radius = GetDynobjOwner()->GetRadius(); for (uint8 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) { if (!HasEffect(effIndex)) continue; UnitList targetList; if (GetSpellProto()->EffectImplicitTargetB[effIndex] == TARGET_DEST_DYNOBJ_ALLY || GetSpellProto()->EffectImplicitTargetB[effIndex] == TARGET_UNIT_AREA_ALLY_DST) { Trinity::AnyFriendlyUnitInObjectRangeCheck u_check(GetDynobjOwner(), dynObjOwnerCaster, radius); Trinity::UnitListSearcher<Trinity::AnyFriendlyUnitInObjectRangeCheck> searcher(GetDynobjOwner(), targetList, u_check); GetDynobjOwner()->VisitNearbyObject(radius, searcher); } else { Trinity::AnyAoETargetUnitInObjectRangeCheck u_check(GetDynobjOwner(), dynObjOwnerCaster, radius); Trinity::UnitListSearcher<Trinity::AnyAoETargetUnitInObjectRangeCheck> searcher(GetDynobjOwner(), targetList, u_check); GetDynobjOwner()->VisitNearbyObject(radius, searcher); } for (UnitList::iterator itr = targetList.begin(); itr!= targetList.end();++itr) { std::map<Unit *, uint8>::iterator existing = targets.find(*itr); if (existing != targets.end()) existing->second |= 1<<effIndex; else targets[*itr] = 1<<effIndex; } } }
Muglackh/cejkaz-tc
src/game/SpellAuras.cpp
C++
gpl-2.0
65,021
using OpenDBDiff.Abstractions.Schema; using OpenDBDiff.Abstractions.Schema.Model; using System; using System.Linq; namespace OpenDBDiff.SqlServer.Schema.Model { public class Columns<T> : SchemaList<Column, T> where T : ISchemaBase { public Columns(T parent) : base(parent) { } /// <summary> /// Clona el objeto Columns en una nueva instancia. /// </summary> public new Columns<T> Clone(T parentObject) { Columns<T> columns = new Columns<T>(parentObject); for (int index = 0; index < this.Count; index++) { columns.Add(this[index].Clone(parentObject)); } return columns; } public override string ToSql() { return string.Join ( ",\r\n", this .Where(c => !c.HasState(ObjectStatus.Drop)) .Select(c => "\t" + c.ToSql(true)) ); } public override SQLScriptList ToSqlDiff(System.Collections.Generic.ICollection<ISchemaBase> schemas) { string sqlDrop = ""; string sqlAdd = ""; string sqlCons = ""; string sqlBinds = ""; SQLScriptList list = new SQLScriptList(); if (Parent.Status != ObjectStatus.Rebuild) { this.ForEach(item => { bool isIncluded = schemas.Count == 0; if (!isIncluded) { foreach (var selectedSchema in schemas) { if (selectedSchema.Id == item.Id) { isIncluded = true; break; } } } if (isIncluded) { if (item.HasState(ObjectStatus.Drop)) { if (item.DefaultConstraint != null) list.Add(item.DefaultConstraint.Drop()); /*Si la columna formula debe ser eliminada y ya fue efectuada la operacion en otro momento, no * se borra nuevamente*/ if (!item.GetWasInsertInDiffList(ScriptAction.AlterColumnFormula)) sqlDrop += "[" + item.Name + "],"; } if (item.HasState(ObjectStatus.Create)) sqlAdd += "\r\n" + item.ToSql(true) + ","; if ((item.HasState(ObjectStatus.Alter) || (item.HasState(ObjectStatus.RebuildDependencies)))) { if ((!item.Parent.HasState(ObjectStatus.RebuildDependencies) || (!item.Parent.HasState(ObjectStatus.Rebuild)))) list.AddRange(item.RebuildSchemaBindingDependencies()); list.AddRange(item.RebuildConstraint(false)); list.AddRange(item.RebuildDependencies()); list.AddRange(item.Alter(ScriptAction.AlterTable)); } if (item.HasState(ObjectStatus.Update)) list.Add("UPDATE " + Parent.FullName + " SET [" + item.Name + "] = " + item.DefaultForceValue + " WHERE [" + item.Name + "] IS NULL\r\nGO\r\n", 0, ScriptAction.UpdateTable); if (item.HasState(ObjectStatus.Bind)) { if (item.Rule.Id != 0) sqlBinds += item.Rule.ToSQLAddBind(); if (item.Rule.Id == 0) sqlBinds += item.Rule.ToSQLAddUnBind(); } if (item.DefaultConstraint != null) list.AddRange(item.DefaultConstraint.ToSqlDiff(schemas)); } }); if (!String.IsNullOrEmpty(sqlDrop)) sqlDrop = "ALTER TABLE " + Parent.FullName + " DROP COLUMN " + sqlDrop.Substring(0, sqlDrop.Length - 1) + "\r\nGO\r\n"; if (!String.IsNullOrEmpty(sqlAdd)) sqlAdd = "ALTER TABLE " + Parent.FullName + " ADD " + sqlAdd.Substring(0, sqlAdd.Length - 1) + "\r\nGO\r\n"; if (!String.IsNullOrEmpty(sqlDrop + sqlAdd + sqlCons + sqlBinds)) list.Add(sqlDrop + sqlAdd + sqlBinds, 0, ScriptAction.AlterTable); } else { this.ForEach(item => { if (item.Status != ObjectStatus.Original) item.RootParent.ActionMessage[item.Parent.FullName].Add(item); }); } return list; } } }
OpenDBDiff/OpenDBDiff
OpenDBDiff.SqlServer.Schema/Model/Columns.cs
C#
gpl-2.0
4,997
#pragma once #include <obs.hpp> #include <map> const std::map<int, const char*> &GetAACEncoderBitrateMap(); const char *GetAACEncoderForBitrate(int bitrate); int FindClosestAvailableAACBitrate(int bitrate);
JohnnyLeone/obs-studio
UI/audio-encoders.hpp
C++
gpl-2.0
210
<?php /** * @package snow-monkey * @author inc2734 * @license GPL-2.0+ * @version 15.13.0 */ use Inc2734\WP_Customizer_Framework\Framework; use Framework\Helper; Framework::control( 'select', 'footer-widget-area-column-size', [ 'label' => __( 'Number of columns in the footer widget area on PC', 'snow-monkey' ), 'priority' => 110, 'default' => '1-4', 'choices' => [ '1-1' => __( '1 column', 'snow-monkey' ), '1-2' => __( '2 columns', 'snow-monkey' ), '1-3' => __( '3 columns', 'snow-monkey' ), '1-4' => __( '4 columns', 'snow-monkey' ), ], 'active_callback' => function() { return Helper::is_active_sidebar( 'footer-widget-area' ); }, ] ); if ( ! is_customize_preview() ) { return; } $panel = Framework::get_panel( 'design' ); $section = Framework::get_section( 'footer' ); $control = Framework::get_control( 'footer-widget-area-column-size' ); $control->join( $section )->join( $panel );
inc2734/snow-monkey
app/customizer/design/sections/footer/controls/footer-widget-area-column-size.php
PHP
gpl-2.0
968
// license:BSD-3-Clause // copyright-holders:Curt Coder /********************************************************************** Kempston Disk Interface emulation **********************************************************************/ #include "kempston_di.h" //************************************************************************** // DEVICE DEFINITIONS //************************************************************************** const device_type KEMPSTON_DISK_INTERFACE = &device_creator<kempston_disk_interface_t>; //------------------------------------------------- // ROM( kempston_disk_system ) //------------------------------------------------- ROM_START( kempston_disk_system ) ROM_REGION( 0x2000, "rom", 0 ) ROM_DEFAULT_BIOS("v114") ROM_SYSTEM_BIOS( 0, "v114", "v1.14" ) ROMX_LOAD( "kempston_disk_system_v1.14_1984.rom", 0x0000, 0x2000, CRC(0b70ad2e) SHA1(ff8158d25864d920f3f6df259167e91c2784692c), ROM_BIOS(1) ) ROM_END //------------------------------------------------- // rom_region - device-specific ROM region //------------------------------------------------- const tiny_rom_entry *kempston_disk_interface_t::device_rom_region() const { return ROM_NAME( kempston_disk_system ); } //************************************************************************** // LIVE DEVICE //************************************************************************** //------------------------------------------------- // kempston_disk_interface_t - constructor //------------------------------------------------- kempston_disk_interface_t::kempston_disk_interface_t(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) : device_t(mconfig, KEMPSTON_DISK_INTERFACE, "Kempston Disk Interface", tag, owner, clock, "ql_kdi", __FILE__), device_ql_expansion_card_interface(mconfig, *this) { } //------------------------------------------------- // device_start - device-specific startup //------------------------------------------------- void kempston_disk_interface_t::device_start() { } //------------------------------------------------- // read - //------------------------------------------------- UINT8 kempston_disk_interface_t::read(address_space &space, offs_t offset, UINT8 data) { return data; } //------------------------------------------------- // write - //------------------------------------------------- void kempston_disk_interface_t::write(address_space &space, offs_t offset, UINT8 data) { }
GiuseppeGorgoglione/mame
src/devices/bus/ql/kempston_di.cpp
C++
gpl-2.0
2,486
//////////////////////////////////////////////////////////////////////////////// // // Copyright 2016 RWS Inc, All Rights Reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of version 2 of the GNU General Public License as published by // the Free Software Foundation // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // 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 // // fire.cpp // Project: Postal // // This module implements the CFire weapon class which is a burning flame // for several different effects and weapons. // // // History: // 01/17/97 BRH Started this weapon object. // // 01/23/97 BRH Updated the time to GetGameTime rather than using // real time.. // // 02/04/97 JMI Changed LoadDib() call to Load() (which now supports // loading of DIBs). // // 02/06/97 BRH Added RAnimSprite animation of the explosion for now. // We are going to do an Alpha effect on the explosion, so // there are two animations, one of the image and one of // the Alpha information stored as a BMP8 animation. When // the Alpha effect is ready, we will pass a frame from // each animation to a function to draw it. // // 02/06/97 BRH Fixed problem with timer. Since all Explosion objects // are using the same resource managed animation, they cannot // use the animation timer, they have to do the timing // themselves. // // 02/07/97 BRH Changed the sprite from CSprite2 to CSpriteAlpha2 for // the Alpha Blit effect. // // 02/09/97 BRH Started the Fire from Explode file since they are // similar. // // 02/10/97 JMI rspReleaseResource() now takes a ptr to a ptr. // // 02/11/97 BRH Changed the fire to start on a random frame number // so if you have many fires, they don't pulsate or all // burn in sync with each other. // // 02/14/97 BRH Changed from using the RAnimSprite to channel data. // // 02/17/97 BRH Now uses the resource manager to get the assets and starts // at a random time interval so the fire will be random again. // // 02/17/97 BRH Changed the lifetime to be time based rather than frame // based which was causing the fire to live on forever // since being switched from RAnimSprite to RChannel1. // // 02/18/97 BRH Now the fire changes to different Alpha channels as it // burns out during its time to live. // // 02/19/97 BRH Checks for collisions and sends messages. // // 02/19/97 BRH Added the ability to run both small and large fire // animations. Change the duration on the alpha layers // so that the initial alpha channel gets played for 80% // of the burning time. Also added bThick parameter to startup // which will start using the 0th Alpha channel which is // more opaque. If you want more Alpha, set to false which // will start on the next Alpha level down. // // 02/23/97 BRH Added static Preload() funciton which will be called // before play begins to cache a resource for this object. // // 02/24/97 JMI No longer sets the m_type member of the m_sprite b/c it // is set by m_sprite's constructor. // // 02/24/97 BRH Set the default state in ProcessMessages // // 02/24/97 BRH Added a timer for checkin collisions so it doesn't have // to check each time, but it was checking only when changing // alpha levels which was too long. // // 03/05/97 JMI Render()'s mapping from 3D to 2D had a typo (was adding m_dY // instead of subtracting). Now uses Map3Dto2D(). // // 03/13/97 JMI Load now takes a version number. // // 04/10/97 BRH Updated this to work with the new multi layer attribute // maps. // // 04/14/97 BRH Added CSmash::Item to the collide bits so that the fire // will send messages to barrels and other items. // // 04/21/97 BRH Added Smoke animation to the fire and the ability of the // fire to change to smoke. // // 02/22/97 BRH Adjusted the timer for the smoke effect to eliminate some // of the final frames so that the smoke wouldn't pulsate // like it did. // // 04/23/97 JMI Changed this item's m_smash bits from CSmash::Item to // CSmash::Fire. // Now affects Characters, Miscs, Mines, and Barrels. // // 04/24/97 BRH Added static wind direction variable that will get // adjusted slightly by each new creation of smoke which // calls WindDirectionUpdate() to randomly vary the wind // direction. // // 04/25/97 BRH Fixed problem with smoke that was created as smoke, // setting people on fire. Also fixed wall detection // and added an individual direction variable to each // instance of smoke that initially copies the wind // direction and uses it until it hits a wall, then it // rotates in one direction or the other until it is // free to move again. // // 05/09/97 JMI Update() now moves the smashatorium object when the CFire // is not Smoke. // // 05/29/97 JMI Removed ASSERT on m_pRealm->m_pAttribMap which no longer // exists. // // 06/11/97 BRH Pass along the m_u16ShooterID value in the Burn message. // // 06/15/97 BRH Fixed Smoke going past animation by 1 frame. // // 06/16/97 BRH Fixed smoke init of static wind direction. Now it // inits the wind direction on class load so that it doesn't // cause problems for the demo mode. // // 06/17/97 MJR Same as previous one for wind velocity. // // MJR Moved resetting of statics to Preload(), since in most // cases, fire or smoke are not Load()'ed. // // 06/18/97 BRH Changed over to using GetRandom() // // 06/26/97 BRH Added CSmash::AlmostDead to the include bits for fire so // that writhing guys can be killed by fire. // // 07/01/97 BRH Added small smoke animation. // // 07/04/97 BRH Added an auto alpha blend on the small smoke for the // rocket trails so they can blend into alpha based on // their time to live. May need to disable the // alpha channel for it to work correctly. // // 07/08/97 JMI Fixed Render() to distribute the homogeneous alpha level // better. Still needs tuning. // // 07/09/97 JMI Now uses m_pRealm->Make2dResPath() to get the fullpath // for 2D image components. // // 07/09/97 JMI Changed Preload() to take a pointer to the calling realm // as a parameter. // // 07/10/97 JMI Now uses alpha mask and level for animation. // // 07/13/97 BRH Changed the animations to use only 1 alpha mask and change // the alpha level based on time. // // 07/20/97 JMI Added some ASSERTs. // // 07/23/97 BRH Changed small fires to create small smokes rather than // large which slows down the game quite a bit. // // 07/27/97 JMI Changed to use Z position (i.e., X/Z plane) instead of // Y2 position (i.e., viewing plane) position for draw // priority. // // 08/11/97 BRH If alpha blending is turned off, as a performance option, // then don't even blit the smoke since without the alpha // effect, you can't see through it at all. // // 08/20/97 JMI Now does a range check on m_sCurrentAlphaLevel after // decrementing. // // 09/02/97 JMI Added m_u16FireStarterID. This is used for a special case // when the starter of the fire is not the thing using the // fire as a weapon (e.g., when a guy catches fire he can // use the fire on other people by running into them causing // them to catch on fire; however, if his own fire kills him // it is to the creator of the fire's credit that he dies). // //////////////////////////////////////////////////////////////////////////////// #define FIRE_CPP #include "RSPiX.h" #include <math.h> #include "fire.h" #include "dude.h" #include "game.h" #include "reality.h" //////////////////////////////////////////////////////////////////////////////// // Macros/types/etc. //////////////////////////////////////////////////////////////////////////////// #define AA_FILE "fire.aan" #define LARGE_FILE "fire.aan" #define SMALL_FILE "smallfire.aan" #define SMOKE_FILE "smoke.aan" #define SMALL_SMOKE_FILE "tinysmoke.aan" #define INIT_WIND_DIR 30 #define INIT_WIND_VEL 30 #define MAX_ALPHA 200 // Used for smoke trails #define THICK_ALPHA 255 // Start alpha level for thick fire #define THIN_ALPHA 200 // Start alpha level for thin fire #define DIEDOWN_ALPHA 100 // Point at which it looks like its dying down #define SMOLDER_ALPHA 30 // Point at which it is too weak to burn anyone #define BRIGHT_PERCENT 0.80 // Amount of the time it should be more opaque //////////////////////////////////////////////////////////////////////////////// // Variables/data //////////////////////////////////////////////////////////////////////////////// // Let this auto-init to 0 int16_t CFire::ms_sFileCount; int16_t CFire::ms_sLargeRadius = 20; int16_t CFire::ms_sSmallRadius = 8; int16_t CFire::ms_sWindDirection = INIT_WIND_DIR; // Start wind in this direction int32_t CFire::ms_lCollisionTime = 250; // Check for collisions this often int32_t CFire::ms_lSmokeTime = 10000; // Time to let smoke run double CFire::ms_dWindVelocity = INIT_WIND_VEL; // Pixels per second drift due to wind //////////////////////////////////////////////////////////////////////////////// // Load object (should call base class version!) //////////////////////////////////////////////////////////////////////////////// int16_t CFire::Load( // Returns 0 if successfull, non-zero otherwise RFile* pFile, // In: File to load from bool bEditMode, // In: True for edit mode, false otherwise int16_t sFileCount, // In: File count (unique per file, never 0) uint32_t ulFileVersion) // In: Version of file format to load. { int16_t sResult = CThing::Load(pFile, bEditMode, sFileCount, ulFileVersion); if (sResult == 0) { // Load common data just once per file (not with each object) if (ms_sFileCount != sFileCount) { ms_sFileCount = sFileCount; // Init the static wind direction and velocity when the class loads. ms_sWindDirection = INIT_WIND_DIR; ms_dWindVelocity = INIT_WIND_VEL; // Load static data. switch (ulFileVersion) { default: case 1: break; } } // Load instance data. switch (ulFileVersion) { default: case 1: pFile->Read(&m_eFireAnim); break; } // Make sure there were no file errors or format errors . . . if (!pFile->Error() && sResult == 0) { // Get resources sResult = GetResources(); } else { sResult = -1; TRACE("CFire::Load(): Error reading from file!\n"); } } else { TRACE("CFire::Load(): CThing::Load() failed.\n"); } return sResult; } //////////////////////////////////////////////////////////////////////////////// // Save object (should call base class version!) //////////////////////////////////////////////////////////////////////////////// int16_t CFire::Save( // Returns 0 if successfull, non-zero otherwise RFile* pFile, // In: File to save to int16_t sFileCount) // In: File count (unique per file, never 0) { int16_t sResult = CThing::Save(pFile, sFileCount); if (sResult == 0) { // Save common data just once per file (not with each object) if (ms_sFileCount != sFileCount) { ms_sFileCount = sFileCount; // Save static data } pFile->Write(&m_eFireAnim); } else { TRACE("CFire::Save(): CThing::Save() failed.\n"); } return sResult; } //////////////////////////////////////////////////////////////////////////////// // Startup object //////////////////////////////////////////////////////////////////////////////// int16_t CFire::Startup(void) // Returns 0 if successfull, non-zero otherwise { return Init(); } //////////////////////////////////////////////////////////////////////////////// // Shutdown object //////////////////////////////////////////////////////////////////////////////// int16_t CFire::Shutdown(void) // Returns 0 if successfull, non-zero otherwise { return 0; } //////////////////////////////////////////////////////////////////////////////// // Suspend object //////////////////////////////////////////////////////////////////////////////// void CFire::Suspend(void) { m_sSuspend++; } //////////////////////////////////////////////////////////////////////////////// // Resume object //////////////////////////////////////////////////////////////////////////////// void CFire::Resume(void) { m_sSuspend--; // If we're actually going to start updating again, we need to reset // the time so as to ignore any time that passed while we were suspended. // This method is far from precise, but I'm hoping it's good enough. if (m_sSuspend == 0) m_lPrevTime = m_pRealm->m_time.GetGameTime(); } //////////////////////////////////////////////////////////////////////////////// // Update object //////////////////////////////////////////////////////////////////////////////// void CFire::Update(void) { int32_t lThisTime; double dSeconds; double dDistance; double dNewX; double dNewZ; if (!m_sSuspend) { // See if we killed ourselves if (ProcessMessages() == State_Deleted) return; if (m_lTimer < m_lBurnUntil) { lThisTime = m_pRealm->m_time.GetGameTime(); m_lTimer += lThisTime - m_lPrevTime; // See if its time to change to the next alpha channel if (m_lTimer > m_lCurrentAlphaTimeout) { m_sCurrentAlphaLevel--; // Range check. if (m_sCurrentAlphaLevel < 0) m_sCurrentAlphaLevel = 0; else if (m_sCurrentAlphaLevel > 255) m_sCurrentAlphaLevel = 255; if (m_lTimer < m_lAlphaBreakPoint) m_lCurrentAlphaTimeout += m_lBrightAlphaInterval; else m_lCurrentAlphaTimeout += m_lDimAlphaInterval; } if (lThisTime > m_lCollisionTimer) { // If the fire is not smoldering out, then it has the ability // to set other things on fire and should check collisions // to see which things it should tell to burn. if (m_bSendMessages && m_sCurrentAlphaLevel > SMOLDER_ALPHA && m_eFireAnim != Smoke && m_eFireAnim != SmallSmoke) { CSmash* pSmashed = NULL; GameMessage msg; msg.msg_Burn.eType = typeBurn; msg.msg_Burn.sPriority = 0; msg.msg_Burn.sDamage = 10; msg.msg_Burn.u16ShooterID = m_u16ShooterID; m_pRealm->m_smashatorium.QuickCheckReset(&m_smash, m_u32CollideIncludeBits, m_u32CollideDontcareBits, m_u32CollideExcludeBits); while (m_pRealm->m_smashatorium.QuickCheckNext(&pSmashed)) { // Default to the standard case where credit is given to the // shooter. msg.msg_Burn.u16ShooterID = m_u16ShooterID; if ((m_bIsBurningDude) && (pSmashed->m_pThing->GetClassID() != CDudeID)) UnlockAchievement(ACHIEVEMENT_TOUCH_SOMEONE_WHILE_BURNING); // If the fire starter ID is set . . . if (m_u16FireStarterID != CIdBank::IdNil) { // If this is the shooter . . . if (pSmashed->m_pThing->GetInstanceID() == m_u16ShooterID) { // The shooter is damaged by his own fire with credit // given to the fire starter. msg.msg_Burn.u16ShooterID = m_u16FireStarterID; } } // Burn. SendThingMessage(&msg, pSmashed->m_pThing); } } // Reset collision timer for next time m_lCollisionTimer = lThisTime + ms_lCollisionTime; } // If this is smoke, make it drift in the wind direction if (m_eFireAnim == Smoke || m_eFireAnim == SmallSmoke) { // Update position using wind direction and velocity dSeconds = ((double) lThisTime - (double) m_lPrevTime) / 1000.0; // Apply internal velocity. dDistance = ms_dWindVelocity * dSeconds; dNewX = m_dX + COSQ[(int16_t) m_sRot] * dDistance; dNewZ = m_dZ - SINQ[(int16_t) m_sRot] * dDistance; // Check attribute map for walls, and if you hit a wall, // set the timer so you will die off next time around. int16_t sHeight = m_pRealm->GetHeight((int16_t) dNewX, (int16_t) dNewZ); // If it hits a wall taller than itself, then it will rotate in the // predetermined direction until it is free to move. if ((int16_t) m_dY < sHeight) { if (m_bTurnRight) m_sRot = rspMod360(m_sRot - 20); else m_sRot = rspMod360(m_sRot + 20); } else // else it is ok, so update its new position { m_dX = dNewX; m_dZ = dNewZ; } } else { // Update our smashatorium location. m_smash.m_sphere.sphere.X = m_dX; m_smash.m_sphere.sphere.Y = m_dY; m_smash.m_sphere.sphere.Z = m_dZ; // Update the smash. m_pRealm->m_smashatorium.Update(&m_smash); } m_lPrevTime = lThisTime; } else { // If its done smoking, then delete it if (m_eFireAnim == Smoke || m_eFireAnim == SmallSmoke) { delete this; } // Else change the fire to smoke else { if (Smokeout() != SUCCESS) delete this; } } } } //////////////////////////////////////////////////////////////////////////////// // Render object //////////////////////////////////////////////////////////////////////////////// void CFire::Render(void) { CAlphaAnim* pAnim; if (m_eFireAnim == Smoke || m_eFireAnim == SmallSmoke) { pAnim = (CAlphaAnim*) m_pAnimChannel->GetAtTime(m_lTimer); // For a performance gain, don't blit the smoke at all if alpha // blending is turned off - its impossible to see through when // alpha blending is off anyway. if (g_GameSettings.m_sAlphaBlend) m_sprite.m_sInFlags = 0; else m_sprite.m_sInFlags = CSprite::InHidden; } else { pAnim = (CAlphaAnim*) m_pAnimChannel->GetAtTime(m_lTimer % m_pAnimChannel->TotalTime()); } if (pAnim) { // Map from 3d to 2d coords Map3Dto2D(m_dX, m_dY, m_dZ, &(m_sprite.m_sX2), &(m_sprite.m_sY2) ); // Offset by animations 2D offsets. m_sprite.m_sX2 += pAnim->m_sX; m_sprite.m_sY2 += pAnim->m_sY; // Priority is based on our Z position. m_sprite.m_sPriority = m_dZ; // Layer should be based on info we get from attribute map. m_sprite.m_sLayer = CRealm::GetLayerViaAttrib(m_pRealm->GetLayer((int16_t) m_dX, (int16_t) m_dZ)); // Copy the color info and the alpha channel to the Alpha Sprite m_sprite.m_pImage = &(pAnim->m_imColor); // If its the tiny smoke (for trails) // Do the alpha based on the time to live. if (m_eFireAnim == SmallSmoke) { // Set the alpha level so it gets more translucent over time. m_sprite.m_sAlphaLevel = MAX_ALPHA - (MAX_ALPHA * (m_lTimer - m_lStartTime) ) / m_lTimeToLive ; // Do a range check. if (m_sprite.m_sAlphaLevel < 0) m_sprite.m_sAlphaLevel = 0; else if (m_sprite.m_sAlphaLevel > MAX_ALPHA) m_sprite.m_sAlphaLevel = MAX_ALPHA; } else { m_sprite.m_sAlphaLevel = m_sCurrentAlphaLevel; } // Now there is only one alpha mask m_sprite.m_pimAlpha = &(pAnim->m_pimAlphaArray[0]); ASSERT(m_sprite.m_sAlphaLevel <= 255); ASSERT(m_sprite.m_sAlphaLevel >= 0); // Update sprite in scene m_pRealm->m_scene.UpdateSprite(&m_sprite); } } //////////////////////////////////////////////////////////////////////////////// // Setup //////////////////////////////////////////////////////////////////////////////// int16_t CFire::Setup( // Returns 0 if successfull, non-zero otherwise int16_t sX, // In: New x coord int16_t sY, // In: New y coord int16_t sZ, // In: New z coord int32_t lTimeToLive, // In: Number of milliseconds to burn, default 1sec bool bThick, // In: Use thick fire (more opaque) default = true FireAnim eAnimType) // In: Animation type to use default = LargeFire { int16_t sResult = 0; // Use specified position m_dX = (double)sX; m_dY = (double)sY; m_dZ = (double)sZ; m_lPrevTime = m_pRealm->m_time.GetGameTime(); m_lCollisionTimer = m_lPrevTime + ms_lCollisionTime; m_eFireAnim = eAnimType; m_lTimeToLive = lTimeToLive; if (bThick) m_sCurrentAlphaLevel = THICK_ALPHA; else m_sCurrentAlphaLevel = THIN_ALPHA; // Load resources sResult = GetResources(); if (sResult == SUCCESS) sResult = Init(); m_sRot = ms_sWindDirection; m_bTurnRight = (GetRandom() & 0x01); return sResult; } //////////////////////////////////////////////////////////////////////////////// // Init //////////////////////////////////////////////////////////////////////////////// int16_t CFire::Init(void) { int16_t sResult = SUCCESS; CAlphaAnim* pAnim = NULL; if (m_pAnimChannel != NULL) { m_lTimer = GetRandom() % m_pAnimChannel->TotalTime(); m_lStartTime = m_lTimer; m_lBurnUntil = m_lTimer + m_lTimeToLive; m_lAlphaBreakPoint = m_lTimer + (m_lTimeToLive * BRIGHT_PERCENT); pAnim = (CAlphaAnim*) m_pAnimChannel->GetAtTime(0); ASSERT(pAnim != NULL); m_lBrightAlphaInterval = (m_lTimeToLive * BRIGHT_PERCENT) / MAX(1, m_sCurrentAlphaLevel - DIEDOWN_ALPHA); m_lDimAlphaInterval = (m_lTimeToLive * (100.0 - BRIGHT_PERCENT)) / MAX(1, DIEDOWN_ALPHA); m_lCurrentAlphaTimeout = m_lTimer + m_lBrightAlphaInterval; m_sTotalAlphaChannels = 1; } switch (m_eFireAnim) { case LargeFire: // Update sphere m_smash.m_sphere.sphere.X = m_dX; m_smash.m_sphere.sphere.Y = m_dY; m_smash.m_sphere.sphere.Z = m_dZ; m_smash.m_sphere.sphere.lRadius = ms_sLargeRadius; m_smash.m_bits = CSmash::Fire; m_smash.m_pThing = this; // Update the smash m_pRealm->m_smashatorium.Update(&m_smash); break; case SmallFire: // Update sphere m_smash.m_sphere.sphere.X = m_dX; m_smash.m_sphere.sphere.Y = m_dY; m_smash.m_sphere.sphere.Z = m_dZ; m_smash.m_sphere.sphere.lRadius = ms_sSmallRadius; m_smash.m_bits = CSmash::Fire; m_smash.m_pThing = this; // Update the smash m_pRealm->m_smashatorium.Update(&m_smash); break; case Smoke: m_smash.m_pThing = NULL; m_bSendMessages = false; break; case SmallSmoke: m_smash.m_pThing = NULL; m_bSendMessages = false; m_lStartTime = m_lTimer = GetRandom() % m_pAnimChannel->TotalTime() / 3; m_lBurnUntil = m_lTimer + m_lTimeToLive; break; } // Set the collision bits m_u32CollideIncludeBits = CSmash::Character | CSmash::Barrel | CSmash::Mine | CSmash::Misc | CSmash::AlmostDead; m_u32CollideDontcareBits = CSmash::Good | CSmash::Bad; m_u32CollideExcludeBits = 0; return sResult; } //////////////////////////////////////////////////////////////////////////////// // Smokeout - Change from fire to smoke //////////////////////////////////////////////////////////////////////////////// int16_t CFire::Smokeout(void) { int16_t sResult = SUCCESS; // Modify the wind direction slightly WindDirectionUpdate(); // Remove smash from the smashatorium if it was being used if (m_smash.m_pThing) m_pRealm->m_smashatorium.Remove(&m_smash); m_bSendMessages = false; // Release the fire animation and get the smoke animation FreeResources(); if (m_eFireAnim == SmallFire) m_eFireAnim = SmallSmoke; else m_eFireAnim = Smoke; sResult = GetResources(); // Reset timers CAlphaAnim* pAnim = NULL; if (m_pAnimChannel != NULL) { // Reset alpha level m_sCurrentAlphaLevel = THICK_ALPHA; pAnim = (CAlphaAnim*) m_pAnimChannel->GetAtTime(0); ASSERT(pAnim != NULL); // m_lTimeToLive = m_pAnimChannel->TotalTime(); // use same time to live as the original m_lStartTime = m_lTimer = 0; m_lBurnUntil = m_lTimer + m_lTimeToLive; m_lAlphaBreakPoint = m_lTimer + (m_lTimeToLive * BRIGHT_PERCENT); m_lBrightAlphaInterval = (m_lTimeToLive * BRIGHT_PERCENT) / MAX(1, m_sCurrentAlphaLevel - DIEDOWN_ALPHA); m_lDimAlphaInterval = (m_lTimeToLive * (1.0 - BRIGHT_PERCENT)) / MAX(1, DIEDOWN_ALPHA); m_lCurrentAlphaTimeout = m_lTimer + m_lBrightAlphaInterval; m_sTotalAlphaChannels = 1; } return sResult; } //////////////////////////////////////////////////////////////////////////////// // Called by editor to init new object at specified position //////////////////////////////////////////////////////////////////////////////// int16_t CFire::EditNew( // Returns 0 if successfull, non-zero otherwise int16_t sX, // In: New x coord int16_t sY, // In: New y coord int16_t sZ) // In: New z coord { int16_t sResult = 0; // Use specified position m_dX = (double)sX; m_dY = (double)sY; m_dZ = (double)sZ; m_lTimer = GetRandom(); //m_pRealm->m_time.GetGameTime() + 1000; m_lPrevTime = m_pRealm->m_time.GetGameTime(); // Load resources sResult = GetResources(); return sResult; } //////////////////////////////////////////////////////////////////////////////// // Called by editor to modify object //////////////////////////////////////////////////////////////////////////////// int16_t CFire::EditModify(void) { return 0; } //////////////////////////////////////////////////////////////////////////////// // Called by editor to move object to specified position //////////////////////////////////////////////////////////////////////////////// int16_t CFire::EditMove( // Returns 0 if successfull, non-zero otherwise int16_t sX, // In: New x coord int16_t sY, // In: New y coord int16_t sZ) // In: New z coord { m_dX = (double)sX; m_dY = (double)sY; m_dZ = (double)sZ; return 0; } //////////////////////////////////////////////////////////////////////////////// // Called by editor to update object //////////////////////////////////////////////////////////////////////////////// void CFire::EditUpdate(void) { } //////////////////////////////////////////////////////////////////////////////// // Called by editor to render object //////////////////////////////////////////////////////////////////////////////// void CFire::EditRender(void) { // In some cases, object's might need to do a special-case render in edit // mode because Startup() isn't called. In this case it doesn't matter, so // we can call the normal Render(). Render(); } //////////////////////////////////////////////////////////////////////////////// // Get all required resources //////////////////////////////////////////////////////////////////////////////// int16_t CFire::GetResources(void) // Returns 0 if successfull, non-zero otherwise { int16_t sResult = SUCCESS; switch (m_eFireAnim) { case LargeFire: sResult = rspGetResource(&g_resmgrGame, m_pRealm->Make2dResPath(LARGE_FILE), &m_pAnimChannel, RFile::LittleEndian); break; case SmallFire: sResult = rspGetResource(&g_resmgrGame, m_pRealm->Make2dResPath(SMALL_FILE), &m_pAnimChannel, RFile::LittleEndian); break; case Smoke: sResult = rspGetResource(&g_resmgrGame, m_pRealm->Make2dResPath(SMOKE_FILE), &m_pAnimChannel, RFile::LittleEndian); break; case SmallSmoke: sResult = rspGetResource(&g_resmgrGame, m_pRealm->Make2dResPath(SMALL_SMOKE_FILE), &m_pAnimChannel, RFile::LittleEndian); break; } if (sResult != 0) TRACE("CFire::GetResources - Error getting fire animation resource\n"); return sResult; } //////////////////////////////////////////////////////////////////////////////// // Free all resources //////////////////////////////////////////////////////////////////////////////// int16_t CFire::FreeResources(void) // Returns 0 if successfull, non-zero otherwise { int16_t sResult = 0; rspReleaseResource(&g_resmgrGame, &m_pAnimChannel); return sResult; } //////////////////////////////////////////////////////////////////////////////// // Preload - basically trick the resource manager into caching resources for fire // animations before play begins so that when a fire is set for // the first time, there won't be a delay while it loads. //////////////////////////////////////////////////////////////////////////////// int16_t CFire::Preload( CRealm* prealm) // In: Calling realm. { // Init the static wind direction and velocity when the class loads. ms_sWindDirection = INIT_WIND_DIR; ms_dWindVelocity = INIT_WIND_VEL; ChannelAA* pRes; int16_t sResult = rspGetResource(&g_resmgrGame, prealm->Make2dResPath(LARGE_FILE), &pRes, RFile::LittleEndian); rspReleaseResource(&g_resmgrGame, &pRes); sResult |= rspGetResource(&g_resmgrGame, prealm->Make2dResPath(SMALL_FILE), &pRes, RFile::LittleEndian); rspReleaseResource(&g_resmgrGame, &pRes); sResult |= rspGetResource(&g_resmgrGame, prealm->Make2dResPath(SMOKE_FILE), &pRes, RFile::LittleEndian); rspReleaseResource(&g_resmgrGame, &pRes); sResult |= rspGetResource(&g_resmgrGame, prealm->Make2dResPath(SMALL_SMOKE_FILE), &pRes, RFile::LittleEndian); rspReleaseResource(&g_resmgrGame, &pRes); return sResult; } //////////////////////////////////////////////////////////////////////////////// // ProcessMessages //////////////////////////////////////////////////////////////////////////////// CFire::CFireState CFire::ProcessMessages(void) { CFireState eNewState = State_Idle; GameMessage msg; if (m_MessageQueue.DeQ(&msg) == true) { switch(msg.msg_Generic.eType) { case typeObjectDelete: m_MessageQueue.Empty(); delete this; return CFire::State_Deleted; break; } } // Dump the rest of the messages m_MessageQueue.Empty(); return eNewState; } //////////////////////////////////////////////////////////////////////////////// // EOF ////////////////////////////////////////////////////////////////////////////////
PixelDevLabs/Ezia-Cleaner_Build-934afd57b26a
fire.cpp
C++
gpl-2.0
29,776
<?php namespace Themosis\Core\Console; use Illuminate\Console\Command; use Illuminate\Console\ConfirmableTrait; use Illuminate\Encryption\Encrypter; class KeyGenerateCommand extends Command { use ConfirmableTrait; /** * Name and signature of the console command. * * @var string */ protected $signature = 'key:generate {--show : Display the key instead of modifying files} {--force : Force the operation to run when in production}'; /** * Console command description. * * @var string */ protected $description = 'Set the application key'; /** * Execute the console command. */ public function handle() { $key = $this->generateRandomKey(); if ($this->option('show')) { $this->line('<comment>'.$key.'</comment>'); return; } // Next, we will replace the application key in the environment file so it is // automatically setup for this developer. This key gets generated using a // secure random byte generator and is later base64 encoded for storage. if (! $this->setKeyInEnvironmentFile($key)) { return; } $this->laravel['config']['app.key'] = $key; $this->info("Application key [$key] set successfully."); } /** * Generate a random key for the application. * * @return string */ protected function generateRandomKey() { return 'base64:'.base64_encode(Encrypter::generateKey($this->laravel['config']['app.cipher'])); } /** * Set the application key in the environment file. * * @param string $key * * @return bool */ protected function setKeyInEnvironmentFile(string $key) { $currentKey = $this->laravel['config']['app.key']; if (0 !== strlen($currentKey) && (! $this->confirmToProceed())) { return false; } $this->writeNewEnvironmentFileWith($key); return true; } /** * Write new environment file with the given key. * * @param string $key */ protected function writeNewEnvironmentFileWith(string $key) { file_put_contents( $this->laravel->environmentFilePath(), preg_replace( $this->keyReplacementPattern(), 'APP_KEY='.$key, file_get_contents($this->laravel->environmentFilePath()) ) ); } /** * Get a regex pattern that will match env APP_KEY with any random key. * * @return string */ protected function keyReplacementPattern() { $escaped = preg_quote('='.$this->laravel['config']['app.key'], '/'); return "/^APP_KEY{$escaped}/m"; } }
themosis/framework
src/Core/Console/KeyGenerateCommand.php
PHP
gpl-2.0
2,827
<?php require_once './includes/bootstrap.inc'; drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); global $base_url; require_once ('tcpdf/pdfcss.php'); require_once('tcpdf/config/lang/eng.php'); require_once('tcpdf/tcpdf.php'); // create new PDF document $pdf = new TCPDF(L, PDF_UNIT, B4, true, 'UTF-8', false); // set document information $pdf->SetCreator(PDF_CREATOR); $pdf->SetAuthor('SC and ST'); $pdf->SetTitle('SC and ST'); $pdf->SetSubject('SC and ST'); $pdf->SetKeywords('SC and ST'); //$pdf->SetHeaderData('tcpdf/images/hpsc.png', PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING); $pdf->SetHeaderData('tcpdf/images/hpsc.png', PDF_HEADER_LOGO_WIDTH, '',''); // set default header data //$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING); // set header and footer fonts $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN)); $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA)); // set default monospaced font $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); //set margins $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $pdf->SetHeaderMargin(PDF_MARGIN_HEADER); $pdf->SetFooterMargin(PDF_MARGIN_FOOTER); //set auto page breaks $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); //set image scale factor $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); //set some language-dependent strings $pdf->setLanguageArray($l); // set font $pdf->SetFont('helvetica', '', 10); // add a page $pdf->AddPage(); if($_REQUEST['op'] == 'assetRegister_report'){ global $user, $base_url; $rid = $_REQUEST['rid']; $fromtime = $_REQUEST['fromtime']; $totime = $_REQUEST['totime']; $from = $fromtime; $to = $totime; //echo $fromtime.'jj';exit; $output =''; // define some HTML content with style $output .= <<<EOF <style> td.header_first{ color:111111; font-family:Verdana; font-size: 12pt; text-align:center; background-color:#ffffff; } td.header_report{ color:111111; font-family:Verdana; font-size: 16pt; text-align:center; font-weight:bold; background-color:#ffffff; } table{ width:1200px; } table.tbl_border{border:1px solid #a7c942; background-color:#a7c942; } td.header1 { color:#3b3c3c; background-color:#ffffff; font-family:Verdana; font-size: 11pt; font-weight: normal; } td.header2 { border-bottom-color:#FFFFFF; color: #ffffff; background-color:#a7c942; font-family:Verdana; font-size: 10pt; font-weight: bold; } td.header3 { color: #222222; background-color:#dddddd; font-family:Verdana; font-size: 11pt; font-weight: bold; } td.header4 { color: #222222; font-family:Verdana; font-size: 11pt; font-weight: bold; background-color:#eeeeee; } td.header4_1 { color:#222222; background-color:#ffffff; font-family:Verdana; font-size: 11pt; font-weight: normal; } td.header4_2 { color:#222222; background-color:#eaf2d3; font-family:Verdana; font-size: 11pt; font-weight: normal; } td.msg{ color:#FF0000; text-align:left; } </style> EOF; // Header Title $output .='<table cellpadding="0" cellspacing="0" border="0"> <tr><td class="header_report" colspan="5" align="center"> Asset Register</td></tr> <tr><td>&nbsp;</td></tr> </table>'; $append=''; if($fromtime){ if($fromtime !='1970-01-01' && $totime !='1970-01-01' ){ $append .= " date_amc BETWEEN '".$fromtime."' AND '".$totime."' AND "; } } $append .= " 1=1 "; $sql="select * from tbl_itassets where $append"; $output .='<table cellpadding="3" cellspacing="2" border="0">'; if($fromtime){ $output .='<tr><td class="header_first" align="left"> <b>From Date: </b>'.date('d-m-Y',strtotime($fromtime)).'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>To Date: </b>'.date('d-m-Y',strtotime($totime)).'</td></tr>'; } $output .='</table>'; $output .='<table cellpadding="2" cellspacing="2" border="0" class="tbl_border" style="width:1095px;"><tr> <td width="5%" colspan="1" class="header2">S. No.</td> <td width="6%" colspan="1" class="header2">Section</td> <td width="6%" colspan="1" class="header2">Asset Type</td> <td width="8%" colspan="1" class="header2">Quantity</td> <td width="5%" colspan="1" class="header2">Amount</td> <td width="5%" colspan="1" class="header2">Procurement Cost</td> <td width="9%" colspan="1" class="header2">Asset Details</td> <td width="9%" colspan="1" class="header2">Insurance Company</td> <td width="9%" colspan="1" class="header2">Sum Insured</td> <td width="9%" colspan="1" class="header2">Date of Renewal</td> <td width="5%" colspan="1" class="header2">Claim Details</td> <td width="9%" colspan="1" class="header2">AMC Vendor Name</td> <td width="9%" colspan="1" class="header2">AMC Date</td> <td width="5%" colspan="1" class="header2">AMC Amount</td> <td width="9%" colspan="1" class="header2">Contract Details</td> </tr>'; $res = db_query($sql); $counter=1; while($rs = db_fetch_object($res)){ $comp_name=ucwords($rs->company_name); if($comp_name==''){$comp_name='N/A';} $sum_insured=($rs->sum_insured); if($sum_insured==''){$sum_insured='N/A';} $date_renewal=date('d-m-Y',strtotime($rs->date_renewal)); if($date_renewal==''){$date_renewal='N/A';} $claim_det=ucwords($rs->claim_details); if($claim_det==''){$claim_det='N/A';} $vendor_name=ucwords($rs->vendor_name);if($vendor_name==''){$vendor_name='N/A';} $date_amc=date('d-m-Y',strtotime($rs->date_amc)); if($date_amc==''){$date_amc='N/A';} $amt_amc=$rs->amount_amc; if($amt_amc==''){$amt_amc='N/A';} $contract_det=ucwords($rs->contract_details);if($contract_det==''){$contract_det='N/A';} if($counter%2==0){ $class='header4_1';}else{$class='header4_2';} $output .='<tr> <td width="5%" class="'.$class.'" align="center">'.$counter.'</td> <td width="6%" class="'.$class.'" align="left">'.ucwords(getLookupName($rs->section)).'</td> <td width="6%" class="'.$class.'" align="left">'.ucwords(getLookupName($rs->asset_type)).'</td> <td width="8%" class="'.$class.'" align="left">'.ucwords($rs->quantity).'</td> <td width="5%" class="'.$class.'" align="right">'.round($rs->amount).'</td> <td width="5%" class="'.$class.'" align="right">'.round($rs->proc_cost).'</td> <td width="9%" class="'.$class.'" align="left">'.ucwords($rs->asset_details).'</td> <td width="9%" class="'.$class.'" align="left">'.$comp_name.'</td> <td width="9%" class="'.$class.'" align="right">'.round($sum_insured).'</td> <td width="9%" class="'.$class.'" align="center">'.$date_renewal.'</td> <td width="5%" class="'.$class.'" align="left">'.$claim_det.'</td> <td width="9%" class="'.$class.'" align="left">'.$vendor_name.'</td> <td width="9%" class="'.$class.'" align="center">'.$date_amc.'</td> <td width="5%" class="'.$class.'" align="right">'.round($amt_amc).'</td> <td width="9%" class="'.$class.'" align="left">'.$contract_det.'</td> </tr>'; $counter++; } $output .='</table>'; ob_end_clean(); // print a block of text using Write() $pdf->writeHTML($output, true,1, false, false); $pdf->Output('assetRegister_'.time().'.pdf', 'I'); }
himan5050/hpbc
assetRegisterpdf.php
PHP
gpl-2.0
7,049
/** * AshtavargaChartData.java * Created On 2006, Mar 31, 2006 5:12:23 PM * @author E. Rajasekar */ package app.astrosoft.beans; import java.util.EnumMap; import app.astrosoft.consts.AshtavargaName; import app.astrosoft.consts.AstrosoftTableColumn; import app.astrosoft.consts.Rasi; import app.astrosoft.core.Ashtavarga; import app.astrosoft.export.Exportable; import app.astrosoft.export.Exporter; import app.astrosoft.ui.table.ColumnMetaData; import app.astrosoft.ui.table.DefaultColumnMetaData; import app.astrosoft.ui.table.Table; import app.astrosoft.ui.table.TableData; import app.astrosoft.ui.table.TableRowData; public class AshtaVargaChartData extends AbstractChartData implements Exportable{ private EnumMap<Rasi, Integer> varga; public AshtaVargaChartData(AshtavargaName name, EnumMap<Rasi, Integer> varga) { super(); this.varga = varga; chartName = name.toString(); int count = Ashtavarga.getCount(name); if ( count != -1){ chartName = chartName + " ( " +String.valueOf(count) + " ) "; } } public Table getChartHouseTable(final Rasi rasi) { Table ashtavargaTable = new Table(){ public TableData<TableRowData> getTableData() { return new TableData<TableRowData>(){ public TableRowData getRow(final int index){ return new TableRowData(){ public Object getColumnData(AstrosoftTableColumn col) { return (index == 1) ? varga.get(rasi) : null; } }; } public int getRowCount() { return 2; } }; } public ColumnMetaData getColumnMetaData() { return colMetaData; } }; return ashtavargaTable; } @Override public DefaultColumnMetaData getHouseTableColMetaData() { return new DefaultColumnMetaData(AstrosoftTableColumn.C1){ @Override public Class getColumnClass(AstrosoftTableColumn col) { return Integer.class; } }; } public EnumMap<Rasi, Integer> getVarga() { return varga; } public void doExport(Exporter e) { e.export(this); } }
erajasekar/Astrosoft
src/app/astrosoft/beans/AshtaVargaChartData.java
Java
gpl-2.0
2,069
package mcmod.nxs.animalwarriors.lib; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemArmor; public class ArmorHelper extends ItemArmor { public ArmorHelper(ArmorMaterial material, int type, int layer) { super(material, type, layer); } public ItemArmor setNameAndTab(String name, CreativeTabs tab) { this.setTextureName(ResourcePathHelper.getResourcesPath() + name); this.setUnlocalizedName(name); this.setCreativeTab(tab); return this; } }
AlphaSwittle-Team/AnimalWarriors
src/main/java/mcmod/nxs/animalwarriors/lib/ArmorHelper.java
Java
gpl-2.0
489
<!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <title> </title> <style> .municipios{ font-size:12px; font-family: 'helvetica','raleway'; padding:1em 1em; background-color:#2C85AF; color:#FFFFFF; } .direccion{ font-size:12px; font-family: 'helvetica','raleway'; padding:1em 4em; background-color:#2C85AF; color:#FFFFFF; } .rellenotabla{ font-size: 10px; padding:1em 1em; font-family: 'helvetica','raleway'; } .rellenotabla2{ font-size: 10px; padding:1em 3em; font-family: 'helvetica','raleway'; } .textocolspan{ font-size:10px; font-family: 'helvetica','raleway'; background-color:#5AAED0; color:#FFFFFF; text-align:left; padding: 0.5em 1em; text-shadow: 1px 1px #000000; } @font-face { font-family: 'helvetica'; src: url('fonts/helvetica-b.eot'); /* IE9 Compat Modes */ src: url('fonts/helvetica-b.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */ url('fonts/helveticaneue-webfont.woff') format('woff'), /* Modern Browsers */ url('fonts/HELVE6.ttf') format('truetype'), /* Safari, Android, iOS */ url('fonts/Helvetica_Neue_typeface_weights.svg#svgFontName') format('svg'); /* Legacy iOS */ } div.boton_ubicacion{ background-color: #035A9F; color: #FFFFFF; } div.boton_ubicacion:hover{ background-color: #E4E5E6; color: #035A9F; } div#terminales{ display:inline-block; background-color:#2C85AF; color:#FFFFFF; font-family: 'raleway'; font-size:14px;padding:5px 15px; cursor:pointer; cursor: hand; margin-right:-4px; } div#terminales:hover{ background-color: #E4E5E6; color: #035A9F; } div#centros{ display:inline-block; background-color:#2C85AF; color:#FFFFFF; font-family: 'raleway'; font-size:14px; padding:5px 15px; cursor:pointer; cursor: hand; margin-right:-4px; } div#centros:hover{ background-color: #E4E5E6; color: #035A9F; } div#agencias{ display:inline-block; background-color:#2C85AF; color:#FFFFFF; font-family: 'raleway'; font-size:14px; padding:5px 15px; cursor:pointer; cursor: hand; margin-right:-4px; } div#agencias:hover{ background-color: #E4E5E6; color: #035A9F; } div#oxxo{ display:inline-block; background-color:#2C85AF; color:#FFFFFF; font-family: 'raleway'; font-size:14px; padding:5px 15px; cursor:pointer; cursor: hand; margin-right:-4px; } div#oxxo:hover{ background-color: #E4E5E6; color: #035A9F; } </style> </head> <body> <div style="width:100%;border:1px solid #BDBDBD;text-align:center;overflow:hidden;float:right"> <div id="terminales" >Terminales y Centrales</div> <div id="centros" >Centros Comerciales</div> <div id="agencias" >Agencias de Viajes</div> <div id="oxxo" >Oxxo</div> <!-- ============================TERMINALES Y CENTRALES================================================================= --> <div id="mostrartermi" style="display:block"> <div style="display:inline-block;text-align:left;font-family: 'helvetica','raleway'"> <div style="display:inline-block"><img src="img/terminales.jpg" alt=""> </div> <div style="display:inline-block"><p style="font-size:12px">TERMINALES Y CENTRALES</p> <p style="color:#1959A0;font-weight:bold">SINALOA</p></div> </div> <div style="display:inline-block;width:100%;font-family: 'helvetica','raleway';"> <div style="display:inline-block;padding:10px;text-align:left"> <p style="font-weight:bold">•Mazatlán</p> <p>Calle Ferrusquilla s/n Interior <br> Edificio central de Autobuses <br> Colonia Palos Prietos <br> Tel: 01 (669) 981 46 59</p> </div> <div style="display:inline-block;padding:10px;text-align:left"> <p style="font-weight:bold">•Plaza San Ignacio</p> <p>Carretera Internacional Km. 1205 <br> Col. Fovisste en Playa Azul <br> Tel. 01 (669) 135 12 34</p> </div> <div style="display:inline-block;padding:10px;text-align:left"> <p style="font-weight:bold">•Culiacán</p> <p style="font-size:12px"><strong>CENTRAL DE AUTOBUSES CULIACÁN</strong> <br> en sala de primera y sala de segunda. <br> Blvd. Rolando Arjona # 2571 Norte y Blvd. <br> Culiacan Colonia Desarrollo Urbano 3 Rios. <br> Tel. 01 (667) 761 27 61</p> </div> <div style="display:inline-block;padding:10px;text-align:left"> <p style="font-weight:bold">•Guamuchil</p> <p>Nicolas Bravo y Adolfo Lopez Mateos # 479 <br> Colonia Morelos <br> Tel: 01 (673) 732 67 50</p> </div> <div style="display:inline-block;padding:10px;text-align:left"> <p style="font-weight:bold">•Guasave</p> <p >Blvd. 16 de Septiembre y 5 de Febrero S/n <br> Colonia <Centrobr></Centrobr> Tel. 01 (687) 872 98 45</p> </div> <div style="display:inline-block;padding:10px;text-align:left"> <p style="font-weight:bold">•Los Mochis</p> <p style="font-size:12px"><strong>TERMINAL</strong> <br> Blvd. Rosendo G. Castro y <br> Belisario Dominguez # 620 Sur <br> Colonia Bienestar <br> Tel: 01 (668) 817 59 07 <br> <strong>CENTRAL DE AUTOBUSES</strong> <br> Blvd. Rosendo G. Castro y Constitucion # 302 Oriente Col. Bienestar <br> Tel: 01 (668) 815 67 84</p> </div> </div> </div> <!-- ====================================CENTROS COMERCIALES============================================================ --> <div id="mostrarcentros" style="display:none"> <div style="display:block;text-align:center;font-family: 'helvetica','raleway'"> <div style="display:inline-block"><img src="img/comerciales.jpg" alt=""> </div> <div style="display:inline-block"><p style="font-size:12px">CENTROS COMERCIALES</p> <p style="color:#1959A0;font-weight:bold">SINALOA</p></div> </div> <div style="display:inline-block;font-family: 'helvetica',raleway';width:100%;text-align:center"> <div style="display:inline-block;font-size:15px;text-align:left;padding:10px"> <img style="width:100px" src="img/bodega_aurrera.png" alt=""> <p style="font-weight:bold;">•Estadio, Culiacán</p> <p>Blvd. Enrique Sáncez Alonso 2402 Nte. <br> Col. Desarrollo Urbano Tres Rios <br> C.P. 80030 <br> Tel. 01 (667) 146 61 60</p> </div> <div style="display:inline-block;font-size:15px;text-align:left;padding:10px"> <img style="width:100px" src="img/walmart.png" alt=""> <p style="font-weight:bold;"> •Los Mochis</p> <p>Blvd. Jiquilpan 1112 <br> Pte Local B <br> Col. Jiquilpan Ahome C.P. 81220 <br> Tel. 01 (668) 818 28 35</p> </div> <div style="display:inline-block;font-size:15px;text-align:left;padding:10px"> <img style="width:100px" src="img/walmart.png" alt=""> <p style="font-weight:bold;">•Culiacán</p> <p>Av. Regional 1330 Norte <br> Col. Sector V de la Primera del <br> Plan Parcial <br> (Tres Tios) C.P. 80000 <br> Tel. 01 (667) 750 95 42</p> </div> <div style="display:inline-block;font-size:15px;text-align:left;padding:10px"> <img style="width:100px" src="img/walmart.png" alt=""> <p style="font-weight:bold;">•Walmart 68, Culiacán</p> <p>Carretera Internacional 2017 <br> Col. Hacienda del Mar C.P. 82128 <br> Tel. 01 (669) 940 81 66</p> </div> <div style="display:inline-block;font-size:15px;text-align:left;padding:10px"> <img style="width:100px" src="img/walmart.png" alt=""> <p style="font-weight:bold;">•El Cochi, Mazatlán</p> <p>Av. Manuel J. Clouthier 4459 <br> Col. El Cochi C.P. 82139</p> </div> <div style="display:inline-block;font-size:15px;text-align:left;padding:10px"> <img style="width:100px" src="img/walmart.png" alt=""> <p style="font-weight:bold;">•Soriana Santa Rosa, Mazatlán</p> <p>Av. Luis Donaldo Colosio 17301 <br> Col. Fracc. Valle Dorado C.P. 82165 <br> Tel. 01 (669) 940 58 34</p> </div> </div> </div> <!-- ======================================AGENCIAS DE VIAJES==================================================== --> <div id="mostraragencias" style="display:none"> <div style="display:inline-block;text-align:left;font-family: 'helvetica','raleway'"> <div style="display:inline-block"><img src="img/agencias.jpg" alt=""> </div> <div style="display:inline-block"><p style="font-size:12px">AGENCIAS DE VIAJES</p> <p style="color:#1959A0;font-weight:bold">SINALOA</p></div> </div> <center><table> <tr> <td class="municipios">MUNICIPIO</td> <td class="municipios">COLONIA</td> <td class="direccion">DIRECCIÓN</td> <td class="municipios">TELÉFONO 1</td> <td class="municipios">TELÉFONO 2</td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: SERVICIOS Y VIAJES MICHEL</td> </tr> <tr> <td class="rellenotabla">CULIACAN</td> <td class="rellenotabla">ALMADA</td> <td class="rellenotabla2">LAZARO CARDENAS N198-G</td> <td class="rellenotabla">6677128033</td> <td class="rellenotabla">6677128711</td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: ROSEF & TURISMO</td> </tr> <tr> <td class="rellenotabla">CULIACAN</td> <td class="rellenotabla">CHAPULTEPEC</td> <td class="rellenotabla2">ALVARO OBREGON 1330 NTE</td> <td class="rellenotabla">6677127700</td> <td class="rellenotabla">6677127701</td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: AGENCIA DE VIAJES NERY TOURS</td> </tr> <tr> <td class="rellenotabla">CULIACAN</td> <td class="rellenotabla">FEDERALISMO</td> <td class="rellenotabla2">BLVD CULIACAN 450-10</td> <td class="rellenotabla">6677612992</td> <td class="rellenotabla"></td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: CULHUACAN TOURS</td> </tr> <tr> <td class="rellenotabla">CULIACAN</td> <td class="rellenotabla">LAS QUINTAS</td> <td class="rellenotabla2">PRESA BALSEQUILLOS N 13</td> <td class="rellenotabla">6677152606</td> <td class="rellenotabla">6677152603</td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: SULLIVAN TURISMO</td> </tr> <tr> <td class="rellenotabla">CULIACAN</td> <td class="rellenotabla">VALLADO</td> <td class="rellenotabla2">BLVD EMILIANO ZAPATA N 2151</td> <td class="rellenotabla">6677178364</td> <td class="rellenotabla">6677176350</td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: AGENCIA MORAGA</td> </tr> <tr> <td class="rellenotabla">GUAMUCHIL</td> <td class="rellenotabla">CENTRO</td> <td class="rellenotabla2">AGUSTINA RAMIREZ SUR NO. 671-A</td> <td class="rellenotabla">673 7322401</td> <td class="rellenotabla"></td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: VIAJES LUDACAR</td> </tr> <tr> <td class="rellenotabla">GUASAVE</td> <td class="rellenotabla">CENTRO</td> <td class="rellenotabla2">EMILIANO ZAPATA N 45</td> <td class="rellenotabla">6878714677</td> <td class="rellenotabla">6878714657</td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: SOLEITOURS</td> </tr> <tr> <td class="rellenotabla">LOS MOCHIS</td> <td class="rellenotabla">CENTRO</td> <td class="rellenotabla2">CARDENAS PONIENTE N.- 509</td> <td class="rellenotabla">6688123030</td> <td class="rellenotabla">018009676534</td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: VIAJES TRANVIA</td> </tr> <tr> <td class="rellenotabla">LOS MOCHIS</td> <td class="rellenotabla">CENTRO</td> <td class="rellenotabla2">CALLEJON TENOCHTITLAN PTE N.- 399</td> <td class="rellenotabla">6688123864</td> <td class="rellenotabla"></td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: SERVICIOS TURISTICOS CONELVA</td> </tr> <tr> <td class="rellenotabla">LOS MOCHIS</td> <td class="rellenotabla">CENTRO AHOME</td> <td class="rellenotabla2">GABRIEL LEYVA SOLANO 357 NTE</td> <td class="rellenotabla">6688152484</td> <td class="rellenotabla">6688158090</td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: VIAJES COPALA</td> </tr> <tr> <td class="rellenotabla">MAZATLAN</td> <td class="rellenotabla">C.C LA GRAN PLAZA</td> <td class="rellenotabla2">APOLO Y REFORMA L -F-4</td> <td class="rellenotabla">6699862120</td> <td class="rellenotabla"></td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: VIAJES MARLOPOS</td> </tr> <tr> <td class="rellenotabla">MAZATLAN</td> <td class="rellenotabla">CENTRO</td> <td class="rellenotabla2">AV OLAS ALTAS N 11</td> <td class="rellenotabla">6699811993</td> <td class="rellenotabla">6699811994</td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: VISTA TOURS MAZATLAN S.A DE C.V</td> </tr> <tr> <td class="rellenotabla">MAZATLAN</td> <td class="rellenotabla">LOMAS DE MAZATLAN</td> <td class="rellenotabla2">AV. CAMARON SABALO NO. 51 LOC. 2 Y 3</td> <td class="rellenotabla">(669) 9868610</td> <td class="rellenotabla"></td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: PROMOTOURS EL CID</td> </tr> <tr> <td class="rellenotabla">MAZATLAN</td> <td class="rellenotabla">ZONA DORADA</td> <td class="rellenotabla2">AV CAMARON SABALO S/N LOC. 18</td> <td class="rellenotabla"></td> <td class="rellenotabla"></td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: AGENCIA DE VIAJES NERY TOURS SUC NOVOLATO</td> </tr> <tr> <td class="rellenotabla">NAVOLATO</td> <td class="rellenotabla">CENTRO</td> <td class="rellenotabla2">AV NIÑOS HEROES 484-A</td> <td class="rellenotabla">6727271850</td> <td class="rellenotabla"></td> </tr> </table></center> </div> <!-- =================================================OXXO======================================================================== --> <div id="mostraroxxo" style="display:none"> <p style="font-family:'helvetica','raleway'">Adquiere tus boletos de autobus TAP en las tiendas Oxxo.</p> </div> </div> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script> $(function(){ $('#oxxo').on('click', mostraroxo); function mostraroxo(){ $('#mostraroxxo').css('display', 'block'); $('#mostrartermi').css('display', 'none'); $('#mostraragencias').css('display', 'none'); $('#mostrarcentros').css('display', 'none'); } ; $('#agencias').on('click',mostraragen); function mostraragen(){ $('#mostraragencias').css('display', 'block'); $('#mostraroxxo').css('display', 'none'); $('#mostrartermi').css('display', 'none'); $('#mostrarcentros').css('display', 'none'); } ; $('#centros').on('click',mostrarcen); function mostrarcen(){ $('#mostrarcentros').css('display', 'block'); $('#mostraroxxo').css('display', 'none'); $('#mostrartermi').css('display', 'none'); $('#mostraragencias').css('display', 'none'); } ; $('#terminales').on('click',mostrarter); function mostrarter (){ $('#mostrartermi').css('display', 'block'); $('#mostraroxxo').css('display', 'none'); $('#mostraragencias').css('display', 'none'); $('#mostrarcentros').css('display', 'none'); } }); </script> </body> </html>
master777/tap
sinaloa.php
PHP
gpl-2.0
19,724
// float_digits(). // General includes. #include "base/cl_sysdep.h" // Specification. #include "cln/dfloat.h" // Implementation. #include "float/dfloat/cl_DF.h" namespace cln { CL_INLINE uintC CL_INLINE_DECL(float_digits) (const cl_DF& x) { unused x; return DF_mant_len+1; // 53 } } // namespace cln
ARudik/feelpp.cln
src/float/dfloat/misc/cl_DF_digits.cc
C++
gpl-2.0
311
package org.scada_lts.dao.model.multichangehistory; import java.util.Objects; /** * @author grzegorz.bylica@abilit.eu on 16.10.2019 */ public class MultiChangeHistoryValues { private int id; private int userId; private String userName; private String viewAndCmpIdentyfication; private String interpretedState; private long timeStamp; private int valueId; private String value; private int dataPointId; private String xidPoint; public MultiChangeHistoryValues() {} public int getId() { return id; } public void setId(int id) { this.id = id; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getViewAndCmpIdentyfication() { return viewAndCmpIdentyfication; } public void setViewAndCmpIdentyfication(String viewAndCmpIdentyfication) { this.viewAndCmpIdentyfication = viewAndCmpIdentyfication; } public String getInterpretedState() { return interpretedState; } public void setInterpretedState(String interpretedState) { this.interpretedState = interpretedState; } public long getTimeStamp() { return timeStamp; } public void setTimeStamp(long timeStamp) { this.timeStamp = timeStamp; } public int getValueId() { return valueId; } public void setValueId(int valueId) { this.valueId = valueId; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public int getDataPointId() { return dataPointId; } public void setDataPointId(int dataPointId) { this.dataPointId = dataPointId; } public String getXidPoint() { return xidPoint; } public void setXidPoint(String xidPoint) { this.xidPoint = xidPoint; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MultiChangeHistoryValues that = (MultiChangeHistoryValues) o; return id == that.id && userId == that.userId && valueId == that.valueId && dataPointId == that.dataPointId && Objects.equals(userName, that.userName) && Objects.equals(viewAndCmpIdentyfication, that.viewAndCmpIdentyfication) && Objects.equals(interpretedState, that.interpretedState) && Objects.equals(timeStamp, that.timeStamp) && Objects.equals(value, that.value) && Objects.equals(xidPoint, that.xidPoint); } @Override public int hashCode() { return Objects.hash(id, userId, userName, viewAndCmpIdentyfication, interpretedState, timeStamp, valueId, value, dataPointId, xidPoint); } @Override public String toString() { return "MultiChangeHistoryValues{" + "id=" + id + ", userId=" + userId + ", userName='" + userName + '\'' + ", viewAndCmpIdentyfication='" + viewAndCmpIdentyfication + '\'' + ", interpretedState='" + interpretedState + '\'' + ", ts=" + timeStamp + ", valueId=" + valueId + ", value='" + value + '\'' + ", dataPointId=" + dataPointId + ", xidPoint='" + xidPoint + '\'' + '}'; } }
SCADA-LTS/Scada-LTS
src/org/scada_lts/dao/model/multichangehistory/MultiChangeHistoryValues.java
Java
gpl-2.0
3,725
<?php /** V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved. Released under both BSD license and Lesser GPL library license. Whenever there is any discrepancy between the two licenses, the BSD license will take precedence. Set tabs to 4 for best viewing. */ // security - hide paths if (!defined('ADODB_DIR')) die(); class ADODB2_ibase extends ADODB_DataDict { var $databaseType = 'ibase'; var $seqField = false; function ActualType($meta) { switch($meta) { case 'C': return 'VARCHAR'; case 'XL': case 'X': return 'VARCHAR(4000)'; case 'C2': return 'VARCHAR'; // up to 32K case 'X2': return 'VARCHAR(4000)'; case 'B': return 'BLOB'; case 'D': return 'DATE'; case 'T': return 'TIMESTAMP'; case 'L': return 'SMALLINT'; case 'I': return 'INTEGER'; case 'I1': return 'SMALLINT'; case 'I2': return 'SMALLINT'; case 'I4': return 'INTEGER'; case 'I8': return 'INTEGER'; case 'F': return 'DOUBLE PRECISION'; case 'N': return 'DECIMAL'; default: return $meta; } } function AlterColumnSQL($tabname, $flds) { if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported"); return array(); } function DropColumnSQL($tabname, $flds) { if ($this->debug) ADOConnection::outp("DropColumnSQL not supported"); return array(); } } ?>
freemed/freemed-0.8.x
lib/acl/adodb/datadict/datadict-ibase.inc.php
PHP
gpl-2.0
1,369
# -*- coding: utf-8 -*- # ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######. # .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....## # .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#.##......##.....#.##...... # .##.....#.########.######..##.##.#..######.##......########.##.....#.########.######..########..######. # .##.....#.##.......##......##..###.......#.##......##...##..########.##.......##......##...##........## # .##.....#.##.......##......##...##.##....#.##....#.##....##.##.....#.##.......##......##....##.##....## # ..#######.##.......#######.##....#..######..######.##.....#.##.....#.##.......#######.##.....#..######. ''' OpenScrapers Project This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import re from openscrapers.modules import cleantitle, source_utils, cfscrape class source: def __init__(self): self.priority = 1 self.language = ['en'] self.domains = ['coolmoviezone.online'] self.base_link = 'https://coolmoviezone.online' self.scraper = cfscrape.create_scraper() def movie(self, imdb, title, localtitle, aliases, year): try: title = cleantitle.geturl(title) url = self.base_link + '/%s-%s' % (title, year) return url except: return def sources(self, url, hostDict, hostprDict): try: sources = [] r = self.scraper.get(url).content match = re.compile('<td align="center"><strong><a href="(.+?)"').findall(r) for url in match: host = url.split('//')[1].replace('www.', '') host = host.split('/')[0].split('.')[0].title() quality = source_utils.check_sd_url(url) sources.append({'source': host, 'quality': quality, 'language': 'en', 'url': url, 'direct': False, 'debridonly': False}) except Exception: return return sources def resolve(self, url): return url
repotvsupertuga/tvsupertuga.repository
script.module.openscrapers/lib/openscrapers/sources_openscrapers/en/coolmoviezone.py
Python
gpl-2.0
2,749
/* * 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 org.apache.fontbox.cff.charset; /** * This is specialized CFFCharset. It's used if the CharsetId of a font is set to 1. * * @author Villu Ruusmann * @version $Revision$ */ public class CFFExpertCharset extends CFFCharset { private CFFExpertCharset() { } /** * Returns an instance of the CFFExpertCharset class. * * @return an instance of CFFExpertCharset */ public static CFFExpertCharset getInstance() { return CFFExpertCharset.INSTANCE; } private static final CFFExpertCharset INSTANCE = new CFFExpertCharset(); static { INSTANCE.register(1, "space"); INSTANCE.register(13, "comma"); INSTANCE.register(14, "hyphen"); INSTANCE.register(15, "period"); INSTANCE.register(27, "colon"); INSTANCE.register(28, "semicolon"); INSTANCE.register(99, "fraction"); INSTANCE.register(109, "fi"); INSTANCE.register(110, "fl"); INSTANCE.register(150, "onesuperior"); INSTANCE.register(155, "onehalf"); INSTANCE.register(158, "onequarter"); INSTANCE.register(163, "threequarters"); INSTANCE.register(164, "twosuperior"); INSTANCE.register(169, "threesuperior"); INSTANCE.register(229, "exclamsmall"); INSTANCE.register(230, "Hungarumlautsmall"); INSTANCE.register(231, "dollaroldstyle"); INSTANCE.register(232, "dollarsuperior"); INSTANCE.register(233, "ampersandsmall"); INSTANCE.register(234, "Acutesmall"); INSTANCE.register(235, "parenleftsuperior"); INSTANCE.register(236, "parenrightsuperior"); INSTANCE.register(237, "twodotenleader"); INSTANCE.register(238, "onedotenleader"); INSTANCE.register(239, "zerooldstyle"); INSTANCE.register(240, "oneoldstyle"); INSTANCE.register(241, "twooldstyle"); INSTANCE.register(242, "threeoldstyle"); INSTANCE.register(243, "fouroldstyle"); INSTANCE.register(244, "fiveoldstyle"); INSTANCE.register(245, "sixoldstyle"); INSTANCE.register(246, "sevenoldstyle"); INSTANCE.register(247, "eightoldstyle"); INSTANCE.register(248, "nineoldstyle"); INSTANCE.register(249, "commasuperior"); INSTANCE.register(250, "threequartersemdash"); INSTANCE.register(251, "periodsuperior"); INSTANCE.register(252, "questionsmall"); INSTANCE.register(253, "asuperior"); INSTANCE.register(254, "bsuperior"); INSTANCE.register(255, "centsuperior"); INSTANCE.register(256, "dsuperior"); INSTANCE.register(257, "esuperior"); INSTANCE.register(258, "isuperior"); INSTANCE.register(259, "lsuperior"); INSTANCE.register(260, "msuperior"); INSTANCE.register(261, "nsuperior"); INSTANCE.register(262, "osuperior"); INSTANCE.register(263, "rsuperior"); INSTANCE.register(264, "ssuperior"); INSTANCE.register(265, "tsuperior"); INSTANCE.register(266, "ff"); INSTANCE.register(267, "ffi"); INSTANCE.register(268, "ffl"); INSTANCE.register(269, "parenleftinferior"); INSTANCE.register(270, "parenrightinferior"); INSTANCE.register(271, "Circumflexsmall"); INSTANCE.register(272, "hyphensuperior"); INSTANCE.register(273, "Gravesmall"); INSTANCE.register(274, "Asmall"); INSTANCE.register(275, "Bsmall"); INSTANCE.register(276, "Csmall"); INSTANCE.register(277, "Dsmall"); INSTANCE.register(278, "Esmall"); INSTANCE.register(279, "Fsmall"); INSTANCE.register(280, "Gsmall"); INSTANCE.register(281, "Hsmall"); INSTANCE.register(282, "Ismall"); INSTANCE.register(283, "Jsmall"); INSTANCE.register(284, "Ksmall"); INSTANCE.register(285, "Lsmall"); INSTANCE.register(286, "Msmall"); INSTANCE.register(287, "Nsmall"); INSTANCE.register(288, "Osmall"); INSTANCE.register(289, "Psmall"); INSTANCE.register(290, "Qsmall"); INSTANCE.register(291, "Rsmall"); INSTANCE.register(292, "Ssmall"); INSTANCE.register(293, "Tsmall"); INSTANCE.register(294, "Usmall"); INSTANCE.register(295, "Vsmall"); INSTANCE.register(296, "Wsmall"); INSTANCE.register(297, "Xsmall"); INSTANCE.register(298, "Ysmall"); INSTANCE.register(299, "Zsmall"); INSTANCE.register(300, "colonmonetary"); INSTANCE.register(301, "onefitted"); INSTANCE.register(302, "rupiah"); INSTANCE.register(303, "Tildesmall"); INSTANCE.register(304, "exclamdownsmall"); INSTANCE.register(305, "centoldstyle"); INSTANCE.register(306, "Lslashsmall"); INSTANCE.register(307, "Scaronsmall"); INSTANCE.register(308, "Zcaronsmall"); INSTANCE.register(309, "Dieresissmall"); INSTANCE.register(310, "Brevesmall"); INSTANCE.register(311, "Caronsmall"); INSTANCE.register(312, "Dotaccentsmall"); INSTANCE.register(313, "Macronsmall"); INSTANCE.register(314, "figuredash"); INSTANCE.register(315, "hypheninferior"); INSTANCE.register(316, "Ogoneksmall"); INSTANCE.register(317, "Ringsmall"); INSTANCE.register(318, "Cedillasmall"); INSTANCE.register(319, "questiondownsmall"); INSTANCE.register(320, "oneeighth"); INSTANCE.register(321, "threeeighths"); INSTANCE.register(322, "fiveeighths"); INSTANCE.register(323, "seveneighths"); INSTANCE.register(324, "onethird"); INSTANCE.register(325, "twothirds"); INSTANCE.register(326, "zerosuperior"); INSTANCE.register(327, "foursuperior"); INSTANCE.register(328, "fivesuperior"); INSTANCE.register(329, "sixsuperior"); INSTANCE.register(330, "sevensuperior"); INSTANCE.register(331, "eightsuperior"); INSTANCE.register(332, "ninesuperior"); INSTANCE.register(333, "zeroinferior"); INSTANCE.register(334, "oneinferior"); INSTANCE.register(335, "twoinferior"); INSTANCE.register(336, "threeinferior"); INSTANCE.register(337, "fourinferior"); INSTANCE.register(338, "fiveinferior"); INSTANCE.register(339, "sixinferior"); INSTANCE.register(340, "seveninferior"); INSTANCE.register(341, "eightinferior"); INSTANCE.register(342, "nineinferior"); INSTANCE.register(343, "centinferior"); INSTANCE.register(344, "dollarinferior"); INSTANCE.register(345, "periodinferior"); INSTANCE.register(346, "commainferior"); INSTANCE.register(347, "Agravesmall"); INSTANCE.register(348, "Aacutesmall"); INSTANCE.register(349, "Acircumflexsmall"); INSTANCE.register(350, "Atildesmall"); INSTANCE.register(351, "Adieresissmall"); INSTANCE.register(352, "Aringsmall"); INSTANCE.register(353, "AEsmall"); INSTANCE.register(354, "Ccedillasmall"); INSTANCE.register(355, "Egravesmall"); INSTANCE.register(356, "Eacutesmall"); INSTANCE.register(357, "Ecircumflexsmall"); INSTANCE.register(358, "Edieresissmall"); INSTANCE.register(359, "Igravesmall"); INSTANCE.register(360, "Iacutesmall"); INSTANCE.register(361, "Icircumflexsmall"); INSTANCE.register(362, "Idieresissmall"); INSTANCE.register(363, "Ethsmall"); INSTANCE.register(364, "Ntildesmall"); INSTANCE.register(365, "Ogravesmall"); INSTANCE.register(366, "Oacutesmall"); INSTANCE.register(367, "Ocircumflexsmall"); INSTANCE.register(368, "Otildesmall"); INSTANCE.register(369, "Odieresissmall"); INSTANCE.register(370, "OEsmall"); INSTANCE.register(371, "Oslashsmall"); INSTANCE.register(372, "Ugravesmall"); INSTANCE.register(373, "Uacutesmall"); INSTANCE.register(374, "Ucircumflexsmall"); INSTANCE.register(375, "Udieresissmall"); INSTANCE.register(376, "Yacutesmall"); INSTANCE.register(377, "Thornsmall"); INSTANCE.register(378, "Ydieresissmall"); } }
sencko/NALB
nalb2013/src/org/apache/fontbox/cff/charset/CFFExpertCharset.java
Java
gpl-2.0
8,359
</main> <div class="footer__break"></div> <footer id="footer" class="footer" role="contentinfo"> <div class="content__wrapper"> <?php get_template_part( 'template-parts/footer/newsletter' ); get_template_part( 'template-parts/footer/social' ); ?> </div> <?php get_template_part( 'template-parts/footer/copyright' ); ?> </footer> <?php get_template_part( 'template-parts/footer/bottom' ); ?> <?php wp_footer(); ?> </body> </html>
Fulcrum-Creatives/wordup
footer.php
PHP
gpl-2.0
454
package com.starfarers.dao; import java.util.List; public interface BaseDao<T> { public void create(T entity); public T save(T entity); public void save(List<T> entities); public void remove(T entity); public T find(Integer id); public List<T> findAll(); public <P> T findBy(String attribute, P parameter); }
Zweanslord/starfarers
src/main/java/com/starfarers/dao/BaseDao.java
Java
gpl-2.0
325
''' Ohm's law is a simple equation describing electrical circuits. It states that the voltage V through a resistor is equal to the current (I) times the resistance: V = I * R The units of these are volts, ampheres (or "amps"), and ohms, respectively. In real circuits, often R is actually measured in kiloohms (10**3 ohms) and I in milliamps (10**-3 amps). Let's create a Resistor class that models this behavior. The constructor takes two arguments - the resistance in ohms, and the voltage in volts: >>> resistor = Resistor(800, 5.5) >>> resistor.resistance 800 >>> resistor.voltage 5.5 The current is derived from these two using Ohm's law: (Hint: use @property) >>> resistor.current 0.006875 Since we may want the value in milliamps, let's make another property to provide that: >>> resistor.current_in_milliamps 6.875 Let's set it up so that we can change the current, and doing so will correspondingly modify the voltage (but keep the resistance constant). >>> resistor.current_in_milliamps = 3.5 >>> resistor.resistance 800 >>> round(resistor.voltage, 2) 2.8 >>> resistor.current = .006875 >>> round(resistor.voltage, 2) 5.5 >>> resistor.resistance 800 Also, we've made a design decision that a Resistor cannot change its resistance value once created: >>> resistor.resistance = 8200 Traceback (most recent call last): AttributeError: can't set attribute ''' # Write your code here: class Resistor: def __init__(self, resistance, voltage): self._resistance = resistance self.voltage = voltage @property def resistance(self): return self._resistance @property def current(self): return self.voltage / self.resistance @current.setter def current(self, value): self.voltage = self.resistance * value @property def current_in_milliamps(self): return self.current * 1000 @current_in_milliamps.setter def current_in_milliamps(self, value): self.current = value / 1000 # Do not edit any code below this line! if __name__ == '__main__': import doctest count, _ = doctest.testmod() if count == 0: print('*** ALL TESTS PASS ***\nGive someone a HIGH FIVE!') # Copyright 2015-2018 Aaron Maxwell. All rights reserved.
ketan-analytics/learnpython
Safaribookonline-Python/courseware-btb/solutions/py3/patterns/properties_extra.py
Python
gpl-2.0
2,255
using UnityEngine; using System.Collections; public class Metrics : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
JoeProgram/monster
Assets/Scripts/Metrics.cs
C#
gpl-2.0
206
<?php declare(strict_types=1); namespace PoPCMSSchema\QueriedObject\TypeResolvers\InterfaceType; use PoP\ComponentModel\TypeResolvers\InterfaceType\AbstractInterfaceTypeResolver; class QueryableInterfaceTypeResolver extends AbstractInterfaceTypeResolver { public function getTypeName(): string { return 'Queryable'; } public function getTypeDescription(): ?string { return $this->__('Entities that can be queried through an URL', 'queriedobject'); } }
leoloso/PoP
layers/CMSSchema/packages/queriedobject/src/TypeResolvers/InterfaceType/QueryableInterfaceTypeResolver.php
PHP
gpl-2.0
497
<?php /** * ifeelweb.de WordPress Plugin Framework * For more information see http://www.ifeelweb.de/wp-plugin-framework * * Adapter to use ZendFramework as admin application * * @author Timo Reith <timo@ifeelweb.de> * @copyright Copyright (c) ifeelweb.de * @version $Id: ZendFw.php 911603 2014-05-10 10:58:23Z worschtebrot $ * @package IfwPsn_Wp_Plugin_Application */ require_once dirname(__FILE__) . '/Interface.php'; class IfwPsn_Wp_Plugin_Application_Adapter_ZendFw implements IfwPsn_Wp_Plugin_Application_Adapter_Interface { /** * @var IfwPsn_Wp_Plugin_Manager */ protected $_pm; /** * @var IfwPsn_Zend_Application */ protected $_application; /** * @var string */ protected $_output; /** * The default error reporting level * @var int */ protected $_errorReporting; /** * @param IfwPsn_Wp_Plugin_Manager $pm */ public function __construct (IfwPsn_Wp_Plugin_Manager $pm) { $this->_pm = $pm; } /** * Loads the admin application */ public function load() { $this->_registerAutostart(); require_once $this->_pm->getPathinfo()->getRootLib() . 'IfwPsn/Zend/Application.php'; $this->_application = new IfwPsn_Zend_Application($this->_pm->getEnv()->getEnvironmet()); // set the dynamic options from php config file $this->_application->setOptions($this->_getApplicationOptions()); // run the application bootstrap $this->_pm->getLogger()->logPrefixed('Bootstrapping application...'); $this->_application->bootstrap(); } /** * */ protected function _registerAutostart() { require_once $this->_pm->getPathinfo()->getRootLib() . 'IfwPsn/Wp/Plugin/Application/Adapter/ZendFw/Autostart/EnqueueScripts.php'; require_once $this->_pm->getPathinfo()->getRootLib() . 'IfwPsn/Wp/Plugin/Application/Adapter/ZendFw/Autostart/StripSlashes.php'; require_once $this->_pm->getPathinfo()->getRootLib() . 'IfwPsn/Wp/Plugin/Application/Adapter/ZendFw/Autostart/ZendFormTranslation.php'; $result = array( new IfwPsn_Wp_Plugin_Application_Adapter_ZendFw_Autostart_EnqueueScripts($this), new IfwPsn_Wp_Plugin_Application_Adapter_ZendFw_Autostart_StripSlashes($this), new IfwPsn_Wp_Plugin_Application_Adapter_ZendFw_Autostart_ZendFormTranslation($this), ); foreach($result as $autostart) { $autostart->execute(); } } /** * Retrieves the application options * @return array */ protected function _getApplicationOptions() { $options = include $this->_pm->getPathinfo()->getRootAdminMenu() . 'configs/application.php'; if ($this->_pm->getEnv()->getEnvironmet() == 'development') { $options['resources']['FrontController']['params']['displayExceptions'] = 1; $options['phpSettings']['error_reporting'] = 6143; // E_ALL & ~E_STRICT $options['phpSettings']['display_errors'] = 1; $options['phpSettings']['display_startup_errors'] = 1; } return $options; } /** * @param $controllerName * @param string $module */ public function overwriteController($controllerName, $module = 'default') { $front = IfwPsn_Zend_Controller_Front::getInstance(); $request = new IfwPsn_Vendor_Zend_Controller_Request_Http(); $request->setParam('controller', $controllerName); $request->setParam('mod', $module); $front->setRequest($request); } /** * Inits the controller */ public function init() { $this->_activateErrorReporting(); try { // init the controller object to add actions before load-{page-id} action $this->_application->initController(); } catch (Exception $e) { $this->_handleException($e); } $this->_deactivateErrorReporting(); } /** * @return mixed|void */ public function render() { $this->_activateErrorReporting(); try { $this->_output = $this->_application->run(); } catch (Exception $e) { $this->_handleException($e); } $this->_deactivateErrorReporting(); } /** * @return mixed|void */ public function display() { $this->_activateErrorReporting(); try { echo $this->_output; } catch (Exception $e) { $this->_handleException($e); } $this->_deactivateErrorReporting(); } /** * Activates the error reporting in dev mode */ protected function _activateErrorReporting() { // store the default error level $this->_errorReporting = error_reporting(); if ($this->_pm->getEnv()->getEnvironmet() == 'development' || $this->_pm->getConfig()->debug->show_errors == '1') { // E_ALL & ~E_STRICT error_reporting(6143); } } /** * Resets the error reporting to default in dev mode */ protected function _deactivateErrorReporting() { if ($this->_pm->getEnv()->getEnvironmet() == 'development' || $this->_pm->getConfig()->debug->show_errors == '1') { error_reporting($this->_errorReporting); } } /** * @param Exception $e */ protected function _handleException(Exception $e) { $this->_pm->getLogger()->error($e->getMessage()); $request = IfwPsn_Zend_Controller_Front::getInstance()->getRequest(); // Repoint the request to the default error handler // $request->setModuleName('default'); // $request->setControllerName('Psn-ewrror'); // $request->setActionName('error'); // Set up the error handler $error = new IfwPsn_Vendor_Zend_Controller_Plugin_ErrorHandler(array( 'controller' => $this->_pm->getAbbrLower() . '-error' )); $error->type = IfwPsn_Vendor_Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER; $error->request = clone($request); $error->exception = $e; $request->setParam('error_handler', $error); } /** * @return IfwPsn_Wp_Plugin_Manager */ public function getPluginManager() { return $this->_pm; } }
brasadesign/wpecotemporadas
wp-content/plugins/post-status-notifier-lite/lib/IfwPsn/Wp/Plugin/Application/Adapter/ZendFw.php
PHP
gpl-2.0
6,435
# coding=utf-8 # --------------------------------------------------------------- # Desenvolvedor: Arannã Sousa Santos # Mês: 12 # Ano: 2015 # Projeto: pagseguro_xml # e-mail: asousas@live.com # --------------------------------------------------------------- import logging from pagseguro_xml.notificacao import ApiPagSeguroNotificacao_v3, CONST_v3 logger = logging.basicConfig(level=logging.DEBUG) PAGSEGURO_API_AMBIENTE = u'sandbox' PAGSEGURO_API_EMAIL = u'seu@email.com' PAGSEGURO_API_TOKEN_PRODUCAO = u'' PAGSEGURO_API_TOKEN_SANDBOX = u'' CHAVE_NOTIFICACAO = u'AA0000-AA00A0A0AA00-AA00AA000000-AA0000' # ela éh de producao api = ApiPagSeguroNotificacao_v3(ambiente=CONST_v3.AMBIENTE.SANDBOX) PAGSEGURO_API_TOKEN = PAGSEGURO_API_TOKEN_PRODUCAO ok, retorno = api.consulta_notificacao_transacao_v3(PAGSEGURO_API_EMAIL, PAGSEGURO_API_TOKEN, CHAVE_NOTIFICACAO) if ok: print u'-' * 50 print retorno.xml print u'-' * 50 for a in retorno.alertas: print a else: print u'Motivo do erro:', retorno
arannasousa/pagseguro_xml
exemplos/testes_notificacao.py
Python
gpl-2.0
1,090
<?php /** * @package Mambo * @author Mambo Foundation Inc see README.php * @copyright Mambo Foundation Inc. * See COPYRIGHT.php for copyright notices and details. * @license GNU/GPL Version 2, see LICENSE.php * Mambo 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. */ /** ensure this file is being included by a parent file */ defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' ); /** * AWSTATS BROWSERS DATABASE * If you want to add a Browser to extend AWStats database detection capabilities, * you must add an entry in BrowsersSearchIDOrder and in BrowsersHashIDLib. * * * BrowsersSearchIDOrder * This list is used to know in which order to search Browsers IDs (Most * frequent one are first in this list to increase detect speed). * It contains all matching criteria to search for in log fields. * Note: Browsers IDs are in lower case and ' ' and '+' are changed into '_' */ $browserSearchOrder = array ( // Most frequent standard web browsers are first in this list "icab", "go!zilla", "konqueror", "links", "lynx", "omniweb", "opera", "msie 6\.0", "apachebench", "wget", // Other standard web browsers "22acidownload", "aol\\-iweng", "amaya", "amigavoyager", "aweb", "bpftp", "chimera", "cyberdog", "dillo", "dreamcast", "downloadagent", "ecatch", "emailsiphon", "encompass", "friendlyspider", "fresco", "galeon", "getright", "headdump", "hotjava", "ibrowse", "intergo", "k-meleon", "linemodebrowser", "lotus-notes", "macweb", "multizilla", "ncsa_mosaic", "netpositive", "nutscrape", "msfrontpageexpress", "phoenix", "firebird", "firefox", "safari", "tzgeturl", "viking", "webfetcher", "webexplorer", "webmirror", "webvcr", // Site grabbers "teleport", "webcapture", "webcopier", // Music only browsers "real", "winamp", // Works for winampmpeg and winamp3httprdr "windows-media-player", "audion", "freeamp", "itunes", "jetaudio", "mint_audio", "mpg123", "nsplayer", "sonique", "uplayer", "xmms", "xaudio", // PDA/Phonecell browsers "alcatel", // Alcatel "mot-", // Motorola "nokia", // Nokia "panasonic", // Panasonic "philips", // Philips "sonyericsson", // SonyEricsson "ericsson", // Ericsson (must be after sonyericsson "mmef", "mspie", "wapalizer", "wapsilon", "webcollage", "up\.", // Works for UP.Browser and UP.Link // PDA/Phonecell I-Mode browsers "docomo", "portalmmm", // Others (TV) "webtv", // Other kind of browsers "csscheck", "w3m", "w3c_css_validator", "w3c_validator", "wdg_validator", "webzip", "staroffice", "mozilla", // Must be at end because a lot of browsers contains mozilla in string "libwww" // Must be at end because some browser have both "browser id" and "libwww" ); $browsersAlias = array ( // Common web browsers text (IE and Netscape must not be in this list) "icab"=>"iCab", "go!zilla"=>"Go!Zilla", "konqueror"=>"Konqueror", "links"=>"Links", "lynx"=>"Lynx", "omniweb"=>"OmniWeb", "opera"=>"Opera", "msie 6\.0"=>"Microsoft Internet Explorer 6.0", "apachebench"=>"ApacheBench", "wget"=>"Wget", "22acidownload"=>"22AciDownload", "aol\\-iweng"=>"AOL-Iweng", "amaya"=>"Amaya", "amigavoyager"=>"AmigaVoyager", "aweb"=>"AWeb", "bpftp"=>"BPFTP", "chimera"=>"Chimera", "cyberdog"=>"Cyberdog", "dillo"=>"Dillo", "dreamcast"=>"Dreamcast", "downloadagent"=>"DownloadAgent", "ecatch", "eCatch", "emailsiphon"=>"EmailSiphon", "encompass"=>"Encompass", "friendlyspider"=>"FriendlySpider", "fresco"=>"ANT Fresco", "galeon"=>"Galeon", "getright"=>"GetRight", "headdump"=>"HeadDump", "hotjava"=>"Sun HotJava", "ibrowse"=>"IBrowse", "intergo"=>"InterGO", "k-meleon"=>"K-Meleon", "linemodebrowser"=>"W3C Line Mode Browser", "lotus-notes"=>"Lotus Notes web client", "macweb"=>"MacWeb", "multizilla"=>"MultiZilla", "ncsa_mosaic"=>"NCSA Mosaic", "netpositive"=>"NetPositive", "nutscrape", "Nutscrape", "msfrontpageexpress"=>"MS FrontPage Express", "phoenix"=>"Phoenix", "firebird"=>"Mozilla Firebird", "firefox"=>"Mozilla Firefox", "safari"=>"Safari", "tzgeturl"=>"TzGetURL", "viking"=>"Viking", "webfetcher"=>"WebFetcher", "webexplorer"=>"IBM-WebExplorer", "webmirror"=>"WebMirror", "webvcr"=>"WebVCR", // Site grabbers "teleport"=>"TelePort Pro", "webcapture"=>"Acrobat", "webcopier", "WebCopier", // Music only browsers "real"=>"RealAudio or compatible (media player)", "winamp"=>"WinAmp (media player)", // Works for winampmpeg and winamp3httprdr "windows-media-player"=>"Windows Media Player (media player)", "audion"=>"Audion (media player)", "freeamp"=>"FreeAmp (media player)", "itunes"=>"Apple iTunes (media player)", "jetaudio"=>"JetAudio (media player)", "mint_audio"=>"Mint Audio (media player)", "mpg123"=>"mpg123 (media player)", "nsplayer"=>"NetShow Player (media player)", "sonique"=>"Sonique (media player)", "uplayer"=>"Ultra Player (media player)", "xmms"=>"XMMS (media player)", "xaudio"=>"Some XAudio Engine based MPEG player (media player)", // PDA/Phonecell browsers "alcatel"=>"Alcatel Browser (PDA/Phone browser)", "ericsson"=>"Ericsson Browser (PDA/Phone browser)", "mot-"=>"Motorola Browser (PDA/Phone browser)", "nokia"=>"Nokia Browser (PDA/Phone browser)", "panasonic"=>"Panasonic Browser (PDA/Phone browser)", "philips"=>"Philips Browser (PDA/Phone browser)", "sonyericsson"=>"Sony/Ericsson Browser (PDA/Phone browser)", "mmef"=>"Microsoft Mobile Explorer (PDA/Phone browser)", "mspie"=>"MS Pocket Internet Explorer (PDA/Phone browser)", "wapalizer"=>"WAPalizer (PDA/Phone browser)", "wapsilon"=>"WAPsilon (PDA/Phone browser)", "webcollage"=>"WebCollage (PDA/Phone browser)", "up\."=>"UP.Browser (PDA/Phone browser)", // Works for UP.Browser and UP.Link // PDA/Phonecell I-Mode browsers "docomo"=>"I-Mode phone (PDA/Phone browser)", "portalmmm"=>"I-Mode phone (PDA/Phone browser)", // Others (TV) "webtv"=>"WebTV browser", // Other kind of browsers "csscheck"=>"WDG CSS Validator", "w3m"=>"w3m", "w3c_css_validator"=>"W3C CSS Validator", "w3c_validator"=>"W3C HTML Validator", "wdg_validator"=>"WDG HTML Validator", "webzip"=>"WebZIP", "staroffice"=>"StarOffice", "mozilla"=>"Mozilla", "libwww"=>"LibWWW", ); // BrowsersHashAreGrabber // Put here an entry for each browser in BrowsersSearchIDOrder that are grabber // browsers. //--------------------------------------------------------------------------- $BrowsersHereAreGrabbers = array ( "teleport"=>"1", "webcapture"=>"1", "webcopier"=>"1", ); // BrowsersHashIcon // Each Browsers Search ID is associated to a string that is the name of icon // file for this browser. //--------------------------------------------------------------------------- $BrowsersHashIcon = array ( // Standard web browsers "msie"=>"msie", "netscape"=>"netscape", "icab"=>"icab", "go!zilla"=>"gozilla", "konqueror"=>"konqueror", "links"=>"notavailable", "lynx"=>"lynx", "omniweb"=>"omniweb", "opera"=>"opera", "wget"=>"notavailable", "22acidownload"=>"notavailable", "aol\\-iweng"=>"notavailable", "amaya"=>"amaya", "amigavoyager"=>"notavailable", "aweb"=>"notavailable", "bpftp"=>"notavailable", "chimera"=>"chimera", "cyberdog"=>"notavailable", "dillo"=>"notavailable", "dreamcast"=>"dreamcast", "downloadagent"=>"notavailable", "ecatch"=>"notavailable", "emailsiphon"=>"notavailable", "encompass"=>"notavailable", "friendlyspider"=>"notavailable", "fresco"=>"notavailable", "galeon"=>"galeon", "getright"=>"getright", "headdump"=>"notavailable", "hotjava"=>"notavailable", "ibrowse"=>"ibrowse", "intergo"=>"notavailable", "k-meleon"=>"kmeleon", "linemodebrowser"=>"notavailable", "lotus-notes"=>"notavailable", "macweb"=>"notavailable", "multizilla"=>"multizilla", "ncsa_mosaic"=>"notavailable", "netpositive"=>"netpositive", "nutscrape"=>"notavailable", "msfrontpageexpress"=>"notavailable", "phoenix"=>"phoenix", "firebird"=>"firebird", "safari"=>"safari", "tzgeturl"=>"notavailable", "viking"=>"notavailable", "webfetcher"=>"notavailable", "webexplorer"=>"notavailable", "webmirror"=>"notavailable", "webvcr"=>"notavailable", // Site grabbers "teleport"=>"teleport", "webcapture"=>"adobe", "webcopier"=>"webcopier", // Music only browsers "real"=>"mediaplayer", "winamp"=>"mediaplayer", // Works for winampmpeg and winamp3httprdr "windows-media-player"=>"mediaplayer", "audion"=>"mediaplayer", "freeamp"=>"mediaplayer", "itunes"=>"mediaplayer", "jetaudio"=>"mediaplayer", "mint_audio"=>"mediaplayer", "mpg123"=>"mediaplayer", "nsplayer"=>"mediaplayer", "sonique"=>"mediaplayer", "uplayer"=>"mediaplayer", "xmms"=>"mediaplayer", "xaudio"=>"mediaplayer", // PDA/Phonecell browsers "alcatel"=>"pdaphone", // Alcatel "ericsson"=>"pdaphone", // Ericsson "mot-"=>"pdaphone", // Motorola "nokia"=>"pdaphone", // Nokia "panasonic"=>"pdaphone", // Panasonic "philips"=>"pdaphone", // Philips "sonyericsson"=>"pdaphone", // Sony/Ericsson "mmef"=>"pdaphone", "mspie"=>"pdaphone", "wapalizer"=>"pdaphone", "wapsilon"=>"pdaphone", "webcollage"=>"pdaphone", "up\."=>"pdaphone", // Works for UP.Browser and UP.Link // PDA/Phonecell I-Mode browsers "docomo"=>"pdaphone", "portalmmm"=>"pdaphone", // Others (TV) "webtv"=>"webtv", // Other kind of browsers "csscheck"=>"notavailable", "w3m"=>"notavailable", "w3c_css_validator"=>"notavailable", "w3c_validator"=>"notavailable", "wdg_validator"=>"notavailable", "webzip"=>"webzip", "staroffice"=>"staroffice", "mozilla"=>"mozilla", "libwww"=>"notavailable" ); // TODO // Add Gecko category -> IE / Netscape / Gecko(except Netscape) / Other // IE (based on Mosaic) // Netscape family // Gecko except Netscape (Mozilla, Firebird (was Phoenix), Galeon, AmiZilla, Dino, and few others) // Opera (Opera 6/7) // KHTML (Konqueror, Safari) ?>
chanhong/mambo
includes/agent_browser.php
PHP
gpl-2.0
9,696
<style type="text/css"> .ppsAdminMainLeftSide { width: 56%; float: left; } .ppsAdminMainRightSide { width: <?php echo (empty($this->optsDisplayOnMainPage) ? 100 : 40)?>%; float: left; text-align: center; } #ppsMainOccupancy { box-shadow: none !important; } </style> <section> <div class="supsystic-item supsystic-panel"> <div id="containerWrapper"> <?php _e('Main page Go here!!!!', PPS_LANG_CODE)?> </div> <div style="clear: both;"></div> </div> </section>
Sciado/whitelabelheros.com
wp-content/plugins/popup-by-supsystic/modules/options/views/tpl/optionsAdminMain.php
PHP
gpl-2.0
486
/* * Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.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/>. */ /* ScriptData SDName: Npc_Taxi SD%Complete: 0% SDComment: To be used for taxi NPCs that are located globally. SDCategory: NPCs EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" #include "Player.h" #include "WorldSession.h" #define GOSSIP_SUSURRUS "I am ready." #define GOSSIP_NETHER_DRAKE "I'm ready to fly! Take me up, dragon!" #define GOSSIP_BRAZEN "I am ready to go to Durnholde Keep." #define GOSSIP_IRONWING "I'd like to take a flight around Stormwind Harbor." #define GOSSIP_DABIREE1 "Fly me to Murketh and Shaadraz Gateways" #define GOSSIP_DABIREE2 "Fly me to Shatter Point" #define GOSSIP_WINDBELLOW1 "Fly me to The Abyssal Shelf" #define GOSSIP_WINDBELLOW2 "Fly me to Honor Point" #define GOSSIP_BRACK1 "Fly me to Murketh and Shaadraz Gateways" #define GOSSIP_BRACK2 "Fly me to The Abyssal Shelf" #define GOSSIP_BRACK3 "Fly me to Spinebreaker Post" #define GOSSIP_IRENA "Fly me to Skettis please" #define GOSSIP_CLOUDBREAKER1 "Speaking of action, I've been ordered to undertake an air strike." #define GOSSIP_CLOUDBREAKER2 "I need to intercept the Dawnblade reinforcements." #define GOSSIP_DRAGONHAWK "<Ride the dragonhawk to Sun's Reach>" #define GOSSIP_VERONIA "Fly me to Manaforge Coruu please" #define GOSSIP_DEESAK "Fly me to Ogri'la please" #define GOSSIP_AFRASASTRASZ1 "I would like to take a flight to the ground, Lord Of Afrasastrasz." #define GOSSIP_AFRASASTRASZ2 "My Lord, I must go to the upper floor of the temple." #define GOSSIP_TARIOLSTRASZ1 "My Lord, I must go to the upper floor of the temple." #define GOSSIP_TARIOLSTRASZ2 "Can you spare a drake to travel to Lord Of Afrasastrasz, in the middle of the temple?" #define GOSSIP_TORASTRASZA1 "I would like to see Lord Of Afrasastrasz, in the middle of the temple." #define GOSSIP_TORASTRASZA2 "Yes, Please. I would like to return to the ground floor of the temple." #define GOSSIP_CRIMSONWING "<Ride the gryphons to Survey Alcaz Island>" #define GOSSIP_WILLIAMKEILAR1 "Take me to Northpass Tower." #define GOSSIP_WILLIAMKEILAR2 "Take me to Eastwall Tower." #define GOSSIP_WILLIAMKEILAR3 "Take me to Crown Guard Tower." class npc_taxi : public CreatureScript { public: npc_taxi() : CreatureScript("npc_taxi") { } bool OnGossipHello(Player* player, Creature* creature) override { if (creature->IsQuestGiver()) player->PrepareQuestMenu(creature->GetGUID()); switch (creature->GetEntry()) { case 17435: // Azuremyst Isle - Susurrus if (player->HasItemCount(23843, 1, true)) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SUSURRUS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF); break; case 20903: // Netherstorm - Protectorate Nether Drake if (player->GetQuestStatus(10438) == QUEST_STATUS_INCOMPLETE && player->HasItemCount(29778)) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_NETHER_DRAKE, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); break; case 18725: // Old Hillsbrad Foothills - Brazen player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_BRAZEN, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2); break; case 29154: // Stormwind City - Thargold Ironwing player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_IRONWING, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 3); break; case 19409: // Hellfire Peninsula - Wing Commander Dabir'ee //Mission: The Murketh and Shaadraz Gateways if (player->GetQuestStatus(10146) == QUEST_STATUS_INCOMPLETE) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_DABIREE1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 4); //Shatter Point if (!player->GetQuestRewardStatus(10340)) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_DABIREE2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 5); break; case 20235: // Hellfire Peninsula - Gryphoneer Windbellow //Mission: The Abyssal Shelf || Return to the Abyssal Shelf if (player->GetQuestStatus(10163) == QUEST_STATUS_INCOMPLETE || player->GetQuestStatus(10346) == QUEST_STATUS_INCOMPLETE) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_WINDBELLOW1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 6); //Go to the Front if (player->GetQuestStatus(10382) != QUEST_STATUS_NONE && !player->GetQuestRewardStatus(10382)) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_WINDBELLOW2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 7); break; case 19401: // Hellfire Peninsula - Wing Commander Brack //Mission: The Murketh and Shaadraz Gateways if (player->GetQuestStatus(10129) == QUEST_STATUS_INCOMPLETE) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_BRACK1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 8); //Mission: The Abyssal Shelf || Return to the Abyssal Shelf if (player->GetQuestStatus(10162) == QUEST_STATUS_INCOMPLETE || player->GetQuestStatus(10347) == QUEST_STATUS_INCOMPLETE) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_BRACK2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 9); //Spinebreaker Post if (player->GetQuestStatus(10242) == QUEST_STATUS_COMPLETE) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_BRACK3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 10); break; case 23413: // Blade's Edge Mountains - Skyguard Handler Irena if (player->GetReputationRank(1031) >= REP_HONORED) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_IRENA, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 11); break; case 25059: // Isle of Quel'Danas - Ayren Cloudbreaker if (player->GetQuestStatus(11532) == QUEST_STATUS_INCOMPLETE || player->GetQuestStatus(11533) == QUEST_STATUS_INCOMPLETE) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_CLOUDBREAKER1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 12); if (player->GetQuestStatus(11542) == QUEST_STATUS_INCOMPLETE || player->GetQuestStatus(11543) == QUEST_STATUS_INCOMPLETE) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_CLOUDBREAKER2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 13); break; case 25236: // Isle of Quel'Danas - Unrestrained Dragonhawk if (player->GetQuestStatus(11542) == QUEST_STATUS_COMPLETE || player->GetQuestStatus(11543) == QUEST_STATUS_COMPLETE) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_DRAGONHAWK, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 14); break; case 20162: // Netherstorm - Veronia //Behind Enemy Lines if (player->GetQuestStatus(10652) != QUEST_STATUS_REWARDED) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_VERONIA, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 15); break; case 23415: // Terokkar Forest - Skyguard Handler Deesak if (player->GetReputationRank(1031) >= REP_HONORED) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_DEESAK, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 16); break; case 27575: // Dragonblight - Lord Afrasastrasz // middle -> ground player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_AFRASASTRASZ1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 17); // middle -> top player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_AFRASASTRASZ2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 18); break; case 26443: // Dragonblight - Tariolstrasz //need to check if quests are required before gossip available (12123, 12124) // ground -> top player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_TARIOLSTRASZ1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 19); // ground -> middle player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_TARIOLSTRASZ2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 20); break; case 26949: // Dragonblight - Torastrasza // top -> middle player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_TORASTRASZA1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 21); // top -> ground player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_TORASTRASZA2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 22); break; case 23704: // Dustwallow Marsh - Cassa Crimsonwing if (player->GetQuestStatus(11142) == QUEST_STATUS_INCOMPLETE) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_CRIMSONWING, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+25); break; case 17209: player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_WILLIAMKEILAR1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 28); player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_WILLIAMKEILAR2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 29); player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_WILLIAMKEILAR3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 30); break; } player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); return true; } bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override { player->PlayerTalkClass->ClearMenus(); switch (action) { case GOSSIP_ACTION_INFO_DEF: //spellId is correct, however it gives flight a somewhat funny effect //TaxiPath 506. player->CLOSE_GOSSIP_MENU(); player->CastSpell(player, 32474, true); break; case GOSSIP_ACTION_INFO_DEF + 1: player->CLOSE_GOSSIP_MENU(); player->ActivateTaxiPathTo(627); //TaxiPath 627 (possibly 627+628(152->153->154->155)) break; case GOSSIP_ACTION_INFO_DEF + 2: if (!player->HasItemCount(25853)) player->SEND_GOSSIP_MENU(9780, creature->GetGUID()); else { player->CLOSE_GOSSIP_MENU(); player->ActivateTaxiPathTo(534); //TaxiPath 534 } break; case GOSSIP_ACTION_INFO_DEF + 3: player->CLOSE_GOSSIP_MENU(); player->CastSpell(player, 53335, true); //TaxiPath 1041 (Stormwind Harbor) break; case GOSSIP_ACTION_INFO_DEF + 4: player->CLOSE_GOSSIP_MENU(); player->CastSpell(player, 33768, true); //TaxiPath 585 (Gateways Murket and Shaadraz) break; case GOSSIP_ACTION_INFO_DEF + 5: player->CLOSE_GOSSIP_MENU(); player->CastSpell(player, 35069, true); //TaxiPath 612 (Taxi - Hellfire Peninsula - Expedition Point to Shatter Point) break; case GOSSIP_ACTION_INFO_DEF + 6: player->CLOSE_GOSSIP_MENU(); player->CastSpell(player, 33899, true); //TaxiPath 589 (Aerial Assault Flight (Alliance)) break; case GOSSIP_ACTION_INFO_DEF + 7: player->CLOSE_GOSSIP_MENU(); player->CastSpell(player, 35065, true); //TaxiPath 607 (Taxi - Hellfire Peninsula - Shatter Point to Beach Head) break; case GOSSIP_ACTION_INFO_DEF + 8: player->CLOSE_GOSSIP_MENU(); player->CastSpell(player, 33659, true); //TaxiPath 584 (Gateways Murket and Shaadraz) break; case GOSSIP_ACTION_INFO_DEF + 9: player->CLOSE_GOSSIP_MENU(); player->CastSpell(player, 33825, true); //TaxiPath 587 (Aerial Assault Flight (Horde)) break; case GOSSIP_ACTION_INFO_DEF + 10: player->CLOSE_GOSSIP_MENU(); player->CastSpell(player, 34578, true); //TaxiPath 604 (Taxi - Reaver's Fall to Spinebreaker Ridge) break; case GOSSIP_ACTION_INFO_DEF + 11: player->CLOSE_GOSSIP_MENU(); player->CastSpell(player, 41278, true); //TaxiPath 706 break; case GOSSIP_ACTION_INFO_DEF + 12: player->CLOSE_GOSSIP_MENU(); player->CastSpell(player, 45071, true); //TaxiPath 779 break; case GOSSIP_ACTION_INFO_DEF + 13: player->CLOSE_GOSSIP_MENU(); player->CastSpell(player, 45113, true); //TaxiPath 784 break; case GOSSIP_ACTION_INFO_DEF + 14: player->CLOSE_GOSSIP_MENU(); player->CastSpell(player, 45353, true); //TaxiPath 788 break; case GOSSIP_ACTION_INFO_DEF + 15: player->CLOSE_GOSSIP_MENU(); player->CastSpell(player, 34905, true); //TaxiPath 606 break; case GOSSIP_ACTION_INFO_DEF + 16: player->CLOSE_GOSSIP_MENU(); player->CastSpell(player, 41279, true); //TaxiPath 705 (Taxi - Skettis to Skyguard Outpost) break; case GOSSIP_ACTION_INFO_DEF + 17: player->CLOSE_GOSSIP_MENU(); player->ActivateTaxiPathTo(882); break; case GOSSIP_ACTION_INFO_DEF + 18: player->CLOSE_GOSSIP_MENU(); player->ActivateTaxiPathTo(881); break; case GOSSIP_ACTION_INFO_DEF + 19: player->CLOSE_GOSSIP_MENU(); player->ActivateTaxiPathTo(878); break; case GOSSIP_ACTION_INFO_DEF + 20: player->CLOSE_GOSSIP_MENU(); player->ActivateTaxiPathTo(883); break; case GOSSIP_ACTION_INFO_DEF + 21: player->CLOSE_GOSSIP_MENU(); player->ActivateTaxiPathTo(880); break; case GOSSIP_ACTION_INFO_DEF + 22: player->CLOSE_GOSSIP_MENU(); player->ActivateTaxiPathTo(879); break; case GOSSIP_ACTION_INFO_DEF + 23: player->CLOSE_GOSSIP_MENU(); player->CastSpell(player, 43074, true); //TaxiPath 736 break; case GOSSIP_ACTION_INFO_DEF + 24: player->CLOSE_GOSSIP_MENU(); //player->ActivateTaxiPathTo(738); player->CastSpell(player, 43136, false); break; case GOSSIP_ACTION_INFO_DEF + 25: player->CLOSE_GOSSIP_MENU(); player->CastSpell(player, 42295, true); break; case GOSSIP_ACTION_INFO_DEF + 26: player->CLOSE_GOSSIP_MENU(); player->ActivateTaxiPathTo(494); break; case GOSSIP_ACTION_INFO_DEF + 27: player->CLOSE_GOSSIP_MENU(); player->ActivateTaxiPathTo(495); break; case GOSSIP_ACTION_INFO_DEF + 28: player->CLOSE_GOSSIP_MENU(); player->ActivateTaxiPathTo(496); break; } return true; } }; void AddSC_npc_taxi() { new npc_taxi; }
madisodr/legacy-core
src/server/scripts/World/npc_taxi.cpp
C++
gpl-2.0
16,513
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2022 UniPro <ugene@unipro.ru> * http://ugene.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ScriptEditorWidget.h" #include <QBoxLayout> #include <QLineEdit> #include <QSplitter> #include <QTextEdit> #include "ScriptHighlighter.h" const char* SCRIPT_TEXT_PROPERTY_NAME = "script text"; namespace U2 { ScriptEditorWidget::ScriptEditorWidget(QWidget* parent, ScriptEditorType typeOfField) : QWidget(parent) { scriptContainer = new QSplitter(Qt::Vertical, this); scriptContainer->setFocusPolicy(Qt::NoFocus); QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom, this); layout->setMargin(0); layout->addWidget(scriptContainer); variablesEdit = new QTextEdit(scriptContainer); variablesEdit->setReadOnly(true); new ScriptHighlighter(variablesEdit->document()); scriptEdit = AbstractScriptEditorDelegate::createInstance(scriptContainer, typeOfField); scriptEdit->installScriptHighlighter(); connect(scriptEdit, SIGNAL(si_textChanged()), SIGNAL(si_textChanged())); connect(scriptEdit, SIGNAL(si_cursorPositionChanged()), SIGNAL(si_cursorPositionChanged())); } void ScriptEditorWidget::setVariablesText(const QString& variablesText) { variablesEdit->setText(variablesText); } QString ScriptEditorWidget::variablesText() const { return variablesEdit->toPlainText(); } void ScriptEditorWidget::setScriptText(const QString& text) { scriptEdit->setText(text); } QString ScriptEditorWidget::scriptText() const { return scriptEdit->text(); } int ScriptEditorWidget::scriptEditCursorLineNumber() const { return scriptEdit->cursorLineNumber(); } } // namespace U2
ugeneunipro/ugene
src/corelibs/U2Gui/src/util/ScriptEditorWidget.cpp
C++
gpl-2.0
2,409
/* YUI 3.7.3 (build 5687) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('dom-class', function(Y) { var addClass, hasClass, removeClass; Y.mix(Y.DOM, { /** * Determines whether a DOM element has the given className. * @method hasClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the given class. */ hasClass: function(node, className) { var re = Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'); return re.test(node.className); }, /** * Adds a class name to a given DOM element. * @method addClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to add to the class attribute */ addClass: function(node, className) { if (!Y.DOM.hasClass(node, className)) { // skip if already present node.className = Y.Lang.trim([node.className, className].join(' ')); } }, /** * Removes a class name from a given element. * @method removeClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to remove from the class attribute */ removeClass: function(node, className) { if (className && hasClass(node, className)) { node.className = Y.Lang.trim(node.className.replace(Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'), ' ')); if ( hasClass(node, className) ) { // in case of multiple adjacent removeClass(node, className); } } }, /** * Replace a class with another class for a given element. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name */ replaceClass: function(node, oldC, newC) { //Y.log('replaceClass replacing ' + oldC + ' with ' + newC, 'info', 'Node'); removeClass(node, oldC); // remove first in case oldC === newC addClass(node, newC); }, /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} className the class name to be toggled * @param {Boolean} addClass optional boolean to indicate whether class * should be added or removed regardless of current state */ toggleClass: function(node, className, force) { var add = (force !== undefined) ? force : !(hasClass(node, className)); if (add) { addClass(node, className); } else { removeClass(node, className); } } }); hasClass = Y.DOM.hasClass; removeClass = Y.DOM.removeClass; addClass = Y.DOM.addClass; }, '3.7.3' ,{requires:['dom-core']});
artefactual-labs/trac
sites/all/libraries/yui/build/dom-class/dom-class-debug.js
JavaScript
gpl-2.0
3,423
import { Injectable } from '@angular/core'; import { of } from 'rxjs'; import { Resolve, ActivatedRouteSnapshot } from '@angular/router'; import { catchError } from 'rxjs/operators'; import { CatalogoService } from './catalogo.service'; @Injectable() export class EdicaoNovoResolverService implements Resolve<any> { constructor(private catalogoService: CatalogoService) {} resolve(snapshot: ActivatedRouteSnapshot) { const params = snapshot.queryParams; return this.catalogoService.getModelo(params['id']) .pipe(catchError((error) => of({error: error}))); } }
lexml/madoc
ui/src/app/service/edicao-novo.resolver.service.ts
TypeScript
gpl-2.0
589
package agaroyun.view; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.ArrayList; import javax.swing.JPanel; import agaroyun.Model.GameObject; import agaroyun.Model.Player; /** * draws GameObjects to panel * @author varyok * @version 1.0 */ public class GamePanel extends JPanel { private ArrayList<GameObject> gameObjects; /** * Keeps gameObjects ArrayList * @param gameObjects */ public GamePanel(ArrayList<GameObject> gameObjects) { this.gameObjects=gameObjects; } /** * draws GameObjects to panel */ @Override protected synchronized void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d=(Graphics2D)g; //Graphics 2d daha fazla özellik sağlayabilir. daha kolaydır for (GameObject gameObject : gameObjects) { gameObject.draw(g2d); } } }
by-waryoq/LYKJava2017Basics
src/agaroyun/view/GamePanel.java
Java
gpl-2.0
916
package net.sf.memoranda.util; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import net.sf.memoranda.ui.AppFrame; /** * <p> * Title: * </p> * <p> * Description: * </p> * <p> * Copyright: Copyright (c) 2002 * </p> * <p> * Company: * </p> * * @author unascribed * @version 1.0 */ /* $Id: Context.java,v 1.3 2004/01/30 12:17:42 alexeya Exp $ */ public class Context { public static LoadableProperties context = new LoadableProperties(); static { CurrentStorage.get().restoreContext(); AppFrame.addExitListener(new ActionListener() { public void actionPerformed(ActionEvent e) { CurrentStorage.get().storeContext(); } }); } public static Object get(Object key) { return context.get(key); } public static void put(Object key, Object value) { context.put(key, value); } }
cst316/spring16project-Fortran
src/net/sf/memoranda/util/Context.java
Java
gpl-2.0
845
<?php /** * * * Created on Jan 4, 2008 * * Copyright © 2008 Yuri Astrakhan <Firstname><Lastname>@gmail.com, * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * http://www.gnu.org/copyleft/gpl.html * * @file */ /** * API module to allow users to watch a page * * @ingroup API */ class ApiWatch extends ApiBase { public function __construct( $main, $action ) { parent::__construct( $main, $action ); } public function execute() { $user = $this->getUser(); if ( !$user->isLoggedIn() ) { $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' ); } $params = $this->extractRequestParams(); $title = Title::newFromText( $params['title'] ); if ( !$title || $title->getNamespace() < 0 ) { $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) ); } $res = array( 'title' => $title->getPrefixedText() ); if ( $params['unwatch'] ) { $res['unwatched'] = ''; $res['message'] = wfMsgExt( 'removedwatchtext', array( 'parse' ), $title->getPrefixedText() ); $success = UnwatchAction::doUnwatch( $title, $user ); } else { $res['watched'] = ''; $res['message'] = wfMsgExt( 'addedwatchtext', array( 'parse' ), $title->getPrefixedText() ); $success = WatchAction::doWatch( $title, $user ); } if ( !$success ) { $this->dieUsageMsg( 'hookaborted' ); } $this->getResult()->addValue( null, $this->getModuleName(), $res ); } public function mustBePosted() { return true; } public function isWriteMode() { return true; } public function needsToken() { return true; } public function getTokenSalt() { return 'watch'; } public function getAllowedParams() { return array( 'title' => array( ApiBase::PARAM_TYPE => 'string', ApiBase::PARAM_REQUIRED => true ), 'unwatch' => false, 'token' => null, ); } public function getParamDescription() { return array( 'title' => 'The page to (un)watch', 'unwatch' => 'If set the page will be unwatched rather than watched', 'token' => 'A token previously acquired via prop=info', ); } public function getDescription() { return 'Add or remove a page from/to the current user\'s watchlist'; } public function getPossibleErrors() { return array_merge( parent::getPossibleErrors(), array( array( 'code' => 'notloggedin', 'info' => 'You must be logged-in to have a watchlist' ), array( 'invalidtitle', 'title' ), array( 'hookaborted' ), ) ); } public function getExamples() { return array( 'api.php?action=watch&title=Main_Page' => 'Watch the page "Main Page"', 'api.php?action=watch&title=Main_Page&unwatch=' => 'Unwatch the page "Main Page"', ); } public function getHelpUrls() { return 'https://www.mediawiki.org/wiki/API:Watch'; } public function getVersion() { return __CLASS__ . ': $Id$'; } }
ezc/mediawiki
includes/api/ApiWatch.php
PHP
gpl-2.0
3,488
<?php /** * @version $Id: #component#.php 125 2012-10-09 11:09:48Z michel $ 1 2014-05-11Z FT $ * @package Kepviselojeloltek * @copyright Copyright (C) 2014, Fogler Tibor. All rights reserved. * @license #GNU/GPL */ //--No direct access defined('_JEXEC') or die('=;)'); // DS has removed from J 3.0 if(!defined('DS')) { define('DS','/'); } // Require the base controller require_once( JPATH_COMPONENT.'/controller.php' ); jimport('joomla.application.component.model'); require_once( JPATH_COMPONENT.'/models/model.php' ); jimport('joomla.application.component.helper'); JHTML::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.'/helpers' ); //set the default view $task = JRequest::getWord('task'); $config =& JComponentHelper::getParams( 'com_kepviselojeloltek' ); $controller = JRequest::getWord('view', 'kepviselojeloltek'); $ControllerConfig = array(); // Require specific controller if requested if ($controller) { $path = JPATH_COMPONENT.'/controllers/'.$controller.'.php'; $ControllerConfig = array('viewname'=>strtolower($controller),'mainmodel'=>strtolower($controller),'itemname'=>ucfirst(strtolower($controller))); if (file_exists($path)) { require_once $path; } else { $controller = ''; } } // Create the controller $classname = 'KepviselojeloltekController'.$controller; $controller = new $classname($ControllerConfig ); // Perform the Request task $controller->execute( JRequest::getVar( 'task' ) ); // Redirect if set by the controller $controller->redirect();
utopszkij/li-de
componens_telepitok/com_kepviselojeltek/site/kepviselojeloltek.php
PHP
gpl-2.0
1,527
package org.emulinker.kaillera.controller.v086.action; import java.util.*; import org.apache.commons.logging.*; import org.emulinker.kaillera.access.AccessManager; import org.emulinker.kaillera.controller.messaging.MessageFormatException; import org.emulinker.kaillera.controller.v086.V086Controller; import org.emulinker.kaillera.controller.v086.protocol.*; import org.emulinker.kaillera.model.exception.ActionException; import org.emulinker.kaillera.model.impl.*; import org.emulinker.kaillera.model.*; import org.emulinker.util.EmuLang; import org.emulinker.util.WildcardStringPattern; public class GameOwnerCommandAction implements V086Action { public static final String COMMAND_HELP = "/help"; //$NON-NLS-1$ public static final String COMMAND_DETECTAUTOFIRE = "/detectautofire"; //$NON-NLS-1$ private static Log log = LogFactory.getLog(GameOwnerCommandAction.class); private static final String desc = "GameOwnerCommandAction"; //$NON-NLS-1$ private static GameOwnerCommandAction singleton = new GameOwnerCommandAction(); public static GameOwnerCommandAction getInstance() { return singleton; } private int actionCount = 0; private GameOwnerCommandAction() { } public int getActionPerformedCount() { return actionCount; } public String toString() { return desc; } public void performAction(V086Message message, V086Controller.V086ClientHandler clientHandler) throws FatalActionException { GameChat chatMessage = (GameChat) message; String chat = chatMessage.getMessage(); KailleraUserImpl user = (KailleraUserImpl) clientHandler.getUser(); KailleraGameImpl game = user.getGame(); if(game == null) { throw new FatalActionException("GameOwner Command Failed: Not in a game: " + chat); //$NON-NLS-1$ } if(!user.equals(game.getOwner())) { log.warn("GameOwner Command Denied: Not game owner: " + game + ": " + user + ": " + chat); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return; } try { if (chat.startsWith(COMMAND_HELP)) { processHelp(chat, game, user, clientHandler); } else if (chat.startsWith(COMMAND_DETECTAUTOFIRE)) { processDetectAutoFire(chat, game, user, clientHandler); } else { log.info("Unknown GameOwner Command: " + game + ": " + user + ": " + chat); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } catch (ActionException e) { log.info("GameOwner Command Failed: " + game + ": " + user + ": " + chat); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ game.announce(EmuLang.getString("GameOwnerCommandAction.CommandFailed", e.getMessage())); //$NON-NLS-1$ } catch (MessageFormatException e) { log.error("Failed to contruct message: " + e.getMessage(), e); //$NON-NLS-1$ } } private void processHelp(String message, KailleraGameImpl game, KailleraUserImpl admin, V086Controller.V086ClientHandler clientHandler) throws ActionException, MessageFormatException { game.announce(EmuLang.getString("GameOwnerCommandAction.AvailableCommands")); //$NON-NLS-1$ game.announce(EmuLang.getString("GameOwnerCommandAction.SetAutofireDetection")); //$NON-NLS-1$ } private void autoFireHelp(KailleraGameImpl game) { int cur = game.getAutoFireDetector().getSensitivity(); game.announce(EmuLang.getString("GameOwnerCommandAction.HelpSensitivity")); //$NON-NLS-1$ game.announce(EmuLang.getString("GameOwnerCommandAction.HelpDisable")); //$NON-NLS-1$ game.announce(EmuLang.getString("GameOwnerCommandAction.HelpCurrentSensitivity", cur) + (cur == 0 ? (EmuLang.getString("GameOwnerCommandAction.HelpDisabled")) : "")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } private void processDetectAutoFire(String message, KailleraGameImpl game, KailleraUserImpl admin, V086Controller.V086ClientHandler clientHandler) throws ActionException, MessageFormatException { if(game.getStatus() != KailleraGame.STATUS_WAITING) { game.announce(EmuLang.getString("GameOwnerCommandAction.AutoFireChangeDeniedInGame")); //$NON-NLS-1$ return; } StringTokenizer st = new StringTokenizer(message, " "); //$NON-NLS-1$ if(st.countTokens() != 2) { autoFireHelp(game); return; } String command = st.nextToken(); String sensitivityStr = st.nextToken(); int sensitivity = -1; try { sensitivity = Integer.parseInt(sensitivityStr); } catch(NumberFormatException e) {} if(sensitivity > 5 || sensitivity < 0) { autoFireHelp(game); return; } game.getAutoFireDetector().setSensitivity(sensitivity); game.announce(EmuLang.getString("GameOwnerCommandAction.HelpCurrentSensitivity", sensitivity) + (sensitivity == 0 ? (EmuLang.getString("GameOwnerCommandAction.HelpDisabled")) : "")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } }
monospacesoftware/emulinker
src/org/emulinker/kaillera/controller/v086/action/GameOwnerCommandAction.java
Java
gpl-2.0
4,749
<?php /** * Manages the social plugins. * * @copyright 2009-2019 Vanilla Forums Inc. * @license GPL-2.0-only * @package Dashboard * @since 2.1 */ /** * Handles /social endpoint, so it must be an extrovert. */ class SocialController extends DashboardController { /** @var array Models to automatically instantiate. */ public $Uses = ['Form', 'Database']; /** * Runs before every call to this controller. */ public function initialize() { parent::initialize(); Gdn_Theme::section('Settings'); } /** * Default method. */ public function index() { redirectTo('social/manage'); } /** * Settings page. */ public function manage() { $this->permission('Garden.Settings.Manage'); $this->title("Social Connect Addons"); $this->setHighlightRoute('/social/manage'); $connections = $this->getConnections(); $this->setData('Connections', $connections); $this->render(); } /** * Find available social plugins. * * @return array|mixed * @throws Exception */ protected function getConnections() { $this->fireEvent('GetConnections'); $connections = []; $addons = Gdn::addonManager()->lookupAllByType(\Vanilla\Addon::TYPE_ADDON); foreach ($addons as $addonName => $addon) { /* @var \Vanilla\Addon $addon */ $addonInfo = $addon->getInfo(); // Limit to designated social addons. if (!array_key_exists('socialConnect', $addonInfo)) { continue; } // See if addon is enabled. $isEnabled = Gdn::addonManager()->isEnabled($addonName, \Vanilla\Addon::TYPE_ADDON); setValue('enabled', $addonInfo, $isEnabled); if (!$isEnabled && !empty($addonInfo['hidden'])) { // Don't show hidden addons unless they are enabled. continue; } // See if we can detect whether connection is configured. $isConfigured = null; if ($isEnabled) { $pluginInstance = Gdn::pluginManager()->getPluginInstance($addonName, Gdn_PluginManager::ACCESS_PLUGINNAME); if (method_exists($pluginInstance, 'isConfigured')) { $isConfigured = $pluginInstance->isConfigured(); } } setValue('configured', $addonInfo, $isConfigured); // Add the connection. $connections[$addonName] = $addonInfo; } return $connections; } }
vanilla/vanilla
applications/dashboard/controllers/class.socialcontroller.php
PHP
gpl-2.0
2,628
<?php // if( isset( $_POST ) ) { // echo '<code><pre>'; // var_dump( $_POST ); // echo '</pre></code>'; // } class SpeoOptions { /** * Holds the values to be used in the fields callbacks */ private $options; /** * Start up */ public function __construct() { add_action( 'admin_menu', array( $this, 'add_plugin_page' ) ); add_action( 'admin_init', array( $this, 'page_init' ) ); } /** * Add options page */ public function add_plugin_page() { // This page will be under "Settings" add_options_page( 'Settings Admin', 'Exiftool Options', 'manage_options', 'speo_exif_options', array( $this, 'create_admin_page' ) ); } /** * Options page callback */ public function create_admin_page() { // Set class property $this->options = get_option( 'speo_options' ); ?> <div class="wrap"> <?php screen_icon(); ?> <h2>Exiftools Settings</h2> <form method="post" action="options.php"> <?php // This prints out all hidden setting fields settings_fields( 'speo_options_group' ); do_settings_sections( 'speo_exif_options' ); echo '</ol>'; submit_button(); ?> </form> </div> <?php } /** * Register and add settings */ public function page_init() { register_setting( 'speo_options_group', // Option group 'speo_options', // Option name array( $this, 'sanitize' ) // Sanitize ); add_settings_section( 'speo_options_all', // ID 'Options', // Title array( $this, 'print_section_info' ), // Callback 'speo_exif_options' // Page ); //get the blog language $this_lang = get_locale(); //get the values from the list.xml $xmldoc = new DOMDocument(); $xmldoc->load( plugin_dir_path( __FILE__ ) . 'list.xml' ); $xpathvar = new Domxpath($xmldoc); $queryResult = $xpathvar->query('//tag/@name'); $possible_values = array(); foreach( $queryResult as $result ){ if( substr( $result->textContent, 0, 9 ) === 'MakerNote' ) continue; $possible_values[ $result->textContent ] = 0; ksort( $possible_values ); } foreach( $possible_values as $value => $bool ) { // $xpath = new Domxpath($xmldoc); // $descs = $xpath->query('//tag[@name="' . $value . '"]/desc[@lang="en"]'); // $titles = $xpath->query('//tag[@name="' . $value . '"]/desc[@lang="' . substr( $this_lang, 0, 2 ) . '"]'); // foreach( $descs as $desc ) { // $i=1; // $opt_title = '<li>' . $value; // foreach( $titles as $title ) { // if( $i > 1 ) // continue; // $opt_title .= '<br />(' . $title->textContent . ')'; // $i++; // } // $opt_title .= '</li>'; //add the actual setting add_settings_field( 'speo_exif_' . $value, // ID $value, // Title array( $this, 'speo_callback' ), // Callback 'speo_exif_options', // Page 'speo_options_all', // Section $value //args ); // } } } /** * Sanitize each setting field as needed * * @param array $input Contains all settings fields as array keys */ public function sanitize( $inputs ) { return $inputs; } /** * Print the Section text */ public function print_section_info() { print 'Check the values you want to retreive from images:<ol>'; } /** * Get the settings option array and print one of its values */ public function speo_callback( $value ) { // echo '<code><pre>'; // var_dump($this->options); // echo '</pre></code>'; printf( '<input type="checkbox" id="speo_exif_' . $value . '" name="speo_options[' . $value . ']" %s />', checked( isset( $this->options[$value] ), true, false ) // ( isset( $this->options[$value] ) ? $this->options[$value] : 'none' ) ); } } if( is_admin() ) $my_settings_page = new SpeoOptions();
alpipego/speo-exiftool
speo-options.php
PHP
gpl-2.0
4,439
var options={}; options.login=true; LoginRadius_SocialLogin.util.ready(function () { $ui = LoginRadius_SocialLogin.lr_login_settings; $ui.interfacesize = Drupal.settings.lrsociallogin.interfacesize; $ui.lrinterfacebackground=Drupal.settings.lrsociallogin.lrinterfacebackground; $ui.noofcolumns= Drupal.settings.lrsociallogin.noofcolumns; $ui.apikey = Drupal.settings.lrsociallogin.apikey; $ui.is_access_token=true; $ui.callback=Drupal.settings.lrsociallogin.location; $ui.lrinterfacecontainer ="interfacecontainerdiv"; LoginRadius_SocialLogin.init(options); }); LoginRadiusSDK.setLoginCallback(function () { var token = LoginRadiusSDK.getToken(); var form = document.createElement('form'); form.action = Drupal.settings.lrsociallogin.location; form.method = 'POST'; var hiddenToken = document.createElement('input'); hiddenToken.type = 'hidden'; hiddenToken.value = token; hiddenToken.name = 'token'; form.appendChild(hiddenToken); document.body.appendChild(form); form.submit(); });
bedesign323/aimhigh
sites/all/modules/contrib/sociallogin/js/sociallogin_interface.js
JavaScript
gpl-2.0
1,057
<?php namespace Drupal\materialize\Plugin\Setting\General\Tables; use Drupal\materialize\Annotation\MaterializeSetting; use Drupal\materialize\Plugin\Setting\SettingBase; use Drupal\Core\Annotation\Translation; /** * The "table_bordered" theme setting. * * @ingroup plugins_setting * * @MaterializeSetting( * id = "table_bordered", * type = "checkbox", * title = @Translation("Bordered table"), * description = @Translation("Add borders on all sides of the table and cells."), * defaultValue = 0, * groups = { * "general" = @Translation("General"), * "tables" = @Translation("Tables"), * }, * ) */ class TableBordered extends SettingBase {}
sunlight25/d8
web/themes/contrib/materialize/src/Plugin/Setting/General/Tables/TableBordered.php
PHP
gpl-2.0
682
package net.senmori.customtextures.events; import net.senmori.customtextures.util.MovementType; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerEvent; import com.sk89q.worldguard.protection.regions.ProtectedRegion; /** * event that is triggered after a player entered a WorldGuard region * @author mewin<mewin001@hotmail.de> */ public class RegionEnteredEvent extends RegionEvent { /** * creates a new RegionEnteredEvent * @param region the region the player entered * @param player the player who triggered the event * @param movement the type of movement how the player entered the region */ public RegionEnteredEvent(ProtectedRegion region, Player player, MovementType movement, PlayerEvent parent) { super(player, region, parent, movement); } }
Senmori/CustomTextures
src/main/java/net/senmori/customtextures/events/RegionEnteredEvent.java
Java
gpl-2.0
851
<?php /* * @package Joomla.Framework * @copyright Copyright (C) 2005 - 2010 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt * * @component Phoca Component * @copyright Copyright (C) Jan Pavelka www.phoca.cz * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License version 2 or later; */ defined('_JEXEC') or die(); jimport('joomla.application.component.modeladmin'); phocagalleryimport('phocagallery.tag.tag'); class PhocaGalleryCpModelPhocaGalleryImg extends JModelAdmin { protected $option = 'com_phocagallery'; protected $text_prefix = 'com_phocagallery'; protected function canDelete($record) { $user = JFactory::getUser(); if ($record->catid) { return $user->authorise('core.delete', 'com_phocagallery.phocagalleryimg.'.(int) $record->catid); } else { return parent::canDelete($record); } } protected function canEditState($record) { $user = JFactory::getUser(); if ($record->catid) { return $user->authorise('core.edit.state', 'com_phocagallery.phocagalleryimg.'.(int) $record->catid); } else { return parent::canEditState($record); } } public function getTable($type = 'PhocaGallery', $prefix = 'Table', $config = array()) { return JTable::getInstance($type, $prefix, $config); } public function getForm($data = array(), $loadData = true) { $app = JFactory::getApplication(); $form = $this->loadForm('com_phocagallery.phocagalleryimg', 'phocagalleryimg', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } return $form; } protected function loadFormData() { // Check the session for previously entered form data. $data = JFactory::getApplication()->getUserState('com_phocagallery.edit.phocagallery.data', array()); if (empty($data)) { $data = $this->getItem(); } return $data; } public function getItem($pk = null) { if ($item = parent::getItem($pk)) { // Convert the params field to an array. $registry = new JRegistry; $registry->loadJSON($item->metadata); $item->metadata = $registry->toArray(); } return $item; } protected function prepareTable(&$table) { jimport('joomla.filter.output'); $date = JFactory::getDate(); $user = JFactory::getUser(); $table->title = htmlspecialchars_decode($table->title, ENT_QUOTES); $table->alias = JApplication::stringURLSafe($table->alias); if (empty($table->alias)) { $table->alias = JApplication::stringURLSafe($table->title); } if (empty($table->id)) { // Set the values //$table->created = $date->toMySQL(); // Set ordering to the last item if not set if (empty($table->ordering)) { $db = JFactory::getDbo(); $db->setQuery('SELECT MAX(ordering) FROM #__phocagallery WHERE catid = '.(int)$table->catid); $max = $db->loadResult(); $table->ordering = $max+1; } } else { // Set the values //$table->modified = $date->toMySQL(); //$table->modified_by = $user->get('id'); } } protected function getReorderConditions($table = null) { $condition = array(); $condition[] = 'catid = '. (int) $table->catid; //$condition[] = 'state >= 0'; return $condition; } function approve(&$pks, $value = 1) { // Initialise variables. $dispatcher = JDispatcher::getInstance(); $user = JFactory::getUser(); $table = $this->getTable('phocagallery'); $pks = (array) $pks; // Include the content plugins for the change of state event. JPluginHelper::importPlugin('content'); // Access checks. foreach ($pks as $i => $pk) { if ($table->load($pk)) { if (!$this->canEditState($table)) { // Prune items that you can't change. unset($pks[$i]); JError::raiseWarning(403, JText::_('JLIB_APPLICATION_ERROR_EDIT_STATE_NOT_PERMITTED')); } } } // Attempt to change the state of the records. if (!$table->approve($pks, $value, $user->get('id'))) { $this->setError($table->getError()); return false; } $context = $this->option.'.'.$this->name; // Trigger the onContentChangeState event. /*$result = $dispatcher->trigger($this->event_change_state, array($context, $pks, $value)); if (in_array(false, $result, true)) { $this->setError($table->getError()); return false; }*/ return true; } function save($data) { $params = &JComponentHelper::getParams( 'com_phocagallery' ); $clean_thumbnails = $params->get( 'clean_thumbnails', 0 ); $fileOriginalNotExist = 0; if ((int)$data['extid'] > 0) { $data['imgorigsize'] = 0; if ($data['title'] == '') { $data['title'] = 'External Image'; } } else { //If this file doesn't exists don't save it if (!PhocaGalleryFile::existsFileOriginal($data['filename'])) { //$this->setError('Original File does not exist'); //return false; $fileOriginalNotExist = 1; $errorMsg = JText::_('COM_PHOCAGALLERY_ORIGINAL_IMAGE_NOT_EXIST'); } $data['imgorigsize'] = PhocaGalleryFile::getFileSize($data['filename'], 0); //If there is no title and no alias, use filename as title and alias if ($data['title'] == '') { $data['title'] = PhocaGalleryFile::getTitleFromFile($data['filename']); } } if ($data['extlink1link'] != '') { $extlink1 = str_replace('http://','', $data['extlink1link']); $data['extlink1'] = $extlink1 . '|'.$data['extlink1title'].'|'.$data['extlink1target'].'|'.$data['extlink1icon']; } else { $data['extlink1'] = $data['extlink1link'] . '|'.$data['extlink1title'].'|'.$data['extlink1target'].'|'.$data['extlink1icon']; } if ($data['extlink2link'] != '') { $extlink2 = str_replace('http://','', $data['extlink2link']); $data['extlink2'] = $extlink2 . '|'.$data['extlink2title'].'|'.$data['extlink2target'].'|'.$data['extlink2icon']; } else { $data['extlink2'] = $data['extlink2link'] . '|'.$data['extlink2title'].'|'.$data['extlink2target'].'|'.$data['extlink2icon']; } // Geo if($data['longitude'] == '' || $data['latitude'] == '') { phocagalleryimport('phocagallery.geo.geo'); $coords = PhocaGalleryGeo::getGeoCoords($data['filename']); if ($data['longitude'] == '' ){ $data['longitude'] = $coords['longitude']; } if ($data['latitude'] == '' ){ $data['latitude'] = $coords['latitude']; } if ($data['latitude'] != '' && $data['longitude'] != '' && $data['zoom'] == ''){ $data['zoom'] = PhocaGallerySettings::getAdvancedSettings('geozoom'); } } if ($data['alias'] == '') { $data['alias'] = $data['title']; } //clean alias name (no bad characters) //$data['alias'] = PhocaGalleryText::getAliasName($data['alias']); // if new item, order last in appropriate group //if (!$row->id) { // $where = 'catid = ' . (int) $row->catid ; // $row->ordering = $row->getNextOrder( $where ); //} // = = = = = = = = = = // Initialise variables; $dispatcher = JDispatcher::getInstance(); $table = $this->getTable(); $pk = (!empty($data['id'])) ? $data['id'] : (int)$this->getState($this->getName().'.id'); $isNew = true; // Include the content plugins for the on save events. JPluginHelper::importPlugin('content'); // Load the row if saving an existing record. if ($pk > 0) { $table->load($pk); $isNew = false; } // Bind the data. if (!$table->bind($data)) { $this->setError($table->getError()); return false; } if(intval($table->date) == 0) { $table->date = JFactory::getDate()->toMySQL(); } // Prepare the row for saving $this->prepareTable($table); // Check the data. if (!$table->check()) { $this->setError($table->getError()); return false; } // Trigger the onContentBeforeSave event. /*$result = $dispatcher->trigger($this->event_before_save, array($this->option.'.'.$this->name, $table, $isNew)); if (in_array(false, $result, true)) { $this->setError($table->getError()); return false; }*/ // Store the data. if (!$table->store()) { $this->setError($table->getError()); return false; } // Store to ref table if (!isset($data['tags'])) { $data['tags'] = array(); } if ((int)$table->id > 0) { PhocaGalleryTag::storeTags($data['tags'], (int)$table->id); } // Clean the cache. $cache = JFactory::getCache($this->option); $cache->clean(); // Trigger the onContentAfterSave event. //$dispatcher->trigger($this->event_after_save, array($this->option.'.'.$this->name, $table, $isNew)); $pkName = $table->getKeyName(); if (isset($table->$pkName)) { $this->setState($this->getName().'.id', $table->$pkName); } $this->setState($this->getName().'.new', $isNew); // = = = = = = $task = JRequest::getVar('task'); if (isset($table->$pkName)) { $id = $table->$pkName; } if ((int)$data['extid'] > 0 || $fileOriginalNotExist == 1) { } else { // - - - - - - - - - - - - - - - - - - //Create thumbnail small, medium, large //file - abc.img, file_no - folder/abc.img //Get folder variables from Helper //Create thumbnails small, medium, large $refresh_url = 'index.php?option=com_phocagallery&task=phocagalleryimg.thumbs'; $task = JRequest::getVar('task'); if (isset($table->$pkName) && $task == 'apply') { $id = $table->$pkName; $refresh_url = 'index.php?option=com_phocagallery&task=phocagalleryimg.edit&id='.(int)$id; } if ($task = 'save2new') { // Don't create automatically thumbnails in case, we are going to add new image } else { $file_thumb = PhocaGalleryFileThumbnail::getOrCreateThumbnail($data['filename'], $refresh_url, 1, 1, 1); } //Clean Thumbs Folder if there are thumbnail files but not original file if ($clean_thumbnails == 1) { phocagalleryimport('phocagallery.file.filefolder'); PhocaGalleryFileFolder::cleanThumbsFolder(); } // - - - - - - - - - - - - - - - - - - - - - } return true; } function delete($cid = array()) { $params = &JComponentHelper::getParams( 'com_phocagallery' ); $clean_thumbnails = $params->get( 'clean_thumbnails', 0 ); $result = false; if (count( $cid )) { JArrayHelper::toInteger($cid); $cids = implode( ',', $cid ); // - - - - - - - - - - - - - // Get all filenames we want to delete from database, we delete all thumbnails from server of this file $queryd = 'SELECT filename as filename FROM #__phocagallery WHERE id IN ( '.$cids.' )'; $this->_db->setQuery($queryd); $fileObject = $this->_db->loadObjectList(); // - - - - - - - - - - - - - //Delete it from DB $query = 'DELETE FROM #__phocagallery' . ' WHERE id IN ( '.$cids.' )'; $this->_db->setQuery( $query ); if(!$this->_db->query()) { $this->setError($this->_db->getErrorMsg()); return false; } // - - - - - - - - - - - - - - // Delete thumbnails - medium and large, small from server // All id we want to delete - gel all filenames foreach ($fileObject as $key => $value) { //The file can be stored in other category - don't delete it from server because other category use it $querys = "SELECT id as id FROM #__phocagallery WHERE filename='".$value->filename."' "; $this->_db->setQuery($queryd); $sameFileObject = $this->_db->loadObject(); // same file in other category doesn't exist - we can delete it if (!$sameFileObject) { PhocaGalleryFileThumbnail::deleteFileThumbnail($value->filename, 1, 1, 1); } } // Clean Thumbs Folder if there are thumbnail files but not original file if ($clean_thumbnails == 1) { phocagalleryimport('phocagallery.file.filefolder'); PhocaGalleryFileFolder::cleanThumbsFolder(); } // - - - - - - - - - - - - - - } return true; } function recreate($cid = array(), &$message) { if (count( $cid )) { JArrayHelper::toInteger($cid); $cids = implode( ',', $cid ); $query = 'SELECT a.filename, a.extid'. ' FROM #__phocagallery AS a' . ' WHERE a.id IN ( '.$cids.' )'; $this->_db->setQuery($query); $files = $this->_db->loadObjectList(); if (isset($files) && count($files)) { foreach($files as $key => $value) { if (isset($value->extid) && ((int)$value->extid > 0)) { // Picasa cannot be recreated $message = JText::_('COM_PHOCAGALLERY_ERROR_EXT_IMG_NOT_RECREATE'); return false; } else if (isset($value->filename) && $value->filename != '') { $original = PhocaGalleryFile::existsFileOriginal($value->filename); if (!$original) { // Original does not exist - cannot generate new thumbnail $message = JText::_('COM_PHOCAGALLERY_FILEORIGINAL_NOT_EXISTS'); return false; } // Delete old thumbnails $deleteThubms = PhocaGalleryFileThumbnail::deleteFileThumbnail($value->filename, 1, 1, 1); } else { $message = JText::_('COM_PHOCAGALLERY_FILENAME_NOT_EXISTS'); return false; } if (!$deleteThubms) { $message = JText::_('COM_PHOCAGALLERY_ERROR_DELETE_THUMBNAIL'); return false; } } } else { $message = JText::_('COM_PHOCAGALLERY_ERROR_LOADING_DATA_DB'); return false; } } else { $message = JText::_('COM_PHOCAGALLERY_ERROR_ITEM_NOT_SELECTED'); return false; } return true; } /* function deletethumbs($id) { if ($id > 0) { $query = 'SELECT a.filename as filename'. ' FROM #__phocagallery AS a' . ' WHERE a.id = '.(int) $id; $this->_db->setQuery($query); $file = $this->_db->loadObject(); if (isset($file->filename) && $file->filename != '') { $deleteThubms = PhocaGalleryFileThumbnail::deleteFileThumbnail($file->filename, 1, 1, 1); if ($deleteThubms) { return true; } else { return false; } } return false; } return false; }*/ public function disableThumbs() { $component = 'com_phocagallery'; $paramsC = JComponentHelper::getParams($component) ; $paramsC->setValue('enable_thumb_creation', 0); $data['params'] = $paramsC->toArray(); $table = JTable::getInstance('extension'); $idCom = $table->find( array('element' => $component )); $table->load($idCom); if (!$table->bind($data)) { JError::raiseWarning( 500, 'Not a valid component' ); return false; } // pre-save checks if (!$table->check()) { JError::raiseWarning( 500, $table->getError('Check Problem') ); return false; } // save the changes if (!$table->store()) { JError::raiseWarning( 500, $table->getError('Store Problem') ); return false; } return true; } function rotate($id, $angle, &$errorMsg) { phocagalleryimport('phocagallery.image.imagerotate'); if ($id > 0 && $angle !='') { $query = 'SELECT a.filename as filename'. ' FROM #__phocagallery AS a' . ' WHERE a.id = '.(int) $id; $this->_db->setQuery($query); $file = $this->_db->loadObject(); if (isset($file->filename) && $file->filename != '') { $thumbNameL = PhocaGalleryFileThumbnail::getThumbnailName ($file->filename, 'large'); $thumbNameM = PhocaGalleryFileThumbnail::getThumbnailName ($file->filename, 'medium'); $thumbNameS = PhocaGalleryFileThumbnail::getThumbnailName ($file->filename, 'small'); $errorMsg = $errorMsgS = $errorMsgM = $errorMsgL =''; PhocaGalleryImageRotate::rotateImage($thumbNameL, 'large', $angle, $errorMsgS); if ($errorMsgS != '') { $errorMsg = $errorMsgS; return false; } PhocaGalleryImageRotate::rotateImage($thumbNameM, 'medium', $angle, $errorMsgM); if ($errorMsgM != '') { $errorMsg = $errorMsgM; return false; } PhocaGalleryImageRotate::rotateImage($thumbNameS, 'small', $angle, $errorMsgL); if ($errorMsgL != '') { $errorMsg = $errorMsgL; return false; } if ($errorMsgL == '' && $errorMsgM == '' && $errorMsgS == '' ) { return true; } else { $errorMsg = ' ('.$errorMsg.')'; return false; } } $errorMsg = JText::_('COM_PHOCAGALLERY_FILENAME_NOT_EXISTS'); return false; } $errorMsg = JText::_('COM_PHOCAGALLERY_ERROR_ITEM_NOT_SELECTED'); return false; } function deletethumbs($id) { if ($id > 0) { $query = 'SELECT a.filename as filename'. ' FROM #__phocagallery AS a' . ' WHERE a.id = '.(int) $id; $this->_db->setQuery($query); $file = $this->_db->loadObject(); if (isset($file->filename) && $file->filename != '') { $deleteThubms = PhocaGalleryFileThumbnail::deleteFileThumbnail($file->filename, 1, 1, 1); if ($deleteThubms) { return true; } else { return false; } } return false; } return false; } protected function batchCopy($value, $pks, $contexts) { $categoryId = (int) $value; $table = $this->getTable(); $db = $this->getDbo(); // Check that the category exists if ($categoryId) { $categoryTable = JTable::getInstance('PhocaGalleryC', 'Table'); if (!$categoryTable->load($categoryId)) { if ($error = $categoryTable->getError()) { // Fatal error $this->setError($error); return false; } else { $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_MOVE_CATEGORY_NOT_FOUND')); return false; } } } if (empty($categoryId)) { $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_MOVE_CATEGORY_NOT_FOUND')); return false; } // Check that the user has create permission for the component $extension = JRequest::getCmd('option'); $user = JFactory::getUser(); if (!$user->authorise('core.create', $extension)) { $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_CREATE')); return false; } //NEW $i = 0; //ENDNEW // Parent exists so we let's proceed while (!empty($pks)) { // Pop the first ID off the stack $pk = array_shift($pks); $table->reset(); // Check that the row actually exists if (!$table->load($pk)) { if ($error = $table->getError()) { // Fatal error $this->setError($error); return false; } else { // Not fatal error $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } } // Alter the title & alias $data = $this->generateNewTitle($categoryId, $table->alias, $table->title); $table->title = $data['0']; $table->alias = $data['1']; // Reset the ID because we are making a copy $table->id = 0; // New category ID $table->catid = $categoryId; // Ordering $table->ordering = $this->increaseOrdering($categoryId); $table->hits = 0; // Check the row. if (!$table->check()) { $this->setError($table->getError()); return false; } // Store the row. if (!$table->store()) { $this->setError($table->getError()); return false; } //NEW // Get the new item ID $newId = $table->get('id'); // Add the new ID to the array $newIds[$i] = $newId; $i++; //ENDNEW } // Clean the cache $this->cleanCache(); //NEW return $newIds; //END NEW } /** * Batch move articles to a new category * * @param integer $value The new category ID. * @param array $pks An array of row IDs. * * @return booelan True if successful, false otherwise and internal error is set. * * @since 11.1 */ protected function batchMove($value, $pks, $contexts) { $categoryId = (int) $value; $table = $this->getTable(); //$db = $this->getDbo(); // Check that the category exists if ($categoryId) { $categoryTable = JTable::getInstance('PhocaGalleryC', 'Table'); if (!$categoryTable->load($categoryId)) { if ($error = $categoryTable->getError()) { // Fatal error $this->setError($error); return false; } else { $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_MOVE_CATEGORY_NOT_FOUND')); return false; } } } if (empty($categoryId)) { $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_MOVE_CATEGORY_NOT_FOUND')); return false; } // Check that user has create and edit permission for the component $extension = JRequest::getCmd('option'); $user = JFactory::getUser(); if (!$user->authorise('core.create', $extension)) { $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_CREATE')); return false; } if (!$user->authorise('core.edit', $extension)) { $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } // Parent exists so we let's proceed foreach ($pks as $pk) { // Check that the row actually exists if (!$table->load($pk)) { if ($error = $table->getError()) { // Fatal error $this->setError($error); return false; } else { // Not fatal error $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } } // Set the new category ID $table->catid = $categoryId; // Check the row. if (!$table->check()) { $this->setError($table->getError()); return false; } // Store the row. if (!$table->store()) { $this->setError($table->getError()); return false; } } // Clean the cache $this->cleanCache(); return true; } protected function batchTag($value, $pks, $contexts) { foreach ($value as $categoryId){ foreach ($pks as $pk) { $query = 'DELETE FROM #__phocagallery_tags_ref' . ' WHERE imgid ='.$pk .' and tagid = '.$categoryId; $this->_db->setQuery( $query ); if(!$this->_db->query()) { $this->setError($this->_db->getErrorMsg()); return false; } $query = 'insert into #__phocagallery_tags_ref(imgid,tagid) values(' . $pk .', '.$categoryId.')'; $this->_db->setQuery( $query ); if(!$this->_db->query()) { $this->setError($this->_db->getErrorMsg()); return false; } } } return true; } public function increaseOrdering($categoryId) { $ordering = 1; $this->_db->setQuery('SELECT MAX(ordering) FROM #__phocagallery WHERE catid='.(int)$categoryId); $max = $this->_db->loadResult(); $ordering = $max + 1; return $ordering; } } ?>
LuxitoHD/mmall-chen
administrator/components/com_phocagallery/models/phocagalleryimg.php
PHP
gpl-2.0
22,198
/* * Xiphos Bible Study Tool * sword.cc - glue * * Copyright (C) 2000-2020 Xiphos Developer Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library 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 St, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <gtk/gtk.h> #include <glib.h> #include <glib/gstdio.h> #include <swmgr.h> #include <swmodule.h> #include <stringmgr.h> #include <localemgr.h> extern "C" { #include "gui/bibletext.h" #include "main/gtk_compat.h" } #include <ctype.h> #include <time.h> #include "gui/main_window.h" #include "gui/font_dialog.h" #include "gui/widgets.h" #include "gui/commentary.h" #include "gui/dialog.h" #include "gui/parallel_dialog.h" #include "gui/parallel_tab.h" #include "gui/parallel_view.h" #include "gui/tabbed_browser.h" #include "gui/xiphos.h" #include "gui/sidebar.h" #include "gui/utilities.h" #include "gui/cipher_key_dialog.h" #include "gui/main_menu.h" #include "main/biblesync_glue.h" #include "main/display.hh" #include "main/lists.h" #include "main/navbar.h" #include "main/navbar_book.h" #include "main/search_sidebar.h" #include "main/previewer.h" #include "main/settings.h" #include "main/sidebar.h" #include "main/sword.h" #include "main/url.hh" #include "main/xml.h" #include "main/parallel_view.h" #include "main/modulecache.hh" #include "backend/sword_main.hh" #include "backend/gs_stringmgr.h" #include "biblesync/biblesync.hh" #include "gui/debug_glib_null.h" #ifdef HAVE_DBUS #include "gui/ipc.h" #endif extern BibleSync *biblesync; using namespace sword; char *sword_locale = NULL; gboolean companion_activity = FALSE; /* Unicode collation necessities. */ UCollator* collator; UErrorCode collator_status; extern gboolean valid_scripture_key; // these track together. when one changes, so does the other. static std::map<string, string> abbrev_name2abbrev, abbrev_abbrev2name; typedef std::map<string, string>::iterator abbrev_iter; /****************************************************************************** * Name * main_add_abbreviation * * Synopsis * #include "main/sword.h" * * void main_add_abbreviation(char *name, char *abbreviation) * * Description * adds an element to each of the abbreviation maps. * * Return value * void */ void main_add_abbreviation(const char *name, const char *abbreviation) { // let's not be stupid about abbreviations chosen, ok? if (!strchr(abbreviation, '(')) { abbrev_name2abbrev[name] = abbreviation; abbrev_abbrev2name[abbreviation] = name; } } /****************************************************************************** * Name * main_get_abbreviation * * Synopsis * #include "main/sword.h" * * const char * main_get_abbreviation(const char *name) * * Description * gets abbreviation from real module, if available. * * Return value * const char * */ const char *main_get_abbreviation(const char *name) { if (name == NULL) return NULL; abbrev_iter it = abbrev_name2abbrev.find(name); if (it != abbrev_name2abbrev.end()) { return it->second.c_str(); } return NULL; } /****************************************************************************** * Name * main_get_name * * Synopsis * #include "main/sword.h" * * const char * main_get_name(const char *abbreviation) * * Description * gets real module name from abbreviation, if available. * * Return value * const char * */ const char *main_get_name(const char *abbreviation) { if (abbreviation == NULL) return NULL; abbrev_iter it = abbrev_abbrev2name.find(abbreviation); if (it != abbrev_abbrev2name.end()) { return it->second.c_str(); } return NULL; } /****************************************************************************** * Name * main_book_heading * * Synopsis * #include "main/sword.h" * * void main_book_heading(char * mod_name) * * Description * * * Return value * void */ void main_book_heading(char *mod_name) { VerseKey *vkey; SWMgr *mgr = backend->get_mgr(); backend->display_mod = mgr->Modules[mod_name]; vkey = (VerseKey *)(SWKey *)(*backend->display_mod); vkey->setIntros(1); vkey->setAutoNormalize(0); vkey->setChapter(0); vkey->setVerse(0); backend->display_mod->display(); } /****************************************************************************** * Name * main_chapter_heading * * Synopsis * #include "main/module_dialogs.h" * * void main_chapter_heading(char * mod_name) * * Description * * * Return value * void */ void main_chapter_heading(char *mod_name) { VerseKey *vkey; SWMgr *mgr = backend->get_mgr(); backend->display_mod = mgr->Modules[mod_name]; backend->display_mod->setKey(settings.currentverse); vkey = (VerseKey *)(SWKey *)(*backend->display_mod); vkey->setIntros(1); vkey->setAutoNormalize(0); vkey->setVerse(0); backend->display_mod->display(); } /****************************************************************************** * Name * main_save_note * * Synopsis * #include "main/sword.h" * * void main_save_note(const gchar * module_name, * const gchar * key_str , * const gchar * note_str ) * * Description * * * Return value * void */ void main_save_note(const gchar *module_name, const gchar *key_str, const gchar *note_str) { // Massage encoded spaces ("%20") back to real spaces. // This is a sick. unreliable hack that should be removed // after the underlying problem is fixed in Sword. gchar *rework; for (rework = (char *)strstr(note_str, "%20"); rework; rework = strstr(rework + 1, "%20")) { *rework = ' '; (void)strcpy(rework + 1, rework + 3); } XI_message(("note module %s\nnote key %s\nnote text%s", module_name, key_str, note_str)); backend->save_note_entry(module_name, key_str, note_str); main_display_commentary(module_name, settings.currentverse); } /****************************************************************************** * Name * main_delete_note * * Synopsis * #include "main/sword.h" * * void main_delete_note(DIALOG_DATA * d) * * Description * * * Return value * void */ void main_delete_note(const gchar *module_name, const gchar *key_str) { backend->set_module_key(module_name, key_str); XI_message(("note module %s\nnote key %s\n", module_name, key_str)); backend->delete_entry(); if ((!strcmp(settings.CommWindowModule, module_name)) && (!strcmp(settings.currentverse, key_str))) main_display_commentary(module_name, key_str); } /****************************************************************************** * Name * set_module_unlocked * * Synopsis * #include "bibletext.h" * * void set_module_unlocked(char *mod_name, char *key) * * Description * unlocks locked module - * * Return value * void */ void main_set_module_unlocked(const char *mod_name, char *key) { SWMgr *mgr = backend->get_mgr(); mgr->setCipherKey(mod_name, key); } /****************************************************************************** * Name * main_save_module_key * * Synopsis * #include "main/configs.h" * * void main_save_module_key(gchar * mod_name, gchar * key) * * Description * to unlock locked modules * * Return value * void */ void main_save_module_key(const char *mod_name, char *key) { backend->save_module_key((char *)mod_name, key); } /****************************************************************************** * Name * main_getText * * Synopsis * #include "main/sword.h" * void main_getText(gchar * key) * * Description * get unabbreviated key * * Return value * char * */ char *main_getText(char *key) { VerseKey vkey(key); return strdup((char *)vkey.getText()); } /****************************************************************************** * Name * main_getShortText * * Synopsis * #include "main/sword.h" * void main_getShortText(gchar * key) * * Description * get short-name key * * Return value * char * */ char *main_getShortText(char *key) { VerseKey vkey(key); return strdup((char *)vkey.getShortText()); } /****************************************************************************** * Name * main_update_nav_controls * * Synopsis * #include "toolbar_nav.h" * * gchar *main_update_nav_controls(const gchar * key) * * Description * updates the nav toolbar controls * * Return value * gchar * */ gchar *main_update_nav_controls(const char *module_name, const gchar *key) { char *val_key = backend->get_valid_key(module_name, key); // we got a valid key. but was it really a valid key within v11n? // for future use in determining whether to show normal navbar content. navbar_versekey.valid_key = main_is_Bible_key(module_name, key); /* * remember verse */ xml_set_value("Xiphos", "keys", "verse", val_key); settings.currentverse = xml_get_value("keys", "verse"); settings.apply_change = FALSE; navbar_versekey.module_name = g_string_assign(navbar_versekey.module_name, settings.MainWindowModule); navbar_versekey.key = g_string_assign(navbar_versekey.key, val_key); main_navbar_versekey_set(navbar_versekey, val_key); settings.apply_change = TRUE; #ifdef HAVE_DBUS IpcObject *ipc = ipc_get_main_ipc(); if (ipc) ipc_object_navigation_signal(ipc, (const gchar *)val_key, NULL); #endif return val_key; } /****************************************************************************** * Name * get_module_key * * Synopsis * #include "main/module.h" * * char *get_module_key(void) * * Description * returns module key * * Return value * char * */ char *main_get_active_pane_key(void) { if (settings.havebible) { switch (settings.whichwindow) { case MAIN_TEXT_WINDOW: case COMMENTARY_WINDOW: return (char *)settings.currentverse; break; case DICTIONARY_WINDOW: return (char *)settings.dictkey; break; case parallel_WINDOW: return (char *)settings.cvparallel; break; case BOOK_WINDOW: return (char *)settings.book_key; break; } } return NULL; } /****************************************************************************** * Name * get_module_name * * Synopsis * #include "main/module.h" * * char *get_module_name(void) * * Description * returns module name * * Return value * char * */ char *main_get_active_pane_module(void) { if (settings.havebible) { switch (settings.whichwindow) { case MAIN_TEXT_WINDOW: return (char *)xml_get_value("modules", "bible"); break; case COMMENTARY_WINDOW: return (char *)xml_get_value("modules", "comm"); break; case DICTIONARY_WINDOW: return (char *)settings.DictWindowModule; break; case BOOK_WINDOW: return (char *)settings.book_mod; break; } } return NULL; } /****************************************************************************** * Name * module_name_from_description * * Synopsis * #include ".h" * * void module_name_from_description(gchar *mod_name, gchar *description) * * Description * * * Return value * void */ char *main_module_name_from_description(char *description) { return backend->module_name_from_description(description); } /****************************************************************************** * Name * main_get_sword_version * * Synopsis * #include "sword.h" * * const char *main_get_sword_version(void) * * Description * * * Return value * const char * */ const char *main_get_sword_version(void) { return backend->get_sword_version(); } /****************************************************************************** * Name * get_search_results_text * * Synopsis * #include "sword.h" * * char *get_search_results_text(char * mod_name, char * key) * * Description * * * Return value * char * */ char *main_get_search_results_text(char *mod_name, char *key) { return backend->get_render_text((char *)mod_name, (char *)key); } /****************************************************************************** * Name * main_get_path_to_mods * * Synopsis * #include "sword.h" * * gchar *main_get_path_to_mods(void) * * Description * returns the path to the sword modules * * Return value * gchar * */ char *main_get_path_to_mods(void) { SWMgr *mgr = backend->get_mgr(); char *path = mgr->prefixPath; return (path ? g_strdup(path) : NULL); } /****************************************************************************** * Name * main_init_language_map * * Synopsis * #include "sword.h" * * void main_init_language_map(void) * * Description * initializes the hard-coded abbrev->name mapping. * * Return value * void */ typedef std::map<SWBuf, SWBuf> ModLanguageMap; ModLanguageMap languageMap; void main_init_language_map() { gchar *language_file; FILE *language; gchar *s, *end, *abbrev, *name, *newline; gchar *mapspace; size_t length; if ((language_file = gui_general_user_file("languages", FALSE)) == NULL) { gui_generic_warning(_("Xiphos's file for language\nabbreviations is missing.")); return; } XI_message(("%s", language_file)); if ((language = g_fopen(language_file, "r")) == NULL) { gui_generic_warning(_("Xiphos's language abbreviation\nfile cannot be opened.")); g_free(language_file); return; } g_free(language_file); (void)fseek(language, 0L, SEEK_END); length = ftell(language); rewind(language); if ((length == 0) || (mapspace = (gchar *)g_malloc(length + 2)) == NULL) { fclose(language); gui_generic_warning(_("Xiphos cannot allocate space\nfor language abbreviations.")); return; } if (fread(mapspace, 1, length, language) != length) { fclose(language); g_free(mapspace); gui_generic_warning(_("Xiphos cannot read the\nlanguage abbreviation file.")); return; } fclose(language); end = length + mapspace; *end = '\0'; for (s = mapspace; s < end; ++s) { if ((newline = strchr(s, '\n')) == NULL) { XI_message(("incomplete last line in languages")); break; } *newline = '\0'; if ((*s == '#') || (s == newline)) { s = newline; // comment or empty line. continue; } abbrev = s; if ((name = strchr(s, '\t')) == NULL) { XI_message(("tab-less line in languages")); break; } *(name++) = '\0'; // NUL-terminate abbrev, mark name. languageMap[SWBuf(abbrev)] = SWBuf(name); s = newline; } g_free(mapspace); } const char *main_get_language_map(const char *language) { if (language == NULL) return "Unknown"; return languageMap[language].c_str(); } char **main_get_module_language_list(void) { return backend->get_module_language_list(); } /****************************************************************************** * Name * set_sword_locale * * Synopsis * #include "main/sword.h" * * char *set_sword_locale(const char *sys_locale) * * Description * set sword's idea of the locale in which the user operates * * Return value * char * */ char *set_sword_locale(const char *sys_locale) { if (sys_locale) { SWBuf locale; StringList localelist = LocaleMgr::getSystemLocaleMgr()->getAvailableLocales(); StringList::iterator it; int ncmp[3] = {100, 5, 2}; // fixed data // length-limited match for (int i = 0; i < 3; ++i) { for (it = localelist.begin(); it != localelist.end(); ++it) { locale = *it; if (!strncmp(sys_locale, locale.c_str(), ncmp[i])) { LocaleMgr::getSystemLocaleMgr()->setDefaultLocaleName(locale.c_str()); return g_strdup(locale.c_str()); } } } } // either we were given a null sys_locale, or it didn't match anything. char *err = g_strdup_printf(_("No matching locale found for `%s'.\n%s"), sys_locale, _("Book names and menus may not be translated.")); gui_generic_warning(err); g_free(err); return NULL; } /****************************************************************************** * Name * backend_init * * Synopsis * #include "main/sword.h" * * void main_init_backend(void) * * Description * start sword * * Return value * void */ void main_init_backend(void) { StringMgr::setSystemStringMgr(new GS_StringMgr()); const char *lang = getenv("LANG"); if (!lang) lang = "C"; sword_locale = set_sword_locale(lang); collator = ucol_open(sword_locale, &collator_status); lang = LocaleMgr::getSystemLocaleMgr()->getDefaultLocaleName(); backend = new BackEnd(); backend->init_SWORD(0); settings.path_to_mods = main_get_path_to_mods(); //#ifndef DEBUG g_chdir(settings.path_to_mods); //#else // XI_warning(("no chdir(SWORD_PATH) => modmgr 'archive' may not work")); //#endif XI_print(("%s sword-%s\n", "Starting", backend->get_sword_version())); XI_print(("%s\n", "Initiating SWORD")); XI_print(("%s: %s\n", "path to sword", settings.path_to_mods)); XI_print(("%s %s\n", "SWORD locale is", lang)); XI_print(("%s\n", "Checking for SWORD Modules")); settings.spell_language = strdup(lang); main_init_lists(); // // BibleSync backend startup. identify the user by name. // biblesync = new BibleSync("Xiphos", VERSION, #ifdef WIN32 // in win32 glib, get_real_name and get_user_name are the same. (string)g_get_real_name() #else (string)g_get_real_name() + " (" + g_get_user_name() + ")" #endif ); } /****************************************************************************** * Name * shutdown_sword * * Synopsis * #include "sword.h" * * void shutdown_sword(void) * * Description * close down sword by deleting backend; * * Return value * void */ void main_shutdown_backend(void) { if (sword_locale) free((char *)sword_locale); sword_locale = NULL; if (backend) delete backend; backend = NULL; XI_print(("%s\n", "SWORD is shutdown")); } /****************************************************************************** * Name * main_dictionary_entry_changed * * Synopsis * #include "main/sword.h" * * void main_dictionary_entry_changed(char * mod_name) * * Description * text in the dictionary entry has changed and the entry activated * * Return value * void */ void main_dictionary_entry_changed(char *mod_name) { gchar *key = NULL; if (!mod_name) return; if (strcmp(settings.DictWindowModule, mod_name)) { xml_set_value("Xiphos", "modules", "dict", mod_name); settings.DictWindowModule = xml_get_value("modules", "dict"); } key = g_strdup((gchar *)gtk_entry_get_text(GTK_ENTRY(widgets.entry_dict))); backend->set_module_key(mod_name, key); g_free(key); key = backend->get_module_key(); xml_set_value("Xiphos", "keys", "dictionary", key); settings.dictkey = xml_get_value("keys", "dictionary"); main_check_unlock(mod_name, TRUE); backend->set_module_key(mod_name, key); backend->display_mod->display(); gtk_entry_set_text(GTK_ENTRY(widgets.entry_dict), key); g_free(key); } static void dict_key_list_select(GtkMenuItem *menuitem, gpointer user_data) { gtk_entry_set_text(GTK_ENTRY(widgets.entry_dict), (gchar *)user_data); gtk_widget_activate(widgets.entry_dict); } /****************************************************************************** * Name * * * Synopsis * #include "main/sword.h" * * * * Description * text in the dictionary entry has changed and the entry activated * * Return value * void */ GtkWidget *main_dictionary_drop_down_new(char *mod_name, char *old_key) { gint count = 9, i; gchar *new_key; gchar *key = NULL; GtkWidget *menu; menu = gtk_menu_new(); if (!settings.havedict || !mod_name) return NULL; if (strcmp(settings.DictWindowModule, mod_name)) { xml_set_value("Xiphos", "modules", "dict", mod_name); settings.DictWindowModule = xml_get_value( "modules", "dict"); } key = g_strdup((gchar *)gtk_entry_get_text(GTK_ENTRY(widgets.entry_dict))); XI_message(("\nold_key: %s\nkey: %s", old_key, key)); backend->set_module_key(mod_name, key); g_free(key); key = backend->get_module_key(); xml_set_value("Xiphos", "keys", "dictionary", key); settings.dictkey = xml_get_value("keys", "dictionary"); main_check_unlock(mod_name, TRUE); backend->set_module_key(mod_name, key); backend->display_mod->display(); new_key = g_strdup((char *)backend->display_mod->getKeyText()); for (i = 0; i < (count / 2) + 1; i++) { (*backend->display_mod)--; } for (i = 0; i < count; i++) { free(new_key); (*backend->display_mod)++; new_key = g_strdup((char *)backend->display_mod->getKeyText()); /* add menu item */ GtkWidget *item = gtk_menu_item_new_with_label((gchar *)new_key); gtk_widget_show(item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(dict_key_list_select), g_strdup(new_key)); gtk_container_add(GTK_CONTAINER(menu), item); } free(new_key); g_free(key); return menu; } /****************************************************************************** * Name * main_dictionary_button_clicked * * Synopsis * #include "main/sword.h" * * void main_dictionary_button_clicked(gint direction) * * Description * The back or foward dictinary key button was clicked. * the module key is set to the current dictkey. * then the module is incremented or decremented. * the new key is returned from the module and the dictionary entry is set * to the new key. The entry is then activated. * * Return value * void */ void main_dictionary_button_clicked(gint direction) { gchar *key = NULL; if (!settings.havedict || !settings.DictWindowModule) return; backend->set_module_key(settings.DictWindowModule, settings.dictkey); if (direction == 0) (*backend->display_mod)--; else (*backend->display_mod)++; key = g_strdup((char *)backend->display_mod->getKeyText()); gtk_entry_set_text(GTK_ENTRY(widgets.entry_dict), key); gtk_widget_activate(widgets.entry_dict); g_free(key); } void main_display_book(const char *mod_name, const char *key) { if (!settings.havebook || !mod_name) return; if (key == NULL) key = "0"; XI_message(("main_display_book\nmod_name: %s\nkey: %s", mod_name, key)); if (!backend->is_module(mod_name)) return; if (!settings.book_mod) settings.book_mod = g_strdup((char *)mod_name); if (strcmp(settings.book_mod, mod_name)) { xml_set_value("Xiphos", "modules", "book", mod_name); gui_reassign_strdup(&settings.book_mod, (gchar *)mod_name); } if (!isdigit(key[0])) { xml_set_value("Xiphos", "keys", "book", key); settings.book_key = xml_get_value("keys", "book"); backend->set_module(mod_name); backend->set_treekey(0); settings.book_offset = backend->treekey_set_key((char *)key); } else { settings.book_offset = atol(key); if (settings.book_offset < 4) settings.book_offset = 4; xml_set_value("Xiphos", "keys", "book", key); settings.book_key = xml_get_value("keys", "book"); xml_set_value("Xiphos", "keys", "offset", key); backend->set_module(mod_name); backend->set_treekey(settings.book_offset); } main_check_unlock(mod_name, TRUE); backend->display_mod->display(); main_setup_navbar_book(settings.book_mod, settings.book_offset); //if (settings.browsing) gui_update_tab_struct(NULL, NULL, NULL, mod_name, NULL, key, FALSE, settings.showtexts, settings.showpreview, settings.showcomms, settings.showdicts); } void main_display_commentary(const char *mod_name, const char *key) { if (!settings.havecomm || !settings.comm_showing) return; if (!mod_name) mod_name = ((settings.browsing && (cur_passage_tab != NULL)) ? g_strdup(cur_passage_tab->commentary_mod) : xml_get_value("modules", "comm")); if (!mod_name || !backend->is_module(mod_name)) return; int modtype = backend->module_type(mod_name); if ((modtype != COMMENTARY_TYPE) && (modtype != PERCOM_TYPE)) return; // what are we doing here? if (!settings.CommWindowModule) settings.CommWindowModule = g_strdup((gchar *)mod_name); settings.comm_showing = TRUE; settings.whichwindow = COMMENTARY_WINDOW; if (strcmp(settings.CommWindowModule, mod_name)) { xml_set_value("Xiphos", "modules", "comm", mod_name); gui_reassign_strdup(&settings.CommWindowModule, (gchar *)mod_name); // handle a conf directive "Companion=This,That,TheOther" char *companion = main_get_mod_config_entry(mod_name, "Companion"); gchar **name_set = (companion ? g_strsplit(companion, ",", -1) : NULL); if (companion && (!companion_activity) && name_set[0] && *name_set[0] && backend->is_module(name_set[0]) && ((settings.MainWindowModule == NULL) || strcmp(name_set[0], settings.MainWindowModule))) { companion_activity = TRUE; gint name_length = g_strv_length(name_set); char *companion_question = g_strdup_printf(_("Module %s has companion modules:\n%s.\n" "Would you like to open these as well?%s"), mod_name, companion, ((name_length > 1) ? _("\n\nThe first will open in the main window\n" "and others in separate windows.") : "")); if (gui_yes_no_dialog(companion_question, NULL)) { main_display_bible(name_set[0], key); for (int i = 1; i < name_length; i++) { main_dialogs_open(name_set[i], key, FALSE); } } g_free(companion_question); companion_activity = FALSE; } if (name_set) g_strfreev(name_set); if (companion) g_free(companion); } main_check_unlock(mod_name, TRUE); valid_scripture_key = main_is_Bible_key(mod_name, key); backend->set_module_key(mod_name, key); backend->display_mod->display(); valid_scripture_key = TRUE; // leave nice for future use. //if (settings.browsing) gui_update_tab_struct(NULL, mod_name, NULL, NULL, NULL, NULL, TRUE, settings.showtexts, settings.showpreview, settings.showcomms, settings.showdicts); } void main_display_dictionary(const char *mod_name, const char *key) { const gchar *old_key, *feature; // for devotional use. gchar buf[10]; if (!settings.havedict || !mod_name) return; XI_message(("main_display_dictionary\nmod_name: %s\nkey: %s", mod_name, key)); if (!backend->is_module(mod_name)) return; if (!settings.DictWindowModule) settings.DictWindowModule = g_strdup((gchar *)mod_name); if (key == NULL) key = (char *)"Grace"; feature = (char *)backend->get_mgr()->getModule(mod_name)->getConfigEntry("Feature"); // turn on "all strong's" iff we have that kind of dictionary. if (feature && (!strcmp(feature, "HebrewDef") || !strcmp(feature, "GreekDef"))) gtk_widget_show(widgets.all_strongs); else gtk_widget_hide(widgets.all_strongs); if (strcmp(settings.DictWindowModule, mod_name)) { // new dict -- is it actually a devotional? time_t curtime; if (feature && !strcmp(feature, "DailyDevotion")) { if ((strlen(key) != 5) || // blunt tests. (key[0] < '0') || (key[0] > '9') || (key[1] < '0') || (key[1] > '9') || (key[2] != '.') || (key[3] < '0') || (key[3] > '9') || (key[4] < '0') || (key[4] > '9')) { // not MM.DD struct tm *loctime; curtime = time(NULL); loctime = localtime(&curtime); strftime(buf, 10, "%m.%d", loctime); key = buf; } } xml_set_value("Xiphos", "modules", "dict", mod_name); gui_reassign_strdup(&settings.DictWindowModule, (gchar *)mod_name); } // old_key is uppercase key = g_utf8_strup(key, -1); old_key = gtk_entry_get_text(GTK_ENTRY(widgets.entry_dict)); if (!strcmp(old_key, key)) main_dictionary_entry_changed(settings.DictWindowModule); else { gtk_entry_set_text(GTK_ENTRY(widgets.entry_dict), key); gtk_widget_activate(widgets.entry_dict); } //if (settings.browsing) gui_update_tab_struct(NULL, NULL, mod_name, NULL, key, NULL, settings.comm_showing, settings.showtexts, settings.showpreview, settings.showcomms, settings.showdicts); } void main_display_bible(const char *mod_name, const char *key) { gchar *bs_key = g_strdup(key); // avoid tab data corruption problem. /* keeps us out of a crash causing loop */ extern guint scroll_adj_signal; extern GtkAdjustment *adjustment; if (adjustment) g_signal_handler_block(adjustment, scroll_adj_signal); if (!gtk_widget_get_realized(GTK_WIDGET(widgets.html_text))) return; if (!mod_name) mod_name = ((settings.browsing && (cur_passage_tab != NULL)) ? g_strdup(cur_passage_tab->text_mod) : xml_get_value("modules", "bible")); if (!settings.havebible || !mod_name) return; if (!backend->is_module(mod_name)) return; int modtype = backend->module_type(mod_name); if (modtype != TEXT_TYPE) return; // what are we doing here? if (!settings.MainWindowModule) settings.MainWindowModule = g_strdup((gchar *)mod_name); if (strcmp(settings.currentverse, key)) { xml_set_value("Xiphos", "keys", "verse", key); settings.currentverse = xml_get_value( "keys", "verse"); } if (strcmp(settings.MainWindowModule, mod_name)) { xml_set_value("Xiphos", "modules", "bible", mod_name); gui_reassign_strdup(&settings.MainWindowModule, (gchar *)mod_name); // handle a conf directive "Companion=This,That,TheOther" char *companion = main_get_mod_config_entry(mod_name, "Companion"); gchar **name_set = (companion ? g_strsplit(companion, ",", -1) : NULL); if (companion && (!companion_activity) && name_set[0] && *name_set[0] && backend->is_module(name_set[0]) && ((settings.CommWindowModule == NULL) || strcmp(name_set[0], settings.CommWindowModule))) { companion_activity = TRUE; gint name_length = g_strv_length(name_set); char *companion_question = g_strdup_printf(_("Module %s has companion modules:\n%s.\n" "Would you like to open these as well?%s"), mod_name, companion, ((name_length > 1) ? _("\n\nThe first will open in the main window\n" "and others in separate windows.") : "")); if (gui_yes_no_dialog(companion_question, NULL)) { main_display_commentary(name_set[0], key); for (int i = 1; i < name_length; i++) { main_dialogs_open(name_set[i], key, FALSE); } } g_free(companion_question); companion_activity = FALSE; } if (name_set) g_strfreev(name_set); if (companion) g_free(companion); navbar_versekey.module_name = g_string_assign(navbar_versekey.module_name, settings.MainWindowModule); navbar_versekey.key = g_string_assign(navbar_versekey.key, settings.currentverse); main_search_sidebar_fill_bounds_combos(); } settings.whichwindow = MAIN_TEXT_WINDOW; main_check_unlock(mod_name, TRUE); valid_scripture_key = main_is_Bible_key(mod_name, key); if (backend->module_has_testament(mod_name, backend->get_key_testament(mod_name, key))) { backend->set_module_key(mod_name, key); backend->display_mod->display(); } else { gchar *val_key = NULL; if (backend->get_key_testament(mod_name, key) == 1) val_key = main_update_nav_controls(mod_name, "Matthew 1:1"); else val_key = main_update_nav_controls(mod_name, "Genesis 1:1"); backend->set_module_key(mod_name, val_key); backend->display_mod->display(); g_free(val_key); } valid_scripture_key = TRUE; // leave nice for future use. XI_message(("mod_name = %s", mod_name)); //if (settings.browsing) { gui_update_tab_struct(mod_name, NULL, NULL, NULL, NULL, NULL, settings.comm_showing, settings.showtexts, settings.showpreview, settings.showcomms, settings.showdicts); gui_set_tab_label(settings.currentverse, FALSE); //} gui_change_window_title(settings.MainWindowModule); // (called _after_ tab data updated so not overwritten with old tab) /* * change parallel verses */ if (settings.dockedInt) main_update_parallel_page(); else { if (settings.showparatab) gui_keep_parallel_tab_in_sync(); else gui_keep_parallel_dialog_in_sync(); } // multicast now, iff user has not asked for keyboard-only xmit. if (!settings.bs_keyboard) biblesync_prep_and_xmit(mod_name, bs_key); g_free(bs_key); if (adjustment) g_signal_handler_unblock(adjustment, scroll_adj_signal); } /****************************************************************************** * Name * main_display_devotional * * Synopsis * #include "main/sword.h" * * void main_display_devotional(void) * * Description * * * Return value * void */ void main_display_devotional(void) { gchar buf[10]; gchar *prettybuf; time_t curtime; struct tm *loctime; gchar *text; /* * This makes sense only if you've installed & defined one. */ if (settings.devotionalmod == NULL) { GList *glist = get_list(DEVOTION_LIST); if (g_list_length(glist) != 0) { xml_set_value("Xiphos", "modules", "devotional", (char *)glist->data); gui_reassign_strdup(&settings.devotionalmod, (gchar *)glist->data); } else { gui_generic_warning(_("Daily devotional was requested, but there are none installed.")); } } /* * Get the current time, converted to local time. */ curtime = time(NULL); loctime = localtime(&curtime); strftime(buf, 10, "%m.%d", loctime); prettybuf = g_strdup_printf("<b>%s %d</b>", gettext(month_names[loctime->tm_mon]), loctime->tm_mday); text = backend->get_render_text(settings.devotionalmod, buf); if (text) { main_entry_display(settings.show_previewer_in_sidebar ? sidebar.html_viewer_widget : widgets.html_previewer_text, settings.devotionalmod, text, prettybuf, TRUE); g_free(text); } g_free(prettybuf); } void main_setup_displays(void) { backend->textDisplay = new GTKChapDisp(widgets.html_text, backend); backend->commDisplay = new GTKEntryDisp(widgets.html_comm, backend); backend->bookDisplay = new GTKEntryDisp(widgets.html_book, backend); backend->dictDisplay = new GTKEntryDisp(widgets.html_dict, backend); } const char *main_get_module_language(const char *module_name) { return backend->module_get_language(module_name); } /****************************************************************************** * Name * main_check_for_option * * Synopsis * #include ".h" * * gint main_check_for_option(const gchar * mod_name, const gchar * key, const gchar * option) * * Description * get any option for a module * * Return value * gint */ gint main_check_for_option(const gchar *mod_name, const gchar *key, const gchar *option) { return backend->has_option(mod_name, key, option); } /****************************************************************************** * Name * main_check_for_global_option * * Synopsis * #include ".h" * * gint main_check_for_global_option(const gchar * mod_name, const gchar * option) * * Description * get global options for a module * * Return value * gint */ gint main_check_for_global_option(const gchar *mod_name, const gchar *option) { return backend->has_global_option(mod_name, option); } /****************************************************************************** * Name * main_is_module * * Synopsis * #include "main/module.h" * * int main_is_module(char * mod_name) * * Description * check for presents of a module by name * * Return value * int */ int main_is_module(char *mod_name) { return backend->is_module(mod_name); } /****************************************************************************** * Name * main_has_search_framework * * Synopsis * #include "main/module.h" * * int main_has_search_framework(char * mod_name) * * Description * tells us whether CLucene is available * * Return value * int (boolean) */ int main_has_search_framework(char *mod_name) { SWMgr *mgr = backend->get_mgr(); SWModule *mod = mgr->getModule(mod_name); return (mod && mod->hasSearchFramework()); } /****************************************************************************** * Name * main_optimal_search * * Synopsis * #include "main/module.h" * * int main_optimal_search(char * mod_name) * * Description * tells us whether a CLucene index exists * * Return value * int (boolean) */ int main_optimal_search(char *mod_name) { SWMgr *mgr = backend->get_mgr(); SWModule *mod = mgr->Modules.find(mod_name)->second; return mod->isSearchOptimallySupported("God", -4, 0, 0); } char *main_get_mod_config_entry(const char *module_name, const char *entry) { return backend->get_config_entry((char *)module_name, (char *)entry); } char *main_get_mod_config_file(const char *module_name, const char *moddir) { #ifdef SWORD_SHOULD_HAVE_A_WAY_TO_GET_A_CONF_FILENAME_FROM_A_MODNAME return backend->get_config_file((char *)module_name, (char *)moddir); #else GDir *dir; SWBuf name; name = moddir; name += "/mods.d"; if ((dir = g_dir_open(name, 0, NULL))) { const gchar *ent; g_dir_rewind(dir); while ((ent = g_dir_read_name(dir))) { name = moddir; name += "/mods.d/"; name += ent; SWConfig *config = new SWConfig(name.c_str()); if (config->getSections().find(module_name) != config->getSections().end()) { gchar *ret_name = g_strdup(ent); g_dir_close(dir); delete config; return ret_name; } else delete config; } g_dir_close(dir); } return NULL; #endif } int main_is_mod_rtol(const char *module_name) { char *direction = backend->get_config_entry((char *)module_name, (char *)"Direction"); return (direction && !strcmp(direction, "RtoL")); } /****************************************************************************** * Name * main_has_cipher_tag * * Synopsis * #include "main/.h" * * int main_has_cipher_tag(char *mod_name) * * Description * * * Return value * int */ int main_has_cipher_tag(char *mod_name) { gchar *cipherkey = backend->get_config_entry(mod_name, (char *)"CipherKey"); int retval = (cipherkey != NULL); g_free(cipherkey); return retval; } #define CIPHER_INTRO \ _("<b>Locked Module.</b>\n\n<u>You are opening a module which requires a <i>key</i>.</u>\n\nThe module is locked, meaning that the content is encrypted by its publisher, and you must enter its key in order for the content to become useful. This key should have been received by you on the web page which confirmed your purchase, or perhaps sent via email after purchase.\n\nPlease enter the key in the dialog.") /****************************************************************************** * Name * main_check_unlock * * Synopsis * #include "main/.h" * * int main_check_unlock(const char *mod_name) * * Description * * * Return value * int */ void main_check_unlock(const char *mod_name, gboolean conditional) { gchar *cipher_old = main_get_mod_config_entry(mod_name, "CipherKey"); /* if forced by the unlock menu item, or it's present but empty... */ if (!conditional || ((cipher_old != NULL) && (*cipher_old == '\0'))) { if (conditional) { GtkWidget *dialog; dialog = gtk_message_dialog_new_with_markup(NULL, /* no need for a parent window */ GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, GTK_BUTTONS_OK, CIPHER_INTRO); g_signal_connect_swapped(dialog, "response", G_CALLBACK(gtk_widget_destroy), dialog); gtk_widget_show(dialog); } gchar *cipher_key = gui_add_cipher_key(mod_name, cipher_old); if (cipher_key) { ModuleCacheErase(mod_name); redisplay_to_realign(); g_free(cipher_key); } } g_free(cipher_old); } /****************************************************************************** * Name * main_get_striptext * * Synopsis * #include "main/sword.h" * * char *main_get_striptext(char *module_name, char *key) * * Description * * * Return value * char * */ char *main_get_striptext(char *module_name, char *key) { return backend->get_strip_text(module_name, key); } /****************************************************************************** * Name * main_get_rendered_text * * Synopsis * #include "main/sword.h" * * char *main_get_rendered_text(char *module_name, char *key) * * Description * * * Return value * char * */ char *main_get_rendered_text(const char *module_name, const char *key) { return backend->get_render_text(module_name, key); } /****************************************************************************** * Name * main_get_raw_text * * Synopsis * #include "main/sword.h" * * char *main_get_raw_text(char *module_name, char *key) * * Description * * * Return value * char * */ char *main_get_raw_text(char *module_name, char *key) { return backend->get_raw_text(module_name, key); } /****************************************************************************** * Name * main_get_mod_type * * Synopsis * #include "main/module.h" * * int main_get_mod_type(char * mod_name) * * Description * * * Return value * int */ int main_get_mod_type(char *mod_name) { return backend->module_type(mod_name); } /****************************************************************************** * Name * main_get_module_description * * Synopsis * #include "main/module.h" * * gchar *main_get_module_description(gchar * module_name) * * Description * * * Return value * gchar * */ const char *main_get_module_description(const char *module_name) { return backend->module_description(module_name); } /****************************************************************************** * Name * main_format_number * * Synopsis * #include "main/sword.h" * char *main_format_number(int x) * * Description * returns a digit string in either "latinate arabic" (normal) or * farsi characters. * re_encode_digits is chosen at startup in settings.c. * caller must free allocated string space when finished with it. * * Return value * char * */ int re_encode_digits = FALSE; char * main_format_number(int x) { char *digits = g_strdup_printf("%d", x); if (re_encode_digits) { // // "\333\260" is farsi "zero". // char *d, *f, *farsi = g_new(char, 2 * (strlen(digits) + 1)); // 2 "chars" per farsi-displayed digit + slop. for (d = digits, f = farsi; *d; ++d) { *(f++) = '\333'; *(f++) = '\260' + ((*d) - '0'); } *f = '\0'; g_free(digits); return farsi; } return digits; } /****************************************************************************** * Name * main_flush_widgets_content * * Synopsis * #include "main/sword.h" * void main_flush_widgets_content() * * Description * cleans content from all subwindow widgets. * * Return value * int */ void main_flush_widgets_content(void) { GString *blank_html_content = g_string_new(NULL); g_string_printf(blank_html_content, "<html><head></head><body bgcolor=\"%s\" text=\"%s\"> </body></html>", settings.bible_bg_color, settings.bible_text_color); if (gtk_widget_get_realized(GTK_WIDGET(widgets.html_text))) HtmlOutput(blank_html_content->str, widgets.html_text, NULL, NULL); if (gtk_widget_get_realized(GTK_WIDGET(widgets.html_comm))) HtmlOutput(blank_html_content->str, widgets.html_comm, NULL, NULL); if (gtk_widget_get_realized(GTK_WIDGET(widgets.html_dict))) HtmlOutput(blank_html_content->str, widgets.html_dict, NULL, NULL); if (gtk_widget_get_realized(GTK_WIDGET(widgets.html_book))) HtmlOutput(blank_html_content->str, widgets.html_book, NULL, NULL); g_string_free(blank_html_content, TRUE); } /****************************************************************************** * Name * main_is_Bible_key * * Synopsis * #include "main/sword.h" * void main_is_Bible_key() * * Description * returns boolean status of whether input is a legit Bible key. * * Return value * gboolean */ gboolean main_is_Bible_key(const gchar *name, const gchar *key) { return (gboolean)(backend->is_Bible_key(name, key, settings.currentverse) != 0); } /****************************************************************************** * Name * main_get_osisref_from_key * * Synopsis * #include "main/sword.h" * void main_get_osisref_from_key() * * Description * returns OSISRef-formatted key value. * * Return value * const char * */ const char * main_get_osisref_from_key(const char *module, const char *key) { return backend->get_osisref_from_key(module, key); }
crosswire/xiphos
src/main/sword.cc
C++
gpl-2.0
45,237
<?php global $PPT,$PPTDesign; PremiumPress_Header(); ?> <div id="premiumpress_box1" class="premiumpress_box premiumpress_box-100"><div class="premiumpress_boxin"><div class="header"> <h3><img src="<?php echo $GLOBALS['template_url']; ?>/images/premiumpress/h-ico/GeneralPreferences.png" align="middle"> Display Setup</h3> <ul> <li><a rel="premiumpress_tab1" href="#" class="active">Layout</a></li> <li><a rel="premiumpress_tab6" href="#">Home</a></li> <!--<li><a rel="premiumpress_tab2" href="#">Search</a></li>--> <li><a rel="premiumpress_tab3" href="#">Sidebar</a></li> <li><a rel="premiumpress_tab4" href="#">Coupon Page</a></li> <li><a rel="premiumpress_tab5" href="#">Sliders</a></li> </ul> </div> <style> select { border-radius: 0px; -webkit-border-radius: 0px; -moz-border-radius: 0px; } </style> <form method="post" name="directorypress" target="_self" > <input name="admin_page" type="hidden" value="directorypress_setup" /> <input name="submitted" type="hidden" value="yes" /> <input name="setup" type="hidden" value="1" /> <input name="featured" type="hidden" value="1" /> <input name="featured1" type="hidden" value="1" /> <input name="listbox" type="hidden" value="yes" /> <input name="featuredstores" type="hidden" value="yes" /> <div id="premiumpress_tab1" class="content"> <table class="maintable" style="background:white;"> <tr class="mainrow"> <td></td> <td class="forminp"> <p><b>Coupon Display</b></p> <select name="adminArray[system]" class="small-input" style="width: 240px; font-size:14px;"> <option value="clicktoreveal" <?php if(get_option("system") == "clicktoreveal"){ echo "selected='selected'"; } ?>>Click To Reveal</option> <option value="normal" <?php if(get_option("system") == "normal"){ echo "selected='selected'"; } ?>>Click To Copy</option> <option value="link" <?php if(get_option("system") == "link"){ echo "selected='selected'"; } ?>>Link Display</option> </select> <br /> <small>Select which type of coupon display you wish to use.</small> </td> <td class="forminp"><img src="<?php echo IMAGE_PATH; ?>/help1/c3.png"> </td> </tr> <tr class="mainrow"><td></td><td class="forminp"> <b>Select theme layout (2 or 3 columns)</b> <table width="100%" border="1"> <tr> <td style="width:150px;"><img src="<?php echo $GLOBALS['template_url']; ?>/PPT/img/layout2.gif" /><br /><center> <input name="display_themecolumns" type="radio" value="2" <?php if(get_option("display_themecolumns") =="2" || get_option("display_themecolumns") =="" ){ print "checked";} ?> />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</center></td> <td style="width:150px;"><img src="<?php echo $GLOBALS['template_url']; ?>/PPT/img/layout3.gif" /><br /><center> <input name="display_themecolumns" type="radio" value="3" <?php if(get_option("display_themecolumns") =="3"){ print "checked";} ?> />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</center> </td> </tr> </table> </td><td class="forminp"><img src="<?php echo IMAGE_PATH; ?>/help1/c4.png"></td></tr> <?php /***************************************** */ ?> <tr class="mainrow"><td></td> <td class="forminp"> <p><b>Footer Text</b></p> <textarea name="adminArray[footer_text]" type="text" style="width:240px;height:150px;"><?php echo stripslashes(get_option("footer_text")); ?></textarea><br /> <small>This will be added to the bottom of your website.</small> </td><td class="forminp"><img src="<?php echo IMAGE_PATH; ?>/help1/a16.png"></td></tr> <?php /***************************************** */ ?> <tr> <td colspan="3"><p><input class="premiumpress_button" type="submit" value="<?php _e('Save changes','cp')?>" style="color:white;" /></p></td> </tr> </table> </div> <div id="premiumpress_tab6" class="content"> <table class="maintable" style="background:white;"> <?php /***************************************** */ ?> <tr class="mainrow"><td></td><td class="forminp"> <p><b>Website Categories Box</b></p> <select name="adminArray[display_homecats]" style="width: 240px; font-size:14px;"> <option value="yes" <?php if(get_option("display_homecats") =="yes"){ print "selected";} ?>>Show</option> <option value="no" <?php if(get_option("display_homecats") =="no"){ print "selected";} ?>>Hide</option> </select><br /> <small>Show/Hide the home page categories area.</small> </td><td class="forminp"><img src="<?php echo IMAGE_PATH; ?>/help1/a1.png"></td></tr> <?php /***************************************** */ ?> <?php if(get_option("display_homecats") =="yes"){ ?> <tr class="mainrow"><td></td><td class="forminp"> <p><b>Order Categories By </b></p> <select name="adminArray[display_homecats_orderby]" style="width: 240px; font-size:14px;"> <option value="id" <?php if(get_option("display_homecats_orderby") =="id"){ print "selected";} ?>>ID (Ascending Order)</option> <option value="id&order=desc" <?php if(get_option("display_homecats_orderby") =="id&order=desc"){ print "selected";} ?>>ID (Descending Order)</option> <option value="name" <?php if(get_option("display_homecats_orderby") =="name"){ print "selected";} ?>>Name (Ascending Order)</option> <option value="name&order=desc" <?php if(get_option("display_homecats_orderby") =="name&order=desc"){ print "selected";} ?>>Name (Descending Order)</option> <option value="slug" <?php if(get_option("display_homecats_orderby") =="slug"){ print "selected";} ?>>Slug (Ascending Order)</option> <option value="slug&order=desc" <?php if(get_option("display_homecats_orderby") =="slug&order=desc"){ print "selected";} ?>>Slug (Descending Order)</option> <option value="count" <?php if(get_option("display_homecats_orderby") =="count"){ print "selected";} ?>>Count (Ascending Order)</option> <option value="count&order=desc" <?php if(get_option("display_homecats_orderby") =="count&order=desc"){ print "selected";} ?>>Count (Descending Order)</option> <!-- <option value="group" <?php if(get_option("display_homecats_orderby") =="group"){ print "selected";} ?>>Group (Ascending Order)</option> <option value="group&order=desc" <?php if(get_option("display_homecats_orderby") =="group&order=desc"){ print "selected";} ?>>Group (Descending Order)</option>--> </select><br /> <small>select in what order to display the categories.</small> </td><td class="forminp"><img src="<?php echo IMAGE_PATH; ?>/help1/a2.png"></td></tr> <?php /***************************************** */ ?> <tr class="mainrow"> <td></td> <td class="forminp"> <p><b>Display Sub Categories</b></p> <select name="adminArray[display_50_subcategories]" style="width: 240px; font-size:14px;"> <option value="yes" <?php if(get_option("display_50_subcategories") =="yes"){ print "selected";} ?>>Show</option> <option value="no" <?php if(get_option("display_50_subcategories") =="no"){ print "selected";} ?>>Hide</option> </select><br /> <small>Show/Hide the list of sub categories under the main category link.</small> </td><td class="forminp"><img src="<?php echo IMAGE_PATH; ?>/help1/a3.png"></td></tr> <?php } ?> <tr class="mainrow"><td></td><td class="forminp"> <b>Home Page Image</b> <p style="width: 240px;"><input type="checkbox" class="checkbox" name="display_featured_image_enable" value="1" <?php if(get_option("display_featured_image_enable") =="1"){ print "checked";} ?> /> Enable Featured Image</p><br /> <small>Add your own image to the front page</small> <?php if(get_option("display_featured_image_enable") =="1"){ ?> <b>Featured Image URL</b><br /> <input name="adminArray[display_featured_image_url]" type="text" style="width: 240px; font-size:14px;" value="<?php echo get_option("display_featured_image_url"); ?>" /><br /> <small>Enter the full URL for the image you would like to display.</small> <br /><b>Featured Image Link URL</b><br /> <input name="adminArray[display_featured_image_link]" type="text" style="width: 240px; font-size:14px;" value="<?php echo get_option("display_featured_image_link"); ?>" /><br /> <small>Enter the link you would like to have when someone clicks on the image.</small> <?php } ?> </td><td class="forminp"><img src="<?php echo IMAGE_PATH; ?>/help1/a0.png"></td></tr> <tr> <td colspan="3"><p><input class="premiumpress_button" type="submit" value="<?php _e('Save changes','cp')?>" style="color:white;" /></p></td> </tr> </table> </div> <div id="premiumpress_tab2" class="content"> <table class="maintable" style="background:white;"> <tr> <td colspan="4"><p><input class="premiumpress_button" type="submit" value="<?php _e('Save changes','cp')?>" style="color:white;" /></p></td> </tr> </table> </div> <div id="premiumpress_tab3" class="content"> <table class="maintable" style="background:white;"> <?php /***************************************** */ ?> <tr class="mainrow"> <td></td> <td class="forminp"> <p><b>Display Recent Articles</b></p> <select name="adminArray[display_sidebar_articles]" style="width: 240px; font-size:14px;"> <option value="yes" <?php if(get_option("display_sidebar_articles") =="yes"){ print "selected";} ?>>Show</option> <option value="no" <?php if(get_option("display_sidebar_articles") =="no"){ print "selected";} ?>>Hide</option> </select><br /><small>Show/Hide the sidebar articles box.</small> <br /> <input name="adminArray[display_sidebar_articles_count]" value="<?php echo get_option("display_sidebar_articles_count"); ?>" class="txt" style="width:50px; font-size:14px;" type="text"> # Articles </td><td class="forminp"><img src="<?php echo IMAGE_PATH; ?>/help1/a7.png"></td></tr> <?php /***************************************** */ ?> <tr class="mainrow"> <td class="titledesc" valign="top">Featured Stores <br /><br /> <small>Select the stores you wish to be displayed as featured on your sidebar. </small> </td> <td class="forminp" valign="top"> <?php $Maincategories= get_categories('use_desc_for_title=1&hide_empty=0&hierarchical=1'); $Maincatcount = count($Maincategories); $SAVED_DISPLAY = get_option("featured_stores"); $i=0; foreach ($Maincategories as $Maincat) { if($Maincat->parent !=0){ print '<div style="background:#efefef; padding:8px; border:1px solid #ddd; font-size:12px; font-weight:bold; float:left; width:270px; margin-right:10px; "> <input name="featured_stores['.$i.'][ID]" type="checkbox" value="'.$Maincat->cat_ID.'"'; if( isset($SAVED_DISPLAY[$i][ID]) ){ print 'checked="checked"'; } print 'style="margin-right:10px;">' . $Maincat->cat_name.' '; print '<br><small>Order: <input name="featured_stores['.$i.'][ORDER]" type="text" value="'; if(isset($SAVED_DISPLAY[$i][ORDER]) && is_numeric($SAVED_DISPLAY[$i][ORDER]) ){ print $SAVED_DISPLAY[$i][ORDER]; } print '" style="width:30px;font-size:11px;"> </small>'; print ' </div> '; $i++; } } ?> </td> </tr> <tr class="mainrow"><td colspan="3"> <center><a href="widgets.php"><img src="<?php echo $GLOBALS['template_url']; ?>/template_couponpress/images/help1/a23.png"></a></center> </td> <tr> <tr> <td colspan="3"><p><input class="premiumpress_button" type="submit" value="<?php _e('Save changes','cp')?>" style="color:white;" /></p></td> </tr> </table> </div> <div id="premiumpress_tab4" class="content"> <table class="maintable" style="background:white;"> <tr class="mainrow"> <td></td> <td class="forminp"> <p><b>Member information box</b></p> <select name="adminArray[display_sidebar_memberinfo]" style="width: 240px; font-size:14px;"> <option value="yes" <?php if(get_option("display_sidebar_memberinfo") =="yes"){ print "selected";} ?>>Show</option> <option value="no" <?php if(get_option("display_sidebar_memberinfo") =="no"){ print "selected";} ?>>Hide</option> </select><br /><small>Show/Hide the sidebar member information box.</small> <br /> </td><td class="forminp"><img src="<?php echo IMAGE_PATH; ?>/help1/c1.png"></td></tr> <tr class="mainrow"> <td></td> <td class="forminp"> <p><b>Related Coupons</b></p> <select name="adminArray[display_related_coupons]" style="width: 240px; font-size:14px;"> <option value="yes" <?php if(get_option("display_related_coupons") =="yes"){ print "selected";} ?>>Show</option> <option value="no" <?php if(get_option("display_related_coupons") =="no"){ print "selected";} ?>>Hide</option> </select><br /><small>Show/Hide the related coupons on the coupon page.</small> <br /> </td><td class="forminp"><img src="<?php echo IMAGE_PATH; ?>/help1/c4.png"></td></tr> <?php /***************************************** */ ?> <tr class="mainrow"> <td></td><td class="forminp"> <p><b> Google Maps Box</b></p> <select name="adminArray[display_googlemaps]" style="width: 240px; font-size:14px;"> <option value="yes2" <?php if(get_option("display_googlemaps") =="yes2"){ print "selected";} ?>>Show - Interactive Map</option> <option value="no" <?php if(get_option("display_googlemaps") =="no"){ print "selected";} ?>>Hide Google Maps</option> </select><br /> <small><b>Remember</b>Google maps will only display for listings that have a map_location custom field value entered. The interative map requires long/Lat coordinates and isnt recommended for unexperienced users.</small> </td><td class="forminp"><img src="<?php echo IMAGE_PATH; ?>/help1/c2.png"></td></tr> <?php /***************************************** */ ?> <tr> <td colspan="3"><p><input class="premiumpress_button" type="submit" value="Save Changes" style="color:white;" /></p></td> </tr> </table> </div> <div id="premiumpress_tab5" class="content"> <table class="maintable" style="background:white;"> <?php /***************************************** */ ?> <tr class="mainrow"> <td></td><td class="forminp"> <p><b> Enable Home Page Slider </b></p> <select name="adminArray[PPT_slider]" style="width: 240px; font-size:14px;"> <option value="off" <?php if(get_option("PPT_slider") =="off"){ print "selected";} ?>>Disable All Sliders</option> <option value="s1" <?php if(get_option("PPT_slider") =="s1"){ print "selected";} ?>>Featured Content Slider (Full Width)</option> <option value="s2" <?php if(get_option("PPT_slider") =="s2"){ print "selected";} ?>>Half Content Slider</option> </select> <p><b> Slider Style</b></p> <select name="adminArray[PPT_slider_style]" style="width: 240px; font-size:14px;"> <option value="1" <?php if(get_option("PPT_slider_style") =="1"){ print "selected";} ?>>Style 1 (image size: 650x X 265px)</option> <option value="2" <?php if(get_option("PPT_slider_style") =="2"){ print "selected";} ?>>Style 2 (image size: 960x X 360px)</option> <option value="3" <?php if(get_option("PPT_slider_style") =="3"){ print "selected";} ?>>Style 3 (image size: 960x X 360px)</option> <option value="4" <?php if(get_option("PPT_slider_style") =="4"){ print "selected";} ?>>Style 4 (image size: 960x X 360px)</option> <option value="5" <?php if(get_option("PPT_slider_style") =="5"){ print "selected";} ?>>Style 5 (image size: 960x X 360px)</option> </select><br /> <p><b> Slider Content Source</b></p> <select name="adminArray[PPT_slider_items]" style="width: 240px; font-size:14px;"> <option value="manual" <?php if(get_option("PPT_slider_items") =="manual"){ print "selected";} ?>>Manually Configure Slides</option> <option value="featured" <?php if(get_option("PPT_slider_items") =="featured"){ print "selected";} ?>>Use Featured Posts</option> </select><br /> </td><td class="forminp"><img src="<?php echo IMAGE_PATH; ?>/help1/a21.png"></td></tr> <?php /***************************************** */ ?> <tr> <td colspan="3"><p><input class="premiumpress_button" type="submit" value="<?php _e('Save changes','cp')?>" style="color:white;" /></p></td> </tr> </table> </form> <div id="DisplayImages" style="display:none;"></div><input type="hidden" id="searchBox1" name="searchBox1" value="" /> <div id="PPT-sliderbox"></div> <div id="PPT-sliderboxAdd" style="margin-left:20px;display:none"> <form method="post" target="_self" > <input name="admin_slider" type="hidden" value="slider" /> <input type="hidden" id="ppsedit" value="0"> <table width="100%" border="0"> <tr> <td valign="top"><b>Slider Title</b> <br /> <input type="text" name="s1" id="pps1" style="width: 200px; font-size:14px;" class="txt" /> </td> <td><b>Title Description</b> <small>(max. 10 words)</small> <br /> <textarea name="s3" id="pps3" style="width: 200px; font-size:14px; height:70px;" class="txt"></textarea> </td> <td><b>Main Description</b> <small>(max. 250 words)</small> <br /> <textarea name="s4" id="pps4" style="width: 200px; font-size:14px; height:70px;" class="txt"></textarea></td> </tr> <tr> <td><b>Slider Image</b> <br/> <input type="text" name="s2" id="pps2" style="width: 200px; font-size:14px;" class="txt" /> <br/><br/> <input type="hidden" value="" name="imgIdblock" id="imgIdblock" /> <script type="text/javascript"> function ChangeImgBlock(divname){ document.getElementById("imgIdblock").value = divname; } jQuery(document).ready(function() { jQuery('#upload_sliderimage').click(function() { ChangeImgBlock('pps2'); formfield = jQuery('#pps2').attr('name'); tb_show('', <?php if(defined('MULTISITE') && MULTISITE != false){ ?>'admin.php?page=images&amp;tab=nw&amp;TB_iframe=true'<?php }else{ ?>'media-upload.php?type=image&amp;TB_iframe=true'<?php } ?>); return false; }); window.send_to_editor = function(html) { imgurl = jQuery('img',html).attr('src'); jQuery('#'+document.getElementById("imgIdblock").value).val(imgurl); tb_remove(); } }); </script> <input id="upload_sliderimage" type="button" size="36" name="upload_sliderimage" value="Upload Image" /> <input onClick="toggleLayer('DisplayImages'); add_image_next(0,'<?php echo get_option("imagestorage_path"); ?>','<?php echo get_option("imagestorage_link"); ?>','pps2');" type="button" value="View Images" /> </td> <td valign="top"><b>Slider Clickable Link</b> <br /> <input type="text" name="s5" id="pps5" style="width: 200px; font-size:14px;" class="txt" value="http://" /> </td> <td valign="top"><b>Display Order</b><br /><select id="pps6" name="s6" style="width: 100px; font-size:14px;"><?php $i=1; while($i<20){ echo '<option>'.$i.'</option>'; $i++; } ?></select></td> </tr> <tr> <td colspan="3"><p><input class="premiumpress_button" type="submit" value="Create New Slide" style="color:white;" /></p></td> </tr> </table> </form> </div> <div id="addBtn1" style="display:visible"><a href="javascript:void();" onClick="jQuery('#PPT-sliderboxAdd').show();jQuery('#addBtn1').hide();" class="premiumpress_button" style=" float:right; margin-right:10px;" >Add Slider Item</a></div> <h2 style="margin-left:10px;">Website Slider Items</h2> <p style="margin-left:10px;">Here you can setup and create new items for your website slider.</p> <?php $sliderData = get_option("slider_array"); if(is_array($sliderData) && count($sliderData) > 0 ){ ?> <table id="ct"><thead><tr id="ct_sort"> <th width="90" class="first">Title</th> <th width="100">Short Description</th> <th width="40"class="last">Display Order</th> <th width="40"class="last">Actions</th> </tr></thead><tbody> <?php $sortedSlider = $PPTDesign->array_sort($sliderData, 'order', SORT_ASC); $i=-1; foreach($sortedSlider as $hh => $slide){ ?> <tr id="srow<?php echo $i; ?>"> <td width="90" class="first"><?php echo $slide['s1']; ?></td> <td width="80"><?php echo $slide['s3']; ?></td> <td width="50"><?php echo $slide['order']; ?></td> <td width="80" class="last"> <a href='#' Onclick="EditsliderItem('<?php echo $hh; ?>');jQuery('#PPT-sliderbox').show();" style="padding:5px; background:#dcffe1; border:1px solid #57b564; color:green;"><img src="<?php echo $GLOBALS['template_url']; ?>/images/premiumpress/led-ico/find.png" align="middle"> Edit &nbsp;&nbsp;</a> - <a href='#' Onclick="DeleteSliderItem('<?php echo $hh; ?>');jQuery('#PPT-sliderbox').show();jQuery('#srow<?php echo $i; ?>').hide();" style="padding:5px; background:#ffb9ba; border:1px solid #bd2e2f; color:red;"><img src="<?php echo $GLOBALS['template_url']; ?>/images/premiumpress/led-ico/delete.png" align="middle"> Delete&nbsp;</a></td> </tr> <?php $i++; } ?> </tbody> </table> <br /> <form method="post" target="_self" > <input name="admin_slider" type="hidden" value="reset" /> <input class="premiumpress_button" type="submit" value="Reset Slider (Delete All Slides)" style="color:white;" /> </form> <?php } ?> </div>
magictortoise/voucheroffer
wp-content/themes/couponpress/admin/_ad_couponpress_1.php
PHP
gpl-2.0
22,576
<?php /** * @copyright Ilch 2.0 * @package ilch */ namespace Modules\Admin\Models; /** * The layout model class. */ class Layout extends \Ilch\Model { /** * Key of the layout. * * @var string */ protected $key; /** * Name of the layout. * * @var string */ protected $name; /** * Author of the layout. * * @var string */ protected $author; /** * Link of the layout. * * @var string */ protected $link; /** * Description of the layout. * * @var string */ protected $desc; /** * Module of the layout. * * @var string */ protected $modulekey; /** * Gets the key. * * @return string */ public function getKey() { return $this->key; } /** * Sets the key. * * @param string $key */ public function setKey($key) { $this->key = (string)$key; } /** * Gets the name. * * @return string */ public function getName() { return $this->name; } /** * Sets the name. * * @param string $key */ public function setName($name) { $this->name = (string)$name; } /** * Gets the author. * * @return string */ public function getAuthor() { return $this->author; } /** * Sets the author. * * @param string $author */ public function setAuthor($author) { $this->author = (string)$author; } /** * Gets the link. * * @return string */ public function getLink() { return $this->link; } /** * Sets the link. * * @param string $link */ public function setLink($link) { $this->link = (string)$link; } /** * Gets the desc. * * @return string */ public function getDesc() { return $this->desc; } /** * Sets the author. * * @param string $desc */ public function setDesc($desc) { $this->desc = (string)$desc; } /** * Gets the modulekey. * * @return string */ public function getModulekey() { return $this->modulekey; } /** * Sets the modulekey. * * @param string $modulekey */ public function setModulekey($modulekey) { $this->modulekey = (string)$modulekey; } }
jurri/Ilch-2.0
application/modules/admin/models/Layout.php
PHP
gpl-2.0
2,550
# # # (C) Copyright 2001 The Internet (Aust) Pty Ltd # ACN: 082 081 472 ABN: 83 082 081 472 # All Rights Reserved # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. # # Author: Andrew Milton <akm@theinternet.com.au> # $Id: Plugins.py,v 1.5 2004/11/10 14:15:33 akm Exp $ import App, Globals, OFS import string import time from Globals import ImageFile, HTMLFile, HTML, MessageDialog, package_home from OFS.Folder import Folder class PluginRegister: def __init__(self, name, description, pluginClass, pluginStartForm, pluginStartMethod, pluginEditForm=None, pluginEditMethod=None): self.name=name #No Spaces please... self.description=description self.plugin=pluginClass self.manage_addForm=pluginStartForm self.manage_addMethod=pluginStartMethod self.manage_editForm=pluginEditForm self.manage_editMethod=pluginEditMethod class CryptoPluginRegister: def __init__(self, name, crypto, description, pluginMethod): self.name = name #No Spaces please... self.cryptoMethod = crypto self.description = description self.plugin = pluginMethod
denys-duchier/Scolar
ZopeProducts/exUserFolder/Plugins.py
Python
gpl-2.0
1,784
using Mono.Data.Sqlite; namespace Noised.Core.DB.Sqlite { /// <summary> /// Factory for creating Sqlite connections /// </summary> public interface ISqliteConnectionFactory { /// <summary> /// Creates a new, still closed connection /// </summary> SqliteConnection Create(); }; }
bennygr/noised
src/NoisedCore/DB/Sqlite/ISqliteConnectionFactory.cs
C#
gpl-2.0
296
module.exports = function(grunt) { require("matchdep").filterDev("grunt-*").forEach(grunt.loadNpmTasks); grunt.initConfig({ pkg: grunt.file.readJSON("package.json"), copy: { main: { expand: true, cwd: "src/", src: ["**", "!css/**/*.scss", "!css/**/*.less"], dest: "dist/" } }, less: { options: { paths: ["src/css"] }, src: { expand: true, cwd: "src/css", src: "*.less", ext: ".css", dest: "src/css" } }, sass: { dist:{ options:{ style: 'expanded', // values: nested, expanded, compact, compressed noCache: true }, files:[{ expand: true, cwd: "src/css", src: ["*.scss"], dest: "src/css", ext: ".css" }] } }, watch: { options: { nospawn: true, livereload: true }, less: { files: ["src/css/**/*.less"], tasks: ["less"] }, sass: { files: ["src/css/**/*.scss"], tasks: ["sass"] }, copy: { files: ["src/**"], tasks: ["copy:main"] } } }); grunt.registerTask("default", ["watch"]); };
MDIAZ88/mad-css-less-sass
Gruntfile.js
JavaScript
gpl-2.0
1,266
#!/usr/bin/python "feed fetcher" from db import MySQLDatabase from fetcher import FeedFetcher def main(): db = MySQLDatabase() fetcher = FeedFetcher() feeds = db.get_feeds(offset=0, limit=10) read_count = 10 while len(feeds) > 0: for feed in feeds: fid = feed[0] url = feed[1] title = feed[2] print "fetching #{0}: {1}".format(fid, url) entries = fetcher.fetch(url) for entry in entries: entry.feed_id = fid try: print "insert {0}".format(entry.url) except UnicodeEncodeError: print "insert {0}".format(entry.url.encode('utf-8')) db.append_feed_content(entry) feeds = db.get_feeds(offset=read_count, limit=10) read_count += 10 if __name__ == '__main__': main()
hylom/grrreader
backend/feedfetcher.py
Python
gpl-2.0
889
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package sv.edu.uesocc.ingenieria.disenio2_2015.pymesell.presentacion.pymesellv1desktopclient; /** * * @author David */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { System.out.println("Hola a todos!!!"); } }
girondave/Proyecto_Disenio2_2015-PymeSell_v1
PymeSellV1DesktopClient/src/java/sv/edu/uesocc/ingenieria/disenio2_2015/pymesell/presentacion/pymesellv1desktopclient/Main.java
Java
gpl-2.0
496
<?php global $post; $date_format = get_option('date_format'); $author_id=$post->post_author; $options = ST_Page_Builder::get_page_options($post->ID, array()); ?> <div <?php post_class(); ?>> <?php // show thumbnails if(st_get_setting('sc_show_featured_img','y')!='n'){ $thumb = st_theme_post_thumbnail($post->ID,array('force_video_size'=> false), false); ?> <?php if($thumb!=''){ ?> <div class="entry-thumbnail main-img"> <?php echo $thumb; if (isset($options['count_lessons']) && ($caption = $options['caption_featured_image']) != '') echo '<p class="lead">'. $caption .'</p>'; ?> </div> <?php } } ?> <div class="entry-content"> <?php // show the content if(function_exists('st_the_builder_content')){ if(!st_the_builder_content($post->ID)){ the_content(); } }else{ the_content(); } ?> </div> <?php // pagination for single $args = array( 'before' => '<p class="single-pagination">' . __('Pages:','smooththemes'), 'after' => '</p>', 'link_before' => '', 'link_after' => '', 'next_or_number' => 'number', 'nextpagelink' => __('Next page','smooththemes'), 'previouspagelink' => __('Previous page','smooththemes'), 'pagelink' => '%', 'echo' => 1 ); wp_link_pages( $args ); if(st_get_setting('sc_show_post_tag','y')!='n'){ echo get_the_term_list( $post->ID, 'course_category', '<div class="entry-tags"> '.__('Categories: '), ', ', '</div>' ); } if(st_get_setting("sc_show_author_desc",'y') != 'n'){ st_theme_author_template($author_id); }; if(st_get_setting("sc_show_comments",'y') != 'n'){ ?> <div id="comments"> <?php comments_template('', true ); ?> </div><!-- /#comments--> <?php } ?> </div><!-- /. end post_class -->
dangxuanha/wordpress_language
wp-content/themes/Edu/content-course.php
PHP
gpl-2.0
2,082
package org.booleanfloat.traveler.links; import org.booleanfloat.traveler.Location; import org.booleanfloat.traveler.interfaces.Traversable; import java.util.ArrayList; import java.util.concurrent.Callable; public class OneWayLink { public OneWayLink(Location start, Location end) { this(start, end, new ArrayList<Traversable>(), null); } public OneWayLink(Location start, Location end, ArrayList<Traversable> steps) { this(start, end, steps, null); } public OneWayLink(Location start, Location end, ArrayList<Traversable> steps, Callable<Boolean> requirement) { new Link(start, end, steps, requirement); } }
BooleanFloat/Traveler
src/org/booleanfloat/traveler/links/OneWayLink.java
Java
gpl-2.0
662
<?php /** * Template Name: Library * @package mjv-theme */ if (is_home()) : get_header(); else : get_header('insiders'); endif; ?> <div id="primary" class="content-area library"> <main id="main" class="site-main" role="main"> <?php //carrega os cases, clients e content get_template_part('template-parts/content', 'library'); ?> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); get_footer();
DiegoDCosta/mjv-wp
page-library.php
PHP
gpl-2.0
472
public class trace { public void mnonnullelements(int[] a) { int i = 0; //@ assert i == 0 && \nonnullelements(a); return ; } public void mnotmodified(int i) { //@ assert \not_modified(i); i = 4; //@ assert i == 4 && \not_modified(i); return ; } }
shunghsiyu/OpenJML_XOR
OpenJML/testfiles/escTraceBS/trace.java
Java
gpl-2.0
342
# จงเขียนโปรแกรมแสดงเลขคู่ในช่วง 0 ถึง 10 (รวม 10 ด้วย) for i in range(11): if (i % 2 == 0): print(i)
supasate/word_prediction
Chapter4/4-7-even-solution.py
Python
gpl-2.0
193
<?php echo '<?xml version="1.0" encoding="utf-8"?>'; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-ca"> <head> <?php $this->RenderAsset('Head'); ?> <meta property="qc:admins" content="266656217765113126654" /> </head> <body id="<?php echo $BodyIdentifier; ?>" class="<?php echo $this->CssClass; ?>"> <div id="Frame"> <div id="Head"> <div class="Menu"> <h1><a class="Title" href="<?php echo Url('/'); ?>"><span><?php echo Gdn_Theme::Logo(); ?></span></a></h1> <?php $Session = Gdn::Session(); if ($this->Menu) { $this->Menu->AddLink('Dashboard', T('Dashboard'), '/dashboard/settings', array('Garden.Settings.Manage')); // $this->Menu->AddLink('Dashboard', T('Users'), '/user/browse', array('Garden.Users.Add', 'Garden.Users.Edit', 'Garden.Users.Delete')); $this->Menu->AddLink('Activity', T('Activity'), '/activity'); if ($Session->IsValid()) { $Name = $Session->User->Name; $CountNotifications = $Session->User->CountNotifications; if (is_numeric($CountNotifications) && $CountNotifications > 0) $Name .= ' <span class="Alert">'.$CountNotifications.'</span>'; if (urlencode($Session->User->Name) == $Session->User->Name) $ProfileSlug = $Session->User->Name; else $ProfileSlug = $Session->UserID.'/'.urlencode($Session->User->Name); $this->Menu->AddLink('User', $Name, '/profile/'.$ProfileSlug, array('Garden.SignIn.Allow'), array('class' => 'UserNotifications')); $this->Menu->AddLink('SignOut', T('Sign Out'), SignOutUrl(), FALSE, array('class' => 'NonTab SignOut')); } else { $Attribs = array(); if (SignInPopup() && strpos(Gdn::Request()->Url(), 'entry') === FALSE) $Attribs['class'] = 'SignInPopup'; $this->Menu->AddLink('Entry', T('Sign In'), SignInUrl($this->SelfUrl), FALSE, array('class' => 'NonTab'), $Attribs); } echo $this->Menu->ToString(); } ?> <div class="Search"><?php $Form = Gdn::Factory('Form'); $Form->InputPrefix = ''; echo $Form->Open(array('action' => Url('/search'), 'method' => 'get')), $Form->TextBox('Search'), $Form->Button('Go', array('Name' => '')), $Form->Close(); ?></div> </div> </div> <div id="Body"> <div id="Content"><?php $this->RenderAsset('Content'); ?></div> <div id="Panel"><?php $this->RenderAsset('Panel'); ?></div> </div> <div id="Foot"> <?php $this->RenderAsset('Foot'); echo Wrap(Anchor(T('Powered by Vanilla'), C('Garden.VanillaUrl')), 'div'); ?> </div> </div> <?php $this->FireEvent('AfterBody'); ?> </body> </html>
ttym7993/Garden
applications/dashboard/views/default.master.php
PHP
gpl-2.0
2,898
var ModuleManager = (function(){ //Directorio donde se encuentran los modulos const BASE_PATH = "js/modules/"; //modules var modules = { "templateManager":{ "className":"TemplateManager", "fileName":"templateManagerModule.js", "order":1, "loaded":false, "dependences":null, "instance":null }, "preferences":{ "className":"Preferences", "fileName":"preferencesModule.js", "order":1, "loaded":false, "dependences":["templateManager"], "instance":null }, "logger":{ "className":"Logger", "fileName":"logModule.js", "order":2, "loaded":false, "dependences":null, "instance":null }, "webSpeech":{ "className":"WebSpeech", "fileName":"webSpeechModule.js", "order":3, "loaded":false, "dependences":null, "instance":null }, "utils":{ "className":"Utils", "fileName":"utils.js", "order":4, "loaded":false, "dependences":null, "instance":null }, "serviceLocator":{ "className":"ServiceLocator", "fileName":"serviceLocatorModule.js", "order":3, "loaded":false, "dependences":["logger","utils"], "instance":null }, "geoLocation":{ "className":"GeoLocation", "fileName":"geolocationModule.js", "order":4, "loaded":false, "dependences":["serviceLocator"], "instance":null }, "notificator":{ "className":"Notificator", "fileName":"notificationsModule.js", "order":5, "loaded":false, "dependences":["templateManager"], "instance":null }, "applicationsManager":{ "className":"ApplicationsManager", "fileName":"applicationsModule.js", "order":6, "loaded":false, "dependences":["templateManager","serviceLocator","notificator"], "instance":null }, "searchs":{ "className":"Searchs", "fileName":"searchsModule.js", "order":7, "loaded":false, "dependences":["templateManager","serviceLocator","webSpeech","applicationsManager","notificator"], "instance":null }, "contacts":{ "className":"Contacts", "fileName":"contactsModule.js", "order":8, "loaded":false, "dependences":["templateManager","serviceLocator","webSpeech","notificator","geoLocation"], "instance":null }, "gui":{ "className":"GUI", "fileName":"guiModule.js", "order":9, "loaded":false, "dependences":["serviceLocator","searchs","contacts","applicationsManager","notificator"], "instance":null } }; /** * Devuelve las dependencias a partir de los nombres. * * @param {Array} arr: names of the dependencies * @return {Array} dependencies to bind */ var getDependencies = function(arr) { return arr instanceof Array && arr.length ? arr.map(function (value) { var o = modules[value] && modules[value].instance; if (!o) { throw new Error('Dependency ' + value + ' not found'); }else{ return o; } }) : false; } /** * Extrae los nombres de las dependencias a inyectar. * * @param {Function} target: function to process * @return {Array} */ var getArgs = function(target) { if (!target instanceof Function) { throw new TypeError('Target to process should be a Function'); }else{ var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; var COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; var SPACES = /[\s|\t|\n|\r]+/mg; var result = target.toString().match(FN_ARGS); //Comprobamos si existe alguna dependencia a inyectar if(result && result[1]) var args = result[1].replace(COMMENTS,'').replace(SPACES,'').split(','); else var args = false; return args; } } /** * Crea el objeto con las dependencias previamente inyectadas. * * @param {Function} constructor: function to call as constructor * @return {Object} object created from its constructor */ var create = function(constructor) { var args = getArgs(constructor); if (args) { var args = [null].concat(getDependencies(args)); var o = new (Function.prototype.bind.apply(constructor, args))(); }else{ var o = new (Function.prototype.bind.apply(constructor))(); } return o; } var loadScript = function(src, callback) { var s,r,t; r = false ; s = document. createElement ('script' ); s.type = 'text/javascript' ; s.src = src; s.onload = s.onreadystatechange = function () { if ( !r && (!this .readyState || this .readyState == 'complete' )){ r = true ; typeof(callback) == "function" && callback(); } }; t = document.getElementsByTagName ('script')[0]; t.parentNode.insertBefore (s, t); } var downloadModules = function(callback){ console.log(modules); for(var module in modules) (function(currentModule){ loadScript(BASE_PATH+currentModule.fileName,function(){ currentModule.loaded = true; Object.keys(modules).map(function(key){ return modules[key].loaded; }).indexOf(false) == -1 && typeof(callback) == "function" && callback(); }); })(modules[module]); } var loadModules = function(callback){ downloadModules(function(){ for(var module in modules){ console.log("Cargando Módulo : " + modules[module].className); modules[module].instance = create(window[modules[module].className]); delete window[modules[module].className]; } typeof(callback) == "function" && callback(); }); } //API pública return{ loadModules:loadModules } })();
sergio11/teVeo
js/managerModule.js
JavaScript
gpl-2.0
6,834
<?php /** * H4PH - HTML4 PHP Helper * @link https://github.com/Coft/H4PH */ class Td { /** * contains all setted attributes * @var array */ private $attrs = array(); /** * keeps content * @var string */ private $content = null; /** * holds markup name * @var string */ private static $markupName = 'td'; /** * tells is this markup can handle content * @var bool */ private static $isContenerable = true; /** * __construct() - can add content to tag * @param null|string $content * @return Td */ public function __construct($content = null) { $argumentsNumber = func_num_args(); for ($i = 0; $i < $argumentsNumber; $i++) { $this->addContent(func_get_arg($i)); } } /** * renders tag and it content to string * @param null|string $content * @return Td */ public static function getInstance($content = null) { $markupTag = new Td; $argumentsNumber = func_num_args(); for ($i = 0; $i < $argumentsNumber; $i++) { $markupTag->addContent(func_get_arg($i)); } return $markupTag; } /** * adds content to tag * @param null|string $content * @return Td */ public function addContent($content = null) { $this->content .= (string) $content; return $this; } /** * renders tag and it content to string * @return string */ public function __toString() { $parsedAttrs = ''; foreach ($this->attrs as $attrName => $attrValue) { $parsedAttrs .= ' '.$attrName.'=\''.$attrValue.'\''; } return '<'.self::$markupName.$parsedAttrs.'>'.$this->content.'</'.self::$markupName.'>'; } /** * sets abbr attribute * @param null|string $value * @return Td */ public function abbr($value = null) { $this->attrs['abbr'] = $value; return $this; } /** * sets align attribute * @param null|string $value * @return Td */ public function align($value = null) { $this->attrs['align'] = $value; return $this; } /** * sets axis attribute * @param null|string $value * @return Td */ public function axis($value = null) { $this->attrs['axis'] = $value; return $this; } /** * sets char attribute * @param null|string $value * @return Td */ public function char($value = null) { $this->attrs['char'] = $value; return $this; } /** * sets charoff attribute * @param null|string $value * @return Td */ public function charoff($value = null) { $this->attrs['charoff'] = $value; return $this; } /** * sets colspan attribute * @param null|string $value * @return Td */ public function colspan($value = null) { $this->attrs['colspan'] = $value; return $this; } /** * sets headers attribute * @param null|string $value * @return Td */ public function headers($value = null) { $this->attrs['headers'] = $value; return $this; } /** * sets rowspan attribute * @param null|string $value * @return Td */ public function rowspan($value = null) { $this->attrs['rowspan'] = $value; return $this; } /** * sets scope attribute * @param null|string $value * @return Td */ public function scope($value = null) { $this->attrs['scope'] = $value; return $this; } /** * sets valign attribute * @param null|string $value * @return Td */ public function valign($value = null) { $this->attrs['valign'] = $value; return $this; } /** * sets classes attribute * @param null|string $value * @return Td */ public function classes($value = null) { $this->attrs['class'] = $value; return $this; } /** * sets dir attribute * @param null|string $value * @return Td */ public function dir($value = null) { $this->attrs['dir'] = $value; return $this; } /** * sets id attribute * @param null|string $value * @return Td */ public function id($value = null) { $this->attrs['id'] = $value; return $this; } /** * sets lang attribute * @param null|string $value * @return Td */ public function lang($value = null) { $this->attrs['lang'] = $value; return $this; } /** * sets style attribute * @param null|string $value * @return Td */ public function style($value = null) { $this->attrs['style'] = $value; return $this; } /** * sets title attribute * @param null|string $value * @return Td */ public function title($value = null) { $this->attrs['title'] = $value; return $this; } /** * sets xmlLang attribute * @param null|string $value * @return Td */ public function xmlLang($value = null) { $this->attrs['xml:lang'] = $value; return $this; } /** * sets onclick attribute * @param null|string $value * @return Td */ public function onclick($value = null) { $this->attrs['onclick'] = $value; return $this; } /** * sets ondblclick attribute * @param null|string $value * @return Td */ public function ondblclick($value = null) { $this->attrs['ondblclick'] = $value; return $this; } /** * sets onmousedown attribute * @param null|string $value * @return Td */ public function onmousedown($value = null) { $this->attrs['onmousedown'] = $value; return $this; } /** * sets onmousemove attribute * @param null|string $value * @return Td */ public function onmousemove($value = null) { $this->attrs['onmousemove'] = $value; return $this; } /** * sets onmouseout attribute * @param null|string $value * @return Td */ public function onmouseout($value = null) { $this->attrs['onmouseout'] = $value; return $this; } /** * sets onmouseover attribute * @param null|string $value * @return Td */ public function onmouseover($value = null) { $this->attrs['onmouseover'] = $value; return $this; } /** * sets onmouseup attribute * @param null|string $value * @return Td */ public function onmouseup($value = null) { $this->attrs['onmouseup'] = $value; return $this; } /** * sets onkeydown attribute * @param null|string $value * @return Td */ public function onkeydown($value = null) { $this->attrs['onkeydown'] = $value; return $this; } /** * sets onkeypress attribute * @param null|string $value * @return Td */ public function onkeypress($value = null) { $this->attrs['onkeypress'] = $value; return $this; } /** * sets onkeyup attribute * @param null|string $value * @return Td */ public function onkeyup($value = null) { $this->attrs['onkeyup'] = $value; return $this; } } ?>
Coft/H4PH
classes/Td.php
PHP
gpl-2.0
7,819
var SPHERE = { getSphereVertex: function (radius, res) { // Se obtienen los vértices, normales y coordenadas de textura var vertexData = [], alpha, beta, x, y, z, u, v; for (var i = 0; i <= res; i++) { // Se recorren las latitudes alpha = i * Math.PI / res; // Ángulo latitud for (var j = 0; j <= res; j++) { // Se recorren las longitudes beta = j * 2 * Math.PI / res; // Ángulo longitud // Cálculo de x, y, z para vértices y normales x = Math.cos(beta) * Math.sin(alpha); y = Math.cos(alpha); z = Math.sin(beta) * Math.sin(alpha); // Cálculo de u, v para las coordenadas de textura u = 1 - (j / res); v = 1 - (i / res); // Vértices vertexData.push(radius * x); vertexData.push(radius * y); vertexData.push(radius * z); // Normales vertexData.push(x); vertexData.push(y); vertexData.push(z); // Coordenadas de textura vertexData.push(u); vertexData.push(v); } } return vertexData; }, getShereFaces: function (res) { // Se obtienen los índices para crear las caras var indexData = [], first, second; for (var i = 0; i < res; i++) { // Se recorren las latitudes for (var j = 0; j < res; j++) { // Se recorren las longitudes // Cálculo de las esquinas superior e inferior izquierda first = (i * (res + 1)) + j; second = first + res + 1; // Cara par indexData.push(first); // Esquina superior izquierda indexData.push(second); // Esquina inferior izquierda indexData.push(first + 1); // Esquina superior derecha // Cara impar indexData.push(second); // Esquina inferior izquierda indexData.push(second + 1); // Esquina inferior derecha indexData.push(first + 1); // Esquina superior derecha } } return indexData; } };
fblupi/grado_informatica-SG
P2/P2_1/SistemaSolar/js/sphere.js
JavaScript
gpl-2.0
2,248
/** * */ package org.sylvani.io.voice.http; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.emf.common.util.EList; import org.eclipse.smarthome.model.sitemap.Sitemap; import org.eclipse.smarthome.model.sitemap.SitemapProvider; import org.eclipse.smarthome.model.sitemap.Widget; import org.eclipse.smarthome.ui.items.ItemUIRegistry; /** * Varianten * - Simple and Stupid HAL9000 * - Volltext * - Tagged Analyse * * @author hkuhn * */ public class RecognitionRelayServlet extends HttpServlet { private static final long serialVersionUID = 1L; private ItemUIRegistry itemUIRegistry; private List<SitemapProvider> sitemaps; public RecognitionRelayServlet(ItemUIRegistry itemUIRegistry, List<SitemapProvider> sitemaps) { this.itemUIRegistry = itemUIRegistry; this.sitemaps = sitemaps; } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { for (SitemapProvider sitemapProvider : sitemaps) { for (String sitemapName : sitemapProvider.getSitemapNames()) { System.out.println("sitemap " + sitemapName); Sitemap sitemap = sitemapProvider.getSitemap(sitemapName); EList<Widget> list = sitemap.getChildren(); for (Widget widget : list) { System.out.println("#Widget " + widget.getLabel() + " " + widget.getItem()); } } } } }
hkuhn42/sylvani
org.sylvani.io/src/main/java/org/sylvani/io/voice/http/RecognitionRelayServlet.java
Java
gpl-2.0
1,853
class Class3_Sub28 extends Class3 { static Class94[] aClass94Array2566 = new Class94[200]; static int anInt2567 = -1; private static Class94 aClass94_2568 = Class3_Sub4.buildString("Started 3d Library"); long aLong2569; Class3_Sub28 aClass3_Sub28_2570; static int anInt2571; static int anInt2572; static Class153 aClass153_2573; static int[] anIntArray2574 = new int[14]; static int anInt2575; static Class94 aClass94_2576 = aClass94_2568; static int anInt2577 = 0; Class3_Sub28 aClass3_Sub28_2578; static final void method518(Class140_Sub4_Sub1 var0, int var1) { try { Class3_Sub9 var2 = (Class3_Sub9)Class3_Sub28_Sub7_Sub1.aClass130_4046.method1780(var0.aClass94_3967.method1578(-121), 0); if(var1 >= -85) { method523(40, -17, -52, -32, 9, -51, -85, -84, -19); } if(var2 != null) { var2.method134(1); } else { Class70.method1286(var0.anIntArray2755[0], false, (Class111)null, 0, (Class140_Sub4_Sub2)null, var0.anIntArray2767[0], Class26.anInt501, var0); } } catch (RuntimeException var3) { throw Class44.method1067(var3, "rg.UA(" + (var0 != null?"{...}":"null") + ',' + var1 + ')'); } } static final int method519(int var0, boolean var1, int var2, int var3) { try { var0 &= 3; if(!var1) { method520((byte)-89); } return 0 != var0?(~var0 != -2?(~var0 == -3?-var3 + 7:-var2 + 7):var2):var3; } catch (RuntimeException var5) { throw Class44.method1067(var5, "rg.RA(" + var0 + ',' + var1 + ',' + var2 + ',' + var3 + ')'); } } static final Class3_Sub28_Sub3 method520(byte var0) { try { int var1 = -122 % ((var0 - -48) / 33); return Class3_Sub30.aClass3_Sub28_Sub3_2600; } catch (RuntimeException var2) { throw Class44.method1067(var2, "rg.OA(" + var0 + ')'); } } public static void method521(int var0) { try { aClass153_2573 = null; if(var0 == -3) { aClass94Array2566 = null; aClass94_2568 = null; anIntArray2574 = null; aClass94_2576 = null; } } catch (RuntimeException var2) { throw Class44.method1067(var2, "rg.QA(" + var0 + ')'); } } static final Class90 method522(int var0, int var1) { try { Class90 var2 = (Class90)Class3_Sub28_Sub7_Sub1.aClass93_4043.method1526((long)var0, (byte)121); if(null == var2) { byte[] var3 = Class29.aClass153_557.method2133(Class38_Sub1.method1031(var0, 2), (byte)-122, Canvas_Sub1.method54(var0, false)); var2 = new Class90(); if(var1 != 27112) { anInt2572 = -67; } var2.anInt1284 = var0; if(null != var3) { var2.method1478(new Class3_Sub30(var3), 74); } var2.method1481(98); Class3_Sub28_Sub7_Sub1.aClass93_4043.method1515((byte)-95, var2, (long)var0); return var2; } else { return var2; } } catch (RuntimeException var4) { throw Class44.method1067(var4, "rg.PA(" + var0 + ',' + var1 + ')'); } } static final void method523(int var0, int var1, int var2, int var3, int var4, int var5, int var6, int var7, int var8) { try { int var9 = var3 - var8; int var11 = (-var5 + var0 << 16) / var9; int var10 = -var4 + var6; int var12 = (var7 + -var1 << 16) / var10; Class83.method1410(var1, 0, var6, var4, var3, var5, var8, var12, var11, var2, -12541); } catch (RuntimeException var13) { throw Class44.method1067(var13, "rg.SA(" + var0 + ',' + var1 + ',' + var2 + ',' + var3 + ',' + var4 + ',' + var5 + ',' + var6 + ',' + var7 + ',' + var8 + ')'); } } final void method524(byte var1) { try { if(this.aClass3_Sub28_2570 != null) { this.aClass3_Sub28_2570.aClass3_Sub28_2578 = this.aClass3_Sub28_2578; this.aClass3_Sub28_2578.aClass3_Sub28_2570 = this.aClass3_Sub28_2570; this.aClass3_Sub28_2578 = null; this.aClass3_Sub28_2570 = null; if(var1 != -107) { this.aClass3_Sub28_2578 = (Class3_Sub28)null; } } } catch (RuntimeException var3) { throw Class44.method1067(var3, "rg.TA(" + var1 + ')'); } } }
Lmctruck30/RiotScape-Client
src/Class3_Sub28.java
Java
gpl-2.0
4,615
/* Kvalobs - Free Quality Control Software for Meteorological Observations $Id: Data.h,v 1.2.6.2 2007/09/27 09:02:22 paule Exp $ Copyright (C) 2007 met.no Contact information: Norwegian Meteorological Institute Box 43 Blindern 0313 OSLO NORWAY email: kvalobs-dev@met.no This file is part of KVALOBS KVALOBS 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. KVALOBS 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 KVALOBS; if not, write to the Free Software Foundation Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <boost/assign.hpp> #include "EncodeBufr302053.h" EncodeBufr302053:: EncodeBufr302053() { } std::string EncodeBufr302053:: logIdentifier() const { return "302053"; } std::list<int> EncodeBufr302053:: encodeIds()const { std::list<int> ids; boost::assign::push_back( ids )(302053); return ids; } void EncodeBufr302053:: encode( ) { bufr->addValue( 7032, stationInfo->heightVisability(), "h_V, height of visibility sensor above marine deck.", false ); bufr->addValue( 7033, FLT_MAX, "h_V, height of visibility sensor above water surface.", false ); bufr->addValue( 20001, data->VV, "VV, horisental visibility" ); }
metno/kvbufrd
src/bufr/EncodeBufr302053.cc
C++
gpl-2.0
1,668
using System; namespace WIC { public enum DXGI_FORMAT { DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_R32G32B32A32_TYPELESS, DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32G32B32A32_UINT, DXGI_FORMAT_R32G32B32A32_SINT, DXGI_FORMAT_R32G32B32_TYPELESS, DXGI_FORMAT_R32G32B32_FLOAT, DXGI_FORMAT_R32G32B32_UINT, DXGI_FORMAT_R32G32B32_SINT, DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_UNORM, DXGI_FORMAT_R16G16B16A16_UINT, DXGI_FORMAT_R16G16B16A16_SNORM, DXGI_FORMAT_R16G16B16A16_SINT, DXGI_FORMAT_R32G32_TYPELESS, DXGI_FORMAT_R32G32_FLOAT, DXGI_FORMAT_R32G32_UINT, DXGI_FORMAT_R32G32_SINT, DXGI_FORMAT_R32G8X24_TYPELESS, DXGI_FORMAT_D32_FLOAT_S8X24_UINT, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS, DXGI_FORMAT_X32_TYPELESS_G8X24_UINT, DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_R10G10B10A2_UINT, DXGI_FORMAT_R11G11B10_FLOAT, DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, DXGI_FORMAT_R8G8B8A8_UINT, DXGI_FORMAT_R8G8B8A8_SNORM, DXGI_FORMAT_R8G8B8A8_SINT, DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_FLOAT, DXGI_FORMAT_R16G16_UNORM, DXGI_FORMAT_R16G16_UINT, DXGI_FORMAT_R16G16_SNORM, DXGI_FORMAT_R16G16_SINT, DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_D32_FLOAT, DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R32_SINT, DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_D24_UNORM_S8_UINT, DXGI_FORMAT_R24_UNORM_X8_TYPELESS, DXGI_FORMAT_X24_TYPELESS_G8_UINT, DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_UNORM, DXGI_FORMAT_R8G8_UINT, DXGI_FORMAT_R8G8_SNORM, DXGI_FORMAT_R8G8_SINT, DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_FLOAT, DXGI_FORMAT_D16_UNORM, DXGI_FORMAT_R16_UNORM, DXGI_FORMAT_R16_UINT, DXGI_FORMAT_R16_SNORM, DXGI_FORMAT_R16_SINT, DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R8_UINT, DXGI_FORMAT_R8_SNORM, DXGI_FORMAT_R8_SINT, DXGI_FORMAT_A8_UNORM, DXGI_FORMAT_R1_UNORM, DXGI_FORMAT_R9G9B9E5_SHAREDEXP, DXGI_FORMAT_R8G8_B8G8_UNORM, DXGI_FORMAT_G8R8_G8B8_UNORM, DXGI_FORMAT_BC1_TYPELESS, DXGI_FORMAT_BC1_UNORM, DXGI_FORMAT_BC1_UNORM_SRGB, DXGI_FORMAT_BC2_TYPELESS, DXGI_FORMAT_BC2_UNORM, DXGI_FORMAT_BC2_UNORM_SRGB, DXGI_FORMAT_BC3_TYPELESS, DXGI_FORMAT_BC3_UNORM, DXGI_FORMAT_BC3_UNORM_SRGB, DXGI_FORMAT_BC4_TYPELESS, DXGI_FORMAT_BC4_UNORM, DXGI_FORMAT_BC4_SNORM, DXGI_FORMAT_BC5_TYPELESS, DXGI_FORMAT_BC5_UNORM, DXGI_FORMAT_BC5_SNORM, DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G5R5A1_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_B8G8R8X8_UNORM, DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM, DXGI_FORMAT_B8G8R8A8_TYPELESS, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, DXGI_FORMAT_B8G8R8X8_TYPELESS, DXGI_FORMAT_B8G8R8X8_UNORM_SRGB, DXGI_FORMAT_BC6H_TYPELESS, DXGI_FORMAT_BC6H_UF16, DXGI_FORMAT_BC6H_SF16, DXGI_FORMAT_BC7_TYPELESS, DXGI_FORMAT_BC7_UNORM, DXGI_FORMAT_BC7_UNORM_SRGB, DXGI_FORMAT_AYUV, DXGI_FORMAT_Y410, DXGI_FORMAT_Y416, DXGI_FORMAT_NV12, DXGI_FORMAT_P010, DXGI_FORMAT_P016, DXGI_FORMAT_420_OPAQUE, DXGI_FORMAT_YUY2, DXGI_FORMAT_Y210, DXGI_FORMAT_Y216, DXGI_FORMAT_NV11, DXGI_FORMAT_AI44, DXGI_FORMAT_IA44, DXGI_FORMAT_P8, DXGI_FORMAT_A8P8, DXGI_FORMAT_B4G4R4A4_UNORM, DXGI_FORMAT_FORCE_UINT = -1 } }
Rambalac/DummyWIC
Wic/WIC/DXGI_FORMAT.cs
C#
gpl-2.0
3,363
/*************************************************************************** getfmtast.cpp - returns the AST for formatted IO ------------------- begin : July 22 2002 copyright : (C) 2002 by Marc Schellens email : m_schellens@users.sf.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. * * * ***************************************************************************/ //#define FMT_DEBUG #undef FMT_DEBUG #include "includefirst.hpp" #include "basegdl.hpp" #include "fmtnode.hpp" #include "print_tree.hpp" #include "FMTLexer.hpp" #include "FMTParser.hpp" #include <antlr/ASTFactory.hpp> using namespace std; antlr::ASTFactory FMTNodeFactory("FMTNode",FMTNode::factory); RefFMTNode GetFMTAST( DString fmtString) { istringstream istr(fmtString); //+"\n"); RefFMTNode fmtAST; try { antlr::TokenStreamSelector selector; FMTLexer lexer( istr); lexer.SetSelector( selector); CFMTLexer cLexer( lexer.getInputState()); cLexer.SetSelector( selector); lexer.SetCLexer( cLexer); selector.select( &lexer); FMTParser parser( selector); // because we use the standard (ANTLR generated) constructor here // we cannot do it in the constructor parser.initializeASTFactory( FMTNodeFactory); parser.setASTFactory( &FMTNodeFactory ); parser.format( 1); fmtAST=parser.getAST(); #ifdef FMT_DEBUG antlr::print_tree pt; pt.pr_tree(static_cast<antlr::RefAST>(fmtAST)); cout << endl; #endif } catch( GDLException& ex) { throw GDLException("Format: "+ex.getMessage()); } catch( antlr::ANTLRException& ex) { throw GDLException("Format parser: "+ex.getMessage()); } catch( exception& ex) { throw GDLException("Format exception: "+string(ex.what())); } catch(...) { throw GDLException("Format: general exception."); } return fmtAST; }
cenit/GDL
src/getfmtast.cpp
C++
gpl-2.0
2,564
<?php /** * Created by PhpStorm. * User: Sheila * Date: 12/12/2014 * Time: 6:51 AM */
experimentX/worklor
wp-content/plugins/booklor/testlor.php
PHP
gpl-2.0
91
#!/usr/bin/env python import math fin = open('figs/single-rod-in-water.dat', 'r') fout = open('figs/single-rods-calculated-density.dat', 'w') kB = 3.16681539628059e-6 # This is Boltzmann's constant in Hartree/Kelvin first = 1 nm = 18.8972613 for line in fin: current = str(line) pieces = current.split('\t') if first: r2 = float(pieces[0])/2*nm E2 = float(pieces[1]) first = 0 else: if ((float(pieces[0])/2*nm - r2) > 0.25): r1 = r2 r2 = float(pieces[0])/2*nm E1 = E2 E2 = float(pieces[1]) # actually it's energy per unit length! length = 1 # arbitrary r = (r1 + r2)/2 dEdR = (E2-E1)/(r2-r1)*length area = 2*math.pi*r*length force = dEdR pressure = force/area kT = kB*298 # about this ncontact = pressure/kT fout.write(str(r)+'\t'+str(ncontact)+'\n') fin.close() fout.close()
droundy/deft
papers/hughes-saft/figs/density_calc.py
Python
gpl-2.0
986
dojo.require("dijit.Dialog"); dojo.require("dijit.form.FilteringSelect"); dojo.require('dijit.form.Button'); dojo.require('dijit.TooltipDialog'); dojo.require('dijit.form.DropDownButton'); dojo.require('dijit.form.CheckBox'); dojo.require('dojox.grid.DataGrid'); dojo.require('dojo.data.ItemFileWriteStore'); dojo.require('openils.widget.OrgUnitFilteringSelect'); dojo.require('openils.acq.CurrencyType'); dojo.require('openils.Event'); dojo.require('openils.Util'); dojo.require('openils.User'); dojo.require('openils.CGI'); dojo.require('openils.PermaCrud'); dojo.require('openils.widget.AutoGrid'); dojo.require('openils.widget.ProgressDialog'); dojo.require('fieldmapper.OrgUtils'); dojo.requireLocalization('openils.acq', 'acq'); var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq'); var contextOrg; var rolloverResponses; var rolloverMode = false; var fundFleshFields = [ 'spent_balance', 'combined_balance', 'spent_total', 'encumbrance_total', 'debit_total', 'allocation_total' ]; var adminPermOrgs = []; var cachedFunds = []; function initPage() { contextOrg = openils.User.user.ws_ou(); /* Reveal controls for rollover without money if org units say ok. * Actual ability to do the operation is controlled in the database, of * course. */ var ouSettings = fieldmapper.aou.fetchOrgSettingBatch( openils.User.user.ws_ou(), ["acq.fund.allow_rollover_without_money"] ); if ( ouSettings["acq.fund.allow_rollover_without_money"] && ouSettings["acq.fund.allow_rollover_without_money"].value ) { dojo.query(".encumb_only").forEach( function(o) { openils.Util.show(o, "table-row"); } ); } var connect = function() { dojo.connect(contextOrgSelector, 'onChange', function() { contextOrg = this.attr('value'); dojo.byId('oils-acq-rollover-ctxt-org').innerHTML = fieldmapper.aou.findOrgUnit(contextOrg).shortname(); rolloverMode = false; gridDataLoader(); } ); }; dojo.connect(refreshButton, 'onClick', function() { rolloverMode = false; gridDataLoader(); }); new openils.User().buildPermOrgSelector( ['ADMIN_ACQ_FUND', 'VIEW_FUND'], contextOrgSelector, contextOrg, connect); dojo.byId('oils-acq-rollover-ctxt-org').innerHTML = fieldmapper.aou.findOrgUnit(contextOrg).shortname(); loadYearSelector(); lfGrid.onItemReceived = function(item) {cachedFunds.push(item)}; new openils.User().getPermOrgList( 'ADMIN_ACQ_FUND', function(list) { adminPermOrgs = list; loadFundGrid( new openils.CGI().param('year') || new Date().getFullYear().toString()); }, true, true ); } function gridDataLoader() { lfGrid.resetStore(); if(rolloverMode) { var offset = lfGrid.displayOffset; for(var i = offset; i < (offset + lfGrid.displayLimit - 1); i++) { var fund = rolloverResponses[i]; if(!fund) break; lfGrid.store.newItem(fieldmapper.acqf.toStoreItem(fund)); } } else { loadFundGrid(); } } function getBalanceInfo(rowIdx, item) { if (!item) return ''; var fundId = this.grid.store.getValue(item, 'id'); var fund = cachedFunds.filter(function(f) { return f.id() == fundId })[0]; var cb = fund.combined_balance(); return cb ? cb.amount() : '0'; } function loadFundGrid(year) { openils.Util.hide('acq-fund-list-rollover-summary'); year = year || fundFilterYearSelect.attr('value'); cachedFunds = []; lfGrid.loadAll( { flesh : 1, flesh_fields : {acqf : fundFleshFields}, // by default, sort funds I can edit to the front order_by : [ { 'class' : 'acqf', field : 'org', compare : {'in' : adminPermOrgs}, direction : 'desc' }, { 'class' : 'acqf', field : 'name' } ] }, { year : year, org : fieldmapper.aou.descendantNodeList(contextOrg, true) } ); } function loadYearSelector() { fieldmapper.standardRequest( ['open-ils.acq', 'open-ils.acq.fund.org.years.retrieve'], { async : true, params : [openils.User.authtoken, {}, {limit_perm : 'VIEW_FUND'}], oncomplete : function(r) { var yearList = openils.Util.readResponse(r); if(!yearList) return; yearList = yearList.map(function(year){return {year:year+''};}); // dojo wants strings var yearStore = {identifier:'year', name:'year', items:yearList}; yearStore.items = yearStore.items.sort().reverse(); fundFilterYearSelect.store = new dojo.data.ItemFileWriteStore({data:yearStore}); // default to this year fundFilterYearSelect.setValue(new Date().getFullYear().toString()); dojo.connect( fundFilterYearSelect, 'onChange', function() { rolloverMode = false; gridDataLoader(); } ); } } ); } function performRollover(args) { rolloverMode = true; progressDialog.show(true, "Processing..."); rolloverResponses = []; var method = 'open-ils.acq.fiscal_rollover'; if(args.rollover[0] == 'on') { method += '.combined'; } else { method += '.propagate'; } var dryRun = args.dry_run[0] == 'on'; if(dryRun) method += '.dry_run'; var encumbOnly = args.encumb_only[0] == 'on'; var count = 0; var amount_rolled = 0; var year = fundFilterYearSelect.attr('value'); // TODO alternate selector? fieldmapper.standardRequest( ['open-ils.acq', method], { async : true, params : [ openils.User.authtoken, year, contextOrg, (args.child_orgs[0] == 'on'), { encumb_only : encumbOnly } ], onresponse : function(r) { var resp = openils.Util.readResponse(r); rolloverResponses.push(resp.fund); count += 1; amount_rolled += Number(resp.rollover_amount); }, oncomplete : function() { var nextYear = Number(year) + 1; rolloverResponses = rolloverResponses.sort( function(a, b) { if(a.code() > b.code()) return 1; return -1; } ) // add the new, rolled funds to the cache. Note that in dry-run // mode, these are ephemeral and no longer exist on the server. cachedFunds = cachedFunds.concat(rolloverResponses); dojo.byId('acq-fund-list-rollover-summary-header').innerHTML = dojo.string.substitute( localeStrings.FUND_LIST_ROLLOVER_SUMMARY, [nextYear] ); dojo.byId('acq-fund-list-rollover-summary-funds').innerHTML = dojo.string.substitute( localeStrings.FUND_LIST_ROLLOVER_SUMMARY_FUNDS, [nextYear, count] ); dojo.byId('acq-fund-list-rollover-summary-rollover-amount').innerHTML = dojo.string.substitute( localeStrings.FUND_LIST_ROLLOVER_SUMMARY_ROLLOVER_AMOUNT, [nextYear, amount_rolled] ); if(!dryRun) { openils.Util.hide('acq-fund-list-rollover-summary-dry-run'); // add the new year to the year selector if it's not already there fundFilterYearSelect.store.fetch({ query : {year : nextYear}, onComplete: function(list) { if(list && list.length > 0) return; fundFilterYearSelect.store.newItem({year : nextYear}); } }); } openils.Util.show('acq-fund-list-rollover-summary'); progressDialog.hide(); gridDataLoader(); } } ); } openils.Util.addOnLoad(initPage);
ubcic/evergreen
Open-ILS/web/js/ui/default/acq/financial/list_funds.js
JavaScript
gpl-2.0
8,907
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("Sims")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Sims")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("69611fa1-6403-4862-abd4-bd4e91c43d06")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
efaruk/playground
sims/Sims/Properties/AssemblyInfo.cs
C#
gpl-2.0
1,420
package lionse.client.stage; import java.util.ArrayList; import java.util.List; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle; import lionse.client.Display; import lionse.client.asset.Asset; import lionse.client.net.Header; import lionse.client.net.Server; public class Character implements Renderable { // character format constant values public static final float RESOLUTION = 1.5f; public static final float C_HEAD = 0 * RESOLUTION; public static final float C_FACE = 10 * RESOLUTION; public static final float C_BODY = 24 * RESOLUTION; public static final float C_HAND = 29 * RESOLUTION; public static final float C_LEG = 30 * RESOLUTION; public static LabelStyle NAME_TAG_STYLE; public static float[] SINE_WAVE = { 0, 0.27f, 0.52f, 0.74f, 0.89f, 0.98f, 0.99f, 0.93f, 0.79f, 0.59f, 0.35f, 0.08f, -0.19f, -0.45f, -0.67f, -0.85f, -0.96f, -0.99f, -0.95f, -0.84f, -0.66f, -0.43f, -0.17f }; static { NAME_TAG_STYLE = new LabelStyle(); NAME_TAG_STYLE.font = Asset.Font.get(Asset.NanumGothic); NAME_TAG_STYLE.fontColor = Color.BLACK; } public boolean me = false; // character property public String name; public int head; public int face; public int body; public int clothes; public int weapon; public float speed = 200f; // positioning property public Point position; public Point target; public Point bottom; // character graphics public Label nameTag; // ��dz�� ��� public TalkBalloon talkBalloon; // ��ũ ���߱� ��� public List<Path> path; public int pathIndex = 0; public int direction = 0; public boolean moving = false; private int step = 0; // graphics variables private float stepTime = 0; private int next = -1; // graphics cache private TextureRegion[] texture_head; private TextureRegion[] texture_face; private TextureRegion[] texture_body; private TextureRegion[] texture_hand; private TextureRegion[] texture_leg_stop; private TextureRegion[] texture_leg_step1; private TextureRegion[] texture_leg_step2; private TextureRegion[] texture_leg_step3; private TextureRegion[] texture_leg_step4; // animated character format (sine-wave) private float p_head; private float p_face; private float p_body; private float p_hand; // name, head, face, body, clothes, weapon public Character(String name, int head, int face, int body, int weapon) { this.name = name; this.head = head; this.face = face; this.body = body; this.weapon = weapon; this.position = new Point(); this.bottom = new Point(); this.talkBalloon = new TalkBalloon(this); this.nameTag = new Label(name, NAME_TAG_STYLE); this.path = new ArrayList<Path>(); cache(); } // cache values. if this method is not called when texture value is // changed.noting happens to the graphic public void cache() { texture_head = Asset.Character.get("HEAD"); texture_face = Asset.Character.get("FACE"); texture_body = Asset.Character.get("BODY"); texture_hand = Asset.Character.get("HAND"); texture_leg_stop = Asset.Character.get("LEG_STAND"); texture_leg_step1 = Asset.Character.get("LEG_STEP1"); texture_leg_step2 = Asset.Character.get("LEG_STEP2"); texture_leg_step3 = Asset.Character.get("LEG_STEP3"); texture_leg_step4 = Asset.Character.get("LEG_STEP4"); } public void talk(String message) { talkBalloon.show(message); } @Override public void draw(SpriteBatch spriteBatch, float delta) { // Debugger.log(texture_head.length); // draw leg if (moving) { switch (step) { case 0: spriteBatch.draw(texture_leg_step1[direction], position.x, Display.HEIGHT - (position.y + C_LEG)); break; case 1: spriteBatch.draw(texture_leg_step2[direction], position.x, Display.HEIGHT - (position.y + C_LEG)); break; case 2: spriteBatch.draw(texture_leg_stop[direction], position.x, Display.HEIGHT - (position.y + C_LEG)); break; case 3: spriteBatch.draw(texture_leg_step3[direction], position.x, Display.HEIGHT - (position.y + C_LEG)); break; case 4: spriteBatch.draw(texture_leg_step4[direction], position.x, Display.HEIGHT - (position.y + C_LEG)); break; case 5: spriteBatch.draw(texture_leg_step3[direction], position.x, Display.HEIGHT - (position.y + C_LEG)); break; } } else { spriteBatch.draw(texture_leg_stop[direction], position.x, Display.HEIGHT - (position.y + C_LEG)); } // draw body spriteBatch.draw(texture_body[direction], position.x, Display.HEIGHT - (position.y + p_body)); // draw hands spriteBatch.draw(texture_hand[direction], position.x, Display.HEIGHT - (position.y + p_hand)); // draw face spriteBatch.draw(texture_face[direction], position.x, Display.HEIGHT - (position.y + p_face)); // draw head spriteBatch.draw(texture_head[direction], position.x, Display.HEIGHT - (position.y + p_head)); // draw name tag nameTag.draw(spriteBatch, 1); // draw talk balloon if (talkBalloon.talking) talkBalloon.draw(spriteBatch, delta); } @Override public void update(float delta) { // update time values. stepTime += delta; next += 1; if (next >= SINE_WAVE.length) next = 0; // increase step if moving. if (stepTime > 0.05f && moving) { step += 1; stepTime = 0; if (step > 5) step = 0; } // �̵����̶�� ��ǥ�� ������Ʈ�Ѵ�. // if (moving) { // updatePosition(delta); // �̵� ���� �� ��ũ ������ �߻��Ѵ�. if (me && moving) { updatePosition(delta); } else if (this.path.size() > 0 && !me && this.path.size() > pathIndex) { Path path = this.path.get(pathIndex); if (path.disabled) { pathIndex++; } else { this.direction = path.direction; if (path.target == null) { updatePosition(delta); } else { // moveTo(path, delta); updatePosition(delta); } // ���� ��ǥ�� Ÿ�� ��ǥ�� �˻��ؼ� ���� �ȿ� ������ �Ϸ� if (path.check(position)) { // �Ϸ� ��, ���ÿ��� �����Ͱ� 0�̸� ������ �ʱ�ȭ�Ѵ� (�޸� ���) if (this.path.size() - 1 <= pathIndex) { this.path.clear(); pathIndex = 0; } else { pathIndex++; } // ���̰� �ʹ� ũ�� �� ��� �ϵ弼���Ѵ�. } else if (path.previousDistance > 2000 && path.target != null) { // ������ ���� ���� position.x = path.target.x; position.y = path.target.y; } } } nameTag.setPosition(position.x - (nameTag.getWidth() / 2) + 27, Display.HEIGHT - position.y + 27); if (talkBalloon.talking) talkBalloon.update(delta); // ���� ������ ���� ������ ���� �Ųٱ� ���� ��δ� �������� �̺�Ʈ�� ���� �� �̸� ����� ���´�. // ���� �Ųٴ� ���� move �̺�Ʈ�� ���Դٸ� ���ÿ� �״´�. // ��� ������ �����̹Ƿ�, ��ǥ üũ�� �����ϴ�! ^^ // animation effect. (sine wave) p_head = C_HEAD + SINE_WAVE[next] * 2f; p_face = C_FACE + SINE_WAVE[next] * 2f; p_body = C_BODY + SINE_WAVE[next] * 2; p_hand = C_HAND + SINE_WAVE[next] * 2; } private void updatePosition(float delta) { switch (direction) { case 0: position.x -= speed * delta; position.y += speed * delta / 2; break; case 1: position.x -= speed * delta; break; case 2: position.x -= speed * delta; position.y -= speed * delta / 2; break; case 3: position.y -= speed * delta / 2; break; case 4: position.x += speed * delta; position.y -= speed * delta / 2; break; case 5: position.x += speed * delta; break; case 6: position.x += speed * delta; position.y += speed * delta / 2; break; case 7: position.y += speed * delta / 2; break; } } @Override public Point getPosition() { bottom.x = position.x; bottom.y = position.y + 150; bottom.z = position.z; return bottom; } public void move(int targetDirection) { this.direction = targetDirection; Server.send(Header.MOVE + Server.H_L + direction + Server.H_L + Math.round(speed) + Server.H_L + Math.round(position.x) + Server.H_L + Math.round(position.y) + Server.H_L + Math.round(position.z)); } public void stop() { Server.send(Header.STOP + Server.H_L + Math.round(position.x) + Server.H_L + Math.round(position.y) + Server.H_L + Math.round(position.z)); } public int getDirection(Point point) { int xdet = 0; // -1-����, 0-���� ����, 1-������ int ydet = 0; // -1-�Ʒ���, 0-���� ����, 1-���� if (point.x - position.x > 0) { // �����ʿ� �ִ�. xdet = 1; } else if (point.x == position.x) { // ����. } else {// ���ʿ� �ִ�. xdet = -1; } if (point.y - position.y > 0) { // ���ʿ� �ִ�. ydet = -1; } else if (point.y == position.y) { // ����. } else {// �Ʒ��ʿ� �ִ�. ydet = 1; } if (xdet > 0) { // ������ if (ydet > 0) { // ������ �� return 4; } else if (ydet == 0) { // �׳� ������ return 5; } else { // ������ �Ʒ� return 6; } } else if (xdet == 0) { // y�� ������ if (ydet > 0) { // �� return 3; } else if (ydet == 0) { // �� ������ (����Ʈ ��ũ!) return -1; } else { // �Ʒ� return 7; } } else { // ���� if (ydet > 0) { // ���� �� return 2; } else if (ydet == 0) { // �׳� ���� return 1; } else { // ���� �Ʒ� return 0; } } } }
agemor/lionse
src/lionse/client/stage/Character.java
Java
gpl-2.0
10,099
package com.lami.tuomatuo.mq.zookeeper.server; import com.lami.tuomatuo.mq.zookeeper.jmx.ZKMBeanInfo; /** * This class implements the data tree MBean * * Created by xujiankang on 2017/3/19. */ public class DataTreeBean implements DataTreeMXBean, ZKMBeanInfo{ public DataTree dataTree; public DataTreeBean(DataTree dataTree) { this.dataTree = dataTree; } @Override public int getNodeCount() { return dataTree.getNodeCount(); } @Override public long approximateDataSize() { return dataTree.approximateDataSize(); } @Override public int countEphemerals() { return dataTree.getEphemeralsCount(); } public int getWatchCount(){ return dataTree.getWatchCount(); } @Override public String getName() { return "InMemoryDataTree"; } @Override public boolean isHidden() { return false; } @Override public String getLastZxid() { return "0x" + Long.toHexString(dataTree.lastProcessedZxid); } }
jackkiexu/tuomatuo
tuomatuo-mq/src/main/java/com/lami/tuomatuo/mq/zookeeper/server/DataTreeBean.java
Java
gpl-2.0
1,052