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
# -*- coding: utf-8 -*- from sqlalchemy import text from listenbrainz import db class User(object): """ User class required by the api-compat """ def __init__(self, id, created, name, api_key): self.id = id self.created = created self.name = name self.api_key = api_key @staticmethod def get_id(mb_id): with db.engine.connect() as connection: result = connection.execute(text(""" SELECT id FROM "user" WHERE musicbrainz_id = :mb_id """), {"mb_id": mb_id}) row = result.fetchone() if row: return row[0] return None @staticmethod def load_by_name(mb_id): with db.engine.connect() as connection: result = connection.execute(text(""" SELECT id, created, musicbrainz_id, auth_token \ FROM "user" \ WHERE musicbrainz_id = :mb_id """), {"mb_id": mb_id}) row = result.fetchone() if row: return User(row['id'], row['created'], row['musicbrainz_id'], row['auth_token']) return None @staticmethod def load_by_id(serial): with db.engine.connect() as connection: result = connection.execute(text(""" SELECT id, created, musicbrainz_id, auth_token \ FROM "user" WHERE id=:id """), {"id": serial}) row = result.fetchone() if row: return User(row['id'], row['created'], row['musicbrainz_id'], row['auth_token']) return None @staticmethod def load_by_sessionkey(session_key, api_key): with db.engine.connect() as connection: result = connection.execute(text(""" SELECT "user".id , "user".created , "user".musicbrainz_id , "user".auth_token FROM api_compat.session, "user" WHERE api_key = :api_key AND sid = :sk AND "user".id = session.user_id """), { "api_key": api_key, "sk": session_key }) row = result.fetchone() if row: return User(row['id'], row['created'], row['musicbrainz_id'], row['auth_token']) return None @staticmethod def get_play_count(user_id, listenstore): """ Get playcount from the given user name. """ user = User.load_by_id(user_id) return listenstore.get_listen_count_for_user(user.id)
metabrainz/listenbrainz-server
listenbrainz/db/lastfm_user.py
Python
gpl-2.0
2,716
require_relative './spec_helper' require 'norikra/typedef' require 'json' require 'digest' describe Norikra::Typedef do context 'instanciated as lazy typedef' do it 'has no fields' do t = Norikra::Typedef.new expect(t.fields.size).to eql(0) expect(t.baseset).to be_nil end it 'has no query/data fieldsets' do t = Norikra::Typedef.new expect(t.queryfieldsets.size).to eql(0) expect(t.datafieldsets.size).to eql(0) end describe '#lazy?' do it 'returns true' do t = Norikra::Typedef.new expect(t.lazy?).to be_true end end describe '#reserve' do it 'add field definition without any baseset' do t = Norikra::Typedef.new t.reserve('k', 'string') expect(t.fields['k'].type).to eql('string') expect(t.fields['k'].optional?).to be_true t.reserve('l', 'long', false) expect(t.fields['l'].type).to eql('long') expect(t.fields['l'].optional?).to be_false end end describe '#activate' do context 'without any fields reserved' do it 'stores all fields in specified fieldset' do t = Norikra::Typedef.new set = Norikra::FieldSet.new({'a'=>'string','b'=>'long','c'=>'double'}) t.activate(set) expect(t.fields.size).to eql(3) expect(t.fields['a'].optional?).to be_false expect(t.fields.object_id).not_to eql(set.fields.object_id) expect(t.baseset.object_id).not_to eql(set.object_id) end end end end context 'instanciated as non-lazy typedef' do it 'has no query/data fieldsets' do t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'}) expect(t.queryfieldsets.size).to eql(0) expect(t.datafieldsets.size).to eql(0) end it 'has all fields as required' do t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'}) expect(t.fields['a'].type).to eql('string') expect(t.fields['a'].optional?).to be_false expect(t.fields['b'].type).to eql('long') expect(t.fields['b'].optional?).to be_false end describe '#lazy?' do it 'returns false' do t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'}) expect(t.lazy?).to be_false end end describe '#field_defined?' do it 'returns boolean to indicate all fields specified exists or not' do t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'}) expect(t.field_defined?(['a','b'])).to be_true expect(t.field_defined?(['a'])).to be_true expect(t.field_defined?(['b'])).to be_true expect(t.field_defined?([])).to be_true expect(t.field_defined?(['a','b','c'])).to be_false expect(t.field_defined?(['a','c'])).to be_false expect(t.field_defined?(['c'])).to be_false end end describe '#reserve' do it 'adds field definitions as required or optional' do t = Norikra::Typedef.new({'a' => 'string'}) expect(t.fields.size).to eql(1) t.reserve('b', 'boolean', false) expect(t.fields.size).to eql(2) expect(t.fields['b'].type).to eql('boolean') expect(t.fields['b'].optional?).to be_false t.reserve('c', 'double', true) expect(t.fields.size).to eql(3) expect(t.fields['c'].type).to eql('double') expect(t.fields['c'].optional?).to be_true end end describe '#consistent?' do context 'without any additional reserved fields' do it 'checks all fields of specified fieldset are super-set of baseset or not' do t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'}) set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'long'}) expect(t.consistent?(set)).to be_true set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'long', 'c' => 'double'}) expect(t.consistent?(set)).to be_true set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'int'}) expect(t.consistent?(set)).to be_false set = Norikra::FieldSet.new({'a' => 'string'}) expect(t.consistent?(set)).to be_false end end context 'with some additional reserved fields' do it 'checks all fields of specified fieldset with baseset and additional reserved fields' do t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'}) t.reserve('c', 'double', false) # required t.reserve('d', 'boolean', true) # optional set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'long'}) expect(t.consistent?(set)).to be_false set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'long', 'c' => 'double'}) expect(t.consistent?(set)).to be_true set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'long', 'c' => 'double', 'd' => 'boolean'}) expect(t.consistent?(set)).to be_true set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'long', 'c' => 'double', 'd' => 'string'}) expect(t.consistent?(set)).to be_false set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'long', 'c' => 'double', 'd' => 'boolean', 'e' => 'string'}) expect(t.consistent?(set)).to be_true end end end describe '#push' do it 'does not accepts fieldset which conflicts pre-defined fields' do t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'}) expect { t.push(:query, Norikra::FieldSet.new({'a'=>'string','b'=>'int'})) }.to raise_error(ArgumentError) expect { t.push(:data, Norikra::FieldSet.new({'a'=>'string'})) }.to raise_error(ArgumentError) end it 'accepts fieldsets which is consistent with self' do t = Norikra::Typedef.new({'a'=>'string','b'=>'long'}) expect(t.fields.size).to eql(2) expect { t.push(:query, Norikra::FieldSet.new({'a'=>'string','b'=>'long'})) }.not_to raise_error(ArgumentError) expect { t.push(:data, Norikra::FieldSet.new({'a'=>'string','b'=>'long'})) }.not_to raise_error(ArgumentError) expect(t.fields.size).to eql(2) set_a = Norikra::FieldSet.new({'a'=>'string','b'=>'long','c'=>'double'}) t.push(:data, set_a) expect(t.fields.size).to eql(3) expect(t.fields['c'].type).to eql('double') expect(t.fields['c'].optional?).to be_true t.push(:query, Norikra::FieldSet.new({'a'=>'string','b'=>'long','d'=>'string'})) expect(t.fields.size).to eql(4) expect(t.fields['d'].type).to eql('string') expect(t.fields['d'].optional?).to be_true end end describe '#refer' do context 'for event defined by data-fieldset already known' do it 'returns fieldset that already known itself' do t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'}) set1 = Norikra::FieldSet.new({'a'=>'string','b'=>'long'}) t.push(:data, set1) r = t.refer({'a'=>'foobar','b'=>200000000}) expect(r).to be_instance_of(Norikra::FieldSet) expect(r.object_id).to eql(set1.object_id) end end context 'for event with known fields only' do it 'returns fieldset that is overwritten with known field definitions' do t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'}) t.reserve('c','boolean',true) t.reserve('d','double',true) r = t.refer({'a'=>'hoge','b'=>'2000','c'=>'true','d'=>'3.14'}) expect(t.datafieldsets.include?(r)).to be_false expect(r.fields['a'].type).to eql('string') expect(r.fields['b'].type).to eql('long') expect(r.fields['c'].type).to eql('boolean') expect(r.fields['d'].type).to eql('double') end end context 'for event with some unknown fields' do it 'returns fieldset that contains fields as string for unknowns' do t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'}) r = t.refer({'a'=>'hoge','b'=>'2000','c'=>'true','d'=>'3.14'}) expect(t.datafieldsets.include?(r)).to be_false expect(r.fields['a'].type).to eql('string') expect(r.fields['b'].type).to eql('long') expect(r.fields['c'].type).to eql('string') expect(r.fields['d'].type).to eql('string') end end end describe '#format' do it 'returns hash value with formatted fields as defined' do t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'}) t.reserve('c','boolean',true) t.reserve('d','double',true) d = t.format({'a'=>'hoge','b'=>'2000','c'=>'true','d'=>'3.14'}) expect(d['a']).to be_instance_of(String) expect(d['a']).to eql('hoge') expect(d['b']).to be_instance_of(Fixnum) expect(d['b']).to eql(2000) expect(d['c']).to be_instance_of(TrueClass) expect(d['c']).to eql(true) expect(d['d']).to be_instance_of(Float) expect(d['d']).to eql(3.14) end end end end
achied/norikra
spec/typedef_spec.rb
Ruby
gpl-2.0
9,075
/** * @file * Main JS file for react functionality. * */ (function ($) { Drupal.behaviors.react_blocks = { attach: function (context) { // A div with some text in it var CommentBox = React.createClass({displayName: 'CommentBox', loadCommentsFromServer: function() { $.ajax({ url: this.props.url, dataType: 'json', success: function(data) { this.setState({data: data}); }.bind(this), error: function(xhr, status, err) { console.error(this.props.url, status, err.toString()); }.bind(this) }); }, getInitialState: function() { return {data: []}; }, componentDidMount: function() { this.loadCommentsFromServer(); setInterval(this.loadCommentsFromServer, this.props.pollInterval); }, render: function() { return ( React.createElement("div", {className: "commentBox"}, React.createElement("h3", null, React.createElement("b", null, "Check them out!")), React.createElement(CommentList, {data: this.state.data}) ) ); } }); var CommentList = React.createClass({displayName: 'CommentList', render: function() { var commentNodes = this.props.data.map(function (comment) { return ( React.createElement(Comment, {author: comment.name}, comment.subject ) ); }); return ( React.createElement("div", {className: "commentList"}, commentNodes ) ); } }); var Comment = React.createClass({displayName: 'Comment', render: function() { return ( React.createElement("div", {className: "comment"}, React.createElement("h2", {className: "commentAuthor"}, this.props.name ), this.props.subject ) ); } }); // Render our reactComponent React.render( React.createElement(CommentBox, {url: "../api/v1/comment.json", pollInterval: 2000}), document.getElementById('recent-comments') ); } } })(jQuery);
changemachine/jellyfish
sites/all/modules/react_blocks/build/.module-cache/fcda948e5eafc0c8b5f89fe71d221f278abccbd5.js
JavaScript
gpl-2.0
2,307
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Noised.Core.DB; using Noised.Core.IOC; using Noised.Logging; namespace Noised.Core.Plugins { /// <summary> /// Basic plugin loader /// </summary> public class PluginLoader : IPluginLoader { #region Fields private const String PLUGIN_TYPE_NAME = "Noised.Core.Plugins.IPlugin"; private List<IPlugin> plugins = new List<IPlugin>(); private readonly Dictionary<IPlugin, PluginMetaData> metaDataStore = new Dictionary<IPlugin, PluginMetaData>(); #endregion #region IPluginLoader public int LoadPlugins() { var logger = IoC.Get<ILogging>(); using (var unitOfWork = IoC.Get<IUnitOfWork>()) { var files = unitOfWork.PluginRepository.GetFiles(".nplugin"); FileInfo currentFile = null; foreach (var file in files) { currentFile = file; IEnumerable<Type> pluginTypes; try { //Getting IPlugin types from the plugin assembly Assembly assembly = Assembly.LoadFrom(file.FullName); Type pluginBaseType = Type.GetType(PLUGIN_TYPE_NAME); pluginTypes = assembly.GetTypes().Where(pluginBaseType.IsAssignableFrom); if (pluginTypes != null && pluginTypes.Any()) { //Plugin init data var pluginInitializer = new PluginInitializer { Logging = logger }; //Instantiate the first IPlugin type found Type concreteType = pluginTypes.First(); var plugin = (IPlugin)Activator.CreateInstance(concreteType, pluginInitializer); plugins.Add(plugin); //Loading meta data PluginMetaData metaData = null; metaData = unitOfWork.PluginRepository.GetForFile(file); if (metaData != null) { metaDataStore.Add(plugin, metaData); } else { throw new Exception("No PluginMetaData found for file " + file); } IoC.Get<ILogging>().Info( String.Format("Loaded Plugin {0} - {1}", metaData.Name, metaData.Description)); } else { IoC.Get<ILogging>().Error( String.Format("No IPlugin implementation found in assembly {0}", file)); } } catch (Exception e) { IoC.Get<ILogging>().Error( "Could not load plugin " + currentFile.FullName); IoC.Get<ILogging>().Error(e.Message); } } plugins = plugins.OrderByDescending(p => p.GetMetaData().Priority).ToList(); return plugins.Count; } } public IEnumerable<IPlugin> GetPlugins() { return plugins; } public IEnumerable<T> GetPlugins<T>() where T : IPlugin { var concretPlugins = new List<T>(); foreach (var plugin in plugins) { if (plugin is T) { concretPlugins.Add((T)plugin); } } return concretPlugins; } public T GetPlugin<T>() where T : IPlugin { IPlugin plugin = GetPlugins<T>().OrderByDescending(p => p.GetMetaData().Priority).FirstOrDefault(); if (plugin != null) return (T)plugin; return default(T); } public PluginMetaData GetMetaData(IPlugin plugin) { PluginMetaData ret; metaDataStore.TryGetValue(plugin, out ret); return ret; } #endregion }; }
bennygr/noised
src/NoisedCore/Plugins/PluginLoader.cs
C#
gpl-2.0
4,643
import javax.swing.JLabel;
plumer/java-8e-assignments
learn/ch12/MyFrameWithComponents.java
Java
gpl-2.0
27
<?php /*-------------------------------------------------------------------------------------------------------------| www.vdm.io |------/ ____ ____ __ __ __ /\ _`\ /\ _`\ __ /\ \__ __/\ \ /\ \__ \ \,\L\_\ __ _ __ ___ ___ ___ ___ \ \ \/\ \/\_\ ____\ \ ,_\ _ __ /\_\ \ \____ __ __\ \ ,_\ ___ _ __ \/_\__ \ /'__`\/\`'__\/' __` __`\ / __`\ /' _ `\ \ \ \ \ \/\ \ /',__\\ \ \/ /\`'__\/\ \ \ '__`\/\ \/\ \\ \ \/ / __`\/\`'__\ /\ \L\ \/\ __/\ \ \/ /\ \/\ \/\ \/\ \L\ \/\ \/\ \ \ \ \_\ \ \ \/\__, `\\ \ \_\ \ \/ \ \ \ \ \L\ \ \ \_\ \\ \ \_/\ \L\ \ \ \/ \ `\____\ \____\\ \_\ \ \_\ \_\ \_\ \____/\ \_\ \_\ \ \____/\ \_\/\____/ \ \__\\ \_\ \ \_\ \_,__/\ \____/ \ \__\ \____/\ \_\ \/_____/\/____/ \/_/ \/_/\/_/\/_/\/___/ \/_/\/_/ \/___/ \/_/\/___/ \/__/ \/_/ \/_/\/___/ \/___/ \/__/\/___/ \/_/ /------------------------------------------------------------------------------------------------------------------------------------/ @version 2.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage default_preachers-table.php @author Llewellyn van der Merwe <https://www.vdm.io/> @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file defined('_JEXEC') or die('Restricted access'); // Column counter $column_nr = 1; // build the table class $color = $this->params->get('preachers_table_color'); switch ($color) { case 1: // Red $tableClass = ' metro-red'; break; case 2: // Purple $tableClass = ' metro-purple'; break; case 3: // Green $tableClass = ' metro-green'; break; case 4: // Dark Blue $tableClass = ' metro-blue'; break; case 6: // Uikit style $tableClass = ' uk-table'; break; case 7: // Custom Style $tableClass = ' preachers-table'; break; default: // Light Blue and other $tableClass = ''; break; } ?> <table class="footable<?php echo $tableClass; ?>" data-page-size="100"> <thead> <tr> <th data-toggle="true"><?php echo JText::_('COM_SERMONDISTRIBUTOR_NAME'); ?></th> <?php if ($this->params->get('preachers_desc')): ?> <th data-hide="all"><?php echo JText::_('COM_SERMONDISTRIBUTOR_DESCRIPTION'); $column_nr++; ?></th> <?php endif; ?> <?php if ($this->params->get('preachers_website')): ?> <th data-hide="all"><?php echo JText::_('COM_SERMONDISTRIBUTOR_WEBSITE'); $column_nr++; ?></th> <?php endif; ?> <?php if ($this->params->get('preachers_email')): ?> <th data-hide="all"><?php echo JText::_('COM_SERMONDISTRIBUTOR_EMAIL'); $column_nr++; ?></th> <?php endif; ?> <?php if ($this->params->get('preachers_hits')): ?> <th data-type="numeric"><?php echo JText::_('COM_SERMONDISTRIBUTOR_HITS'); $column_nr++; ?></th> <?php endif; ?> <?php if ($this->params->get('preachers_sermon_count')): ?> <th data-type="numeric" data-hide="phone,tablet"><?php echo JText::_('COM_SERMONDISTRIBUTOR_SERMON_COUNT'); $column_nr++;?></th> <?php endif; ?> </tr> </thead> <tfoot class="hide-if-no-paging"> <tr> <td colspan="<?php echo $column_nr; ?>"> <div class="pagination pagination-centered"></div> </td> </tr> </tfoot> <tbody> <?php foreach ($this->items as $item): ?> <tr><?php $item->params = $this->params; echo JLayoutHelper::render('preachersrow', $item); ?></tr> <?php endforeach; ?> </tbody> </table> <script> // page loading pause jQuery(window).load(function() { // do some stuff once page is loaded jQuery('.footable').footable(); }); </script>
SermonDistributor/Joomla-3-Component
site/views/preachers/tmpl/default_preachers-table.php
PHP
gpl-2.0
4,011
<?php /* * * * * * * * * * * Author: Calc, calc@list.ru, 8(916) 506-7002 * mxtel, 2010, Calc (r) * * * * * * * * * */ defined("INDEX") or die('404 go to <a href="/">index.php</a>'); $do = get_var('do',0); $id = get_var('id',0); $pid = get_var('pid',0); $type= get_var('type','port'); //get for ajah $oid = get_var('oid',0); $table = 'inbound_opts'; $tbl = new tbl($table); // id oid pid type tid list($oid, $pid, $type, $tid) = array( post_var('oid',$oid), post_var('pid',$pid), post_var('type',$type), post_var('tid')); switch($do) { case 1: //добавляем элемент _mysql_query($tbl->insert( array(0, $oid, $pid, $type, $tid))); redir("gr=$gr&oid=$oid&pid=$pid",1); break; case 2: $hide = $_GET['hide']; if($hide!=1) $hide=0; _mysql_query($tbl->update_k(array('id'=>$id), array('hide'=>$hide))); redir("gr=$gr&oid=$oid&pid=$pid",1); break; case 10: _mysql_query($tbl->update(array('id'=>$id), array(0, $oid, $pid, $type, $tid))); redir("gr=$gr&oid=$oid&pid=$pid",1); break; case 11: do_del($table,$id,"gr=$gr&oid=$oid&pid=$pid",'','',1); break; case 'ajah_tid': $ret = ''; $tbl = $type; if($type=='port'){ $tbl = 'users'; $n = 'intno';} $ret.= tag_f_se('tid', $tid, db_sel1($tbl, $n, '', "where oid=$oid")); echo $ret; exit(); break; case 'ajah_main': $ret = maintbl(); echo $ret; exit(); break; } $tid = 0; if($id) { $q = "select * from $table where id=$id"; $r = mysql_query($q); list($id,$oid, $pid,$type,$tid) = mysql_fetch_array($r); } $int_a = db_sel('users','intno','',"oid=$oid and "); $int_a[0] = 'Внешний'; $peer_a = db_sel('peers','','',"oid in($oid,24) and "); //$peer_a1 = $peer_a2; $peer_a[0] = 'Все'; $body.=' <form action="?gr='.$gr.'&oid='.$oid.'&pid='.$pid.'&do='.( ($id==0) ? 1 : 10 ).'&id='.$id.'" method="post"> Пир: '.tag_f_se('pid',$pid, $peer_a,'pid').' Тип: '.tag_f_se('type',$type,$r_types,'type',1).' Значение: <span id="tid">'.tag_f_se('tid',$tid,db_sel1('users', 'intno','',$w="where oid=$oid")).'</span> '.tag_f_sm($id).' '.tag_f_hi('oid',$oid).' </form>'; // запрос для формы ajah $jq.= " $(\"#pid\").change(function() { val = $(\"#pid\").val(); url = './?gr=$gr&oid=$oid&pid=' + val + '&do=ajah_main'; $(\"#main\").text(\"\").load(url); }); $(\"#type\").change(function() { val = $(\"#type\").val(); url = './?gr=$gr&oid=$oid&pid=$pid&do=ajah_tid&type=' + val; $(\"#tid\").text(\"\").load(url); }); "; $body.= tag_a("?gr=user&oid=$oid",'Назад'); $body.= '<div id="main">'; $body.= maintbl(); $body.= '</div>'; function maintbl() { global $gr,$oid,$pid,$table; $q = " select io.id, io.oid, io.pid, io.type, io.tid, p.name, o.name from $table as io left join peers as p on p.id=io.pid left join org as o on o.id=io.oid where io.pid=$pid order by io.type"; //echo $q; $r = _mysql_query($q); $n = mysql_num_rows($r); $body = ''; $body.= tag_t_o_('maintbl'); $body.= tag_tr(); $body.= tag_th('id'); $body.= tag_th('oid'); $body.= tag_th('pid'); $body.= tag_th('type'); $body.= tag_th('tid'); $body.= tag_th('x'); $body.= tag_tr(1); $exten = ''; if($n) { for($i=0;$i<$n;$i++) { list($id, $oid, $pid, $type, $tid, $pname, $oname) = mysql_fetch_array($r); $body.= tag_tr(); $body.= tag_td(tag_a("?gr=$gr&oid=$oid&pid=$pid&id=$id",$id),$i); $body.= tag_td($oname,$i); $body.= tag_td($pname,$i); $body.= tag_td($type,$i); $body.= tag_td(db_field('users', $tid, 'intno'),$i); $body.= tag_td(tag_a_x("?gr=$gr&oid=$oid&pid=$pid&id=$id&do=11"),$i); $acc = ''; $body.= tag_tr(1); } } $body.= '<td colspan="9">'.$n.' записей</td>'; $body.= tag_t_c(); $exten = file_get_contents("./tmp/ext.inbound"); $body.= '<pre>'; $body.= $exten; $body.= '</pre>'; $body.= 'Входящая маршрутизация устанавливает макрос, который будет обслуживать входящий вызов. Если макрос не указан, то вызов будет поступать на все локальные номера, закрепленные за пиром.'; return $body; }
Calc86/tel
mods/iopt.php
PHP
gpl-2.0
4,787
package com.dynamo2.tianma.model; public class ObjectField extends MongodbModel { private String name; private String uniqueMark; private int type; private String linkedObject; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUniqueMark() { return uniqueMark; } public void setUniqueMark(String uniqueMark) { this.uniqueMark = uniqueMark; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getLinkedObject() { return linkedObject; } public void setLinkedObject(String linkedObject) { this.linkedObject = linkedObject; } }
dynamo2/tianma
mycrm/src/main/java/com/dynamo2/tianma/model/ObjectField.java
Java
gpl-2.0
715
# datepicker-1.py from wax import * from wax.tools.datepicker import DatePicker import datetime import time class MainFrame(VerticalFrame): def Body(self): p1 = HorizontalPanel(self) dp1 = DatePicker(p1) p1.AddComponent(dp1) p1.AddSpace(10) b1 = Button(p1, "Add 1 day", event=self.AddOneDay) p1.AddComponent(b1) p1.Pack() self.AddComponent(p1, expand='h', border=4) p2 = HorizontalPanel(self) dp2 = DatePicker(p2, style='dropdown', show_century=1) p2.AddComponent(dp2) p2.AddSpace(10) b2 = Button(p2, "Yesterday", event=self.SetToYesterday) p2.AddComponent(b2) p2.Pack() self.AddComponent(p2, expand='h', border=4) self.Pack() self.BackgroundColor = p1.BackgroundColor self.dp1 = dp1 self.dp2 = dp2 # restrict dp2's range to current year thisyear = time.localtime(time.time())[0] dp2.SetRange((thisyear, 1, 1), (thisyear, 12, 31)) def AddOneDay(self, event): self.dp1.Inc() print "Date set to:", self.dp1.Value def SetToYesterday(self, event): now = time.localtime(time.time()) self.dp2.Value = now[:3] # tuple: (year, month, day) self.dp2.Dec() app = Application(MainFrame, title='datepicker-1') app.Run()
MSMBA/msmba-workflow
msmba-workflow/srclib/wax/examples/datepicker-1.py
Python
gpl-2.0
1,480
## # This file is part of WhatWeb and may be subject to # redistribution and commercial restrictions. Please see the WhatWeb # web site for more information on licensing and terms of use. # https://morningstarsecurity.com/research/whatweb ## Plugin.define do name "Hughes-Satellite-Router" authors [ "Brendan Coles <bcoles@gmail.com>", # 2011-08-14 ] version "0.1" description "Hughes IPoS (IP over Satellite) router" website "http://www.hughes.com/ProductsAndTechnology/BroadbandSatelliteSystems/Pages/default.aspx" # ShodanHQ results as at 2011-08-14 # # 3,874 for HUGHES Terminal # Google results as at 2011-08-14 # # 2 for inurl:sys_info "Print this page. It will be needed if your system fails." # Dorks # dorks [ 'inurl:sys_info "Print this page. It will be needed if your system fails."' ] # Matches # matches [ # Frameset { :text=>'<frame src=/fs/dynaform/dw_logo.html scrolling=no marginheight=0 marginwidth=0 NORESIZE>' }, # Model Detection # Frameset # Title { :model=>/<title>([A-Z]{0,2}[\d]{1,5}[A-Z]?) System Control Center<\/title>/ }, # Model Detection # /fs/dynaform/welcome.html { :url=>"/fs/dynaform/welcome.html", :model=>/<ctrlCenter style="font-size: 14pt; color: #000000; font-weight: bold">([^\s]+) <\/ctrlCenter>/ }, # Version Detection # /sys_info/ { :url=>"/sys_info/", :version=>/<\/td><\/tr><tr><td><div class=text>Software Release:<\/td><td><div class=text>([^<^\s]+)<\/td><\/tr>/ }, # MAC Address Detection # /sys_info/ { :url=>"/sys_info/", :string=>/<\/td><\/tr><tr><td><div class=text>LAN[\d]{1,2} MAC Address:<\/td><td><div class=text>([A-F\d:]{17})<\/td><\/tr>/ }, # WWW-Authenticate Header { :search=>"headers[www-authenticate]", :regexp=>/^Basic realm="HUGHES Terminal"$/ }, ] end
urbanadventurer/WhatWeb
plugins/hughes-satellite-router.rb
Ruby
gpl-2.0
1,736
#include <iostream> #include <map> #include <vector> #include <string> #include <algorithm> #include <fstream> using namespace std; vector<string> dict; map<string, int> map_dict; void reformat(string &line) { int sz = line.size(); int j = 1; for(int i = 1; i < sz; ++i) { if(isalpha(line[i])) line[j++] = line[i]; } line.resize(j); } int main() { freopen("./critical.txt", "r", stdin); string word; while(cin>>word) { if(word[0]=='#') break; if(word.size() <= 7) { dict.push_back(word); map_dict[word]++; } } sort(dict.begin(), dict.end()); cin.ignore(); string line; while(getline(cin, line)) { if(line[0] == '#') break; reformat(line); sort(line.begin(), line.end()); map<string,int> key; do { int sz = line.size(); for(int i = 0; i < sz; ++i) { string s = line.substr(i, sz); if(!key[s]) key[s]++; } }while(next_permutation(line.begin(),line.end())); int cnt = 0; map<string, int>::iterator it; for(it = key.begin(); it != key.end(); ++it) { if(binary_search(dict.begin(), dict.end(), it->first)) { if(map_dict[it->first] > 1) cnt += map_dict[it->first]; else cnt++; } } cout << cnt << endl; key.clear(); line.clear(); } return 0; }
rahulroot/Uva
895/program.cpp
C++
gpl-2.0
1,399
export default (sequelize, dataTypes) => { return sequelize.define( 'Community', { id: sequelize.idType, subdomain: { type: dataTypes.TEXT, unique: true, allowNull: false, validate: { isLowercase: true, len: [1, 280], is: /^[a-zA-Z0-9-]+$/, // Must contain at least one letter, alphanumeric and hyphens }, }, domain: { type: dataTypes.TEXT, unique: true, }, title: { type: dataTypes.TEXT, allowNull: false }, citeAs: { type: dataTypes.TEXT }, publishAs: { type: dataTypes.TEXT }, description: { type: dataTypes.TEXT, validate: { len: [0, 280], }, }, avatar: { type: dataTypes.TEXT }, favicon: { type: dataTypes.TEXT }, accentColorLight: { type: dataTypes.STRING }, accentColorDark: { type: dataTypes.STRING }, hideCreatePubButton: { type: dataTypes.BOOLEAN }, headerLogo: { type: dataTypes.TEXT }, headerLinks: { type: dataTypes.JSONB }, headerColorType: { type: dataTypes.ENUM, values: ['light', 'dark', 'custom'], defaultValue: 'dark', }, useHeaderTextAccent: { type: dataTypes.BOOLEAN }, hideHero: { type: dataTypes.BOOLEAN }, hideHeaderLogo: { type: dataTypes.BOOLEAN }, heroLogo: { type: dataTypes.TEXT }, heroBackgroundImage: { type: dataTypes.TEXT }, heroBackgroundColor: { type: dataTypes.TEXT }, heroTextColor: { type: dataTypes.TEXT }, useHeaderGradient: { type: dataTypes.BOOLEAN }, heroImage: { type: dataTypes.TEXT }, heroTitle: { type: dataTypes.TEXT }, heroText: { type: dataTypes.TEXT }, heroPrimaryButton: { type: dataTypes.JSONB }, heroSecondaryButton: { type: dataTypes.JSONB }, heroAlign: { type: dataTypes.TEXT }, navigation: { type: dataTypes.JSONB }, hideNav: { type: dataTypes.BOOLEAN }, navLinks: { type: dataTypes.JSONB }, footerLinks: { type: dataTypes.JSONB }, footerLogoLink: { type: dataTypes.TEXT }, footerTitle: { type: dataTypes.TEXT }, footerImage: { type: dataTypes.TEXT }, website: { type: dataTypes.TEXT }, facebook: { type: dataTypes.TEXT }, twitter: { type: dataTypes.TEXT }, email: { type: dataTypes.TEXT }, issn: { type: dataTypes.TEXT }, isFeatured: { type: dataTypes.BOOLEAN }, viewHash: { type: dataTypes.STRING }, editHash: { type: dataTypes.STRING }, premiumLicenseFlag: { type: dataTypes.BOOLEAN, defaultValue: false }, defaultPubCollections: { type: dataTypes.JSONB }, /* Set by Associations */ organizationId: { type: dataTypes.UUID }, }, { classMethods: { associate: (models) => { const { Community, Organization, Collection, Page, Pub, ScopeSummary } = models; Community.belongsTo(Organization, { onDelete: 'CASCADE', as: 'organization', foreignKey: 'organizationId', }); Community.hasMany(Collection, { onDelete: 'CASCADE', as: 'collections', foreignKey: 'communityId', }); Community.hasMany(Pub, { onDelete: 'CASCADE', as: 'pubs', foreignKey: 'communityId', }); Community.hasMany(Page, { onDelete: 'CASCADE', as: 'pages', foreignKey: 'communityId', }); Community.belongsTo(ScopeSummary, { as: 'scopeSummary', foreignKey: 'scopeSummaryId', }); }, }, }, ); };
pubpub/pubpub
server/community/model.ts
TypeScript
gpl-2.0
3,307
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # # Copyright (C) 2006 Lukáš Lalinský # # 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.
Sophist-UK/Sophist_picard
picard/browser/__init__.py
Python
gpl-2.0
823
/* * EntityManager.cpp * * Created on: 29 Nov 2015 * Author: osboxes */ #include "EntityManager.h" #include "../syscalls/SysCalls.h" using namespace std; EntityManager::EntityManager(std::string fileName) :m_index("entity.idx"){ m_fname = fileName; m_fdReader = syscalls::open ( m_fname.c_str(),O_CREAT|O_RDONLY,0777 ); m_fdWriter = syscalls::open ( m_fname.c_str(),O_CREAT|O_WRONLY,0777 ); syscalls::lseek(m_fdWriter,0,SEEK_END); struct stat buf; fstat(m_fdWriter, &buf); m_offset = buf.st_size; } EntityManager::~EntityManager() { syscalls::close(m_fdReader); syscalls::close(m_fdWriter); } void EntityManager::persist(Entity entity){ char buffer[sizeof(Entity)]; memcpy(buffer, &entity, sizeof(Entity)); syscalls::write(m_fdWriter,buffer,sizeof(Entity)); m_index.addIndex(entity.nombre, m_offset); m_offset += sizeof(Entity); } void EntityManager::findAll(const char* name,std::list<Entity>& results){ std::list<long> offsets; m_index.getOffsets(name, offsets); for (std::list<long>::iterator it = offsets.begin(); it != offsets.end(); it++){ long offset = *it; Entity entity; syscalls::lseek(m_fdReader, offset,SEEK_SET); syscalls::read(m_fdReader, &entity, sizeof(Entity)); results.push_back(entity); } }
gguzelj/7559-TP2
DbLib/persistence/EntityManager.cpp
C++
gpl-2.0
1,262
public class Star { int x; int y; int owner; int colony; public Star(int x,int y,int owner,int colony){ this.x = x; this.y = y; this.owner = owner; this.colony = colony; } }
TravisRidge/Gigaquadrant
Gigaquadrant/src/Star.java
Java
gpl-2.0
191
/* QUYNH NGA NGUYEN - ID: 700110099 Project FSE Chatroom - 18-652 Server-side file handles requests from clien-side. */ var app = require('express')(); var server = require('http').createServer(app); var io = require('socket.io')(server); var fs = require('fs'); var dbfile = "database.db"; var existed = fs.existsSync(dbfile); var sqlite3 = require('sqlite3').verbose(); var db = new sqlite3.Database(dbfile); app.get("/", function(req, res) { res.sendFile(__dirname + "/index.html"); }); app.get("/chatroom", function(req, res) { res.sendFile(__dirname + "/chatroom.html"); }); app.get("/style.css", function(req, res) { res.sendFile(__dirname + "/style.css"); }); app.get("/FSEChatroomLogo.png", function(req, res) { res.sendFile(__dirname + "/FSEChatroomLogo.png"); }); db.serialize(function() { if (!existed) { db.run("CREATE TABLE chatHistory (name TEXT, message TEXT, time TEXT)"); } }); io.on("connection", function(socket) { socket.on("join", function(name) { // if name already taken, emits an error event back to chatroom var socketList = io.sockets.sockets; var nameTaken = false; for (var i = 0; i < socketList.length; i++) { if (socketList[i].nickname === name) { nameTaken = true; break; } } if (nameTaken) { socket.emit("nameTaken", name); return; } // accepts new user. Sets the name associated with this user socket.nickname = name; // announces new user socket.broadcast.emit("newUser", name); socket.emit("newUser", name); // loads chat history db.serialize(function() { if (existed) { db.each("SELECT * FROM chatHistory", function(err, row) { socket.emit("message", row.name, row.message, row.time); }); } }); }); socket.on("newMessage", function(message) { var time = getTimeString(); socket.broadcast.emit("message", socket.nickname, message, time); socket.emit("message", socket.nickname, message, time); // saves message into database db.serialize(function() { db.run("INSERT into chatHistory (name, message, time)" + " VALUES (?, ?, ?)", socket.nickname, message, time); }); }); socket.on("disconnect", function() { socket.broadcast.emit("exit", socket.nickname); }); }); function getTimeString() { var date = new Date(); var ret = date.getMonth() + "." + date.getDate() + "." + date.getFullYear() + " "; var time = date.getHours(); if (time < 12) { ret += time + ":" + date.getMinutes() + "AM"; } else { if (time > 12) { time -= 12; } ret += time + ":" + date.getMinutes() + "PM"; } return ret; } server.listen(8080); //db.close();
quynhnga-nguyen/FSEChatRoom
server.js
JavaScript
gpl-2.0
2,600
<?php /** * Tools for creating thumbnails. * * @package Image * @author C. Erdmann * @link http://www.cerdmann.de/thumb * @author Robert Wetzlmayr * * Refactored from function.thumb.php by C. Erdmann, which contained * the following credit and licensing terms: * * Smarty plugin "Thumb" * Purpose: creates cached thumbnails * Home: http://www.cerdmann.com/thumb/ * Copyright (C) 2005 Christoph Erdmann * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA * * @author Christoph Erdmann (CE) <smarty@cerdmann.com> * @link http://www.cerdmann.com * * @author Benjamin Fleckenstein (BF) * @link http://www.benjaminfleckenstein.de * * @author Marcus Gueldenmeister (MG) * @link http://www.gueldenmeister.de/marcus/ * * @author Andreas Bösch (AB) */ /** * Output debug log. * * @global bool $verbose */ $verbose = false; /** * Creates thumbnails for larger images. * * @package Image */ class wet_thumb { /** * The width of your thumbnail. The height (if not set) will be * automatically calculated. * * @var int */ public $width; /** * The height of your thumbnail. The width (if not set) will be * automatically calculated. * * @var int */ public $height; /** * Set the longest side of the image if width, height and shortside is * not set. */ public $longside; /** * Set the shortest side of the image if width, height and longside is * not set. */ public $shortside; /** * Set to 'false' if your source image is smaller than the calculated * thumb and you do not want the image to get extrapolated. */ public $extrapolate; /** * Crops the image. * * If set to TRUE, image will be cropped in the center to destination width * and height params, while keeping aspect ratio. Otherwise the image will * get resized. * * @var bool */ public $crop; /** * Applies unsharpen mask. * * Set to FALSE if you don't want to use the Unsharp-Mask. * Thumbnail creation will be faster, but quality is reduced. * * @var bool */ public $sharpen; /** * If set to FALSE the image will not have a lens icon. * * @var bool */ public $hint; /** * Set to FALSE to get no lightgrey bottom bar. * * @var bool */ public $addgreytohint; /** * JPEG image quality (0...100, defaults to 80). * * @var int */ public $quality; /** * Set to your target URL (a href="linkurl"). * * @var string */ public $linkurl; /** * Will be inserted in the image-tag. * * @var string */ public $html; /** * An array of accepted image formats. * * @var array */ public $types = array('', '.gif', '.jpg', '.png'); /** * Source. * * @var array */ public $_SRC; /** * Destination. * * @var array */ public $_DST; /** * Constructor. */ public function __construct() { $this->extrapolate = false; $this->crop = true; $this->sharpen = true; $this->hint = true; $this->addgreytohint = true; $this->quality = 80; $this->html = ' alt="" title="" '; $this->link = true; } /** * Writes a thumbnail file. * * @param string $infile Image file name. * @param array $outfile Array of thumb file names (1...n) * @return bool TRUE on success */ public function write($infile, $outfile) { global $verbose; if ($verbose) { echo "writing thumb nail..."; } // Get source image info. if (!($temp = txpimagesize($infile, true)) || empty($temp['image'])) { return false; } $this->_SRC['file'] = $infile; $this->_SRC['width'] = $temp[0]; $this->_SRC['height'] = $temp[1]; $this->_SRC['type'] = $temp[2]; // 1=GIF, 2=JPEG, 3=PNG, 18=WebP, 19=AVIF. $this->_SRC['string'] = $temp[3]; $this->_SRC['image'] = $temp['image']; $this->_SRC['filename'] = basename($infile); //$this->_SRC['modified'] = filemtime($infile); /* // Make sure we have enough memory if the image is large. if (max($this->_SRC['width'], $this->_SRC['height']) > 1024) { $shorthand = array('K', 'M', 'G'); $tens = array('000', '000000', '000000000'); // A good enough decimal approximation of K, M, and G. // Do not *decrease* memory_limit. list($ml, $extra) = str_ireplace($shorthand, $tens, array(ini_get('memory_limit'), EXTRA_MEMORY)); if ($ml < $extra) { ini_set('memory_limit', EXTRA_MEMORY); } } // Read source image. if ($this->_SRC['type'] == 1) { $this->_SRC['image'] = imagecreatefromgif($this->_SRC['file']); } elseif ($this->_SRC['type'] == 2) { $this->_SRC['image'] = imagecreatefromjpeg($this->_SRC['file']); } elseif ($this->_SRC['type'] == 3) { $this->_SRC['image'] = imagecreatefrompng($this->_SRC['file']); } elseif ($this->_SRC['type'] == 18) { $this->_SRC['image'] = imagecreatefromwebp($this->_SRC['file']); } elseif ($this->_SRC['type'] == 19) { $this->_SRC['image'] = imagecreatefromavif($this->_SRC['file']); } */ // Ensure non-zero height/width. if (!$this->_SRC['height']) { $this->_SRC['height'] = 100; } if (!$this->_SRC['width']) { $this->_SRC['width'] = 100; } // Check image orientation. if ($this->_SRC['width'] >= $this->_SRC['height']) { $this->_SRC['format'] = 'landscape'; } else { $this->_SRC['format'] = 'portrait'; } // Get destination image info. if (is_numeric($this->width) and empty($this->height)) { $this->_DST['width'] = $this->width; $this->_DST['height'] = round($this->width/($this->_SRC['width']/$this->_SRC['height'])); } elseif (is_numeric($this->height) and empty($this->width)) { $this->_DST['height'] = $this->height; $this->_DST['width'] = round($this->height/($this->_SRC['height']/$this->_SRC['width'])); } elseif (is_numeric($this->width) and is_numeric($this->height)) { $this->_DST['width'] = $this->width; $this->_DST['height'] = $this->height; } elseif (is_numeric($this->longside) and empty($this->shortside)) { // Preserve aspect ratio based on provided height. if ($this->_SRC['format'] == 'portrait') { $this->_DST['height'] = $this->longside; $this->_DST['width'] = round($this->longside/($this->_SRC['height']/$this->_SRC['width'])); } else { $this->_DST['width'] = $this->longside; $this->_DST['height'] = round($this->longside/($this->_SRC['width']/$this->_SRC['height'])); } } elseif (is_numeric($this->shortside)) { // Preserve aspect ratio based on provided width. if ($this->_SRC['format'] == 'portrait') { $this->_DST['width'] = $this->shortside; $this->_DST['height'] = round($this->shortside/($this->_SRC['width']/$this->_SRC['height'])); } else { $this->_DST['height'] = $this->shortside; $this->_DST['width'] = round($this->shortside/($this->_SRC['height']/$this->_SRC['width'])); } } else { // Default dimensions. $this->width = 100; $this->_DST['width'] = $this->width; $this->_DST['height'] = round($this->width/($this->_SRC['width']/$this->_SRC['height'])); } // Don't make the new image larger than the original image. if ( $this->extrapolate === false && $this->_DST['height'] > $this->_SRC['height'] && $this->_DST['width'] > $this->_SRC['width'] ) { $this->_DST['width'] = $this->_SRC['width']; $this->_DST['height'] = $this->_SRC['height']; } $this->_DST['type'] = $this->_SRC['type']; $this->_DST['file'] = $outfile; // Crop image. $off_w = 0; $off_h = 0; if ($this->crop != false) { if ($this->_SRC['height'] < $this->_SRC['width']) { $ratio = (double) ($this->_SRC['height'] / $this->_DST['height']); $cpyWidth = round($this->_DST['width'] * $ratio); if ($cpyWidth > $this->_SRC['width']) { $ratio = (double) ($this->_SRC['width'] / $this->_DST['width']); $cpyWidth = $this->_SRC['width']; $cpyHeight = round($this->_DST['height'] * $ratio); $off_w = 0; $off_h = round(($this->_SRC['height'] - $cpyHeight) / 2); $this->_SRC['height'] = $cpyHeight; } else { $cpyHeight = $this->_SRC['height']; $off_w = round(($this->_SRC['width'] - $cpyWidth) / 2); $off_h = 0; $this->_SRC['width'] = $cpyWidth; } } else { $ratio = (double) ($this->_SRC['width'] / $this->_DST['width']); $cpyHeight = round($this->_DST['height'] * $ratio); if ($cpyHeight > $this->_SRC['height']) { $ratio = (double) ($this->_SRC['height'] / $this->_DST['height']); $cpyHeight = $this->_SRC['height']; $cpyWidth = round($this->_DST['width'] * $ratio); $off_w = round(($this->_SRC['width'] - $cpyWidth) / 2); $off_h = 0; $this->_SRC['width'] = $cpyWidth; } else { $cpyWidth = $this->_SRC['width']; $off_w = 0; $off_h = round(($this->_SRC['height'] - $cpyHeight) / 2); $this->_SRC['height'] = $cpyHeight; } } } // Create DST. $this->_DST['image'] = imagecreatetruecolor($this->_DST['width'], $this->_DST['height']); // GIF or PNG destination, set the transparency up. if ($this->_DST['type'] == 1 || $this->_DST['type'] == 3 || $this->_DST['type'] == 18) { $trans_idx = imagecolortransparent($this->_SRC['image']); $pallet_size = imagecolorstotal($this->_SRC['image']); // Is there a specific transparent colour? if ($trans_idx >= 0 && ($trans_idx < $pallet_size)) { $trans_color = imagecolorsforindex($this->_SRC['image'], $trans_idx); $trans_idx = imagecolorallocate( $this->_DST['image'], $trans_color['red'], $trans_color['green'], $trans_color['blue'] ); imagefill($this->_DST['image'], 0, 0, $trans_idx); imagecolortransparent($this->_DST['image'], $trans_idx); } elseif ($this->_DST['type'] == 3 || $this->_DST['type'] == 18 || $this->_DST['type'] == 19) { imagealphablending($this->_DST['image'], false); $transparent = imagecolorallocatealpha($this->_DST['image'], 0, 0, 0, 127); imagefill($this->_DST['image'], 0, 0, $transparent); imagesavealpha($this->_DST['image'], true); } } imagecopyresampled( $this->_DST['image'], $this->_SRC['image'], 0, 0, $off_w, $off_h, $this->_DST['width'], $this->_DST['height'], $this->_SRC['width'], $this->_SRC['height'] ); // avif weirdness if ($this->_DST['type'] == 19) { imageflip($this->_DST['image'], IMG_FLIP_HORIZONTAL); } if ($this->sharpen === true) { $this->_DST['image'] = UnsharpMask($this->_DST['image'], 80, .5, 3); } // Finally, the real dimensions. $this->height = $this->_DST['height']; $this->width = $this->_DST['width']; // Add magnifying glass. if ($this->hint === true) { // Should we really add white bars? if ($this->addgreytohint === true) { $trans = imagecolorallocatealpha($this->_DST['image'], 255, 255, 255, 25); imagefilledrectangle( $this->_DST['image'], 0, $this->_DST['height'] - 9, $this->_DST['width'], $this->_DST['height'], $trans ); } $magnifier = imagecreatefromstring(gzuncompress(base64_decode("eJzrDPBz5+WS4mJgYOD19HAJAtLcIMzBBiRXrilXA1IsxU6eIRxAUMOR0gHkcxZ4RBYD1QiBMOOlu3V/gIISJa4RJc5FqYklmfl5CiGZuakMBoZ6hkZ6RgYGJs77ex2BalRBaoLz00rKE4tSGXwTk4vyc1NTMhMV3DKLUsvzi7KLFXwjFEAa2svWnGdgYPTydHEMqZhTOsE++1CAyNHzm2NZjgau+dAmXlAwoatQmOld3t/NPxlLMvY7sovPzXHf7re05BPzjpQTMkZTPjm1HlHkv6clYWK43Zt16rcDjdZ/3j2cd7qD4/HHH3GaprFrw0QZDHicORXl2JsPsveVTDz//L3N+WpxJ5Hff+10Tjdd2/Vi17vea79Om5w9zzyne9GLnWGrN8atby/ayXPOsu2w4quvVtxNCVVz5nAf3nDpZckBCedpqSc28WTOWnT7rZNXZSlPvFybie9EFc6y3bIMCn3JAoJ+kyyfn9qWq+LZ9Las26Jv482cDRE6Ci0B6gVbo2oj9KabzD8vyMK4ZMqMs2kSvW4chz88SXNzmeGjtj1QZK9M3HHL8L7HITX3t19//VVY8CYDg9Kvy2vDXu+6mGGxNOiltMPsjn/t9eJr0ja/FOdi5TyQ9Lz3fOqstOr99/dnro2vZ1jy76D/vYivPsBoYPB09XNZ55TQBAAJjs5s</body>"))); imagealphablending($this->_DST['image'], true); imagecopy($this->_DST['image'], $magnifier, $this->_DST['width'] - 15, $this->_DST['height'] - 14, 0, 0, 11, 11); imagedestroy($magnifier); } if ($verbose) { echo "... saving image ..."; } $result = false; if ($this->_DST['type'] == 1) { imagetruecolortopalette($this->_DST['image'], false, 256); $imagefn = 'imagegif'; } elseif ($this->_DST['type'] == 2) { $imagefn = 'imagejpeg'; } elseif ($this->_DST['type'] == 3) { $imagefn = 'imagepng'; } elseif ($this->_DST['type'] == 18) { $imagefn = 'imagewebp'; } elseif ($this->_DST['type'] == 19) { $imagefn = 'imageavif'; } if (isset($imagefn) && function_exists($imagefn)) { $result = $imagefn == 'imagejpeg' ? imagejpeg($this->_DST['image'], $this->_DST['file'], $this->quality) : $imagefn($this->_DST['image'], $this->_DST['file']); } imagedestroy($this->_DST['image']); imagedestroy($this->_SRC['image']); if ($verbose) { echo $result ? "... image successfully saved ..." : "... failed to save image ..."; } return $result; } /** * Return a reference to the the thumbnail image as a HTML a or img tag. * * @param bool $aslink Return an anchor tag to the source image * @param bool $aspopup Open the link in new window * @return string HTML markup */ public function asTag($aslink = true, $aspopup = false) { $imgtag = '<img src="'.$this->_DST['file'].'" '.$this->html.' width="'.$this->width.'" height="'.$this->height.'" />'; if ($aslink === true) { return '<a href="'.((empty($this->linkurl)) ? $this->_SRC['file'] : $this->linkurl).'" '. (($aspopup === true) ? ' target="_blank"' : '').'>'.$imgtag.'</a>'; } return $imgtag; } } /** * Wrapper for wet_thumb interfacing Textpattern. * * @package Image */ class txp_thumb extends wet_thumb { /** * File extension. * * @var string */ public $m_ext; /** * Image ID. * * @var int */ public $m_id; /** * Constructor. * * @param int $id The Image id. */ public function __construct($id) { $id = assert_int($id); $rs = safe_row("*", 'txp_image', "id = $id LIMIT 1"); if ($rs) { extract($rs); $this->m_ext = $ext; $this->m_id = $id; } parent::__construct(); } /** * Creates a thumbnail image from a source image. * * @param string $dummy1 Isn't used. * @param string $dummy2 Isn't used. * @return bool TRUE on success */ public function write($dummy1 = '', $dummy2 = '') { if (!isset($this->m_ext)) { return false; } if (parent::write( IMPATH.$this->m_id.$this->m_ext, IMPATH.$this->m_id.'t'.$this->m_ext )) { safe_update( 'txp_image', "thumbnail = 1, thumb_w = $this->width, thumb_h = $this->height, date = NOW()", "id = ".$this->m_id ); chmod(IMPATH.$this->m_id.'t'.$this->m_ext, 0644); return true; } return false; } /** * Removes a thumbnail. * * @return bool TRUE on success */ public function delete() { if (!isset($this->m_ext)) { return false; } if (unlink(IMPATH.$this->m_id.'t'.$this->m_ext)) { safe_update('txp_image', "thumbnail = 0", "id = ".$this->m_id); return true; } return false; } } /** * Unsharp mask. * * Unsharp mask algorithm by Torstein Hønsi 2003 (thoensi_at_netcom_dot_no) * Christoph Erdmann: changed it a little, because I could not reproduce the * darker blurred image, now it is up to 15% faster with same results * * @author Torstein Hønsi * @author Christoph Erdmann * @param resource $img Image as a resource * @param int $amount Filter parameter * @param int $radius Filter parameter * @param int $threshold Filter parameter * @return resource Sharpened image as a resource. * * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. */ function UnsharpMask($img, $amount, $radius, $threshold) { // Attempt to calibrate the parameters to Photoshop: if ($amount > 500) { $amount = 500; } $amount = (int)($amount * 0.016); if ($radius > 50) { $radius = 50; } $radius = $radius * 2; if ($threshold > 255) { $threshold = 255; } $radius = abs(round($radius)); // Only integers make sense. if ($radius == 0) { return $img; } $w = imagesx($img); $h = imagesy($img); $imgCanvas = $img; $imgCanvas2 = $img; $imgBlur = imagecreatetruecolor($w, $h); // Gaussian blur matrix: // 1 2 1 // 2 4 2 // 1 2 1 // Move copies of the image around one pixel at the time and merge them // with weight according to the matrix. The same matrix is simply // repeated for higher radii. for ($i = 0; $i < $radius; $i++) { imagecopy($imgBlur, $imgCanvas, 0, 0, 1, 1, $w - 1, $h - 1); // up left imagecopymerge($imgBlur, $imgCanvas, 1, 1, 0, 0, $w, $h, 50); // down right imagecopymerge($imgBlur, $imgCanvas, 0, 1, 1, 0, $w - 1, $h, 33); // down left imagecopymerge($imgBlur, $imgCanvas, 1, 0, 0, 1, $w, $h - 1, 25); // up right imagecopymerge($imgBlur, $imgCanvas, 0, 0, 1, 0, $w - 1, $h, 33); // left imagecopymerge($imgBlur, $imgCanvas, 1, 0, 0, 0, $w, $h, 25); // right imagecopymerge($imgBlur, $imgCanvas, 0, 0, 0, 1, $w, $h - 1, 20); // up imagecopymerge($imgBlur, $imgCanvas, 0, 1, 0, 0, $w, $h, 17); // down imagecopymerge($imgBlur, $imgCanvas, 0, 0, 0, 0, $w, $h, 50); // center } $imgCanvas = $imgBlur; // Calculate the difference between the blurred pixels and the original // and set the pixels. for ($x = 0; $x < $w; $x++) { // Each row. for ($y = 0; $y < $h; $y++) { // Each pixel. $rgbOrig = ImageColorAt($imgCanvas2, $x, $y); $rOrig = (($rgbOrig >> 16) & 0xFF); $gOrig = (($rgbOrig >> 8) & 0xFF); $bOrig = ($rgbOrig & 0xFF); $rgbBlur = ImageColorAt($imgCanvas, $x, $y); $rBlur = (($rgbBlur >> 16) & 0xFF); $gBlur = (($rgbBlur >> 8) & 0xFF); $bBlur = ($rgbBlur & 0xFF); // When the masked pixels differ less from the original than the // threshold specifies, they are set to their original value. $rNew = (abs($rOrig - $rBlur) >= $threshold) ? max(0, min(255, ($amount * ($rOrig - $rBlur)) + $rOrig)) : $rOrig; $gNew = (abs($gOrig - $gBlur) >= $threshold) ? max(0, min(255, ($amount * ($gOrig - $gBlur)) + $gOrig)) : $gOrig; $bNew = (abs($bOrig - $bBlur) >= $threshold) ? max(0, min(255, ($amount * ($bOrig - $bBlur)) + $bOrig)) : $bOrig; if (($rOrig != $rNew) || ($gOrig != $gNew) || ($bOrig != $bNew)) { $pixCol = ImageColorAllocate($img, $rNew, $gNew, $bNew); ImageSetPixel($img, $x, $y, $pixCol); } } } return $img; }
textpattern/textpattern
textpattern/lib/class.thumb.php
PHP
gpl-2.0
22,703
#!/usr/bin/php -q <?php /** * pbxassist.php * This file is part of the YATE Project http://YATE.null.ro * * Yet Another Telephony Engine - a fully featured software PBX and IVR * Copyright (C) 2007-2013 Null Team * * This software is distributed under multiple licenses; * see the COPYING file in the main directory for licensing * information for this specific distribution. * * This use of this software may be subject to additional restrictions. * See the LEGAL file in the main directory for details. * * 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. */ /* Sample PBX assistant for the Yate PHP interface To use add in regexroute.conf ^NNN$=external/nochan/pbxassist.php;real_callto=real/resource/to/call You will also need a priority= in extmodule.conf [general] in range 50-85 */ require_once("libyate.php"); $ourcallid = true; function onStartup(&$ev) { global $ourcallid; Yate::Output("Channel $ourcallid is being assisted"); } function onHangup($ev) { global $ourcallid; Yate::Output("Channel $ourcallid has hung up"); } function onDisconnect(&$ev,$reason) { global $ourcallid; Yate::Output("Channel $ourcallid was disconnected, reason: '$reason'"); // Sample action: redirect to info tone if user is busy if ($reason == "busy") { $m = new Yate("call.execute"); $m->id = $ev->id; $m->SetParam("id",$ourcallid); $m->SetParam("callto","tone/info"); $m->Dispatch(); // Also send progressing so the tone goes through in early media $m = new Yate("call.progress"); $m->SetParam("targetid",$ourcallid); $m->Dispatch(); return true; } return false; } /* Always the first action to do */ Yate::Init(); /* The main loop. We pick events and handle them */ while ($ourcallid) { $ev=Yate::GetEvent(); /* If Yate disconnected us then exit cleanly */ if ($ev === false) break; /* No need to handle empty events in this application */ if ($ev === true) continue; /* If we reached here we should have a valid object */ switch ($ev->type) { case "incoming": // Yate::Debug("PHP Message: " . $ev->name . " id: " . $ev->id); switch ($ev->name) { case "call.execute": $ourcallid = $ev->GetValue("id"); $callto = $ev->GetValue("real_callto"); if ($ourcallid && $callto) { // Put back the real callto and let the message flow $ev->SetParam("callto",$callto); Yate::Install("chan.hangup",75,"id",$ourcallid); Yate::Install("chan.disconnected",75,"id",$ourcallid); onStartup($ev); } else { Yate::Output("Invalid assist: '$ourcallid' -> '$callto'"); $ourcallid = false; } break; case "chan.hangup": // We were hung up. Do any cleanup and exit. onHangup($ev); $ourcallid = false; break; case "chan.disconnected": // Our party disconnected and we're ready to hang up. // We should reconnect before this message is acknowledged if (onDisconnect($ev,$ev->GetValue("reason"))) $ev->handled = true; break; } /* This is extremely important. We MUST let messages return, handled or not */ if ($ev !== false) $ev->Acknowledge(); break; case "answer": // Yate::Debug("PHP Answered: " . $ev->name . " id: " . $ev->id); break; case "installed": // Yate::Debug("PHP Installed: " . $ev->name); break; case "uninstalled": // Yate::Debug("PHP Uninstalled: " . $ev->name); break; default: // Yate::Output("PHP Event: " . $ev->type); } } Yate::Output("PHP: bye!"); /* vi: set ts=8 sw=4 sts=4 noet: */ ?>
shimaore/yate
share/scripts/pbxassist.php
PHP
gpl-2.0
3,723
/* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "my_global.h" #include <signal.h> #include "sys_vars.h" #include "my_stacktrace.h" #include "global_threads.h" #ifdef __WIN__ #include <crtdbg.h> #define SIGNAL_FMT "exception 0x%x" #else #define SIGNAL_FMT "signal %d" #endif /* We are handling signals in this file. Any global variables we read should be 'volatile sig_atomic_t' to guarantee that we read some consistent value. */ static volatile sig_atomic_t segfaulted= 0; extern ulong max_used_connections; extern volatile sig_atomic_t calling_initgroups; extern my_bool opt_core_file; /** * Handler for fatal signals * * Fatal events (seg.fault, bus error etc.) will trigger * this signal handler. The handler will try to dump relevant * debugging information to stderr and dump a core image. * * Signal handlers can only use a set of 'safe' system calls * and library functions. A list of safe calls in POSIX systems * are available at: * http://pubs.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html * For MS Windows, guidelines are available at: * http://msdn.microsoft.com/en-us/library/xdkz3x12(v=vs.71).aspx * * @param sig Signal number */ extern "C" sig_handler handle_fatal_signal(int sig) { if (segfaulted) { my_safe_printf_stderr("Fatal " SIGNAL_FMT " while backtracing\n", sig); _exit(1); /* Quit without running destructors */ } segfaulted = 1; #ifdef __WIN__ SYSTEMTIME utc_time; GetSystemTime(&utc_time); const long hrs= utc_time.wHour; const long mins= utc_time.wMinute; const long secs= utc_time.wSecond; #else /* Using time() instead of my_time() to avoid looping */ const time_t curr_time= time(NULL); /* Calculate time of day */ const long tmins = curr_time / 60; const long thrs = tmins / 60; const long hrs = thrs % 24; const long mins = tmins % 60; const long secs = curr_time % 60; #endif char hrs_buf[3]= "00"; char mins_buf[3]= "00"; char secs_buf[3]= "00"; my_safe_itoa(10, hrs, &hrs_buf[2]); my_safe_itoa(10, mins, &mins_buf[2]); my_safe_itoa(10, secs, &secs_buf[2]); my_safe_printf_stderr("%s:%s:%s UTC - mysqld got " SIGNAL_FMT " ;\n", hrs_buf, mins_buf, secs_buf, sig); my_safe_printf_stderr("%s", "This could be because you hit a bug. It is also possible that this binary\n" "or one of the libraries it was linked against is corrupt, improperly built,\n" "or misconfigured. This error can also be caused by malfunctioning hardware.\n"); my_safe_printf_stderr("%s", "We will try our best to scrape up some info that will hopefully help\n" "diagnose the problem, but since we have already crashed, \n" "something is definitely wrong and this may fail.\n\n"); my_safe_printf_stderr("key_buffer_size=%lu\n", (ulong) dflt_key_cache->key_cache_mem_size); my_safe_printf_stderr("read_buffer_size=%ld\n", (long) global_system_variables.read_buff_size); my_safe_printf_stderr("max_used_connections=%lu\n", (ulong) max_used_connections); my_safe_printf_stderr("max_threads=%u\n", (uint) thread_scheduler->max_threads); my_safe_printf_stderr("thread_count=%u\n", get_thread_count()); my_safe_printf_stderr("connection_count=%u\n", (uint) connection_count); my_safe_printf_stderr("It is possible that mysqld could use up to \n" "key_buffer_size + " "(read_buffer_size + sort_buffer_size)*max_threads = " "%lu K bytes of memory\n", ((ulong) dflt_key_cache->key_cache_mem_size + (global_system_variables.read_buff_size + global_system_variables.sortbuff_size) * thread_scheduler->max_threads + max_connections * sizeof(THD)) / 1024); my_safe_printf_stderr("%s", "Hope that's ok; if not, decrease some variables in the equation.\n\n"); #if defined(HAVE_LINUXTHREADS) #define UNSAFE_DEFAULT_LINUX_THREADS 200 if (sizeof(char*) == 4 && thread_count > UNSAFE_DEFAULT_LINUX_THREADS) { my_safe_printf_stderr( "You seem to be running 32-bit Linux and have " "%d concurrent connections.\n" "If you have not changed STACK_SIZE in LinuxThreads " "and built the binary \n" "yourself, LinuxThreads is quite likely to steal " "a part of the global heap for\n" "the thread stack. Please read " "http://dev.mysql.com/doc/mysql/en/linux-installation.html\n\n" thread_count); } #endif /* HAVE_LINUXTHREADS */ #ifdef HAVE_STACKTRACE THD *thd=current_thd; if (!(test_flags & TEST_NO_STACKTRACE)) { my_safe_printf_stderr("Thread pointer: 0x%p\n", thd); my_safe_printf_stderr("%s", "Attempting backtrace. You can use the following " "information to find out\n" "where mysqld died. If you see no messages after this, something went\n" "terribly wrong...\n"); my_print_stacktrace(thd ? (uchar*) thd->thread_stack : NULL, my_thread_stack_size); } if (thd) { const char *kreason= "UNKNOWN"; switch (thd->killed.load()) { case THD::NOT_KILLED: kreason= "NOT_KILLED"; break; case THD::KILL_BAD_DATA: kreason= "KILL_BAD_DATA"; break; case THD::KILL_CONNECTION: kreason= "KILL_CONNECTION"; break; case THD::KILL_QUERY: kreason= "KILL_QUERY"; break; case THD::KILL_TIMEOUT: kreason= "KILL_TIMEOUT"; break; case THD::KILLED_NO_VALUE: kreason= "KILLED_NO_VALUE"; break; case THD::ABORT_QUERY: kreason= "ABORT_QUERY"; break; } my_safe_printf_stderr("%s", "\n" "Trying to get some variables.\n" "Some pointers may be invalid and cause the dump to abort.\n"); thd->raw_query_buffer[thd->RAW_QUERY_BUFFER_LENGTH] = '\0'; my_safe_printf_stderr("Last run query buffer: %s\n", thd->raw_query_buffer); my_safe_printf_stderr("Query (%p): ", thd->query()); my_safe_print_str(thd->query(), MY_MIN(1024U, thd->query_length())); my_safe_printf_stderr("Connection ID (thread ID): %u\n", thd->thread_id()); my_safe_printf_stderr("Status: %s\n\n", kreason); } my_safe_printf_stderr("%s", "The manual page at " "http://dev.mysql.com/doc/mysql/en/crashing.html contains\n" "information that should help you find out what is causing the crash.\n"); #endif /* HAVE_STACKTRACE */ #ifdef HAVE_INITGROUPS if (calling_initgroups) { my_safe_printf_stderr("%s", "\n" "This crash occured while the server was calling initgroups(). This is\n" "often due to the use of a mysqld that is statically linked against \n" "glibc and configured to use LDAP in /etc/nsswitch.conf.\n" "You will need to either upgrade to a version of glibc that does not\n" "have this problem (2.3.4 or later when used with nscd),\n" "disable LDAP in your nsswitch.conf, or use a " "mysqld that is not statically linked.\n"); } #endif if (locked_in_memory) { my_safe_printf_stderr("%s", "\n" "The \"--memlock\" argument, which was enabled, " "uses system calls that are\n" "unreliable and unstable on some operating systems and " "operating-system versions (notably, some versions of Linux).\n" "This crash could be due to use of those buggy OS calls.\n" "You should consider whether you really need the " "\"--memlock\" parameter and/or consult the OS distributer about " "\"mlockall\" bugs.\n"); } #ifdef HAVE_WRITE_CORE if (opt_core_file) { my_safe_printf_stderr("%s", "Writing a core file\n"); my_write_core(sig); } #endif #ifndef __WIN__ /* Quit, without running destructors (etc.) On Windows, do not terminate, but pass control to exception filter. */ _exit(1); // Using _exit(), since exit() is not async signal safe #endif } /** * Extended handler for fatal signals. * * @param sig Signal number * @param info Detailed signal information * @param ctx Signal context including registers in uc_mcontext */ extern "C" sig_handler handle_fatal_signal_ex(int sig, siginfo_t *info, void *ctx) { /* Save detailed information on stack in volatile variables to make sure they are not optimized out. For reference on Intel, ucontext->uc_mcontext.gregs is an array of registers: R8 - R15 0 - 7 RAX 13 RDI 8 RCX 14 RSI 9 RSP 15 RBP 10 RIP 16 RBX 11 EFL 17 RDX 12 */ siginfo_t * volatile MY_ATTRIBUTE((unused)) siginfo = info; ucontext_t * volatile MY_ATTRIBUTE((unused)) ucontext = reinterpret_cast<ucontext_t *>(ctx); return handle_fatal_signal(sig); }
facebook/mysql-5.6
sql/signal_handler.cc
C++
gpl-2.0
9,684
/** * @file * @brief Monsters doing stuff (monsters acting). **/ #include "AppHdr.h" #include "mon-act.h" #include "areas.h" #include "arena.h" #include "artefact.h" #include "attitude-change.h" #include "beam.h" #include "cloud.h" #include "coordit.h" #include "dbg-scan.h" #include "delay.h" #include "dungeon.h" #include "effects.h" #include "env.h" #include "food.h" #include "fight.h" #include "fineff.h" #include "godpassive.h" #include "godprayer.h" #include "itemname.h" #include "itemprop.h" #include "items.h" #include "item_use.h" #include "libutil.h" #include "map_knowledge.h" #include "mapmark.h" #include "message.h" #include "misc.h" #include "mon-abil.h" #include "mon-behv.h" #include "mon-cast.h" #include "mon-death.h" #include "mon-iter.h" #include "mon-place.h" #include "mon-project.h" #include "mgen_data.h" #include "mon-stuff.h" #include "mon-util.h" #include "notes.h" #include "player.h" #include "random.h" #include "religion.h" #include "shopping.h" // for item values #include "spl-book.h" #include "spl-damage.h" #include "spl-summoning.h" #include "spl-util.h" #include "state.h" #include "stuff.h" #include "target.h" #include "teleport.h" #include "terrain.h" #include "throw.h" #include "traps.h" #include "hints.h" #include "view.h" #include "shout.h" static bool _handle_pickup(monster* mons); static void _mons_in_cloud(monster* mons); static void _heated_area(monster* mons); static bool _is_trap_safe(const monster* mons, const coord_def& where, bool just_check = false); static bool _monster_move(monster* mons); static spell_type _map_wand_to_mspell(wand_type kind); static void _shedu_movement_clamp(monster* mons); // [dshaligram] Doesn't need to be extern. static coord_def mmov; static const coord_def mon_compass[8] = { coord_def(-1,-1), coord_def(0,-1), coord_def(1,-1), coord_def(1,0), coord_def(1, 1), coord_def(0, 1), coord_def(-1,1), coord_def(-1,0) }; static int _compass_idx(const coord_def& mov) { for (int i = 0; i < 8; i++) if (mon_compass[i] == mov) return i; return -1; } static inline bool _mons_natural_regen_roll(monster* mons) { const int regen_rate = mons_natural_regen_rate(mons); return x_chance_in_y(regen_rate, 25); } // Do natural regeneration for monster. static void _monster_regenerate(monster* mons) { if (crawl_state.disables[DIS_MON_REGEN]) return; if (mons->has_ench(ENCH_SICK) || mons->has_ench(ENCH_DEATHS_DOOR) || (!mons_can_regenerate(mons) && !(mons->has_ench(ENCH_REGENERATION)))) { return; } // Non-land creatures out of their element cannot regenerate. if (mons_primary_habitat(mons) != HT_LAND && !monster_habitable_grid(mons, grd(mons->pos()))) { return; } if (monster_descriptor(mons->type, MDSC_REGENERATES) || (mons->type == MONS_FIRE_ELEMENTAL && (grd(mons->pos()) == DNGN_LAVA || cloud_type_at(mons->pos()) == CLOUD_FIRE)) || (mons->type == MONS_WATER_ELEMENTAL && feat_is_watery(grd(mons->pos()))) || (mons->type == MONS_AIR_ELEMENTAL && env.cgrid(mons->pos()) == EMPTY_CLOUD && one_chance_in(3)) || mons->has_ench(ENCH_REGENERATION) || mons->has_ench(ENCH_WITHDRAWN) || _mons_natural_regen_roll(mons)) { mons->heal(1); } } static void _escape_water_hold(monster* mons) { if (mons->has_ench(ENCH_WATER_HOLD)) { if (mons_habitat(mons) != HT_AMPHIBIOUS && mons_habitat(mons) != HT_WATER) { mons->speed_increment -= 5; } simple_monster_message(mons, " pulls free of the water."); mons->del_ench(ENCH_WATER_HOLD); } } static bool _swap_monsters(monster* mover, monster* moved) { // Can't swap with a stationary monster. // Although nominally stationary kraken tentacles can be swapped // with the main body. if (moved->is_stationary() && !moved->is_child_tentacle()) return false; // If the target monster is constricted it is stuck // and not eligible to be swapped with if (moved->is_constricted()) { dprf("%s fails to swap with %s, constricted.", mover->name(DESC_THE).c_str(), moved->name(DESC_THE).c_str()); return false; } // Swapping is a purposeful action. if (mover->confused()) return false; // Right now just happens in sanctuary. if (!is_sanctuary(mover->pos()) || !is_sanctuary(moved->pos())) return false; // A friendly or good-neutral monster moving past a fleeing hostile // or neutral monster, or vice versa. if (mover->wont_attack() == moved->wont_attack() || mons_is_retreating(mover) == mons_is_retreating(moved)) { return false; } // Don't swap places if the player explicitly ordered their pet to // attack monsters. if ((mover->friendly() || moved->friendly()) && you.pet_target != MHITYOU && you.pet_target != MHITNOT) { return false; } if (!mover->can_pass_through(moved->pos()) || !moved->can_pass_through(mover->pos())) { return false; } if (!monster_habitable_grid(mover, grd(moved->pos())) && !mover->can_cling_to(moved->pos()) || !monster_habitable_grid(moved, grd(mover->pos())) && !moved->can_cling_to(mover->pos())) { return false; } // Okay, we can do the swap. const coord_def mover_pos = mover->pos(); const coord_def moved_pos = moved->pos(); mover->set_position(moved_pos); moved->set_position(mover_pos); mover->clear_far_constrictions(); moved->clear_far_constrictions(); mover->check_clinging(true); moved->check_clinging(true); mgrd(mover->pos()) = mover->mindex(); mgrd(moved->pos()) = moved->mindex(); if (you.can_see(mover) && you.can_see(moved)) { mprf("%s and %s swap places.", mover->name(DESC_THE).c_str(), moved->name(DESC_THE).c_str()); } _escape_water_hold(mover); return true; } static bool _do_mon_spell(monster* mons, bolt &beem) { // Shapeshifters don't get spells. if (!mons->is_shapeshifter() || !mons->is_actual_spellcaster()) { if (handle_mon_spell(mons, beem)) { // If a Pan lord/pghost is known to be a spellcaster, it's safer // to assume it has ranged spells too. For others, it'd just // lead to unnecessary false positives. if (mons_is_ghost_demon(mons->type)) mons->flags |= MF_SEEN_RANGED; mmov.reset(); return true; } } return false; } static void _swim_or_move_energy(monster* mon, bool diag = false) { const dungeon_feature_type feat = grd(mon->pos()); // FIXME: Replace check with mons_is_swimming()? mon->lose_energy((feat >= DNGN_LAVA && feat <= DNGN_SHALLOW_WATER && mon->ground_level()) ? EUT_SWIM : EUT_MOVE, diag ? 10 : 1, diag ? 14 : 1); } static bool _unfriendly_or_insane(const monster* mon) { return !mon->wont_attack() || mon->has_ench(ENCH_INSANE); } // Check up to eight grids in the given direction for whether there's a // monster of the same alignment as the given monster that happens to // have a ranged attack. If this is true for the first monster encountered, // returns true. Otherwise returns false. static bool _ranged_allied_monster_in_dir(monster* mon, coord_def p) { coord_def pos = mon->pos(); for (int i = 1; i <= LOS_RADIUS; i++) { pos += p; if (!in_bounds(pos)) break; const monster* ally = monster_at(pos); if (ally == NULL) continue; if (mons_aligned(mon, ally)) { // Hostile monsters of normal intelligence only move aside for // monsters of the same type. if (mons_intel(mon) <= I_NORMAL && _unfriendly_or_insane(mon) && mons_genus(mon->type) != mons_genus(ally->type)) { return false; } if (mons_has_ranged_attack(ally)) return true; } break; } return false; } // Check whether there's a monster of the same type and alignment adjacent // to the given monster in at least one of three given directions (relative to // the monster position). static bool _allied_monster_at(monster* mon, coord_def a, coord_def b, coord_def c) { vector<coord_def> pos; pos.push_back(mon->pos() + a); pos.push_back(mon->pos() + b); pos.push_back(mon->pos() + c); for (unsigned int i = 0; i < pos.size(); i++) { if (!in_bounds(pos[i])) continue; const monster* ally = monster_at(pos[i]); if (ally == NULL) continue; if (ally->is_stationary() || ally->reach_range() > REACH_NONE) continue; // Hostile monsters of normal intelligence only move aside for // monsters of the same genus. if (mons_intel(mon) <= I_NORMAL && _unfriendly_or_insane(mon) && mons_genus(mon->type) != mons_genus(ally->type)) { continue; } if (mons_aligned(mon, ally)) return true; } return false; } // Altars as well as branch entrances are considered interesting for // some monster types. static bool _mon_on_interesting_grid(monster* mon) { // Patrolling shouldn't happen all the time. if (one_chance_in(4)) return false; const dungeon_feature_type feat = grd(mon->pos()); switch (feat) { // Holy beings will tend to patrol around altars to the good gods. case DNGN_ALTAR_ELYVILON: if (!one_chance_in(3)) return false; // else fall through case DNGN_ALTAR_ZIN: case DNGN_ALTAR_SHINING_ONE: return mon->is_holy(); // Orcs will tend to patrol around altars to Beogh, and guard the // stairway from and to the Orcish Mines. case DNGN_ALTAR_BEOGH: case DNGN_ENTER_ORCISH_MINES: case DNGN_RETURN_FROM_ORCISH_MINES: return mons_is_native_in_branch(mon, BRANCH_ORCISH_MINES); // Same for elves and the Elven Halls. case DNGN_ENTER_ELVEN_HALLS: case DNGN_RETURN_FROM_ELVEN_HALLS: return mons_is_native_in_branch(mon, BRANCH_ELVEN_HALLS); // Spiders... case DNGN_ENTER_SPIDER_NEST: return mons_is_native_in_branch(mon, BRANCH_SPIDER_NEST); // And the forest natives. case DNGN_ENTER_FOREST: return mons_is_native_in_branch(mon, BRANCH_FOREST); default: return false; } } // If a hostile monster finds itself on a grid of an "interesting" feature, // while unoccupied, it will remain in that area, and try to return to it // if it left it for fighting, seeking etc. static void _maybe_set_patrol_route(monster* mons) { if (mons_is_wandering(mons) && !mons->friendly() && !mons->is_patrolling() && _mon_on_interesting_grid(mons)) { mons->patrol_point = mons->pos(); } } static bool _mons_can_cast_dig(const monster* mons, bool random) { return (mons->foe != MHITNOT && mons->can_use_spells() && mons->has_spell(SPELL_DIG) && !mons->confused() && !(silenced(mons->pos()) || mons->has_ench(ENCH_MUTE)) && (!mons->has_ench(ENCH_ANTIMAGIC) || (random && x_chance_in_y(4 * BASELINE_DELAY, 4 * BASELINE_DELAY + mons->get_ench(ENCH_ANTIMAGIC).duration) || (!random && 4 * BASELINE_DELAY >= mons->get_ench(ENCH_ANTIMAGIC).duration)))); } static bool _mons_can_zap_dig(const monster* mons) { return (mons->foe != MHITNOT && !mons->asleep() && !mons->confused() // they don't get here anyway && !mons->submerged() && mons_itemuse(mons) >= MONUSE_STARTING_EQUIPMENT && mons->inv[MSLOT_WAND] != NON_ITEM && mitm[mons->inv[MSLOT_WAND]].base_type == OBJ_WANDS && mitm[mons->inv[MSLOT_WAND]].sub_type == WAND_DIGGING && mitm[mons->inv[MSLOT_WAND]].plus > 0); } static void _set_mons_move_dir(const monster* mons, coord_def* dir, coord_def* delta) { ASSERT(dir); ASSERT(delta); // Some calculations. if ((mons_class_flag(mons->type, M_BURROWS) || _mons_can_cast_dig(mons, false)) && mons->foe == MHITYOU) { // Boring beetles always move in a straight line in your // direction. *delta = you.pos() - mons->pos(); } else { *delta = (mons->firing_pos.zero() ? mons->target : mons->firing_pos) - mons->pos(); } // Move the monster. *dir = delta->sgn(); if (mons_is_retreating(mons) && mons->travel_target != MTRAV_WALL && (!mons->friendly() || mons->target != you.pos())) { *dir *= -1; } } static void _tweak_wall_mmov(const monster* mons, bool move_trees = false) { // The rock worm will try to move along through rock for as long as // possible. If the player is walking through a corridor, for example, // moving along in the wall beside him is much preferable to actually // leaving the wall. // This might cause the rock worm to take detours but it still // comes off as smarter than otherwise. // If we're already moving into a shielded spot, don't adjust move // (this leads to zig-zagging) if (feat_is_solid(grd(mons->pos() + mmov))) return; int dir = _compass_idx(mmov); ASSERT(dir != -1); // If we're already adjacent to our target and shielded, don't shift position. // If we're adjacent and unshielded, widen our search angle to include any // spot adjacent to both us and our target int range = 1; if (mons->target == mons->pos() + mmov) { if (feat_is_solid(grd(mons->pos()))) return; else { if (dir % 2 == 1) range = 2; } } int count = 0; int choice = dir; // stick with mmov if none are good for (int i = -range; i <= range; ++i) { const int altdir = (dir + i + 8) % 8; const coord_def t = mons->pos() + mon_compass[altdir]; const bool good = in_bounds(t) && (move_trees ? feat_is_tree(grd(t)) : feat_is_rock(grd(t)) && !feat_is_permarock(grd(t))); if (good && one_chance_in(++count)) choice = altdir; } mmov = mon_compass[choice]; } typedef FixedArray< bool, 3, 3 > move_array; static void _fill_good_move(const monster* mons, move_array* good_move) { for (int count_x = 0; count_x < 3; count_x++) for (int count_y = 0; count_y < 3; count_y++) { const int targ_x = mons->pos().x + count_x - 1; const int targ_y = mons->pos().y + count_y - 1; // Bounds check: don't consider moving out of grid! if (!in_bounds(targ_x, targ_y)) { (*good_move)[count_x][count_y] = false; continue; } (*good_move)[count_x][count_y] = mon_can_move_to_pos(mons, coord_def(count_x-1, count_y-1)); } } // This only tracks movement, not whether hitting an // adjacent monster is a possible move. bool mons_can_move_towards_target(const monster* mon) { coord_def mov, delta; _set_mons_move_dir(mon, &mov, &delta); move_array good_move; _fill_good_move(mon, &good_move); int dir = _compass_idx(mov); for (int i = -1; i <= 1; ++i) { const int altdir = (dir + i + 8) % 8; const coord_def p = mon_compass[altdir] + coord_def(1, 1); if (good_move(p)) return true; } return false; } //--------------------------------------------------------------- // // handle_movement // // Move the monster closer to its target square. // //--------------------------------------------------------------- static void _handle_movement(monster* mons) { _maybe_set_patrol_route(mons); // Monsters will try to flee out of a sanctuary. if (is_sanctuary(mons->pos()) && mons_is_influenced_by_sanctuary(mons) && !mons_is_fleeing_sanctuary(mons)) { mons_start_fleeing_from_sanctuary(mons); } else if (mons_is_fleeing_sanctuary(mons) && !is_sanctuary(mons->pos())) { // Once outside there's a chance they'll regain their courage. // Nonliving and berserking monsters always stop immediately, // since they're only being forced out rather than actually // scared. if (mons->holiness() == MH_NONLIVING || mons->berserk() || mons->has_ench(ENCH_INSANE) || x_chance_in_y(2, 5)) { mons_stop_fleeing_from_sanctuary(mons); } } coord_def delta; _set_mons_move_dir(mons, &mmov, &delta); // Don't allow monsters to enter a sanctuary or attack you inside a // sanctuary, even if you're right next to them. if (is_sanctuary(mons->pos() + mmov) && (!is_sanctuary(mons->pos()) || mons->pos() + mmov == you.pos())) { mmov.reset(); } // Bounds check: don't let fleeing monsters try to run off the grid. const coord_def s = mons->pos() + mmov; if (!in_bounds_x(s.x)) mmov.x = 0; if (!in_bounds_y(s.y)) mmov.y = 0; if (delta.rdist() > 3) { // Reproduced here is some semi-legacy code that makes monsters // move somewhat randomly along oblique paths. It is an // exceedingly good idea, given crawl's unique line of sight // properties. // // Added a check so that oblique movement paths aren't used when // close to the target square. -- bwr // Sometimes we'll just move parallel the x axis. if (abs(delta.x) > abs(delta.y) && coinflip()) mmov.y = 0; // Sometimes we'll just move parallel the y axis. if (abs(delta.y) > abs(delta.x) && coinflip()) mmov.x = 0; } // Now quit if we can't move. if (mmov.origin()) return; const coord_def newpos(mons->pos() + mmov); move_array good_move; _fill_good_move(mons, &good_move); // Make rock worms and dryads prefer shielded terrain. if (mons_wall_shielded(mons)) _tweak_wall_mmov(mons, mons->type == MONS_DRYAD); // If the monster is moving in your direction, whether to attack or // protect you, or towards a monster it intends to attack, check // whether we first need to take a step to the side to make sure the // reinforcement can follow through. Only do this with 50% chance, // though, so it's not completely predictable. // First, check whether the monster is smart enough to even consider // this. if ((newpos == you.pos() || monster_at(newpos) && mons->foe == mgrd(newpos)) && mons_intel(mons) >= I_ANIMAL && coinflip() && !mons_is_confused(mons) && !mons->caught() && !mons->berserk_or_insane()) { // If the monster is moving parallel to the x or y axis, check // whether // // a) the neighbouring grids are blocked // b) there are other unblocked grids adjacent to the target // c) there's at least one allied monster waiting behind us. // // (For really smart monsters, also check whether there's a // monster farther back in the corridor that has some kind of // ranged attack.) if (mmov.y == 0) { if (!good_move[1][0] && !good_move[1][2] && (good_move[mmov.x+1][0] || good_move[mmov.x+1][2]) && (_allied_monster_at(mons, coord_def(-mmov.x, -1), coord_def(-mmov.x, 0), coord_def(-mmov.x, 1)) || mons_intel(mons) >= I_NORMAL && _unfriendly_or_insane(mons) && _ranged_allied_monster_in_dir(mons, coord_def(-mmov.x, 0)))) { if (good_move[mmov.x+1][0]) mmov.y = -1; if (good_move[mmov.x+1][2] && (mmov.y == 0 || coinflip())) mmov.y = 1; } } else if (mmov.x == 0) { if (!good_move[0][1] && !good_move[2][1] && (good_move[0][mmov.y+1] || good_move[2][mmov.y+1]) && (_allied_monster_at(mons, coord_def(-1, -mmov.y), coord_def(0, -mmov.y), coord_def(1, -mmov.y)) || mons_intel(mons) >= I_NORMAL && _unfriendly_or_insane(mons) && _ranged_allied_monster_in_dir(mons, coord_def(0, -mmov.y)))) { if (good_move[0][mmov.y+1]) mmov.x = -1; if (good_move[2][mmov.y+1] && (mmov.x == 0 || coinflip())) mmov.x = 1; } } else // We're moving diagonally. { if (good_move[mmov.x+1][1]) { if (!good_move[1][mmov.y+1] && (_allied_monster_at(mons, coord_def(-mmov.x, -1), coord_def(-mmov.x, 0), coord_def(-mmov.x, 1)) || mons_intel(mons) >= I_NORMAL && _unfriendly_or_insane(mons) && _ranged_allied_monster_in_dir(mons, coord_def(-mmov.x, -mmov.y)))) { mmov.y = 0; } } else if (good_move[1][mmov.y+1] && (_allied_monster_at(mons, coord_def(-1, -mmov.y), coord_def(0, -mmov.y), coord_def(1, -mmov.y)) || mons_intel(mons) >= I_NORMAL && _unfriendly_or_insane(mons) && _ranged_allied_monster_in_dir(mons, coord_def(-mmov.x, -mmov.y)))) { mmov.x = 0; } } } // Now quit if we can't move. if (mmov.origin()) return; // Try to stay in sight of the player if we're moving towards // him/her, in order to avoid the monster coming into view, // shouting, and then taking a step in a path to the player which // temporarily takes it out of view, which can lead to the player // getting "comes into view" and shout messages with no monster in // view. // Doesn't matter for arena mode. if (crawl_state.game_is_arena()) return; // Did we just come into view? // TODO: This doesn't seem to work right. Fix, or remove? if (mons->seen_context != SC_JUST_SEEN) return; if (testbits(mons->flags, MF_WAS_IN_VIEW)) return; const coord_def old_pos = mons->pos(); const int old_dist = grid_distance(you.pos(), old_pos); // We're already staying in the player's LOS. if (you.see_cell(old_pos + mmov)) return; // We're not moving towards the player. if (grid_distance(you.pos(), old_pos + mmov) >= old_dist) { // Instead of moving out of view, we stay put. if (you.see_cell(old_pos)) mmov.reset(); return; } // Try to find a move that brings us closer to the player while // keeping us in view. int matches = 0; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) { if (i == 0 && j == 0) continue; if (!good_move[i][j]) continue; coord_def d(i - 1, j - 1); coord_def tmp = old_pos + d; if (grid_distance(you.pos(), tmp) < old_dist && you.see_cell(tmp)) { if (one_chance_in(++matches)) mmov = d; break; } } // We haven't been able to find a visible cell to move to. If previous // position was visible, we stay put. if (you.see_cell(old_pos) && !you.see_cell(old_pos + mmov)) mmov.reset(); } //--------------------------------------------------------------- // // _handle_potion // // Give the monster a chance to quaff a potion. Returns true if // the monster imbibed. // //--------------------------------------------------------------- static bool _handle_potion(monster* mons, bolt & beem) { if (mons->asleep() || mons->inv[MSLOT_POTION] == NON_ITEM || !one_chance_in(3)) { return false; } if (mons_itemuse(mons) < MONUSE_STARTING_EQUIPMENT) return false; // Make sure the item actually is a potion. if (mitm[mons->inv[MSLOT_POTION]].base_type != OBJ_POTIONS) return false; bool rc = false; const int potion_idx = mons->inv[MSLOT_POTION]; item_def& potion = mitm[potion_idx]; const potion_type ptype = static_cast<potion_type>(potion.sub_type); if (mons->can_drink_potion(ptype) && mons->should_drink_potion(ptype)) { const bool was_visible = you.can_see(mons); // Drink the potion. const item_type_id_state_type id = mons->drink_potion_effect(ptype); // Give ID if necessary. if (was_visible && id != ID_UNKNOWN_TYPE) set_ident_type(OBJ_POTIONS, ptype, id); // Remove it from inventory. if (dec_mitm_item_quantity(potion_idx, 1)) mons->inv[MSLOT_POTION] = NON_ITEM; else if (is_blood_potion(potion)) remove_oldest_blood_potion(potion); mons->lose_energy(EUT_ITEM); rc = true; } return rc; } static bool _handle_evoke_equipment(monster* mons, bolt & beem) { // TODO: check non-ring, non-amulet equipment if (mons->asleep() || mons->inv[MSLOT_JEWELLERY] == NON_ITEM || !one_chance_in(3)) { return false; } if (mons_itemuse(mons) < MONUSE_STARTING_EQUIPMENT) return false; // Make sure the item actually is a ring or amulet. if (mitm[mons->inv[MSLOT_JEWELLERY]].base_type != OBJ_JEWELLERY) return false; bool rc = false; const int jewellery_idx = mons->inv[MSLOT_JEWELLERY]; item_def& jewellery = mitm[jewellery_idx]; const jewellery_type jtype = static_cast<jewellery_type>(jewellery.sub_type); if (mons->can_evoke_jewellery(jtype) && mons->should_evoke_jewellery(jtype)) { const bool was_visible = you.can_see(mons); // Drink the potion. const item_type_id_state_type id = mons->evoke_jewellery_effect(jtype); // Give ID if necessary. if (was_visible && id != ID_UNKNOWN_TYPE) set_ident_type(OBJ_JEWELLERY, jtype, id); mons->lose_energy(EUT_ITEM); rc = true; } return rc; } static bool _handle_reaching(monster* mons) { bool ret = false; const reach_type range = mons->reach_range(); actor *foe = mons->get_foe(); if (!foe || range <= REACH_NONE) return false; if (is_sanctuary(mons->pos()) || is_sanctuary(foe->pos())) return false; if (mons->submerged()) return false; if (mons_aligned(mons, foe) && !mons->has_ench(ENCH_INSANE)) return false; // Greatly lowered chances if the monster is fleeing or pacified and // leaving the level. if ((mons_is_fleeing(mons) || mons->pacified()) && !one_chance_in(8)) return false; const coord_def foepos(foe->pos()); const coord_def delta(foepos - mons->pos()); const int grid_distance(delta.rdist()); const coord_def first_middle(mons->pos() + delta / 2); const coord_def second_middle(foepos - delta / 2); if (grid_distance == 2 // The monster has to be attacking the correct position. && mons->target == foepos // With a reaching attack with a large enough range: && delta.abs() <= range // And with no dungeon furniture in the way of the reaching // attack; && (feat_is_reachable_past(grd(first_middle)) || feat_is_reachable_past(grd(second_middle))) // The foe should be on the map (not stepped from time). && in_bounds(foepos)) { ret = true; ASSERT(foe->is_player() || foe->is_monster()); fight_melee(mons, foe); if (mons->alive()) { // Player saw the item reach. item_def *wpn = mons->weapon(0); if (wpn && !is_artefact(*wpn) && you.can_see(mons) // Don't auto-identify polearm brands && get_weapon_brand(*wpn) == SPWPN_REACHING) { set_ident_flags(*wpn, ISFLAG_KNOW_TYPE); } } } return ret; } //--------------------------------------------------------------- // // handle_scroll // // Give the monster a chance to read a scroll. Returns true if // the monster read something. // //--------------------------------------------------------------- static bool _handle_scroll(monster* mons) { // Yes, there is a logic to this ordering {dlb}: if (mons->asleep() || mons_is_confused(mons) || mons->submerged() || mons->inv[MSLOT_SCROLL] == NON_ITEM || mons->has_ench(ENCH_BLIND) || !one_chance_in(3)) { return false; } if (mons_itemuse(mons) < MONUSE_STARTING_EQUIPMENT) return false; if (silenced(mons->pos())) return false; // Make sure the item actually is a scroll. if (mitm[mons->inv[MSLOT_SCROLL]].base_type != OBJ_SCROLLS) return false; bool read = false; item_type_id_state_type ident = ID_UNKNOWN_TYPE; bool was_visible = you.can_see(mons); // Notice how few cases are actually accounted for here {dlb}: const int scroll_type = mitm[mons->inv[MSLOT_SCROLL]].sub_type; switch (scroll_type) { case SCR_TELEPORTATION: if (!mons->has_ench(ENCH_TP) && !mons->no_tele(true, false)) { if (mons->caught() || mons_is_fleeing(mons) || mons->pacified()) { simple_monster_message(mons, " reads a scroll."); read = true; ident = ID_KNOWN_TYPE; monster_teleport(mons, false); } } break; case SCR_BLINKING: if ((mons->caught() || mons_is_fleeing(mons) || mons->pacified()) && mons_near(mons) && !mons->no_tele(true, false)) { simple_monster_message(mons, " reads a scroll."); read = true; if (mons->caught()) { ident = ID_KNOWN_TYPE; monster_blink(mons); } else if (blink_away(mons)) ident = ID_KNOWN_TYPE; } break; case SCR_SUMMONING: if (mons_near(mons)) { simple_monster_message(mons, " reads a scroll."); mprf("Wisps of shadow swirl around %s.", mons->name(DESC_THE).c_str()); read = true; int count = roll_dice(2, 2); for (int i = 0; i < count; ++i) { create_monster( mgen_data(RANDOM_MOBILE_MONSTER, SAME_ATTITUDE(mons), mons, 3, SPELL_SHADOW_CREATURES, mons->pos(), mons->foe, 0, GOD_NO_GOD)); } ident = ID_KNOWN_TYPE; } break; } if (read) { if (dec_mitm_item_quantity(mons->inv[MSLOT_SCROLL], 1)) mons->inv[MSLOT_SCROLL] = NON_ITEM; if (ident != ID_UNKNOWN_TYPE && was_visible) set_ident_type(OBJ_SCROLLS, scroll_type, ident); mons->lose_energy(EUT_ITEM); } return read; } static int _generate_rod_power(monster *mons, int overriding_power = 0) { // power is actually 5 + Evocations + 2d(Evocations) // modified by shield and shield skill int shield_num = 1; int shield_den = 1; int shield_base = 1; if (mons->inv[MSLOT_SHIELD] != NON_ITEM) { item_def *shield = mons->mslot_item(MSLOT_SHIELD); switch (shield->sub_type) { case ARM_BUCKLER: shield_base += 4; break; case ARM_SHIELD: shield_base += 2; break; case ARM_LARGE_SHIELD: shield_base++; break; default: break; } } const int power_base = mons->skill(SK_EVOCATIONS); int power = 5 + power_base + (2 * random2(power_base)); if (shield_base > 1) { const int shield_mod = ((power / shield_base) * shield_num) / shield_den; power -= shield_mod; } if (overriding_power > 0) power = overriding_power; return power; } static bolt& _generate_item_beem(bolt &beem, bolt& from, monster* mons) { beem.name = from.name; beem.beam_source = mons->mindex(); beem.source = mons->pos(); beem.colour = from.colour; beem.range = from.range; beem.damage = from.damage; beem.ench_power = from.ench_power; beem.hit = from.hit; beem.glyph = from.glyph; beem.flavour = from.flavour; beem.thrower = from.thrower; beem.is_beam = from.is_beam; beem.is_explosion = from.is_explosion; return beem; } static bool _setup_wand_beam(bolt& beem, monster* mons) { item_def &wand(mitm[mons->inv[MSLOT_WAND]]); // map wand type to monster spell type const spell_type mzap = _map_wand_to_mspell((wand_type)wand.sub_type); if (mzap == SPELL_NO_SPELL) return false; // set up the beam int power = 30 + mons->hit_dice; bolt theBeam = mons_spell_beam(mons, mzap, power); beem = _generate_item_beem(beem, theBeam, mons); beem.aux_source = wand.name(DESC_QUALNAME, false, true, false, false); return true; } static void _mons_fire_wand(monster* mons, item_def &wand, bolt &beem, bool was_visible, bool niceWand) { if (!simple_monster_message(mons, " zaps a wand.")) { if (!silenced(you.pos())) mpr("You hear a zap.", MSGCH_SOUND); } // charge expenditure {dlb} wand.plus--; beem.is_tracer = false; beem.fire(); if (was_visible) { const int wand_type = wand.sub_type; if (niceWand || !beem.is_enchantment() || beem.obvious_effect) { set_ident_type(OBJ_WANDS, wand_type, ID_KNOWN_TYPE); mons->props["wand_known"] = true; } else { set_ident_type(OBJ_WANDS, wand_type, ID_MON_TRIED_TYPE); mons->props["wand_known"] = false; } // Increment zap count. if (wand.plus2 >= 0) wand.plus2++; mons->flags |= MF_SEEN_RANGED; } mons->lose_energy(EUT_ITEM); } static void _rod_fired_pre(monster* mons) { make_mons_stop_fleeing(mons); if (!simple_monster_message(mons, " zaps a rod.") && !silenced(you.pos())) { mpr("You hear a zap.", MSGCH_SOUND); } } static bool _rod_fired_post(monster* mons, item_def &rod, int idx, bolt &beem, int rate, bool was_visible) { rod.plus -= rate; dprf("rod charge: %d, %d", rod.plus, rod.plus2); if (was_visible) { if (!beem.is_enchantment() || beem.obvious_effect) set_ident_flags(rod, ISFLAG_KNOW_TYPE); } mons->lose_energy(EUT_ITEM); return true; } static bool _get_rod_spell_and_cost(const item_def& rod, spell_type& spell, int& cost) { bool success = false; for (int i = 0; i < SPELLBOOK_SIZE; ++i) { spell_type s = which_spell_in_book(rod, i); int c = spell_difficulty(spell) * ROD_CHARGE_MULT; if (s == SPELL_NO_SPELL || rod.plus < c) continue; success = true; spell = s; cost = c; if (one_chance_in(SPELLBOOK_SIZE - i + 1)) break; } return success; } static bool _thunderbolt_tracer(monster *caster, int pow, coord_def aim) { coord_def prev; if (caster->props.exists("thunderbolt_last") && caster->props["thunderbolt_last"].get_int() + 1 == you.num_turns) { prev = caster->props["thunderbolt_aim"].get_coord(); } targetter_thunderbolt hitfunc(caster, spell_range(SPELL_THUNDERBOLT, pow), prev); hitfunc.set_aim(aim); mon_attitude_type castatt = caster->temp_attitude(); int friendly = 0, enemy = 0; for (map<coord_def, aff_type>::const_iterator p = hitfunc.zapped.begin(); p != hitfunc.zapped.end(); ++p) { if (p->second <= 0) continue; const actor *victim = actor_at(p->first); if (!victim) continue; int dam = 4 >> victim->res_elec(); if (mons_atts_aligned(castatt, victim->temp_attitude())) friendly += dam; else enemy += dam; } return enemy > friendly; return false; } // handle_rod // -- implemented as a dependent to handle_wand currently // (no wand + rod turns this way) // notes: // shamelessly repurposing handle_wand code // not one word about the name of this function! static bool _handle_rod(monster *mons, bolt &beem) { const int weapon = mons->inv[MSLOT_WEAPON]; item_def &rod(mitm[weapon]); // Make sure the item actually is a rod. ASSERT(rod.base_type == OBJ_RODS); // was the player visible when we started? bool was_visible = you.can_see(mons); bool check_validity = true; bool is_direct_effect = false; spell_type mzap = SPELL_NO_SPELL; int rate = 0; if (!_get_rod_spell_and_cost(rod, mzap, rate)) return false; // XXX: There should be a better way to do this than hardcoding // monster-castable rod spells! switch (mzap) { case SPELL_BOLT_OF_FIRE: case SPELL_BOLT_OF_INACCURACY: case SPELL_IRON_SHOT: case SPELL_LIGHTNING_BOLT: case SPELL_POISON_ARROW: case SPELL_THROW_FLAME: case SPELL_THROW_FROST: break; case SPELL_FIREBALL: if (mons->foe_distance() < 2) return false; break; case SPELL_FREEZING_CLOUD: case SPELL_POISONOUS_CLOUD: if (mons->foe_distance() <= 2) return false; break; case SPELL_THUNDERBOLT: if (mons->props.exists("thunderbolt_last") && mons->props["thunderbolt_last"].get_int() + 1 == you.num_turns) { rate = min(5 * ROD_CHARGE_MULT, (int)rod.plus); mons->props["thunderbolt_mana"].get_int() = rate; } break; case SPELL_CALL_IMP: case SPELL_CAUSE_FEAR: case SPELL_SUMMON_DEMON: case SPELL_SUMMON_SWARM: case SPELL_OLGREBS_TOXIC_RADIANCE: _rod_fired_pre(mons); mons_cast(mons, beem, mzap, false); _rod_fired_post(mons, rod, weapon, beem, rate, was_visible); return true; default: return false; } bool zap = false; // set up the beam const int power = max(_generate_rod_power(mons), 1); dprf("using rod with power %d", power); bolt theBeam = mons_spell_beam(mons, mzap, power, check_validity); beem = _generate_item_beem(beem, theBeam, mons); beem.aux_source = rod.name(DESC_QUALNAME, false, true, false, false); if (mons->confused()) { beem.target = dgn_random_point_from(mons->pos(), LOS_RADIUS); if (beem.target.origin()) return false; zap = true; } else if (mzap == SPELL_THUNDERBOLT) zap = _thunderbolt_tracer(mons, power, beem.target); else { fire_tracer(mons, beem); zap = mons_should_fire(beem); } if (is_direct_effect) { actor* foe = mons->get_foe(); if (!foe) return false; _rod_fired_pre(mons); direct_effect(mons, mzap, beem, foe); return _rod_fired_post(mons, rod, weapon, beem, rate, was_visible); } else if (mzap == SPELL_THUNDERBOLT) { _rod_fired_pre(mons); cast_thunderbolt(mons, power, beem.target); return _rod_fired_post(mons, rod, weapon, beem, rate, was_visible); } else if (zap) { _rod_fired_pre(mons); beem.is_tracer = false; beem.fire(); return _rod_fired_post(mons, rod, weapon, beem, rate, was_visible); } return false; } //--------------------------------------------------------------- // // handle_wand // // Give the monster a chance to zap a wand or rod. Returns true // if the monster zapped. // //--------------------------------------------------------------- static bool _handle_wand(monster* mons, bolt &beem) { // Yes, there is a logic to this ordering {dlb}: // FIXME: monsters should be able to use wands or rods // out of sight of the player [rob] if (!mons_near(mons) || mons->asleep() || mons->has_ench(ENCH_SUBMERGED) || coinflip()) { return false; } if (mons_itemuse(mons) < MONUSE_STARTING_EQUIPMENT) return false; if (mons->inv[MSLOT_WEAPON] != NON_ITEM && mitm[mons->inv[MSLOT_WEAPON]].base_type == OBJ_RODS) { return _handle_rod(mons, beem); } if (mons->inv[MSLOT_WAND] == NON_ITEM || mitm[mons->inv[MSLOT_WAND]].plus <= 0) { return false; } // Make sure the item actually is a wand. if (mitm[mons->inv[MSLOT_WAND]].base_type != OBJ_WANDS) return false; bool niceWand = false; bool zap = false; bool was_visible = you.can_see(mons); if (!_setup_wand_beam(beem, mons)) return false; item_def &wand = mitm[mons->inv[MSLOT_WAND]]; const wand_type kind = (wand_type)wand.sub_type; switch (kind) { case WAND_DISINTEGRATION: // Dial down damage from wands of disintegration, since // disintegration beams can do large amounts of damage. beem.damage.size = beem.damage.size * 2 / 3; break; case WAND_ENSLAVEMENT: case WAND_RANDOM_EFFECTS: // These have been deemed "too tricky" at this time {dlb}: return false; case WAND_DIGGING: // This is handled elsewhere. return false; // These are wands that monsters will aim at themselves {dlb}: case WAND_HASTING: if (!mons->has_ench(ENCH_HASTE)) { beem.target = mons->pos(); niceWand = true; break; } return false; case WAND_HEAL_WOUNDS: if (mons->hit_points <= mons->max_hit_points / 2) { beem.target = mons->pos(); niceWand = true; break; } return false; case WAND_INVISIBILITY: if (!mons->has_ench(ENCH_INVIS) && !mons->has_ench(ENCH_SUBMERGED) && !mons->glows_naturally() && (!mons->friendly() || you.can_see_invisible(false))) { beem.target = mons->pos(); niceWand = true; break; } return false; case WAND_TELEPORTATION: if (mons->hit_points <= mons->max_hit_points / 2 || mons->caught()) { if (!mons->has_ench(ENCH_TP) && !one_chance_in(20)) { beem.target = mons->pos(); niceWand = true; break; } // This break causes the wand to be tried on the player. break; } return false; default: break; } if (mons->confused()) { beem.target = dgn_random_point_from(mons->pos(), LOS_RADIUS); if (beem.target.origin()) return false; zap = true; } else if (!niceWand) { // Fire tracer, if necessary. fire_tracer(mons, beem); // Good idea? zap = mons_should_fire(beem); } if (niceWand || zap) { if (!niceWand) make_mons_stop_fleeing(mons); _mons_fire_wand(mons, wand, beem, was_visible, niceWand); return true; } return false; } static bool _mons_has_launcher(const monster* mons) { for (int i = MSLOT_WEAPON; i <= MSLOT_ALT_WEAPON; ++i) { if (item_def *item = mons->mslot_item(static_cast<mon_inv_type>(i))) { if (is_range_weapon(*item)) return true; } } return false; } //--------------------------------------------------------------- // // handle_throw // // Give the monster a chance to throw something. Returns true if // the monster hurled. // //--------------------------------------------------------------- static bool _handle_throw(monster* mons, bolt & beem) { // Yes, there is a logic to this ordering {dlb}: if (mons->incapacitated() || mons->submerged()) { return false; } if (mons_itemuse(mons) < MONUSE_STARTING_EQUIPMENT && mons->type != MONS_SPECTRAL_THING) { return false; } bool archer = mons->is_archer(); const bool liquefied = mons->liquefied_ground(); // Highly-specialised archers are more likely to shoot than talk. (?) // If we're standing on liquefied ground, try to stand and fire! // (Particularly archers.) if ((liquefied && !archer && one_chance_in(9)) || (!liquefied && one_chance_in(archer ? 9 : 5))) return false; if (mons_class_flag(mons->type, M_STABBER) && mons->get_foe() != NULL) { // Stabbers going in for the kill don't use ranged attacks. if (mons->get_foe()->incapacitated()) return false; // But assassins WILL use their blowguns in melee range, if their foe is // not already incapacitated and they have useful ammo left. else if (mons_has_incapacitating_ranged_attack(mons, mons->get_foe())) archer = true; } // Don't allow offscreen throwing for now. if (mons->foe == MHITYOU && !mons_near(mons)) return false; // Monsters won't shoot in melee range, largely for balance reasons. // Specialist archers are an exception to this rule. if (!archer && adjacent(beem.target, mons->pos())) return false; // If the monster is a spellcaster, don't bother throwing stuff. // Exception: Spellcasters that already start out with some kind // ranged weapon. Seeing how monsters are disallowed from picking // up launchers if they have ranged spells, this will only apply // to very few monsters. if (mons_has_ranged_spell(mons, true, false) && !_mons_has_launcher(mons)) { return false; } // Greatly lowered chances if the monster is fleeing or pacified and // leaving the level. if ((mons_is_fleeing(mons) || mons->pacified()) && !one_chance_in(8)) { return false; } item_def *launcher = NULL; const item_def *weapon = NULL; const int mon_item = mons_pick_best_missile(mons, &launcher); if (mon_item == NON_ITEM || !mitm[mon_item].defined()) return false; if (player_or_mon_in_sanct(mons)) return false; item_def *missile = &mitm[mon_item]; const actor *act = actor_at(beem.target); if (missile->base_type == OBJ_MISSILES && missile->sub_type == MI_THROWING_NET && act) { // Throwing a net at a target that is already caught would be // completely useless, so bail out. if (act->caught()) return false; // Netting targets that are already permanently stuck in place // is similarly useless. if (mons_class_is_stationary(act->type)) return false; } // If the attack needs a launcher that we can't wield, bail out. if (launcher) { weapon = mons->mslot_item(MSLOT_WEAPON); if (weapon && weapon != launcher && weapon->cursed()) return false; } // Ok, we'll try it. setup_monster_throw_beam(mons, beem); // Set fake damage for the tracer. beem.damage = dice_def(10, 10); // Set item for tracer, even though it probably won't be used beem.item = missile; // Fire tracer. fire_tracer(mons, beem); // Clear fake damage (will be set correctly in mons_throw). beem.damage = 0; // Good idea? if (mons_should_fire(beem)) { // Monsters shouldn't shoot if fleeing, so let them "turn to attack". make_mons_stop_fleeing(mons); if (launcher && launcher != weapon) mons->swap_weapons(); beem.name.clear(); return mons_throw(mons, beem, mon_item); } return false; } // Give the monster its action energy (aka speed_increment). static void _monster_add_energy(monster* mons) { if (mons->speed > 0) { // Randomise to make counting off monster moves harder: const int energy_gained = max(1, div_rand_round(mons->speed * you.time_taken, 10)); mons->speed_increment += energy_gained; } } #ifdef DEBUG # define DEBUG_ENERGY_USE(problem) \ if (mons->speed_increment == old_energy && mons->alive()) \ mprf(MSGCH_DIAGNOSTICS, \ problem " for monster '%s' consumed no energy", \ mons->name(DESC_PLAIN).c_str()); #else # define DEBUG_ENERGY_USE(problem) ((void) 0) #endif static void _confused_move_dir(monster *mons) { mmov.reset(); int pfound = 0; for (adjacent_iterator ai(mons->pos(), false); ai; ++ai) if (mons->can_pass_through(*ai)) { // Highly intelligent monsters don't move if they might drown. if (mons_intel(mons) == I_HIGH && !mons->is_habitable(*ai)) { // Players without a spoiler sheet have no way to know which // monsters are I_HIGH, and this behaviour is obscure. // Thus, give a message. const string where = make_stringf("%s@%d,%d", level_id::current().describe().c_str(), mons->pos().x, mons->pos().y); if (!mons->props.exists("no_conf_move") || mons->props["no_conf_move"].get_string() != where) { // But don't spam. mons->props["no_conf_move"] = where; simple_monster_message(mons, make_stringf(" stays still, afraid of the %s.", feat_type_name(grd(*ai))).c_str()); } mmov.reset(); break; } else if (one_chance_in(++pfound)) mmov = *ai - mons->pos(); } } static int _tentacle_move_speed(monster_type type) { if (type == MONS_KRAKEN) return 10; else if (type == MONS_TENTACLED_STARSPAWN) return 18; else return 0; } static void _pre_monster_move(monster* mons) { mons->hit_points = min(mons->max_hit_points, mons->hit_points); if (mons->type == MONS_SPATIAL_MAELSTROM && !player_in_branch(BRANCH_ABYSS) && !player_in_branch(BRANCH_ZIGGURAT)) { for (int i = 0; i < you.time_taken; ++i) { if (one_chance_in(100)) { mons->banish(mons); return; } } } if (mons->type == MONS_SNAPLASHER_VINE && mons->props.exists("vine_awakener")) { monster* awakener = monster_by_mid(mons->props["vine_awakener"].get_int()); if (awakener && !awakener->can_see(mons)) { simple_monster_message(mons, " falls limply to the ground."); monster_die(mons, KILL_RESET, NON_MONSTER); return; } } if (mons_stores_tracking_data(mons)) { actor* foe = mons->get_foe(); if (foe) { if (!mons->props.exists("foe_pos")) mons->props["foe_pos"].get_coord() = foe->pos(); else { if (mons->props["foe_pos"].get_coord().distance_from(mons->pos()) > foe->pos().distance_from(mons->pos())) mons->props["foe_approaching"].get_bool() = true; else mons->props["foe_approaching"].get_bool() = false; mons->props["foe_pos"].get_coord() = foe->pos(); } } else mons->props.erase("foe_pos"); } reset_battlesphere(mons); reset_spectral_weapon(mons); // This seems to need to go here to actually get monsters to slow down. // XXX: Replace with a new ENCH_LIQUEFIED_GROUND or something. if (mons->liquefied_ground()) { mon_enchant me = mon_enchant(ENCH_SLOW, 0, 0, 20); if (mons->has_ench(ENCH_SLOW)) mons->update_ench(me); else mons->add_ench(me); mons->calc_speed(); } fedhas_neutralise(mons); // Monster just summoned (or just took stairs), skip this action. if (!mons_is_mimic(mons->type) && testbits(mons->flags, MF_JUST_SUMMONED)) { mons->flags &= ~MF_JUST_SUMMONED; return; } mon_acting mact(mons); // Mimics get enough energy to act immediately when revealed. if (mons_is_mimic(mons->type) && testbits(mons->flags, MF_JUST_SUMMONED)) { mons->speed_increment = 80; mons->flags &= ~MF_JUST_SUMMONED; } else _monster_add_energy(mons); // Handle clouds on nonmoving monsters. if (mons->speed == 0) { _mons_in_cloud(mons); // Update constriction durations mons->accum_has_constricted(); _heated_area(mons); if (mons->type == MONS_NO_MONSTER) return; } // Apply monster enchantments once for every normal-speed // player turn. mons->ench_countdown -= you.time_taken; while (mons->ench_countdown < 0) { mons->ench_countdown += 10; mons->apply_enchantments(); // If the monster *merely* died just break from the loop // rather than quit altogether, since we have to deal with // giant spores and ball lightning exploding at the end of the // function, but do return if the monster's data has been // reset, since then the monster type is invalid. if (mons->type == MONS_NO_MONSTER) return; else if (mons->hit_points < 1) break; } // Memory is decremented here for a reason -- we only want it // decrementing once per monster "move". if (mons->foe_memory > 0 && !you.penance[GOD_ASHENZARI] && !mons_class_flag(mons->type, M_VIGILANT)) { mons->foe_memory -= you.time_taken; } // Otherwise there are potential problems with summonings. if (mons->type == MONS_GLOWING_SHAPESHIFTER) mons->add_ench(ENCH_GLOWING_SHAPESHIFTER); if (mons->type == MONS_SHAPESHIFTER) mons->add_ench(ENCH_SHAPESHIFTER); // We reset batty monsters from wander to seek here, instead // of in handle_behaviour() since that will be called with // every single movement, and we want these monsters to // hit and run. -- bwr if (mons->foe != MHITNOT && mons_is_wandering(mons) && mons_is_batty(mons)) { mons->behaviour = BEH_SEEK; } mons->check_speed(); } void handle_monster_move(monster* mons) { const monsterentry* entry = get_monster_data(mons->type); if (!entry) return; int old_energy = mons->speed_increment; int non_move_energy = min(entry->energy_usage.move, entry->energy_usage.swim); #ifdef DEBUG_MONS_SCAN bool monster_was_floating = mgrd(mons->pos()) != mons->mindex(); #endif coord_def old_pos = mons->pos(); coord_def kraken_last_update = mons->pos(); if (!mons->has_action_energy()) return; move_solo_tentacle(mons); if (!mons->alive()) return; if (old_pos != mons->pos() && mons_is_tentacle_head(mons_base_type(mons))) { move_child_tentacles(mons); kraken_last_update = mons->pos(); } old_pos = mons->pos(); #ifdef DEBUG_MONS_SCAN if (!monster_was_floating && mgrd(mons->pos()) != mons->mindex()) { mprf(MSGCH_ERROR, "Monster %s became detached from mgrd " "in handle_monster_move() loop", mons->name(DESC_PLAIN, true).c_str()); mpr("[[[[[[[[[[[[[[[[[[", MSGCH_WARN); debug_mons_scan(); mpr("]]]]]]]]]]]]]]]]]]", MSGCH_WARN); monster_was_floating = true; } else if (monster_was_floating && mgrd(mons->pos()) == mons->mindex()) { mprf(MSGCH_DIAGNOSTICS, "Monster %s re-attached itself to mgrd " "in handle_monster_move() loop", mons->name(DESC_PLAIN, true).c_str()); monster_was_floating = false; } #endif if (mons->is_projectile()) { if (iood_act(*mons)) return; mons->lose_energy(EUT_MOVE); return; } if (mons->type == MONS_BATTLESPHERE) { if (fire_battlesphere(mons)) mons->lose_energy(EUT_SPECIAL); } if (mons->type == MONS_FULMINANT_PRISM) { ++mons->number; if (mons->number == 2) mons->suicide(); else { if (player_can_hear(mons->pos())) { if (you.can_see(mons)) { simple_monster_message(mons, " crackles loudly.", MSGCH_WARN); } else mpr("You hear a loud crackle.", MSGCH_SOUND); } // Done this way to keep the detonation timer predictable mons->speed_increment -= 10; } return; } mons->shield_blocks = 0; const int cloud_num = env.cgrid(mons->pos()); const bool avoid_cloud = mons_avoids_cloud(mons, cloud_num); _mons_in_cloud(mons); _heated_area(mons); if (!mons->alive()) return; slime_wall_damage(mons, speed_to_duration(mons->speed)); if (!mons->alive()) return; if (mons->type == MONS_TIAMAT && one_chance_in(3)) draconian_change_colour(mons); _monster_regenerate(mons); if (mons->cannot_act() || mons->type == MONS_SIXFIRHY // these move only 8 of 24 turns && ++mons->number / 8 % 3 != 2 // but are not helpless || mons->type == MONS_JIANGSHI // similarly, but more irregular (48 of 90) && (++mons->number / 6 % 3 == 1 || mons->number / 3 % 5 == 1)) { mons->speed_increment -= non_move_energy; return; } if (mons->has_ench(ENCH_DAZED) && one_chance_in(5)) { simple_monster_message(mons, " is lost in a daze."); mons->speed_increment -= non_move_energy; return; } if (crawl_state.disables[DIS_MON_ACT] && _unfriendly_or_insane(mons)) { mons->speed_increment -= non_move_energy; return; } handle_behaviour(mons); // handle_behaviour() could make the monster leave the level. if (!mons->alive()) return; ASSERT(!crawl_state.game_is_arena() || mons->foe != MHITYOU); ASSERT_IN_BOUNDS_OR_ORIGIN(mons->target); // Submerging monsters will hide from clouds. if (avoid_cloud && monster_can_submerge(mons, grd(mons->pos())) && !mons->caught() && !mons->submerged()) { mons->add_ench(ENCH_SUBMERGED); mons->speed_increment -= ENERGY_SUBMERGE(entry); return; } if (mons->speed >= 100) { mons->speed_increment -= non_move_energy; return; } if (igrd(mons->pos()) != NON_ITEM && (mons_itemuse(mons) >= MONUSE_WEAPONS_ARMOUR || mons_itemeat(mons) != MONEAT_NOTHING)) { // Keep neutral, charmed, summoned monsters from picking up stuff. // Same for friendlies if friendly_pickup is set to "none". if ((!mons->neutral() && !mons->has_ench(ENCH_CHARM) || (you_worship(GOD_JIYVA) && mons_is_slime(mons))) && !mons->is_summoned() && !mons->is_perm_summoned() && (!mons->friendly() || you.friendly_pickup != FRIENDLY_PICKUP_NONE)) { if (_handle_pickup(mons)) { DEBUG_ENERGY_USE("handle_pickup()"); return; } } } // Lurking monsters only stop lurking if their target is right // next to them, otherwise they just sit there. // However, if the monster is involuntarily submerged but // still alive (e.g., nonbreathing which had water poured // on top of it), this doesn't apply. if (mons_is_lurking(mons) || mons->has_ench(ENCH_SUBMERGED)) { if (mons->foe != MHITNOT && grid_distance(mons->target, mons->pos()) <= 1) { if (mons->submerged()) { // Don't unsubmerge if the monster is avoiding the // cloud on top of the water. if (avoid_cloud) { mons->speed_increment -= non_move_energy; return; } if (!mons->del_ench(ENCH_SUBMERGED)) { // Couldn't unsubmerge. mons->speed_increment -= non_move_energy; return; } } mons->behaviour = BEH_SEEK; } else { mons->speed_increment -= non_move_energy; return; } } if (mons->caught()) { // Struggling against the net takes time. _swim_or_move_energy(mons); } else if (!mons->petrified()) { // Calculates mmov based on monster target. _handle_movement(mons); _shedu_movement_clamp(mons); if (mons_is_confused(mons) || mons->type == MONS_AIR_ELEMENTAL && mons->submerged()) { _confused_move_dir(mons); // OK, mmov determined. const coord_def newcell = mmov + mons->pos(); monster* enemy = monster_at(newcell); if (enemy && newcell != mons->pos() && !is_sanctuary(mons->pos())) { if (fight_melee(mons, enemy)) { mmov.reset(); DEBUG_ENERGY_USE("fight_melee()"); return; } else { // FIXME: None of these work! // Instead run away! if (mons->add_ench(mon_enchant(ENCH_FEAR))) behaviour_event(mons, ME_SCARE, 0, newcell); return; } } } } mon_nearby_ability(mons); if (!mons->alive()) return; // XXX: A bit hacky, but stores where we WILL move, if we don't take // another action instead (used for decision-making) if (mons_stores_tracking_data(mons)) mons->props["mmov"].get_coord() = mmov; if (!mons->asleep() && !mons_is_wandering(mons) && !mons->withdrawn() // Berserking monsters are limited to running up and // hitting their foes. && !mons->berserk_or_insane() // Slime creatures can split while wandering or resting. || mons->type == MONS_SLIME_CREATURE) { bolt beem; beem.source = mons->pos(); beem.target = mons->target; beem.beam_source = mons->mindex(); // XXX: Otherwise perma-confused monsters can almost never properly // aim spells, since their target is constantly randomized. // This does make them automatically aware of the player in several // situations they otherwise would not, however. if (mons_class_flag(mons->type, M_CONFUSED)) { actor* foe = mons->get_foe(); if (foe && mons->can_see(foe)) beem.target = foe->pos(); } // Prevents unfriendlies from nuking you from offscreen. // How nice! const bool friendly_or_near = mons->friendly() && mons->foe == MHITYOU || mons->near_foe(); if (friendly_or_near || mons->type == MONS_TEST_SPAWNER // Slime creatures can split when offscreen. || mons->type == MONS_SLIME_CREATURE // Lost souls can flicker away at any time they're isolated || mons->type == MONS_LOST_SOUL // Let monsters who have Dig use it off-screen. || mons->has_spell(SPELL_DIG)) { // [ds] Special abilities shouldn't overwhelm // spellcasting in monsters that have both. This aims // to give them both roughly the same weight. if (coinflip() ? mon_special_ability(mons, beem) || _do_mon_spell(mons, beem) : _do_mon_spell(mons, beem) || mon_special_ability(mons, beem)) { DEBUG_ENERGY_USE("spell or special"); mmov.reset(); return; } } if (friendly_or_near) { if (_handle_potion(mons, beem)) { DEBUG_ENERGY_USE("_handle_potion()"); return; } if (_handle_scroll(mons)) { DEBUG_ENERGY_USE("_handle_scroll()"); return; } if (_handle_evoke_equipment(mons, beem)) { DEBUG_ENERGY_USE("_handle_evoke_equipment()"); return; } if (_handle_wand(mons, beem)) { DEBUG_ENERGY_USE("_handle_wand()"); return; } if (_handle_reaching(mons)) { DEBUG_ENERGY_USE("_handle_reaching()"); return; } } if (_handle_throw(mons, beem)) { DEBUG_ENERGY_USE("_handle_throw()"); return; } } if (!mons->caught()) { if (mons->pos() + mmov == you.pos()) { ASSERT(!crawl_state.game_is_arena()); if (_unfriendly_or_insane(mons) && !mons->has_ench(ENCH_CHARM) && !mons->withdrawn()) { if (!mons->wont_attack()) { // If it steps into you, cancel other targets. mons->foe = MHITYOU; mons->target = you.pos(); } fight_melee(mons, &you); if (mons_is_batty(mons)) { mons->behaviour = BEH_WANDER; set_random_target(mons); } DEBUG_ENERGY_USE("fight_melee()"); mmov.reset(); return; } } // See if we move into (and fight) an unfriendly monster. monster* targ = monster_at(mons->pos() + mmov); //If a tentacle owner is attempting to move into an adjacent //segment, kill the segment and adjust connectivity data. if (targ && mons_tentacle_adjacent(mons, targ)) { bool basis = targ->props.exists("outwards"); int out_idx = basis ? targ->props["outwards"].get_int() : -1; if (out_idx != -1) menv[out_idx].props["inwards"].get_int() = mons->mindex(); monster_die(targ, KILL_MISC, NON_MONSTER, true); targ = NULL; } if (targ && targ != mons && mons->behaviour != BEH_WITHDRAW && (!mons_aligned(mons, targ) || mons->has_ench(ENCH_INSANE)) && monster_can_hit_monster(mons, targ)) { // Maybe they can swap places? if (_swap_monsters(mons, targ)) { _swim_or_move_energy(mons); return; } // Figure out if they fight. else if ((!mons_is_firewood(targ) || mons->is_child_tentacle()) && fight_melee(mons, targ)) { if (mons_is_batty(mons)) { mons->behaviour = BEH_WANDER; set_random_target(mons); // mons->speed_increment -= mons->speed; } mmov.reset(); DEBUG_ENERGY_USE("fight_melee()"); return; } } else if (mons->behaviour == BEH_WITHDRAW && ((targ && targ != mons && targ->friendly()) || (you.pos() == mons->pos() + mmov))) { // Don't count turns spent blocked by friendly creatures // (or the player) as an indication that we're stuck mons->props.erase("blocked_deadline"); } if (invalid_monster(mons) || mons->is_stationary()) { if (mons->speed_increment == old_energy) mons->speed_increment -= non_move_energy; return; } if (mons->cannot_move() || !_monster_move(mons)) { mons->speed_increment -= non_move_energy; mons->check_clinging(false); } } you.update_beholder(mons); you.update_fearmonger(mons); // Reevaluate behaviour, since the monster's surroundings have // changed (it may have moved, or died for that matter). Don't // bother for dead monsters. :) if (mons->alive()) { handle_behaviour(mons); ASSERT_IN_BOUNDS_OR_ORIGIN(mons->target); } if (mons_is_tentacle_head(mons_base_type(mons))) { if (mons->pos() != kraken_last_update) move_child_tentacles(mons); mons->number += (old_energy - mons->speed_increment) * _tentacle_move_speed(mons_base_type(mons)); while (mons->number >= 100) { move_child_tentacles(mons); mons->number -= 100; } } } static void _post_monster_move(monster* mons) { if (invalid_monster(mons)) return; mons->handle_constriction(); if (mons->type == MONS_ANCIENT_ZYME) ancient_zyme_sicken(mons); if (mons->type == MONS_ASMODEUS || mons->type == MONS_CHAOS_BUTTERFLY) { cloud_type ctype; switch (mons->type) { case MONS_ASMODEUS: ctype = CLOUD_FIRE; break; case MONS_CHAOS_BUTTERFLY: ctype = CLOUD_RAIN; break; default: ctype = CLOUD_NONE; break; } for (adjacent_iterator ai(mons->pos()); ai; ++ai) if (!feat_is_solid(grd(*ai)) && (env.cgrid(*ai) == EMPTY_CLOUD || env.cloud[env.cgrid(*ai)].type == ctype)) { place_cloud(ctype, *ai, 2 + random2(6), mons); } } if (mons->type != MONS_NO_MONSTER && mons->hit_points < 1) monster_die(mons, KILL_MISC, NON_MONSTER); } priority_queue<pair<monster *, int>, vector<pair<monster *, int> >, MonsterActionQueueCompare> monster_queue; // Inserts a monster into the monster queue (needed to ensure that any monsters // given energy or an action by a effect can actually make use of that energy // this round) void queue_monster_for_action(monster* mons) { monster_queue.push(pair<monster *, int>(mons, mons->speed_increment)); } //--------------------------------------------------------------- // // handle_monsters // // This is the routine that controls monster AI. // //--------------------------------------------------------------- void handle_monsters(bool with_noise) { for (monster_iterator mi; mi; ++mi) { _pre_monster_move(*mi); if (!invalid_monster(*mi) && mi->alive() && mi->has_action_energy()) monster_queue.push(pair<monster *, int>(*mi, mi->speed_increment)); } int tries = 0; // infinite loop protection, shouldn't be ever needed while (!monster_queue.empty()) { if (tries++ > 32767) { die("infinite handle_monsters() loop, mons[0 of %d] is %s", (int)monster_queue.size(), monster_queue.top().first->name(DESC_PLAIN, true).c_str()); } monster *mon = monster_queue.top().first; const int oldspeed = monster_queue.top().second; monster_queue.pop(); if (invalid_monster(mon) || !mon->alive() || !mon->has_action_energy()) continue; // Only move the monster if nothing else has played with its energy // during their turn. // This can happen with, e.g., headbutt stuns, cold attacks on cold- // -blooded monsters, etc. // If something's played with the energy, they get added back to // the queue just after this. if (oldspeed == mon->speed_increment) { handle_monster_move(mon); _post_monster_move(mon); fire_final_effects(); } if (mon->has_action_energy()) { monster_queue.push( pair<monster *, int>(mon, mon->speed_increment)); } // If the player got banished, discard pending monster actions. if (you.banished) { // Clear list of mesmerising monsters. you.clear_beholders(); you.clear_fearmongers(); you.stop_constricting_all(); you.stop_being_constricted(); break; } } // Process noises now (before clearing the sleep flag). if (with_noise) apply_noises(); // Clear one-turn deep sleep flag. // XXX: With the current handling, it would be cleaner to // not treat this as an enchantment. // XXX: ENCH_SLEEPY only really works for player-cast // hibernation. for (monster_iterator mi; mi; ++mi) mi->del_ench(ENCH_SLEEPY); // Clear any summoning flags so that lower indiced // monsters get their actions in the next round. for (int i = 0; i < MAX_MONSTERS; i++) menv[i].flags &= ~MF_JUST_SUMMONED; } static bool _jelly_divide(monster* parent) { if (!mons_class_flag(parent->type, M_SPLITS)) return false; const int reqd = max(parent->hit_dice * 8, 50); if (parent->hit_points < reqd) return false; monster* child = NULL; coord_def child_spot; int num_spots = 0; // First, find a suitable spot for the child {dlb}: for (adjacent_iterator ai(parent->pos()); ai; ++ai) if (actor_at(*ai) == NULL && parent->can_pass_through(*ai) && one_chance_in(++num_spots)) { child_spot = *ai; } if (num_spots == 0) return false; // Now that we have a spot, find a monster slot {dlb}: child = get_free_monster(); if (!child) return false; // Handle impact of split on parent {dlb}: parent->max_hit_points /= 2; if (parent->hit_points > parent->max_hit_points) parent->hit_points = parent->max_hit_points; parent->init_experience(); parent->experience = parent->experience * 3 / 5 + 1; // Create child {dlb}: // This is terribly partial and really requires // more thought as to generation ... {dlb} *child = *parent; child->max_hit_points = child->hit_points; child->speed_increment = 70 + random2(5); child->moveto(child_spot); child->set_new_monster_id(); mgrd(child->pos()) = child->mindex(); if (!simple_monster_message(parent, " splits in two!") && (player_can_hear(parent->pos()) || player_can_hear(child->pos()))) { mpr("You hear a squelching noise.", MSGCH_SOUND); } if (crawl_state.game_is_arena()) arena_placed_monster(child); return true; } // XXX: This function assumes that only jellies eat items. static bool _monster_eat_item(monster* mons, bool nearby) { if (!mons_eats_items(mons)) return false; // Friendly jellies won't eat (unless worshipping Jiyva). if (mons->friendly() && !you_worship(GOD_JIYVA)) return false; // Off-limit squares are off-limit. if (testbits(env.pgrid(mons->pos()), FPROP_NO_JIYVA)) return false; int hps_changed = 0; // Zotdef jellies are toned down slightly int max_eat = roll_dice(1, (crawl_state.game_is_zotdef() ? 8 : 10)); int eaten = 0; bool eaten_net = false; bool death_ooze_ate_good = false; bool death_ooze_ate_corpse = false; bool shown_msg = false; piety_gain_t gain = PIETY_NONE; int js = JS_NONE; // Jellies can swim, so don't check water for (stack_iterator si(mons->pos()); si && eaten < max_eat && hps_changed < 50; ++si) { if (!is_item_jelly_edible(*si)) continue; #if defined(DEBUG_DIAGNOSTICS) || defined(DEBUG_EATERS) mprf(MSGCH_DIAGNOSTICS, "%s eating %s", mons->name(DESC_PLAIN, true).c_str(), si->name(DESC_PLAIN).c_str()); #endif int quant = si->quantity; death_ooze_ate_good = (mons->type == MONS_DEATH_OOZE && (get_weapon_brand(*si) == SPWPN_HOLY_WRATH || get_ammo_brand(*si) == SPMSL_SILVER)); death_ooze_ate_corpse = (mons->type == MONS_DEATH_OOZE && ((si->base_type == OBJ_CORPSES && si->sub_type == CORPSE_BODY) || si->base_type == OBJ_FOOD && si->sub_type == FOOD_CHUNK)); if (si->base_type != OBJ_GOLD) { quant = min(quant, max_eat - eaten); hps_changed += (quant * item_mass(*si)) / (crawl_state.game_is_zotdef() ? 30 : 20) + quant; eaten += quant; if (mons->caught() && si->base_type == OBJ_MISSILES && si->sub_type == MI_THROWING_NET && item_is_stationary(*si)) { mons->del_ench(ENCH_HELD, true); eaten_net = true; } } else { // Shouldn't be much trouble to digest a huge pile of gold! if (quant > 500) quant = 500 + roll_dice(2, (quant - 500) / 2); hps_changed += quant / 10 + 1; eaten++; } if (eaten && !shown_msg && player_can_hear(mons->pos())) { mprf(MSGCH_SOUND, "You hear a%s slurping noise.", nearby ? "" : " distant"); shown_msg = true; } if (you_worship(GOD_JIYVA)) { gain = sacrifice_item_stack(*si, &js, quant); if (gain > PIETY_NONE) simple_god_message(" appreciates your sacrifice."); jiyva_slurp_message(js); } if (quant >= si->quantity) item_was_destroyed(*si, mons->mindex()); if (is_blood_potion(*si)) { for (int i = 0; i < quant; ++i) remove_oldest_blood_potion(*si); } dec_mitm_item_quantity(si.link(), quant); } if (eaten > 0) { hps_changed = max(hps_changed, 1); hps_changed = min(hps_changed, 50); if (death_ooze_ate_good) mons->hurt(NULL, hps_changed, BEAM_NONE, false); else { // This is done manually instead of using heal_monster(), // because that function doesn't work quite this way. - bwr const int base_max = mons_avg_hp(mons->type); mons->hit_points += hps_changed; mons->hit_points = min(MAX_MONSTER_HP, min(base_max * 2, mons->hit_points)); mons->max_hit_points = max(mons->hit_points, mons->max_hit_points); } if (death_ooze_ate_corpse) place_cloud(CLOUD_MIASMA, mons->pos(), 4 + random2(5), mons); if (death_ooze_ate_good) simple_monster_message(mons, " twists violently!"); else if (eaten_net) simple_monster_message(mons, " devours the net!"); else _jelly_divide(mons); } return (eaten > 0); } static bool _monster_eat_single_corpse(monster* mons, item_def& item, bool do_heal, bool nearby) { if (item.base_type != OBJ_CORPSES || item.sub_type != CORPSE_BODY) return false; const monster_type mt = item.mon_type; if (do_heal) { const int base_max = mons_avg_hp(mons->type); mons->hit_points += 1 + random2(mons_weight(mt)) / 100; mons->hit_points = min(MAX_MONSTER_HP, min(base_max * 2, mons->hit_points)); mons->max_hit_points = max(mons->hit_points, mons->max_hit_points); } if (nearby) { mprf("%s eats %s.", mons->name(DESC_THE).c_str(), item.name(DESC_THE).c_str()); } // Butcher the corpse without leaving chunks. butcher_corpse(item, MB_MAYBE, false); return true; } static bool _monster_eat_corpse(monster* mons, bool do_heal, bool nearby) { if (!mons_eats_corpses(mons)) return false; int eaten = 0; for (stack_iterator si(mons->pos()); si; ++si) { if (_monster_eat_single_corpse(mons, *si, do_heal, nearby)) { eaten++; break; } } return (eaten > 0); } static bool _monster_eat_food(monster* mons, bool nearby) { if (!mons_eats_food(mons)) return false; if (mons_is_fleeing(mons)) return false; int eaten = 0; for (stack_iterator si(mons->pos()); si; ++si) { const bool is_food = (si->base_type == OBJ_FOOD); const bool is_corpse = (si->base_type == OBJ_CORPSES && si->sub_type == CORPSE_BODY); const bool free_to_eat = (mons->wont_attack() || grid_distance(mons->pos(), you.pos()) > 1); if (!is_food && !is_corpse) continue; if (free_to_eat && coinflip()) { if (is_food) { if (nearby) { mprf("%s eats %s.", mons->name(DESC_THE).c_str(), quant_name(*si, 1, DESC_THE).c_str()); } dec_mitm_item_quantity(si.link(), 1); eaten++; break; } else { // Assume that only undead can heal from eating corpses. if (_monster_eat_single_corpse(mons, *si, mons->holiness() == MH_UNDEAD, nearby)) { eaten++; break; } } } } return (eaten > 0); } //--------------------------------------------------------------- // // handle_pickup // // Returns false if monster doesn't spend any time picking something up. // //--------------------------------------------------------------- static bool _handle_pickup(monster* mons) { if (mons->asleep() || mons->submerged()) return false; // Flying over water doesn't let you pick up stuff. This is inexact, as // a merfolk could be flying, but that's currently impossible except for // being tornadoed, and with *that* low life expectancy let's not care. dungeon_feature_type feat = grd(mons->pos()); if ((feat == DNGN_LAVA || feat == DNGN_DEEP_WATER) && mons->flight_mode()) return false; const bool nearby = mons_near(mons); int count_pickup = 0; if (mons_itemeat(mons) != MONEAT_NOTHING) { if (mons_eats_items(mons)) { if (_monster_eat_item(mons, nearby)) return false; } else if (mons_eats_corpses(mons)) { // Assume that only undead can heal from eating corpses. if (_monster_eat_corpse(mons, mons->holiness() == MH_UNDEAD, nearby)) { return false; } } else if (mons_eats_food(mons)) { if (_monster_eat_food(mons, nearby)) return false; } } if (mons_itemuse(mons) >= MONUSE_WEAPONS_ARMOUR) { // Note: Monsters only look at stuff near the top of stacks. // // XXX: Need to put in something so that monster picks up // multiple items (e.g. ammunition) identical to those it's // carrying. // // Monsters may now pick up up to two items in the same turn. // (jpeg) for (stack_iterator si(mons->pos()); si; ++si) { if (si->flags & ISFLAG_NO_PICKUP) continue; if (mons->pickup_item(*si, nearby)) count_pickup++; if (count_pickup > 1 || coinflip()) break; } } return (count_pickup > 0); } // Randomise potential damage. static int _estimated_trap_damage(trap_type trap) { switch (trap) { case TRAP_BLADE: return (10 + random2(30)); case TRAP_DART: return random2(4); case TRAP_ARROW: return random2(7); case TRAP_SPEAR: return random2(10); case TRAP_BOLT: return random2(13); default: return 0; } } // Check whether a given trap (described by trap position) can be // regarded as safe. Takes into account monster intelligence and // allegiance. // (just_check is used for intelligent monsters trying to avoid traps.) static bool _is_trap_safe(const monster* mons, const coord_def& where, bool just_check) { const int intel = mons_intel(mons); const trap_def *ptrap = find_trap(where); if (!ptrap) return true; const trap_def& trap = *ptrap; const bool player_knows_trap = (trap.is_known(&you)); // No friendly monsters will ever enter a Zot trap you know. if (player_knows_trap && mons->friendly() && trap.type == TRAP_ZOT) return false; // Dumb monsters don't care at all. if (intel == I_PLANT) return true; // Known shafts are safe. Unknown ones are unknown. if (trap.type == TRAP_SHAFT) return true; // Hostile monsters are not afraid of non-mechanical traps. // Allies will try to avoid teleportation and zot traps. const bool mechanical = (trap.category() == DNGN_TRAP_MECHANICAL); if (trap.is_known(mons)) { if (just_check) return false; // Square is blocked. else { // Test for corridor-like environment. const int x = where.x - mons->pos().x; const int y = where.y - mons->pos().y; // The question is whether the monster (m) can easily reach its // presumable destination (x) without stepping on the trap. Traps // in corridors do not allow this. See e.g // #x# ## // #^# or m^x // m ## // // The same problem occurs if paths are blocked by monsters, // hostile terrain or other traps rather than walls. // What we do is check whether the squares with the relative // positions (-1,0)/(+1,0) or (0,-1)/(0,+1) form a "corridor" // (relative to the _trap_ position rather than the monster one). // If they don't, the trap square is marked as "unsafe" (because // there's a good alternative move for the monster to take), // otherwise the decision will be made according to later tests // (monster hp, trap type, ...) // If a monster still gets stuck in a corridor it will usually be // because it has less than half its maximum hp. if ((mon_can_move_to_pos(mons, coord_def(x-1, y), true) || mon_can_move_to_pos(mons, coord_def(x+1,y), true)) && (mon_can_move_to_pos(mons, coord_def(x,y-1), true) || mon_can_move_to_pos(mons, coord_def(x,y+1), true))) { return false; } } } // Friendlies will try not to be parted from you. if (intelligent_ally(mons) && trap.type == TRAP_TELEPORT && player_knows_trap && mons_near(mons)) { return false; } // Healthy monsters don't mind a little pain. if (mechanical && mons->hit_points >= mons->max_hit_points / 2 && (intel == I_ANIMAL || mons->hit_points > _estimated_trap_damage(trap.type))) { return true; } // In Zotdef critters will risk death to get to the Orb if (crawl_state.game_is_zotdef() && mechanical) return true; // Friendly and good neutral monsters don't enjoy Zot trap perks; // handle accordingly. In the arena Zot traps affect all monsters. if (mons->wont_attack() || crawl_state.game_is_arena()) { return (mechanical ? mons_flies(mons) : !trap.is_known(mons) || trap.type != TRAP_ZOT); } else return (!mechanical || mons_flies(mons) || !trap.is_known(mons)); } static void _mons_open_door(monster* mons, const coord_def &pos) { const char *adj = "", *noun = "door"; bool was_seen = false; set<coord_def> all_door = connected_doors(pos); get_door_description(all_door.size(), &adj, &noun); for (set<coord_def>::iterator i = all_door.begin(); i != all_door.end(); ++i) { const coord_def& dc = *i; if (you.see_cell(dc)) was_seen = true; grd(dc) = DNGN_OPEN_DOOR; set_terrain_changed(dc); } if (was_seen) { viewwindow(); string open_str = "opens the "; open_str += adj; open_str += noun; open_str += "."; // Should this be conditionalized on you.can_see(mons?) mons->seen_context = (all_door.size() <= 2) ? SC_DOOR : SC_GATE; if (!you.can_see(mons)) { mprf("Something unseen %s", open_str.c_str()); interrupt_activity(AI_FORCE_INTERRUPT); } else if (!you_are_delayed()) { mprf("%s %s", mons->name(DESC_A).c_str(), open_str.c_str()); } } mons->lose_energy(EUT_MOVE); dungeon_events.fire_position_event(DET_DOOR_OPENED, pos); } static bool _no_habitable_adjacent_grids(const monster* mon) { for (adjacent_iterator ai(mon->pos()); ai; ++ai) if (monster_habitable_grid(mon, grd(*ai))) return false; return true; } static bool _same_tentacle_parts(const monster* mpusher, const monster* mpushee) { if (!mons_is_tentacle_head(mons_base_type(mpusher))) return false; if (mpushee->is_child_tentacle_of(mpusher)) return true; if (mons_tentacle_adjacent(mpusher, mpushee)) return true; return false; } static bool _mons_can_displace(const monster* mpusher, const monster* mpushee) { if (invalid_monster(mpusher) || invalid_monster(mpushee)) return false; const int ipushee = mpushee->mindex(); if (invalid_monster_index(ipushee)) return false; if (!mpushee->has_action_energy() && !_same_tentacle_parts(mpusher, mpushee)) { return false; } // Confused monsters can't be pushed past, sleeping monsters // can't push. Note that sleeping monsters can't be pushed // past, either, but they may be woken up by a crowd trying to // elbow past them, and the wake-up check happens downstream. // Monsters caught in a net also can't be pushed past. if (mons_is_confused(mpusher) || mons_is_confused(mpushee) || mpusher->cannot_move() || mpusher->is_stationary() || mpusher->is_constricted() || mpushee->is_constricted() || (!_same_tentacle_parts(mpusher, mpushee) && (mpushee->cannot_move() || mpushee->is_stationary())) || mpusher->asleep() || mpushee->caught()) { return false; } // Batty monsters are unpushable. if (mons_is_batty(mpusher) || mons_is_batty(mpushee)) return false; // Anyone can displace a submerged monster (otherwise monsters can // get stuck behind a trapdoor spider, giving away its presence). if (mpushee->submerged()) return true; if (!monster_shover(mpusher)) return false; // Fleeing monsters of the same type may push past higher ranking ones. if (!monster_senior(mpusher, mpushee, mons_is_retreating(mpusher))) return false; return true; } static int _count_adjacent_slime_walls(const coord_def &pos) { int count = 0; for (adjacent_iterator ai(pos); ai; ++ai) if (env.grid(*ai) == DNGN_SLIMY_WALL) count++; return count; } // Returns true if the monster should try to avoid that position // because of taking damage from slime walls. static bool _check_slime_walls(const monster *mon, const coord_def &targ) { if (!player_in_branch(BRANCH_SLIME_PITS) || mons_is_slime(mon) || actor_slime_wall_immune(mon) || mons_intel(mon) <= I_REPTILE) { return false; } const int target_count = _count_adjacent_slime_walls(targ); // Entirely safe. if (!target_count) return false; const int current_count = _count_adjacent_slime_walls(mon->pos()); if (target_count <= current_count) return false; // The monster needs to have a purpose to risk taking damage. if (!mons_is_seeking(mon)) return true; // With enough hit points monsters will consider moving // onto more dangerous squares. return (mon->hit_points < mon->max_hit_points / 2); } // Check whether a monster can move to given square (described by its relative // coordinates to the current monster position). just_check is true only for // calls from is_trap_safe when checking the surrounding squares of a trap. bool mon_can_move_to_pos(const monster* mons, const coord_def& delta, bool just_check) { const coord_def targ = mons->pos() + delta; // Bounds check: don't consider moving out of grid! if (!in_bounds(targ)) return false; // No monster may enter the open sea. if (grd(targ) == DNGN_OPEN_SEA || grd(targ) == DNGN_LAVA_SEA) return false; // Non-friendly and non-good neutral monsters won't enter // sanctuaries. if (!mons->wont_attack() && is_sanctuary(targ) && !is_sanctuary(mons->pos())) { return false; } // Inside a sanctuary don't attack anything! if (is_sanctuary(mons->pos()) && actor_at(targ)) return false; const dungeon_feature_type target_grid = grd(targ); const habitat_type habitat = mons_primary_habitat(mons); // The kraken is so large it cannot enter shallow water. // Its tentacles can, and will, though. if (mons_base_type(mons) == MONS_KRAKEN && target_grid == DNGN_SHALLOW_WATER) { return false; } bool no_water = false; const int targ_cloud_num = env.cgrid(targ); if (mons_avoids_cloud(mons, targ_cloud_num)) return false; if (_check_slime_walls(mons, targ)) return false; const bool burrows = mons_class_flag(mons->type, M_BURROWS); const bool digs = _mons_can_cast_dig(mons, false) || _mons_can_zap_dig(mons); const bool flattens_trees = mons_flattens_trees(mons); if (((burrows || digs) && (target_grid == DNGN_ROCK_WALL || target_grid == DNGN_CLEAR_ROCK_WALL)) || (flattens_trees && feat_is_tree(target_grid))) { // Don't burrow out of bounds. if (!in_bounds(targ)) return false; } else if (no_water && feat_is_water(target_grid)) return false; else if (!mons_can_traverse(mons, targ, false) && !monster_habitable_grid(mons, target_grid)) { // If the monster somehow ended up in this habitat (and is // not dead by now), give it a chance to get out again. if (grd(mons->pos()) == target_grid && mons->ground_level() && _no_habitable_adjacent_grids(mons)) { return true; } return false; } // Wandering mushrooms usually don't move while you are looking. if (mons->type == MONS_WANDERING_MUSHROOM || mons->type == MONS_DEATHCAP || mons->type == MONS_CURSE_SKULL || (mons->type == MONS_LURKING_HORROR && mons->foe_distance() > random2(LOS_RADIUS + 1))) { if (!mons->wont_attack() && is_sanctuary(mons->pos())) { return true; } if (!mons->friendly() && you.see_cell(targ) || mon_enemies_around(mons)) { return false; } } // Fire elementals avoid water and cold. if (mons->type == MONS_FIRE_ELEMENTAL && feat_is_watery(target_grid)) return false; // Submerged water creatures avoid the shallows where // they would be forced to surface. -- bwr // [dshaligram] Monsters now prefer to head for deep water only if // they're low on hitpoints. No point in hiding if they want a // fight. if (habitat == HT_WATER && targ != you.pos() && target_grid != DNGN_DEEP_WATER && grd(mons->pos()) == DNGN_DEEP_WATER && mons->hit_points < (mons->max_hit_points * 3) / 4) { return false; } // Smacking the player is always a good move if we're // hostile (even if we're heading somewhere else). // Also friendlies want to keep close to the player // so it's okay as well. // Smacking another monster is good, if the monsters // are aligned differently. if (monster* targmonster = monster_at(targ)) { if (just_check) { if (targ == mons->pos()) return true; return false; // blocks square } if (!summon_can_attack(mons, targ)) return false; // Cut down plants only when no alternative, or they're // our target. if (mons_is_firewood(targmonster) && mons->target != targ) return false; if (mons_aligned(mons, targmonster) && !mons->has_ench(ENCH_INSANE) && !_mons_can_displace(mons, targmonster)) { // In Zotdef hostiles will whack other hostiles if immobile // - prevents plugging gaps with hostile oklobs if (crawl_state.game_is_zotdef()) { if (!targmonster->is_stationary() || targmonster->attitude != ATT_HOSTILE) { return false; } } else return false; } // Prefer to move past enemies instead of hit them, if we're retreating else if ((!mons_aligned(mons, targmonster) || mons->has_ench(ENCH_INSANE)) && mons->behaviour == BEH_WITHDRAW) { return false; } } // Friendlies shouldn't try to move onto the player's // location, if they are aiming for some other target. if (!_unfriendly_or_insane(mons) && mons->foe != MHITYOU && (mons->foe != MHITNOT || mons->is_patrolling()) && targ == you.pos()) { return false; } // Wandering through a trap is OK if we're pretty healthy, // really stupid, or immune to the trap. if (!_is_trap_safe(mons, targ, just_check)) return false; // If we end up here the monster can safely move. return true; } // Uses, and updates the global variable mmov. static void _find_good_alternate_move(monster* mons, const move_array& good_move) { const coord_def target = mons->firing_pos.zero() ? mons->target : mons->firing_pos; const int current_distance = distance2(mons->pos(), target); int dir = _compass_idx(mmov); // Only handle if the original move is to an adjacent square. if (dir == -1) return; int dist[2]; // First 1 away, then 2 (3 is silly). for (int j = 1; j <= 2; j++) { const int FAR_AWAY = 1000000; // Try both directions (but randomise which one is first). const int sdir = coinflip() ? j : -j; const int inc = -2 * sdir; for (int mod = sdir, i = 0; i < 2; mod += inc, i++) { const int newdir = (dir + 8 + mod) % 8; if (good_move[mon_compass[newdir].x+1][mon_compass[newdir].y+1]) dist[i] = distance2(mons->pos()+mon_compass[newdir], target); else dist[i] = mons_is_retreating(mons) ? (-FAR_AWAY) : FAR_AWAY; } const int dir0 = ((dir + 8 + sdir) % 8); const int dir1 = ((dir + 8 - sdir) % 8); // Now choose. if (dist[0] == dist[1] && abs(dist[0]) == FAR_AWAY) continue; // Which one was better? -- depends on FLEEING or not. if (mons_is_retreating(mons)) { if (dist[0] >= dist[1] && dist[0] >= current_distance) { mmov = mon_compass[dir0]; break; } if (dist[1] >= dist[0] && dist[1] >= current_distance) { mmov = mon_compass[dir1]; break; } } else { if (dist[0] <= dist[1] && dist[0] <= current_distance) { mmov = mon_compass[dir0]; break; } if (dist[1] <= dist[0] && dist[1] <= current_distance) { mmov = mon_compass[dir1]; break; } } } } static void _jelly_grows(monster* mons) { if (player_can_hear(mons->pos())) { mprf(MSGCH_SOUND, "You hear a%s slurping noise.", mons_near(mons) ? "" : " distant"); } mons->hit_points += 5; // possible with ridiculous farming on a full level mons->hit_points = min(mons->hit_points, MAX_MONSTER_HP); // note here, that this makes jellies "grow" {dlb}: if (mons->hit_points > mons->max_hit_points) mons->max_hit_points = mons->hit_points; _jelly_divide(mons); } static bool _monster_swaps_places(monster* mon, const coord_def& delta) { if (delta.origin()) return false; monster* const m2 = monster_at(mon->pos() + delta); if (!m2) return false; if (!_mons_can_displace(mon, m2)) return false; if (m2->asleep()) { if (coinflip()) { dprf("Alerting monster %s at (%d,%d)", m2->name(DESC_PLAIN).c_str(), m2->pos().x, m2->pos().y); behaviour_event(m2, ME_ALERT); } return false; } // Check that both monsters will be happy at their proposed new locations. const coord_def c = mon->pos(); const coord_def n = mon->pos() + delta; if (!monster_habitable_grid(mon, grd(n)) && !mon->can_cling_to(n) || !monster_habitable_grid(m2, grd(c)) && !m2->can_cling_to(c)) { return false; } // Okay, do the swap! #ifdef EUCLIDEAN _swim_or_move_energy(mon, delta.abs() == 2); #else _swim_or_move_energy(mon); #endif mon->set_position(n); mgrd(n) = mon->mindex(); m2->set_position(c); mon->clear_far_constrictions(); m2->clear_far_constrictions(); const int m2i = m2->mindex(); ASSERT_RANGE(m2i, 0, MAX_MONSTERS); mgrd(c) = m2i; _swim_or_move_energy(m2); mon->check_redraw(c, false); if (mon->is_wall_clinging()) mon->check_clinging(true); else mon->apply_location_effects(c); m2->check_redraw(n, false); if (m2->is_wall_clinging()) m2->check_clinging(true); else m2->apply_location_effects(n); // The seen context no longer applies if the monster is moving normally. mon->seen_context = SC_NONE; m2->seen_context = SC_NONE; return false; } static bool _do_move_monster(monster* mons, const coord_def& delta) { const coord_def f = mons->pos() + delta; if (!in_bounds(f)) return false; if (f == you.pos()) { fight_melee(mons, &you); return true; } // This includes the case where the monster attacks itself. if (monster* def = monster_at(f)) { fight_melee(mons, def); return true; } if (mons->is_constricted()) { if (mons->attempt_escape()) simple_monster_message(mons, " escapes!"); else { simple_monster_message(mons, " struggles to escape constriction."); _swim_or_move_energy(mons); return true; } } if (grd(f) == DNGN_CLOSED_DOOR || grd(f) == DNGN_SEALED_DOOR) { if (mons_can_open_door(mons, f)) { _mons_open_door(mons, f); return true; } else if (mons_can_eat_door(mons, f)) { grd(f) = DNGN_FLOOR; set_terrain_changed(f); _jelly_grows(mons); if (you.see_cell(f)) { viewwindow(); if (!you.can_see(mons)) { mpr("The door mysteriously vanishes."); interrupt_activity(AI_FORCE_INTERRUPT); } else simple_monster_message(mons, " eats the door!"); } } // done door-eating jellies } // The monster gave a "comes into view" message and then immediately // moved back out of view, leaing the player nothing to see, so give // this message to avoid confusion. if (mons->seen_context == SC_JUST_SEEN && !you.see_cell(f)) simple_monster_message(mons, " moves out of view."); else if (crawl_state.game_is_hints() && (mons->flags & MF_WAS_IN_VIEW) && !you.see_cell(f)) { learned_something_new(HINT_MONSTER_LEFT_LOS, mons->pos()); } // The seen context no longer applies if the monster is moving normally. mons->seen_context = SC_NONE; // This appears to be the real one, ie where the movement occurs: #ifdef EUCLIDEAN _swim_or_move_energy(mons, delta.abs() == 2); #else _swim_or_move_energy(mons); #endif _escape_water_hold(mons); if (grd(mons->pos()) == DNGN_DEEP_WATER && grd(f) != DNGN_DEEP_WATER && !monster_habitable_grid(mons, DNGN_DEEP_WATER)) { // er, what? Seems impossible. mons->seen_context = SC_NONSWIMMER_SURFACES_FROM_DEEP; } mgrd(mons->pos()) = NON_MONSTER; coord_def old_pos = mons->pos(); mons->set_position(f); mgrd(mons->pos()) = mons->mindex(); mons->check_clinging(true); ballisto_on_move(mons, old_pos); // Let go of all constrictees; only stop *being* constricted if we are now // too far away. mons->stop_constricting_all(true); mons->clear_far_constrictions(); mons->check_redraw(mons->pos() - delta); mons->apply_location_effects(mons->pos() - delta); return true; } // May mons attack targ if it's in its way, despite // possibly aligned attitudes? // The aim of this is to have monsters cut down plants // to get to the player if necessary. static bool _may_cutdown(monster* mons, monster* targ) { // Save friendly plants from allies. // [ds] I'm deliberately making the alignment checks symmetric here. // The previous check involved good-neutrals never attacking friendlies // and friendlies never attacking anything other than hostiles. if ((mons->friendly() || mons->good_neutral()) && (targ->friendly() || targ->good_neutral())) { return false; } // Outside of that case, can always cut mundane plants. if (mons_is_firewood(targ)) { // Don't try to attack briars unless their damage will be insignificant if (targ->type == MONS_BRIAR_PATCH && mons->type != MONS_THORN_HUNTER && (mons->armour_class() * mons->hit_points) < 400) return false; else return true; } // In normal games, that's it. Gotta keep those butterflies alive... if (!crawl_state.game_is_zotdef()) return false; return targ->is_stationary() || mons_class_flag(mons_base_type(targ), M_NO_EXP_GAIN) && !mons_is_tentacle_or_tentacle_segment(targ->type); } static bool _monster_move(monster* mons) { move_array good_move; const habitat_type habitat = mons_primary_habitat(mons); bool deep_water_available = false; if (mons->type == MONS_TRAPDOOR_SPIDER) { if (mons->submerged()) return false; // Trapdoor spiders sometime hide if they can't see their foe. // (Note that friendly trapdoor spiders will thus hide even // if they can see you.) const actor *foe = mons->get_foe(); const bool can_see = foe && mons->can_see(foe); if (monster_can_submerge(mons, grd(mons->pos())) && !can_see && !mons_is_confused(mons) && !mons->caught() && !mons->berserk_or_insane() && one_chance_in(5)) { mons->add_ench(ENCH_SUBMERGED); mons->behaviour = BEH_LURK; return false; } } // Berserking monsters make a lot of racket. if (mons->berserk_or_insane()) { int noise_level = get_shout_noise_level(mons_shouts(mons->type)); if (noise_level > 0) { if (you.can_see(mons) && mons->berserk()) { if (one_chance_in(10)) { mprf(MSGCH_TALK_VISUAL, "%s rages.", mons->name(DESC_THE).c_str()); } noisy(noise_level, mons->pos(), mons->mindex()); } else if (one_chance_in(5)) handle_monster_shouts(mons, true); else { // Just be noisy without messaging the player. noisy(noise_level, mons->pos(), mons->mindex()); } } } if (mons->confused()) { if (!mmov.origin() || one_chance_in(15)) { const coord_def newpos = mons->pos() + mmov; if (in_bounds(newpos) && (habitat == HT_LAND || monster_habitable_grid(mons, grd(newpos)))) { return _do_move_monster(mons, mmov); } } return false; } // If a water monster is currently flopping around on land, it cannot // really control where it wants to move, though there's a 50% chance // of flopping into an adjacent water grid. if (mons->has_ench(ENCH_AQUATIC_LAND)) { vector<coord_def> adj_water; vector<coord_def> adj_move; for (adjacent_iterator ai(mons->pos()); ai; ++ai) { if (!cell_is_solid(*ai)) { adj_move.push_back(*ai); if (feat_is_watery(grd(*ai))) adj_water.push_back(*ai); } } if (adj_move.empty()) { simple_monster_message(mons, " flops around on dry land!"); return false; } vector<coord_def> moves = adj_water; if (adj_water.empty() || coinflip()) moves = adj_move; coord_def newpos = mons->pos(); int count = 0; for (unsigned int i = 0; i < moves.size(); ++i) if (one_chance_in(++count)) newpos = moves[i]; const monster* mon2 = monster_at(newpos); if (!mons->has_ench(ENCH_INSANE) && (newpos == you.pos() && mons->wont_attack() || (mon2 && mons->wont_attack() == mon2->wont_attack()))) { simple_monster_message(mons, " flops around on dry land!"); return false; } return _do_move_monster(mons, newpos - mons->pos()); } // Let's not even bother with this if mmov is zero. if (mmov.origin()) return false; for (int count_x = 0; count_x < 3; count_x++) for (int count_y = 0; count_y < 3; count_y++) { const int targ_x = mons->pos().x + count_x - 1; const int targ_y = mons->pos().y + count_y - 1; // Bounds check: don't consider moving out of grid! if (!in_bounds(targ_x, targ_y)) { good_move[count_x][count_y] = false; continue; } dungeon_feature_type target_grid = grd[targ_x][targ_y]; if (target_grid == DNGN_DEEP_WATER) deep_water_available = true; good_move[count_x][count_y] = mon_can_move_to_pos(mons, coord_def(count_x-1, count_y-1)); } // Now we know where we _can_ move. const coord_def newpos = mons->pos() + mmov; // Water creatures have a preference for water they can hide in -- bwr // [ds] Weakened the powerful attraction to deep water if the monster // is in good health. if (habitat == HT_WATER && deep_water_available && grd(mons->pos()) != DNGN_DEEP_WATER && grd(newpos) != DNGN_DEEP_WATER && newpos != you.pos() && (one_chance_in(3) || mons->hit_points <= (mons->max_hit_points * 3) / 4)) { int count = 0; for (int cx = 0; cx < 3; cx++) for (int cy = 0; cy < 3; cy++) { if (good_move[cx][cy] && grd[mons->pos().x + cx - 1][mons->pos().y + cy - 1] == DNGN_DEEP_WATER) { if (one_chance_in(++count)) { mmov.x = cx - 1; mmov.y = cy - 1; } } } } // Now, if a monster can't move in its intended direction, try // either side. If they're both good, move in whichever dir // gets it closer (farther for fleeing monsters) to its target. // If neither does, do nothing. if (good_move[mmov.x + 1][mmov.y + 1] == false) _find_good_alternate_move(mons, good_move); // ------------------------------------------------------------------ // If we haven't found a good move by this point, we're not going to. // ------------------------------------------------------------------ if (mons->type == MONS_SPATIAL_MAELSTROM) { const dungeon_feature_type feat = grd(mons->pos() + mmov); if (!feat_is_permarock(feat) && feat_is_solid(feat)) { const coord_def target(mons->pos() + mmov); create_monster( mgen_data(MONS_SPATIAL_VORTEX, SAME_ATTITUDE(mons), mons, 2, MON_SUMM_ANIMATE, target, MHITNOT, 0, GOD_LUGONU)); nuke_wall(target); } } const bool burrows = mons_class_flag(mons->type, M_BURROWS); const bool flattens_trees = mons_flattens_trees(mons); const bool digs = _mons_can_cast_dig(mons, false) || _mons_can_zap_dig(mons); // Take care of beetle burrowing. if (burrows || flattens_trees || digs) { const dungeon_feature_type feat = grd(mons->pos() + mmov); if ((feat == DNGN_ROCK_WALL || feat == DNGN_CLEAR_ROCK_WALL) && !burrows && digs) { bolt beem; if (_mons_can_cast_dig(mons, true)) { setup_mons_cast(mons, beem, SPELL_DIG); beem.target = mons->pos() + mmov; mons_cast(mons, beem, SPELL_DIG, true, true); } else if (_mons_can_zap_dig(mons)) { ASSERT(mons->inv[MSLOT_WAND] != NON_ITEM); item_def &wand = mitm[mons->inv[MSLOT_WAND]]; beem.target = mons->pos() + mmov; _setup_wand_beam(beem, mons); _mons_fire_wand(mons, wand, beem, you.can_see(mons), false); } else simple_monster_message(mons, " falters for a moment."); mons->lose_energy(EUT_SPELL); return true; } else if ((((feat == DNGN_ROCK_WALL || feat == DNGN_CLEAR_ROCK_WALL) && burrows) || (flattens_trees && feat_is_tree(feat))) && good_move[mmov.x + 1][mmov.y + 1] == true) { const coord_def target(mons->pos() + mmov); nuke_wall(target); if (flattens_trees) { // Flattening trees has a movement cost to the monster // - 100% over and above its normal move cost. _swim_or_move_energy(mons); if (you.see_cell(target)) { const bool actor_visible = you.can_see(mons); mprf("%s knocks down a tree!", actor_visible? mons->name(DESC_THE).c_str() : "Something"); noisy(25, target); } else noisy(25, target, "You hear a crashing sound."); } else if (player_can_hear(mons->pos() + mmov)) { // Message depends on whether caused by boring beetle or // acid (Dissolution). mpr((mons->type == MONS_BORING_BEETLE) ? "You hear a grinding noise." : "You hear a sizzling sound.", MSGCH_SOUND); } } } bool ret = false; if (good_move[mmov.x + 1][mmov.y + 1] && !mmov.origin()) { // Check for attacking player. if (mons->pos() + mmov == you.pos()) { ret = fight_melee(mons, &you); mmov.reset(); } // If we're following the player through stairs, the only valid // movement is towards the player. -- bwr if (testbits(mons->flags, MF_TAKING_STAIRS)) { const delay_type delay = current_delay_action(); if (delay != DELAY_ASCENDING_STAIRS && delay != DELAY_DESCENDING_STAIRS) { mons->flags &= ~MF_TAKING_STAIRS; dprf("BUG: %s was marked as follower when not following!", mons->name(DESC_PLAIN).c_str()); } else { ret = true; mmov.reset(); dprf("%s is skipping movement in order to follow.", mons->name(DESC_THE).c_str()); } } // Check for attacking another monster. if (monster* targ = monster_at(mons->pos() + mmov)) { if (mons_aligned(mons, targ) && !mons->has_ench(ENCH_INSANE) && (!crawl_state.game_is_zotdef() || !_may_cutdown(mons, targ))) { // Zotdef: monsters will cut down firewood ret = _monster_swaps_places(mons, mmov); } else { fight_melee(mons, targ); ret = true; } // If the monster swapped places, the work's already done. mmov.reset(); } // The monster could die after a melee attack due to a mummy // death curse or something. if (!mons->alive()) return true; if (mons_genus(mons->type) == MONS_EFREET || mons->type == MONS_FIRE_ELEMENTAL) { place_cloud(CLOUD_FIRE, mons->pos(), 2 + random2(4), mons); } if (mons->type == MONS_ROTTING_DEVIL || mons->type == MONS_CURSE_TOE) place_cloud(CLOUD_MIASMA, mons->pos(), 2 + random2(3), mons); } else { monster* targ = monster_at(mons->pos() + mmov); if (!mmov.origin() && targ && _may_cutdown(mons, targ)) { fight_melee(mons, targ); ret = true; } mmov.reset(); // zotdef: sometimes seem to get gridlock. Reset travel path // if we can't move, occasionally if (crawl_state.game_is_zotdef() && one_chance_in(20)) { mons->travel_path.clear(); mons->travel_target = MTRAV_NONE; } // Fleeing monsters that can't move will panic and possibly // turn to face their attacker. make_mons_stop_fleeing(mons); } if (mmov.x || mmov.y || (mons->confused() && one_chance_in(6))) return _do_move_monster(mons, mmov); // Battlespheres need to preserve their tracking targets after each move if (mons_is_wandering(mons) && mons->type != MONS_BATTLESPHERE) { // trigger a re-evaluation of our wander target on our next move -cao mons->target = mons->pos(); if (!mons->is_patrolling()) { mons->travel_target = MTRAV_NONE; mons->travel_path.clear(); } mons->firing_pos.reset(); } return ret; } static void _mons_in_cloud(monster* mons) { // Submerging in water or lava saves from clouds. if (mons->submerged() && env.grid(mons->pos()) != DNGN_FLOOR) return; actor_apply_cloud(mons); } static void _heated_area(monster* mons) { if (!heated(mons->pos())) return; if (mons->is_fiery()) return; // HACK: Currently this prevents even auras not caused by lava orcs... if (you_worship(GOD_BEOGH) && mons->friendly() && mons->god == GOD_BEOGH) return; const int base_damage = random2(11); // Timescale, like with clouds: const int speed = mons->speed > 0 ? mons->speed : 10; const int timescaled = max(0, base_damage) * 10 / speed; // rF protects: const int resist = mons->res_fire(); const int adjusted_damage = resist_adjust_damage(mons, BEAM_FIRE, resist, timescaled, true); // So does AC: const int final_damage = max(0, adjusted_damage - random2(mons->armour_class())); if (final_damage > 0) { if (mons->observable()) mprf("%s is %s by your radiant heat.", mons->name(DESC_THE).c_str(), (final_damage) > 10 ? "blasted" : "burned"); behaviour_event(mons, ME_DISTURB, 0, mons->pos()); #ifdef DEBUG_DIAGNOSTICS mprf(MSGCH_DIAGNOSTICS, "%s %s %d damage from heat.", mons->name(DESC_THE).c_str(), mons->conj_verb("take").c_str(), final_damage); #endif mons->hurt(&you, final_damage, BEAM_MISSILE); if (mons->alive() && mons->observable()) print_wounds(mons); } } static spell_type _map_wand_to_mspell(wand_type kind) { switch (kind) { case WAND_FLAME: return SPELL_THROW_FLAME; case WAND_FROST: return SPELL_THROW_FROST; case WAND_SLOWING: return SPELL_SLOW; case WAND_HASTING: return SPELL_HASTE; case WAND_MAGIC_DARTS: return SPELL_MAGIC_DART; case WAND_HEAL_WOUNDS: return SPELL_MINOR_HEALING; case WAND_PARALYSIS: return SPELL_PARALYSE; case WAND_FIRE: return SPELL_BOLT_OF_FIRE; case WAND_COLD: return SPELL_BOLT_OF_COLD; case WAND_CONFUSION: return SPELL_CONFUSE; case WAND_INVISIBILITY: return SPELL_INVISIBILITY; case WAND_TELEPORTATION: return SPELL_TELEPORT_OTHER; case WAND_LIGHTNING: return SPELL_LIGHTNING_BOLT; case WAND_DRAINING: return SPELL_BOLT_OF_DRAINING; case WAND_DISINTEGRATION: return SPELL_DISINTEGRATE; case WAND_POLYMORPH: return SPELL_POLYMORPH; case WAND_DIGGING: return SPELL_DIG; default: return SPELL_NO_SPELL; } } // Keep kraken tentacles from wandering too far away from the boss monster. static void _shedu_movement_clamp(monster *shedu) { if (!mons_is_shedu(shedu)) return; monster *my_pair = get_shedu_pair(shedu); if (!my_pair) return; if (grid_distance(shedu->pos(), my_pair->pos()) >= 10) mmov = (my_pair->pos() - shedu->pos()).sgn(); }
xFleury/crawl-0.13.0-fairplay
source/mon-act.cc
C++
gpl-2.0
126,596
/* * Copyright (c) 2012-2013 Open Source Community - <http://www.peerfact.org> * Copyright (c) 2011-2012 University of Paderborn - UPB * Copyright (c) 2005-2011 KOM - Multimedia Communications Lab * * This file is part of PeerfactSim.KOM. * * PeerfactSim.KOM 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 * any later version. * * PeerfactSim.KOM 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 PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>. * */ package org.peerfact.impl.overlay.unstructured.heterogeneous.api; import org.peerfact.api.overlay.dht.DHTEntry; import org.peerfact.api.overlay.dht.DHTKey; import org.peerfact.api.overlay.dht.DHTValue; /** * Abstract resource that is published and queried in the network. Can be * anything that can be matched to a given query info. * * @author Leo Nobach <peerfact@kom.tu-darmstadt.de> * * @version 05/06/2011 */ public interface IResource extends DHTEntry<DHTKey<?>>, DHTValue { /** * Returns the size of this resource. * * @return */ int getSize(); }
flyroom/PeerfactSimKOM_Clone
src/org/peerfact/impl/overlay/unstructured/heterogeneous/api/IResource.java
Java
gpl-2.0
1,474
<?php /** * @package Extly.Library * @subpackage lib_extly - Extly Framework * * @author Prieco S.A. <support@extly.com> * @copyright Copyright (C) 2007 - 2014 Prieco, S.A. All rights reserved. * @license http://http://www.gnu.org/licenses/gpl-3.0.html GNU/GPL * @link http://www.extly.com http://support.extly.com */ // No direct access defined('_JEXEC') or die('Restricted access'); // Load F0F if (!defined('F0F_INCLUDED')) { include_once JPATH_LIBRARIES . '/f0f/include.php'; } if (!defined('F0F_INCLUDED')) { JError::raiseError('500', 'Your Extly Framework installation is broken; please re-install. Alternatively, extract the installation archive and copy the f0f directory inside your site\'s libraries directory.'); } if (!defined('EXTLY_VERSION')) { /** * @name EXTLY_VERSION */ define('EXTLY_VERSION', '3.3.6'); // CSS Styling define('EXTLY_BASE', '3_2_0'); defined('DS') || define('DS', DIRECTORY_SEPARATOR); defined('EPATH_LIBRARY') || define('EPATH_LIBRARY', JPATH_LIBRARIES . '/extly'); defined('EJSON_START') || define('EJSON_START', '@EXTLYSTART@'); defined('EJSON_END') || define('EJSON_END', '@EXTLYEND@'); defined('EXTLY_J3') || define('EXTLY_J3', (version_compare(JVERSION, '3.0', 'gt'))); defined('EXTLY_J25') || define('EXTLY_J25', !EXTLY_J3); } JLoader::register('Extly', EPATH_LIBRARY . '/core/extly.php'); JLoader::register('ETable', EPATH_LIBRARY . '/core/etable.php'); JLoader::register('ELog', EPATH_LIBRARY . '/core/elog.php'); JLoader::register('EParameter', EPATH_LIBRARY . '/core/eparameter.php'); JLoader::register('EForm', EPATH_LIBRARY . '/form/eform.php'); JLoader::register('EHtmlGrid', EPATH_LIBRARY . '/html/egrid.php'); JLoader::register('EHtml', EPATH_LIBRARY . '/html/ehtml.php'); JLoader::register('EHtmlFormbehavior', EPATH_LIBRARY . '/html/formbehavior.php'); JLoader::register('EHtmlSelect', EPATH_LIBRARY . '/html/html/eselect.php'); JLoader::register('EExtensionHelper', EPATH_LIBRARY . '/helpers/extension.php'); JLoader::register('ExtlyModelExtensions', EPATH_LIBRARY . '/models/extensions.php'); JLoader::register('ExtlyTableExtension', EPATH_LIBRARY . '/tables/extension.php'); JLoader::register('EDbProxyHelper', EPATH_LIBRARY . '/helpers/dbproxy.php'); /** * This is the base class for the Extlyframework. * * @package Extly.Library * @subpackage lib_extly * @since 1.0 */ class Extlyframework { }
shukdelmadrij/shukdelmadrij
libraries/extly/extlyframework.php
PHP
gpl-2.0
2,432
//#include "..\kgb_arch_mfc\kgb_arch_mfcdlg.cpp" // kgb_arch_decompressDlg.cpp : implementation file // #include "stdafx.h" #include "kgb_arch_decompress.h" #include "kgb_arch_decompressDlg.h" #include "dDecompress.h" //#include "../compress/compress.cpp" #include <vector> #include <string> #include "io.h" #include "dlgPasswd.h" #include <psapi.h> #include "../zip/zipArchive.h" using namespace std; int MEM = 3; //GLOBALNE ZMIENNE DLA STATYSTYK!!! __int64 _size; __int64 _done; __int64 _size_all; __int64 _done_all; __int64 _compressed; string _filename; __int64 sTime; #define COMPRESS_PREPARING "\1" #define COMPRESS_GETTING_FILE_SIZES "\2" #define COMPRESS_SORTING "\3" #define COMPRESS_ADDING_SFX_MOD "\4" #define COMPRESS_ENCODING "\5" #define DECOMPRESS_PREPARING "\1" #define DECOMPRESS_CREATING_DIRS "\2" #define DECOMPRESS_SKIPPING "\3" //GLOBALNE ZMIENNE DLA W¥TKÓW char *archive_name; vector<string> filename; vector<string> files4decompress; char passwd[32];//256bit bool sfx_arch; void resetSettings(){ free(archive_name); filename.clear(); files4decompress.clear(); MEM = 3; _size = 0; _done = 0; _size_all = 0; _done_all = 0; sTime = 0; passwd[0] = '\0'; sfx_arch = 0; } #ifdef _DEBUG #define new DEBUG_NEW #endif dDecompress _dDecompress; void zipGetFiles(char *arch, vector<string>&filenames, vector<__int64>&filesizes){ CZipArchive zip; zip.Open(arch, CZipArchive::zipOpenReadOnly); for(int i=0;i<zip.GetCount(true);i++){ CZipFileHeader fhInfo; zip.GetFileInfo(fhInfo, i); filenames.push_back(fhInfo.GetFileName().GetBuffer()); filesizes.push_back(fhInfo.GetEffComprSize() != 0 ? __int64((float)fhInfo.GetEffComprSize()*100.0f/fhInfo.GetCompressionRatio()) : 0); } zip.Close(); } DWORD WINAPI zipDecompress(LPVOID lpParam){ _filename = DECOMPRESS_PREPARING; sTime = _time64(NULL); CZipArchive zip; vector<string>filenames; vector<__int64>filesizes; FILE *archive = fopen(archive_name, "rb"); if(!archive){ MessageBox(0, loadString(IDS_ARCHIVE_DOESNT_EXIST), "KGB Archiver", 0); return false; } fseek(archive, 0L, SEEK_END); _compressed = ftell(archive); fclose(archive); zipGetFiles(archive_name, filenames, filesizes); //char buff[123]; for(int i=0;i<filesizes.size();i++){ _size_all += filesizes[i]; /*if(filesizes[i] <= 0){ sprintf(buff, "%s %lld", filenames[i].c_str(), filesizes[i]); MessageBox(0, buff, "", 0);}*/ } /*sprintf(buff, "%lld", _size_all); MessageBox(0, buff, "", 0);*/ //MessageBox(0, "", "", 0); zip.Open(archive_name, CZipArchive::zipOpenReadOnly); for(int i=0;i<filenames.size();i++){ if(files4decompress.size() != 0){ for(int j=0;j<files4decompress.size();j++){ if(filenames[i] == files4decompress[j]){ _filename = filenames[i]; try{ zip.ExtractFile(i, ""); }catch(...){ CZipFileHeader fhInfo; zip.GetFileInfo(fhInfo, i); if(fhInfo.IsEncrypted()){ dlgPasswd dlgPass; if(dlgPass.DoModal() != IDOK){ _dDecompress.EndDialog(IDCANCEL); return false; } zip.SetPassword(dlgPass._passwd); j--; continue; } } break; } } }else{ _filename = filenames[i]; try{ zip.ExtractFile(i, ""); }catch(...){ CZipFileHeader fhInfo; zip.GetFileInfo(fhInfo, i); if(fhInfo.IsEncrypted()){ dlgPasswd dlgPass; if(dlgPass.DoModal() != IDOK){ _dDecompress.EndDialog(IDCANCEL); return false; } zip.SetPassword(dlgPass._passwd); i--; continue; } } } _done_all += filesizes[i]; } zip.Close(); return 0; } // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // Ckgb_arch_decompressDlg dialog Ckgb_arch_decompressDlg::Ckgb_arch_decompressDlg(CWnd* pParent /*=NULL*/) : CDialog(Ckgb_arch_decompressDlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void Ckgb_arch_decompressDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //DDX_Control(pDX, IDC_EARCHNAME, eArchName); DDX_Control(pDX, IDC_EARCHNAME2, eDestination); DDX_Control(pDX, IDC_LIST1, lFiles); DDX_Control(pDX, IDC_CHECK1, cSelect); } BEGIN_MESSAGE_MAP(Ckgb_arch_decompressDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_BN_CLICKED(IDC_BUTTON2, OnBnClickedButton2) // ON_BN_CLICKED(IDC_BBROWSE, OnBnClickedBbrowse) ON_BN_CLICKED(IDC_BUTTON1, OnBnClickedButton1) ON_BN_CLICKED(IDC_BBROWSE2, OnBnClickedBbrowse2) ON_BN_CLICKED(IDC_CHECK1, OnBnClickedCheck1) // ON_EN_CHANGE(IDC_EARCHNAME, OnEnChangeEarchname) END_MESSAGE_MAP() // Ckgb_arch_decompressDlg message handlers BOOL Ckgb_arch_decompressDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon //SetIcon(m_hIcon, TRUE); // Set small icon // TODO: Add extra initialization here lFiles.InsertColumn(0, loadString(IDS_FILE), LVCFMT_LEFT, 300); lFiles.InsertColumn(1, loadString(IDS_SIZE), LVCFMT_RIGHT, 100); char curDir[MAX_PATH]; GetCurrentDirectory(MAX_PATH, curDir); eDestination.SetWindowText(curDir); vector<string>files; vector<__int64>fsize; char arch[MAX_PATH]; HANDLE hProc = GetCurrentProcess(); HMODULE hMod; DWORD cbNeeded; EnumProcessModules(hProc, &hMod, sizeof(hMod), &cbNeeded); GetModuleFileNameEx(hProc, hMod, arch, MAX_PATH); //pierwszy modu³ jest aplikacj¹ //MessageBox(""); //getFilesFromArchive(arch, files, fsize); zipGetFiles(arch, files, fsize); //MessageBox(""); for(unsigned long i=0;i<files.size();i++){ char buffer[32]; /*if(filesizes[i] < 1024) sprintf(buffer, "%dB", filesizes[i]); else if(filesizes[i] < 1024*1024) sprintf(buffer, "%dKB", filesizes[i]/1024); else sprintf(buffer, "%dMB", filesizes[i]/1024/1024); */ sprintf(buffer, "%.1fKB", (double)fsize[i]/1024.0); lFiles.InsertItem(0, i, 0, 0, 0, 0, 0); lFiles.SetItemText(i, 0, files[i].c_str()); lFiles.SetItemText(i, 1, buffer); } return TRUE; // return TRUE unless you set the focus to a control } void Ckgb_arch_decompressDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void Ckgb_arch_decompressDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR Ckgb_arch_decompressDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void Ckgb_arch_decompressDlg::OnBnClickedButton2() { EndDialog(IDCANCEL); } DWORD WINAPI updateForm(LPVOID lpParam){ char buffer[1024]; unsigned __int64 time_sTime; unsigned __int64 temp; while(1){ try{ if(_size_all != 0 && /*_size != 0 && _done != 0 && _done_all != 0 && */_dDecompress.m_hWnd != NULL){ sprintf(buffer, "%s %.1f%%", loadString(IDS_DECOMPRESS_PROGRESS), (float)((_done_all+_done)*100)/(float)(_size_all)); _dDecompress.SetWindowText(buffer); _dDecompress.pTotal.SetRange32(0, 100); _dDecompress.pTotal.SetPos(((_done_all+_done)*100)/(_size_all)); _dDecompress.pCurrent.SetRange32(0, 100); _dDecompress.pCurrent.SetPos((_done*100)/(_size+1)); if(_filename.c_str()[0] > 32) _dDecompress.sFilename.SetWindowText(_filename.c_str()); else _dDecompress.sFilename.SetWindowText(loadString(IDS_DECOMPRESS_STATUS+_filename.c_str()[0]-1)); sprintf(buffer, "%.1fKB", (float)_size_all/1024.0); _dDecompress.sFullSize.SetWindowText(buffer); sprintf(buffer, "%.1fKB", (float)_compressed/1024.0); _dDecompress.sCompressedSize.SetWindowText(buffer); sprintf(buffer, "%.1f%%", ((float)_compressed*100.0)/(float)(_size_all)); _dDecompress.sRatio.SetWindowText(buffer); time_sTime = time(NULL)-sTime; if((temp = time_sTime/3600) < 10) sprintf(buffer, "0"); sprintf(buffer, "%s%ld:", buffer, temp); if((temp = (time_sTime%3600)/60) < 10) sprintf(buffer, "%s0", buffer); sprintf(buffer, "%s%ld:", buffer, temp); if((temp = time_sTime%60) < 10) sprintf(buffer, "%s0", buffer); sprintf(buffer, "%s%ld", buffer, temp); _dDecompress.sTime.SetWindowText(buffer); buffer[0] = '\0'; time_sTime = (unsigned __int64)((double)time_sTime/((double)(_done+_done_all+1)/(double)(_size_all))) - time_sTime; if((temp = time_sTime/3600) < 10) sprintf(buffer, "0"); sprintf(buffer, "%s%ld:", buffer, temp); if((temp = (time_sTime%3600)/60) < 10) sprintf(buffer, "%s0", buffer); sprintf(buffer, "%s%ld:", buffer, temp); if((temp = time_sTime%60) < 10) sprintf(buffer, "%s0", buffer); sprintf(buffer, "%s%ld", buffer, temp); _dDecompress.sRemaining.SetWindowText(buffer); //_dDecompress.UpdateWindow(); //_shutdown = _dDecompress.cShutdown.GetCheck(); if(_done_all == _size_all){ _dDecompress.EndDialog(IDOK); //return 0; } } }catch(...){} Sleep(500); } free(buffer); return 0; } void Ckgb_arch_decompressDlg::OnBnClickedButton1() { if(eDestination.GetWindowTextLength() == 0){ MessageBox(loadString(IDS_CHOOSE_EXTRACT_DIR), "KGB Archiver"); return; } resetSettings(); archive_name = (char *)malloc(sizeof(char)*MAX_PATH); //eArchName.GetWindowText(archive_name, MAX_PATH); HANDLE hProc = GetCurrentProcess(); HMODULE hMod; DWORD cbNeeded; EnumProcessModules(hProc, &hMod, sizeof(hMod), &cbNeeded); GetModuleFileNameEx(hProc, hMod, archive_name, MAX_PATH); //pierwszy modu³ jest aplikacj¹ if(_access(archive_name, 4) != 0){ MessageBox(loadString(IDS_ARCHIVE_NOT_FOUND), "KGB Archiver"); return; } char buffer[MAX_PATH]; eDestination.GetWindowText(buffer, MAX_PATH); CreateDirectory(buffer, NULL); if(!SetCurrentDirectory(buffer)){ MessageBox(loadString(IDS_CANT_CREATE_EXTRACT_DIR), "KGB Archiver"); return; } if(cSelect.GetCheck() == true){ if(lFiles.GetSelectedCount() == 0){ MessageBox(loadString(IDS_CHOOSE_FILES2DECOMPRESS), "KGB Archiver"); return; } POSITION i = lFiles.GetFirstSelectedItemPosition(); while(i != NULL){ //lFiles.DeleteItem(lFiles.GetNextSelectedItem(i)); //i = lFiles.GetFirstSelectedItemPosition(); char buffer[MAX_PATH]; lFiles.GetItemText(lFiles.GetNextSelectedItem(i), 0, buffer, MAX_PATH); files4decompress.push_back((string)buffer); } } ShowWindow(SW_HIDE); HANDLE hDecompress; DWORD hDecompressId; hDecompress = CreateThread(NULL, 0, zipDecompress, 0, 0, &hDecompressId); SetThreadPriority(hDecompress, THREAD_PRIORITY_LOWEST); HANDLE hUpdate; DWORD hUpdateId; hUpdate = CreateThread(NULL, 0, updateForm, 0, 0, &hUpdateId); if(_dDecompress.DoModal() == IDCANCEL){ TerminateThread(hDecompress, 0); MessageBox(loadString(IDS_EXTRACT_CANCELED), "KGB Archiver"); }else{ char buff[1024]; sprintf(buff, loadString(IDS_EXTRACT_SUCCED), (float)_size_all/1024.0, (float)_compressed/1024.0, ((float)_compressed*100.0)/(float)_size_all); MessageBox(buff, "KGB Archiver"); } TerminateThread(hUpdate, 0); EndDialog(IDOK); } void Ckgb_arch_decompressDlg::OnBnClickedBbrowse2() { BROWSEINFO bInfo; bInfo.hwndOwner = m_hWnd; bInfo.lpfn = NULL; bInfo.lParam = NULL; bInfo.lpszTitle = loadString(IDS_CHOOSE_DIR2DECOMPRESS); bInfo.pidlRoot = NULL; bInfo.ulFlags = BIF_USENEWUI | BIF_VALIDATE; bInfo.pszDisplayName = NULL;//foldername; LPITEMIDLIST pidl; if((pidl = SHBrowseForFolder(&bInfo)) != NULL){ char buff[MAX_PATH]; SHGetPathFromIDList(pidl, buff); //GetCurrentDirectory(MAX_PATH, foldername); //eDestination.SetWindowText(foldername); eDestination.SetWindowText(buff); } } void Ckgb_arch_decompressDlg::OnBnClickedCheck1() { lFiles.EnableWindow(cSelect.GetCheck()); } /*void Ckgb_arch_decompressDlg::OnEnChangeEarchname() { CString _arch; string arch; eArchName.GetWindowText(_arch); arch = _arch; vector<string> files; vector<unsigned long> filesizes; lFiles.DeleteAllItems(); if(fopen(arch.c_str(), "r") == 0) return; _fcloseall(); //dekodowanie archiwum if(arch.c_str()[arch.length()-1] == 'e' || arch.c_str()[arch.length()-1] == 'E'){ dlgPasswd dlgPass; if(dlgPass.DoModal() != IDOK){ eArchName.SetWindowText(""); return; } strcpy(passwd, dlgPass._passwd); for(int i=strlen(passwd);i<32;i++) passwd[i] = '\0'; char arch2[MAX_PATH]; //strcpy(arch2, arch.c_str()); GetTempPath(MAX_PATH, arch2); strcat(arch2, "temp.kgb"); //arch2[strlen(arch2)-1] = 'b'; aes_ctx ctx[1]; ctx->n_rnd = 0; // ensure all flags are initially set to zero ctx->n_blk = 0; aes_dec_key((const unsigned char*)passwd, 32, ctx); FILE *fin = fopen(arch.c_str(), "rb"); if(fin == 0) return; FILE *fout = fopen(arch2, "wb"); if(fout == 0) return; decfile(fin, fout, ctx, arch.c_str(), arch2); fclose(fin); fclose(fout); if(!checkArchiveFormat(arch2)){ _fcloseall(); DeleteFile(arch2); eArchName.SetWindowText(""); MessageBox("Nieprawid³owe has³o!"); return; } eArchName.SetWindowText(arch2); return; } if(!getFilesFromArchive((char *)arch.c_str(), files, filesizes)){ MessageBox("Wybrany plik nie jest prawid³owym archiwum KGB!"); eArchName.SetWindowText(""); return; } for(unsigned long i=0;i<files.size();i++){ char buffer[32]; /*if(filesizes[i] < 1024) sprintf(buffer, "%dB", filesizes[i]); else if(filesizes[i] < 1024*1024) sprintf(buffer, "%dKB", filesizes[i]/1024); else sprintf(buffer, "%dMB", filesizes[i]/1024/1024); * / sprintf(buffer, "%.1fKB", (double)filesizes[i]/1024.0); lFiles.InsertItem(0, i, 0, 0, 0, 0, 0); lFiles.SetItemText(i, 0, files[i].c_str()); lFiles.SetItemText(i, 1, buffer); } }*/
RandallFlagg/kgbarchiver
KGB Archiver 1/sfx/kgb_arch_sfx_zip/kgb_arch_decompressDlg.cpp
C++
gpl-2.0
15,501
#!/usr/bin/env python # -*- coding: utf-8 -*- class User(object): def __init__(self): self.first_name = None self.last_name = None self.username = None self.password = None def set_full_name(self, name): # Jaa välilyönnin mukaan pass
mtpajula/ijonmap
core/users/user.py
Python
gpl-2.0
308
/* putpwent.c */ #include "passwd.h" #ifdef L_putpwent int putpwent(pwd, f) struct passwd *pwd; FILE * f; { if (pwd == NULL || f == NULL) { errno = EINVAL; return -1; } if (fprintf(f, "%s:%s:%u:%u:%s:%s:%s\n", pwd->pw_name, pwd->pw_passwd, pwd->pw_uid, pwd->pw_gid, pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell) < 0) return -1; return 0; } #endif 
marioaugustorama/uzix-libc
LIBC/PUTPWENT.C
C++
gpl-2.0
402
# UPDATE THIS SECRET INFORMATION ! # # UNCOMMENT THIS FILE IN .gitignore BEFORE YOU COMMIT! # # SuperUser Default Password SUPER_USER_PASSWORD = 'CHANGEME' # Log into your Loggly account, visit: https://<Username>.loggly.com/tokens and copy the token here LOGGLY_TOKEN = 'CHANGEME' # Generate a very secure Django Secret to replace this one DJANGO_SECRET = 'CHANGEME' # OPTIONAL # # Replace the following with a copy of your environment variables if you wish to run the code locally # THe variables will only be available after you first deploy an app to Bluemix, whether the deployment succeeds or not. LOCALDEV_VCAP = { "cloudamqp": [ { "name": "CloudAMQP-sa", "label": "cloudamqp", "plan": "lemur", "credentials": { "uri": "amqp://CHANGEME:CHANGEME/CHANGEME", "http_api_uri": "https://CHANGEME:CHANGEME/api/" } } ], "user-provided": [ { "name": "PostgreSQL by Compose-lj", "label": "user-provided", "credentials": { "username": "CHANGEME", "password": "CHANGEME", "public_hostname": "localhost:5432" } } ] }
Chaffleson/blupy
settings_local.py
Python
gpl-2.0
1,195
/* * This file is part of the AshamaneCore Project. See AUTHORS file for Copyright information * Copyright (C) 2018+ MagicStormProject <https://github.com/MagicStormTeam> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "AreaTrigger.h" #include "AreaTriggerAI.h" #include "ScriptedCreature.h" #include "ScriptMgr.h" #include "SpellAuras.h" #include "Player.h" #include "SpellScript.h" #include "ScriptedGossip.h" #include "InstanceScript.h" #include "antorus_the_burning_throne.h" enum Spells { SPELL_TAESHALACH_S_REACH = 243431, //SPELL_TAESHALACH_S_REACH = 245990, //SPELL_FLAME_REND = 244033, SPELL_FLAME_REND = 245463,//???? //SPELL_FLAME_REND = 254654, //SPELL_FOE_BREAKER = 244291, SPELL_FOE_BREAKER = 245458,//??? //SPELL_FOE_BREAKER = 254655, SPELL_WAKE_OF_FLAME = 244693, //SPELL_WAKE_OF_FLAME = 244736, SPELL_BURNING_RAGE = 244713, SPELL_CORRUPT_AEGIS = 244894, SPELL_SEARING_TEMPEST = 245301, //SPELL_SEARING_TEMPEST = 246014, SPELL_SCORCHING_BLAZE = 245994, SPELL_EMPOWERED_FLAME_REND = 247079, //SPELL_EMPOWERED_FLAME_REND = 255058, SPELL_RAVENOUS_BLAZE = 254452, SPELL_EMPOWERED_FOE_BREAKER = 255059, //SPELL_EMPOWERED_FOE_BREAKER = 255060, SPELL_EMPOWERED_SEARING_TEMPEST = 255061, //SPELL_EMPOWERED_SEARING_TEMPEST = 255062, SPELL_SEARING_BINDING = 255528, SPELL_TAESHALACH_TECHNIQUE = 256208, // 244688 NPC_EMBER_OF_TAESHALACH = 122532, SPELL_BLAZING_ERUPTION = 244912, SPELL_MOLTEN_REMNANTS = 245905, //SPELL_SEARING_TEMPEST = 254653, SPELL_UNENDING_BLAZE = 254695, SPELL_TITANS_ASSEMBLE_MOVIE = 254311, SPELL_FLARE = 245983 }; enum Events { // Intro EVENT_INTRO = 1, EVNET_PHASE_2 = 2, EVNET_PHASE_3 = 3, EVENT_A1 = 4, EVENT_A2 = 5, EVENT_A3 = 6, EVENT_A4 = 7 }; enum Talk { TALK_AGGRAMAR_AGGRO = 1, TALK_AGGRAMAR_DEATH = 2, TALK_AGGRAMAR_LOS = 3, TALK_AGGRAMAR_HP80 = 4, TALK_AGGRAMAR_WAKE_OF_FLAME = 5 }; enum Phases { PHASE_NORMAL, PHASE_INTRO, PHASE_1, PHASE_2, PHASE_3, PHASE_4, }; struct SpawnData { uint32 event, npcId; float X; float Y; float Z; float orientation; }; SpawnData const spawnData[] = { { EVNET_PHASE_2, NPC_EMBER_OF_TAESHALACH, -12679.456f, -2254.8264f, 2514.2646f }, { EVNET_PHASE_2, NPC_EMBER_OF_TAESHALACH, -12588.12f, -2254.8215f, 2514.6276f, 3.101369f }, { EVNET_PHASE_3, NPC_EMBER_OF_TAESHALACH, -12679.456f, -2254.8264f, 2514.2646f }, { EVNET_PHASE_3, NPC_EMBER_OF_TAESHALACH, -12588.12f, -2254.8215f, 2514.6276f, 3.101369f }, }; struct boss_aggramar : public BossAI { boss_aggramar(Creature* creature) : BossAI(creature, DATA_AGGRAMAR) { Initialize(); } void Initialize() { PhaseStatus = Phases::PHASE_INTRO; } void LoadNPC(uint32 event, const SpawnData* data) { while (data->event) { if (data->event == event) me->SummonCreature(data->npcId, Position(data->X, data->Y, data->Z, data->orientation), TEMPSUMMON_MANUAL_DESPAWN, WEEK); ++data; } } void EnterCombat(Unit* who) override { if (who->ToPlayer()) if (roll_chance_i(30)) Talk(TALK_AGGRAMAR_AGGRO); } void JustDied(Unit* killer) override { _JustDied(); instance->SetBossState(DATA_AGGRAMAR, DONE); if (killer->ToPlayer()) if (roll_chance_i(30)) Talk(TALK_AGGRAMAR_DEATH); instance->DoDelayedConversation(2000, 6127); } void DamageTaken(Unit* /*attacker*/, uint32& damage) override { if (me->HealthWillBeBelowPctDamaged(80, damage)) { PhaseStatus = PHASE_2; events.Reset(); me->GetMotionMaster()->MovePoint(1, Position(-12634.2f, -2255.2478f, 2514.2617f, 4.674f)); Talk(TALK_AGGRAMAR_HP80); DoCastSelf(SPELL_CORRUPT_AEGIS); LoadNPC(EVNET_PHASE_2, spawnData); killCount = 2; events.RescheduleEvent(EVNET_PHASE_2, 1s); } else if (me->HealthWillBeBelowPctDamaged(40, damage)) { PhaseStatus = PHASE_3; events.Reset(); me->GetMotionMaster()->MovePoint(1, Position(-12634.2f, -2255.2478f, 2514.2617f, 4.674f)); DoCastSelf(SPELL_CORRUPT_AEGIS); LoadNPC(EVNET_PHASE_3, spawnData); killCount = 2; events.RescheduleEvent(EVNET_PHASE_3, 1s); //SPELL_WAKE_OF_FLAME replace by 245983 flare Talk(7) } } void DoAction(int32 action) override { if (action == 1) { PhaseStatus = PHASE_INTRO; instance->SetBossState(DATA_AGGRAMAR, SPECIAL); events.Reset(); //events.ScheduleEvent(EVENT_INTRO_GLAIDALIS_1, 5000); } if (action == 2) { --killCount; if (killCount <= 0) { me->RemoveAurasDueToSpell(SPELL_CORRUPT_AEGIS); //events.ScheduleEvent(SPELL_FLAME_REND, 5s); //events.ScheduleEvent(SPELL_FOE_BREAKER, 5s); if(PhaseStatus<PHASE_2) events.ScheduleEvent(SPELL_WAKE_OF_FLAME, 6s); else events.ScheduleEvent(SPELL_FLARE, 6s); //events.ScheduleEvent(SPELL_BURNING_RAGE, 5s); //events.ScheduleEvent(SPELL_CORRUPT_AEGIS, 5s); //events.ScheduleEvent(SPELL_SEARING_TEMPEST, 5s); events.ScheduleEvent(SPELL_SCORCHING_BLAZE, 8s); events.ScheduleEvent(SPELL_TAESHALACH_TECHNIQUE, 60s); if (me->GetMap()->IsMythic()) { events.ScheduleEvent(SPELL_EMPOWERED_FLAME_REND, 5s); events.ScheduleEvent(SPELL_RAVENOUS_BLAZE, 5s); events.ScheduleEvent(SPELL_EMPOWERED_FOE_BREAKER, 5s); events.ScheduleEvent(SPELL_EMPOWERED_SEARING_TEMPEST, 5s); events.ScheduleEvent(SPELL_SEARING_BINDING, 5s); } } } } void ScheduleTasks() override { //Talk(0); DoCastSelf(SPELL_TAESHALACH_S_REACH); //events.ScheduleEvent(SPELL_FLAME_REND, 5s); //events.ScheduleEvent(SPELL_FOE_BREAKER, 5s); if (PhaseStatus<PHASE_2) events.ScheduleEvent(SPELL_WAKE_OF_FLAME, 6s); else events.ScheduleEvent(SPELL_FLARE, 6s); //events.ScheduleEvent(SPELL_BURNING_RAGE, 5s); //events.ScheduleEvent(SPELL_CORRUPT_AEGIS, 5s); //events.ScheduleEvent(SPELL_SEARING_TEMPEST, 5s); events.ScheduleEvent(SPELL_SCORCHING_BLAZE, 8s); events.ScheduleEvent(SPELL_TAESHALACH_TECHNIQUE, 60s); if (me->GetMap()->IsMythic()) { events.ScheduleEvent(SPELL_EMPOWERED_FLAME_REND, 5s); events.ScheduleEvent(SPELL_RAVENOUS_BLAZE, 5s); events.ScheduleEvent(SPELL_EMPOWERED_FOE_BREAKER, 5s); events.ScheduleEvent(SPELL_EMPOWERED_SEARING_TEMPEST, 5s); events.ScheduleEvent(SPELL_SEARING_BINDING, 5s); } } void ExecuteEvent(uint32 eventId) override { switch (eventId) { case SPELL_WAKE_OF_FLAME: { Talk(TALK_AGGRAMAR_WAKE_OF_FLAME); DoCast(SPELL_WAKE_OF_FLAME); events.Repeat(25s); break; } case SPELL_FLARE: { if (Unit* target1 = SelectTarget(SELECT_TARGET_RANDOM, 0.0, 0.0, true)) me->CastSpell(target1, SPELL_FLARE, false); if (Unit* target2 = SelectTarget(SELECT_TARGET_RANDOM, 0.0, 0.0, true)) me->CastSpell(target2, SPELL_FLARE, false); if (Unit* target3 = SelectTarget(SELECT_TARGET_RANDOM, 0.0, 0.0, true)) me->CastSpell(target3, SPELL_FLARE, false); events.Repeat(25s); break; } case SPELL_SEARING_TEMPEST: { DoCast(SPELL_SEARING_TEMPEST); //events.Repeat(20s); break; } case SPELL_SCORCHING_BLAZE: { if (Unit* target1 = SelectTarget(SELECT_TARGET_RANDOM, 0.0, 0.0, true)) me->CastSpell(target1, SPELL_SCORCHING_BLAZE, false); if (Unit* target2 = SelectTarget(SELECT_TARGET_RANDOM, 0.0, 0.0, true)) me->CastSpell(target2, SPELL_SCORCHING_BLAZE, false); events.Repeat(8s); break; } case SPELL_TAESHALACH_TECHNIQUE: { // alexkulya: text & textemote? //Talk(2); //Talk(3); DoCast(SPELL_TAESHALACH_TECHNIQUE); events.ScheduleEvent(EVENT_A1, 1s); events.Repeat(60s); break; } case EVENT_A1: { DoCast(SPELL_FOE_BREAKER); events.ScheduleEvent(EVENT_A2, 4s); break; } case EVENT_A2: { DoCast(SPELL_FLAME_REND); DoCast(SPELL_BURNING_RAGE); events.ScheduleEvent(EVENT_A3, 4s); break; } case EVENT_A3: { DoCast(SPELL_FOE_BREAKER); events.ScheduleEvent(EVENT_A4, 4s); break; } case EVENT_A4: { DoCast(SPELL_FLAME_REND); DoCast(SPELL_BURNING_RAGE); events.ScheduleEvent(SPELL_SEARING_TEMPEST, 5s); break; } case SPELL_EMPOWERED_FLAME_REND: { DoCast(SPELL_EMPOWERED_FLAME_REND); events.Repeat(5s); break; } case SPELL_RAVENOUS_BLAZE: { DoCast(SPELL_RAVENOUS_BLAZE); events.Repeat(5s); break; } case SPELL_EMPOWERED_FOE_BREAKER: { DoCast(SPELL_EMPOWERED_FOE_BREAKER); events.Repeat(5s); break; } case SPELL_EMPOWERED_SEARING_TEMPEST: { DoCast(SPELL_EMPOWERED_SEARING_TEMPEST); events.Repeat(5s); break; } case SPELL_SEARING_BINDING: { DoCast(SPELL_SEARING_BINDING); events.Repeat(5s); break; } default: break; } } void MoveInLineOfSight(Unit* who) override { if (who->IsPlayer() && me->IsWithinDist(who, 50.0f, false) && PhaseStatus == Phases::PHASE_INTRO) { PhaseStatus = Phases::PHASE_1; Talk(TALK_AGGRAMAR_LOS); me->RemoveUnitFlag(UnitFlags(UNIT_FLAG_IMMUNE_TO_PC)); } } void JustSummoned(Creature* summon) override { BossAI::JustSummoned(summon); switch (summon->GetEntry()) { case NPC_EMBER_OF_TAESHALACH: { summon->SetFaction(me->GetFaction()); summon->GetMotionMaster()->MovePoint(1, Position(-12634.2f, -2255.2478f, 2514.2617f, 4.674f)); break; } } } uint8 PhaseStatus; uint8 killCount; }; struct npc_ember_of_taeshalach_122532 : public ScriptedAI { npc_ember_of_taeshalach_122532(Creature* creature) : ScriptedAI(creature) { } void UpdateAI(uint32 diff) override { events.Update(diff); if (!UpdateVictim()) return; } void JustDied(Unit* /*killer*/) override { if (Creature* aggramar = me->FindNearestCreature(NPC_AGGRAMAR, 50.0f, true)) aggramar->AI()->DoAction(2); DoCastSelf(SPELL_MOLTEN_REMNANTS); } void MoveInLineOfSight(Unit* who) override { if (who->GetEntry() == NPC_AGGRAMAR && me->IsWithinDist(who, 3.0f, false)) { DoCastAOE(SPELL_BLAZING_ERUPTION); me->KillSelf(); } } }; struct npc_magni_bronzebeard_128169 : public ScriptedAI { npc_magni_bronzebeard_128169(Creature* creature) : ScriptedAI(creature) { } bool GossipSelect(Player* player, uint32 /*menuId*/, uint32 gossipListId) { CloseGossipMenuFor(player); player->CastSpell(player, SPELL_TITANS_ASSEMBLE_MOVIE, true); player->TeleportTo(4000, 1712, 2826.39f, -4567.94f, 291.95f, 0.02513274f); return false; } }; void AddSC_boss_aggramar() { RegisterCreatureAI(boss_aggramar); RegisterCreatureAI(npc_ember_of_taeshalach_122532); RegisterCreatureAI(npc_magni_bronzebeard_128169); }
AshamaneProject/AshamaneCore
src/server/scripts/BrokenIsles/Anthorus/boss_aggramar.cpp
C++
gpl-2.0
14,489
/* * Copyright 2008 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. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact 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. */ package neomantic.com.sun.beans; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.util.Map; import java.util.WeakHashMap; /** * A hashtable-based cache with weak keys and weak values. * An entry in the map will be automatically removed * when its key is no longer in the ordinary use. * A value will be automatically removed as well * when it is no longer in the ordinary use. * * @since 1.7 * * @author Sergey A. Malenkov */ public final class WeakCache<K, V> { private final Map<K, Reference<V>> map = new WeakHashMap<K, Reference<V>>(); /** * Returns a value to which the specified {@code key} is mapped, * or {@code null} if this map contains no mapping for the {@code key}. * * @param key the key whose associated value is returned * @return a value to which the specified {@code key} is mapped */ public V get(K key) { Reference<V> reference = this.map.get(key); if (reference == null) { return null; } V value = reference.get(); if (value == null) { this.map.remove(key); } return value; } /** * Associates the specified {@code value} with the specified {@code key}. * Removes the mapping for the specified {@code key} from this cache * if it is present and the specified {@code value} is {@code null}. * If the cache previously contained a mapping for the {@code key}, * the old value is replaced by the specified {@code value}. * * @param key the key with which the specified value is associated * @param value the value to be associated with the specified key */ public void put(K key, V value) { if (value != null) { this.map.put(key, new WeakReference<V>(value)); } else { this.map.remove(key); } } /** * Removes all of the mappings from this cache. */ public void clear() { this.map.clear(); } }
neomantic/Android-SISC-Scheme-Eval
src/neomantic/com/sun/beans/WeakCache.java
Java
gpl-2.0
3,231
/* * Copyright (C) 2005-2017 Team Kodi * http://kodi.tv * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with KODI; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "DialogNumeric.h" #include "addons/kodi-addon-dev-kit/include/kodi/gui/DialogNumeric.h" #include "XBDateTime.h" #include "addons/AddonDll.h" #include "dialogs/GUIDialogNumeric.h" #include "utils/log.h" extern "C" { namespace ADDON { void Interface_GUIDialogNumeric::Init(AddonGlobalInterface* addonInterface) { addonInterface->toKodi->kodi_gui->dialogNumeric = static_cast<AddonToKodiFuncTable_kodi_gui_dialogNumeric*>(malloc(sizeof(AddonToKodiFuncTable_kodi_gui_dialogNumeric))); addonInterface->toKodi->kodi_gui->dialogNumeric->show_and_verify_new_password = show_and_verify_new_password; addonInterface->toKodi->kodi_gui->dialogNumeric->show_and_verify_password = show_and_verify_password; addonInterface->toKodi->kodi_gui->dialogNumeric->show_and_verify_input = show_and_verify_input; addonInterface->toKodi->kodi_gui->dialogNumeric->show_and_get_time = show_and_get_time; addonInterface->toKodi->kodi_gui->dialogNumeric->show_and_get_date = show_and_get_date; addonInterface->toKodi->kodi_gui->dialogNumeric->show_and_get_ip_address = show_and_get_ip_address; addonInterface->toKodi->kodi_gui->dialogNumeric->show_and_get_number = show_and_get_number; addonInterface->toKodi->kodi_gui->dialogNumeric->show_and_get_seconds = show_and_get_seconds; } void Interface_GUIDialogNumeric::DeInit(AddonGlobalInterface* addonInterface) { free(addonInterface->toKodi->kodi_gui->dialogNumeric); } bool Interface_GUIDialogNumeric::show_and_verify_new_password(void* kodiBase, char** password) { CAddonDll* addon = static_cast<CAddonDll*>(kodiBase); if (!addon) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid data", __FUNCTION__); return false; } std::string str; bool bRet = CGUIDialogNumeric::ShowAndVerifyNewPassword(str); if (bRet) *password = strdup(str.c_str()); return bRet; } int Interface_GUIDialogNumeric::show_and_verify_password(void* kodiBase, const char* password, const char* heading, int retries) { CAddonDll* addon = static_cast<CAddonDll*>(kodiBase); if (!addon) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid data", __FUNCTION__); return -1; } if (!password || !heading) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid handler data (password='%p', heading='%p') on addon '%s'", __FUNCTION__, password, heading, addon->ID().c_str()); return -1; } std::string pw(password); return CGUIDialogNumeric::ShowAndVerifyPassword(pw, heading, retries); } bool Interface_GUIDialogNumeric::show_and_verify_input(void* kodiBase, const char* verify_in, char** verify_out, const char* heading, bool verify_input) { CAddonDll* addon = static_cast<CAddonDll*>(kodiBase); if (!addon) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid data", __FUNCTION__); return false; } if (!verify_in || !verify_out || !heading) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid handler data (verify_in='%p', verify_out='%p', heading='%p') on addon '%s'", __FUNCTION__, verify_in, verify_out, heading, addon->ID().c_str()); return false; } std::string str = verify_in; bool bRet = CGUIDialogNumeric::ShowAndVerifyInput(str, heading, verify_input); if (bRet) *verify_out = strdup(str.c_str()); return bRet; } bool Interface_GUIDialogNumeric::show_and_get_time(void* kodiBase, tm* time, const char* heading) { CAddonDll* addon = static_cast<CAddonDll*>(kodiBase); if (!addon) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid data", __FUNCTION__); return false; } if (!time || !heading) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid handler data (time='%p', heading='%p') on addon '%s'", __FUNCTION__, time, heading, addon->ID().c_str()); return false; } SYSTEMTIME systemTime; CDateTime dateTime(*time); dateTime.GetAsSystemTime(systemTime); if (CGUIDialogNumeric::ShowAndGetTime(systemTime, heading)) { dateTime = systemTime; dateTime.GetAsTm(*time); return true; } return false; } bool Interface_GUIDialogNumeric::show_and_get_date(void* kodiBase, tm *date, const char *heading) { CAddonDll* addon = static_cast<CAddonDll*>(kodiBase); if (!addon) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid data", __FUNCTION__); return false; } if (!date || !heading) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid handler data (date='%p', heading='%p') on addon '%s'", __FUNCTION__, date, heading, addon->ID().c_str()); return false; } SYSTEMTIME systemTime; CDateTime dateTime(*date); dateTime.GetAsSystemTime(systemTime); if (CGUIDialogNumeric::ShowAndGetDate(systemTime, heading)) { dateTime = systemTime; dateTime.GetAsTm(*date); return true; } return false; } bool Interface_GUIDialogNumeric::show_and_get_ip_address(void* kodiBase, const char* ip_address_in, char** ip_address_out, const char *heading) { CAddonDll* addon = static_cast<CAddonDll*>(kodiBase); if (!addon) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid data", __FUNCTION__); return false; } if (!ip_address_in || !ip_address_out || !heading) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid handler data (ip_address_in='%p', ip_address_out='%p', heading='%p') on addon '%s'", __FUNCTION__, ip_address_in, ip_address_out, heading, addon->ID().c_str()); return false; } std::string strIP = ip_address_in; bool bRet = CGUIDialogNumeric::ShowAndGetIPAddress(strIP, heading); if (bRet) *ip_address_out = strdup(strIP.c_str()); return bRet; } bool Interface_GUIDialogNumeric::show_and_get_number(void* kodiBase, const char* number_in, char** number_out, const char *heading, unsigned int auto_close_ms) { CAddonDll* addon = static_cast<CAddonDll*>(kodiBase); if (!addon) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid data", __FUNCTION__); return false; } if (!number_in || !number_out || !heading) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid handler data (number_in='%p', number_out='%p', heading='%p') on addon '%s'", __FUNCTION__, number_in, number_out, heading, addon->ID().c_str()); return false; } std::string str = number_in; bool bRet = CGUIDialogNumeric::ShowAndGetNumber(str, heading, auto_close_ms); if (bRet) *number_out = strdup(str.c_str()); return bRet; } bool Interface_GUIDialogNumeric::show_and_get_seconds(void* kodiBase, const char* time_in, char** time_out, const char *heading) { CAddonDll* addon = static_cast<CAddonDll*>(kodiBase); if (!addon) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid data", __FUNCTION__); return false; } if (!time_in || !time_out || !heading) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid handler data (time_in='%p', time_out='%p', heading='%p') on addon '%s'", __FUNCTION__, time_in, time_out, heading, addon->ID().c_str()); return false; } std::string str = time_in; bool bRet = CGUIDialogNumeric::ShowAndGetSeconds(str, heading); if (bRet) *time_out = strdup(str.c_str()); return bRet; } } /* namespace ADDON */ } /* extern "C" */
ObvB/xbmc
xbmc/addons/interfaces/GUI/DialogNumeric.cpp
C++
gpl-2.0
8,182
/* * DAWN OF LIGHT - The first free open source DAoC server emulator * * 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. * */ namespace Niflib { #if OpenTK using OpenTK; #elif SharpDX using SharpDX; #elif MonoGame using Microsoft.Xna.Framework; #endif using System; using System.IO; /// <summary> /// Class SkinData. /// </summary> public class SkinData { /// <summary> /// The transform /// </summary> public SkinTransform Transform; /// <summary> /// The bounding sphere offset /// </summary> public Vector3 BoundingSphereOffset; /// <summary> /// The bounding sphere radius /// </summary> public float BoundingSphereRadius; /// <summary> /// The unkown13 shorts /// </summary> public ushort[] Unkown13Shorts; /// <summary> /// The number vertices /// </summary> public ushort NumVertices; /// <summary> /// The vertex weights /// </summary> public SkinWeight[] VertexWeights; /// <summary> /// Initializes a new instance of the <see cref="SkinData"/> class. /// </summary> /// <param name="file">The file.</param> /// <param name="reader">The reader.</param> /// <param name="hasVertexWeights">if set to <c>true</c> [has vertex weights].</param> public SkinData(NiFile file, BinaryReader reader, bool hasVertexWeights) { this.Transform = new SkinTransform(file, reader); this.BoundingSphereOffset = reader.ReadVector3(); this.BoundingSphereRadius = reader.ReadSingle(); if (file.Version == eNifVersion.VER_20_3_0_9 && file.Header.UserVersion == 131072u) { this.Unkown13Shorts = new ushort[13]; for (int i = 0; i < 13; i++) { this.Unkown13Shorts[i] = reader.ReadUInt16(); } } this.NumVertices = reader.ReadUInt16(); if (hasVertexWeights) { this.VertexWeights = new SkinWeight[(int)this.NumVertices]; for (int j = 0; j < (int)this.NumVertices; j++) { this.VertexWeights[j] = new SkinWeight(file, reader); } } } } }
dol-leodagan/niflib.net
Niflib/SkinData.cs
C#
gpl-2.0
2,847
<?php error_reporting(E_ALL); if (!defined('DIR_KVZLIB')) { define('DIR_KVZLIB', dirname(dirname(dirname(dirname(dirname(__FILE__)))))); } ?> // LANG::xml // Sample starts here <?php require_once DIR_KVZLIB.'/php/classes/KvzHTML.php'; $H = new KvzHTML(array( 'xml' => true, )); $cdataOpts = array('__cdata' => true); $H->setOption('echo', true); $H->xml(true, array( 'version' => '2.0', 'encoding' => 'UTF-16', )); $H->setOption('echo', false); echo $H->auth( $H->username('kvz', $cdataOpts) . $H->api_key(sha1('xxxxxxxxxxxxxxxx'), $cdataOpts) ); echo $H->users_list(true); echo $H->users(true, array('type' => 'array')); echo $H->user( $H->id(442, $cdataOpts) . $H->name('Jason Shellen', $cdataOpts) . $H->screen_name('shellen', $cdataOpts) . $H->location('iPhone: 37.889321,-122.173345', $cdataOpts) . $H->description('CEO and founder of Thing Labs, makers of Brizzly! Former Blogger/Google dude, father of two little dudes.', $cdataOpts) ); echo $H->users(false); echo $H->users_list(false); ?>
thebillkidy/desple.com
wp-content/themes/capsule/ui/lib/phpjs/ext/kvzlib/php/samples/classes/KvzHTML/sample5-xml-complex.php
PHP
gpl-2.0
1,109
from getdist import loadMCSamples,plots,covmat import numpy as np import os,fnmatch #filenames = fnmatch.filter(os.listdir("../output/chains/"),"mcmc_*.txt") #for index in range(len(filenames)): # os.rename("../output/chains/"+str(filenames[index]),"../output/chains/mcmc_final_output_"+str(index+1)+".txt") number_of_parameters = 10 samples = loadMCSamples('../output/chains/NC-run4/mcmc_final_output',settings={'ignore_rows':0.}) p = samples.getParams() samples.addDerived(np.log(1.e1**10*p.A_s),name='ln1010As',label='\ln 10^{10}A_s') samples.addDerived(np.log10(p.cs2_fld),name='logcs2fld',label='\log c_s^2') bestfit = samples.getLikeStats() means = samples.setMeans() filebestfit = open("../output/chains/bestfit.txt",'w') filemeans = open("../output/chains/means.txt",'w') for index in range(number_of_parameters) : filebestfit.write(str(bestfit.names[index].bestfit_sample)+"\n") filemeans.write(str(means[index])+"\n") filebestfit.close() filemeans.close() covariance_matrix = samples.getCov(pars=[0,1,2,10,4,5,6,11,8,9])#nparam=number_of_parameters) covariance_matrix_2 = covmat.CovMat(matrix=covariance_matrix) covariance_matrix_2.saveToFile('../output/chains/covariance_matrix.txt') print 'COVARIANCE MATRIX CREATED' exit()
wilmarcardonac/fisher-mcmc
analyzer/compute_cov.py
Python
gpl-2.0
1,275
/* * CINELERRA * Copyright (C) 2009 Adam Williams <broadcast at earthling dot net> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include "asset.h" #include "bcsignals.h" #include "cache.h" #include "condition.h" #include "datatype.h" #include "edits.h" #include "edl.h" #include "edlsession.h" #include "file.h" #include "format.inc" #include "localsession.h" #include "mainsession.h" #include "mwindow.h" #include "overlayframe.h" #include "playabletracks.h" #include "playbackengine.h" #include "preferences.h" #include "preferencesthread.h" #include "renderengine.h" #include "strategies.inc" #include "tracks.h" #include "transportque.h" #include "units.h" #include "vedit.h" #include "vframe.h" #include "videoconfig.h" #include "videodevice.h" #include "virtualconsole.h" #include "virtualvconsole.h" #include "vmodule.h" #include "vrender.h" #include "vtrack.h" VRender::VRender(RenderEngine *renderengine) : CommonRender(renderengine) { data_type = TRACK_VIDEO; transition_temp = 0; overlayer = new OverlayFrame(renderengine->preferences->processors); input_temp = 0; vmodule_render_fragment = 0; playback_buffer = 0; session_frame = 0; asynchronous = 0; // render 1 frame at a time framerate_counter = 0; video_out = 0; render_strategy = -1; } VRender::~VRender() { if(input_temp) delete input_temp; if(transition_temp) delete transition_temp; if(overlayer) delete overlayer; } VirtualConsole* VRender::new_vconsole_object() { return new VirtualVConsole(renderengine, this); } int VRender::get_total_tracks() { return renderengine->get_edl()->tracks->total_video_tracks(); } Module* VRender::new_module(Track *track) { return new VModule(renderengine, this, 0, track); } int VRender::flash_output() { if(video_out) return renderengine->video->write_buffer(video_out, renderengine->get_edl()); else return 0; } int VRender::process_buffer(VFrame *video_out, int64_t input_position, int use_opengl) { // process buffer for non realtime int64_t render_len = 1; int reconfigure = 0; this->video_out = video_out; current_position = input_position; reconfigure = vconsole->test_reconfigure(input_position, render_len); if(reconfigure) restart_playback(); return process_buffer(input_position, use_opengl); } int VRender::process_buffer(int64_t input_position, int use_opengl) { VEdit *playable_edit = 0; int colormodel; int use_vconsole = 1; int use_brender = 0; int result = 0; int use_cache = renderengine->command->single_frame(); int use_asynchronous = renderengine->command->realtime && renderengine->get_edl()->session->video_every_frame && renderengine->get_edl()->session->video_asynchronous; const int debug = 0; // Determine the rendering strategy for this frame. use_vconsole = get_use_vconsole(&playable_edit, input_position, use_brender); if(debug) printf("VRender::process_buffer %d use_vconsole=%d\n", __LINE__, use_vconsole); // Negotiate color model colormodel = get_colormodel(playable_edit, use_vconsole, use_brender); if(debug) printf("VRender::process_buffer %d\n", __LINE__); // Get output buffer from device if(renderengine->command->realtime && !renderengine->is_nested) { renderengine->video->new_output_buffer(&video_out, colormodel); } if(debug) printf("VRender::process_buffer %d video_out=%p\n", __LINE__, video_out); // printf("VRender::process_buffer use_vconsole=%d colormodel=%d video_out=%p\n", // use_vconsole, // colormodel, // video_out); // Read directly from file to video_out if(!use_vconsole) { if(use_brender) { Asset *asset = renderengine->preferences->brender_asset; File *file = renderengine->get_vcache()->check_out(asset, renderengine->get_edl()); if(file) { int64_t corrected_position = current_position; if(renderengine->command->get_direction() == PLAY_REVERSE) corrected_position--; // Cache single frames only if(use_asynchronous) file->start_video_decode_thread(); else file->stop_video_thread(); if(use_cache) file->set_cache_frames(1); int64_t normalized_position = (int64_t)(corrected_position * asset->frame_rate / renderengine->get_edl()->session->frame_rate); file->set_video_position(normalized_position, 0); file->read_frame(video_out); if(use_cache) file->set_cache_frames(0); renderengine->get_vcache()->check_in(asset); } } else if(playable_edit) { if(debug) printf("VRender::process_buffer %d\n", __LINE__); result = ((VEdit*)playable_edit)->read_frame(video_out, current_position, renderengine->command->get_direction(), renderengine->get_vcache(), 1, use_cache, use_asynchronous); if(debug) printf("VRender::process_buffer %d\n", __LINE__); } video_out->set_opengl_state(VFrame::RAM); } else // Read into virtual console { // process this buffer now in the virtual console result = ((VirtualVConsole*)vconsole)->process_buffer(input_position, use_opengl); } return result; } // Determine if virtual console is needed int VRender::get_use_vconsole(VEdit* *playable_edit, int64_t position, int &use_brender) { *playable_edit = 0; // Background rendering completed if((use_brender = renderengine->brender_available(position, renderengine->command->get_direction())) != 0) return 0; // Descend into EDL nest return renderengine->get_edl()->get_use_vconsole(playable_edit, position, renderengine->command->get_direction(), vconsole->playable_tracks); } int VRender::get_colormodel(VEdit *playable_edit, int use_vconsole, int use_brender) { int colormodel = renderengine->get_edl()->session->color_model; if(!use_vconsole && !renderengine->command->single_frame()) { // Get best colormodel supported by the file int driver = renderengine->config->vconfig->driver; File *file; Asset *asset; if(use_brender) { asset = renderengine->preferences->brender_asset; } else { int64_t source_position = 0; asset = playable_edit->get_nested_asset(&source_position, current_position, renderengine->command->get_direction()); } if(asset) { file = renderengine->get_vcache()->check_out(asset, renderengine->get_edl()); if(file) { colormodel = file->get_best_colormodel(driver); renderengine->get_vcache()->check_in(asset); } } } return colormodel; } void VRender::run() { int reconfigure; const int debug = 0; // Want to know how many samples rendering each frame takes. // Then use this number to predict the next frame that should be rendered. // Be suspicious of frames that render late so have a countdown // before we start dropping. int64_t current_sample, start_sample, end_sample; // Absolute counts. int64_t skip_countdown = VRENDER_THRESHOLD; // frames remaining until drop int64_t delay_countdown = VRENDER_THRESHOLD; // Frames remaining until delay // Number of frames before next reconfigure int64_t current_input_length; // Number of frames to skip. int64_t frame_step = 1; int use_opengl = (renderengine->video && renderengine->video->out_config->driver == PLAYBACK_X11_GL); first_frame = 1; // Number of frames since start of rendering session_frame = 0; framerate_counter = 0; framerate_timer.update(); start_lock->unlock(); if(debug) printf("VRender::run %d\n", __LINE__); while(!done && !interrupt ) { // Perform the most time consuming part of frame decompression now. // Want the condition before, since only 1 frame is rendered // and the number of frames skipped after this frame varies. current_input_length = 1; reconfigure = vconsole->test_reconfigure(current_position, current_input_length); if(debug) printf("VRender::run %d\n", __LINE__); if(reconfigure) restart_playback(); if(debug) printf("VRender::run %d\n", __LINE__); process_buffer(current_position, use_opengl); if(debug) printf("VRender::run %d\n", __LINE__); if(renderengine->command->single_frame()) { if(debug) printf("VRender::run %d\n", __LINE__); flash_output(); frame_step = 1; done = 1; } else // Perform synchronization { // Determine the delay until the frame needs to be shown. current_sample = (int64_t)(renderengine->sync_position() * renderengine->command->get_speed()); // latest sample at which the frame can be shown. end_sample = Units::tosamples(session_frame, renderengine->get_edl()->session->sample_rate, renderengine->get_edl()->session->frame_rate); // earliest sample by which the frame needs to be shown. start_sample = Units::tosamples(session_frame - 1, renderengine->get_edl()->session->sample_rate, renderengine->get_edl()->session->frame_rate); if(first_frame || end_sample < current_sample) { // Frame rendered late or this is the first frame. Flash it now. //printf("VRender::run %d\n", __LINE__); flash_output(); if(renderengine->get_edl()->session->video_every_frame) { // User wants every frame. frame_step = 1; } else if(skip_countdown > 0) { // Maybe just a freak. frame_step = 1; skip_countdown--; } else { // Get the frames to skip. delay_countdown = VRENDER_THRESHOLD; frame_step = 1; frame_step += (int64_t)Units::toframes(current_sample, renderengine->get_edl()->session->sample_rate, renderengine->get_edl()->session->frame_rate); frame_step -= (int64_t)Units::toframes(end_sample, renderengine->get_edl()->session->sample_rate, renderengine->get_edl()->session->frame_rate); } } else { // Frame rendered early or just in time. frame_step = 1; if(delay_countdown > 0) { // Maybe just a freak delay_countdown--; } else { skip_countdown = VRENDER_THRESHOLD; if(start_sample > current_sample) { int64_t delay_time = (int64_t)((float)(start_sample - current_sample) * 1000 / renderengine->get_edl()->session->sample_rate); if( delay_time > 1000 ) delay_time = 1000; timer.delay(delay_time); } else { // Came after the earliest sample so keep going } } // Flash frame now. //printf("VRender::run %d " _LD "\n", __LINE__, current_input_length); flash_output(); } } if(debug) printf("VRender::run %d\n", __LINE__); // Trigger audio to start if(first_frame) { renderengine->first_frame_lock->unlock(); first_frame = 0; renderengine->reset_sync_position(); } if(debug) printf("VRender::run %d\n", __LINE__); session_frame += frame_step; // advance position in project current_input_length = frame_step; // Subtract frame_step in a loop to allow looped playback to drain // printf("VRender::run %d %d %d %d\n", // __LINE__, // done, // frame_step, // current_input_length); while(frame_step && current_input_length) { // trim current_input_length to range get_boundaries(current_input_length); // advance 1 frame advance_position(current_input_length); frame_step -= current_input_length; current_input_length = frame_step; if(done) break; // printf("VRender::run %d %d %d %d\n", // __LINE__, // done, // frame_step, // current_input_length); } if(debug) printf("VRender::run %d current_position=" _LD " done=%d\n", __LINE__, current_position, done); // Update tracking. if(renderengine->command->realtime && renderengine->playback_engine && renderengine->command->command != CURRENT_FRAME) { renderengine->playback_engine->update_tracking(fromunits(current_position)); } if(debug) printf("VRender::run %d\n", __LINE__); // Calculate the framerate counter framerate_counter++; if(framerate_counter >= renderengine->get_edl()->session->frame_rate && renderengine->command->realtime) { renderengine->update_framerate((float)framerate_counter / ((float)framerate_timer.get_difference() / 1000)); framerate_counter = 0; framerate_timer.update(); } if(debug) printf("VRender::run %d done=%d\n", __LINE__, done); if( !interrupt ) interrupt = renderengine->video->interrupt; } // In case we were interrupted before the first loop renderengine->first_frame_lock->unlock(); stop_plugins(); if(debug) printf("VRender::run %d done=%d\n", __LINE__, done); } int VRender::start_playback() { // start reading input and sending to vrenderthread // use a thread only if there's a video device if(renderengine->command->realtime) { start(); } return 0; } int64_t VRender::tounits(double position, int round) { if(round) return Units::round(position * renderengine->get_edl()->session->frame_rate); else return Units::to_int64(position * renderengine->get_edl()->session->frame_rate); } double VRender::fromunits(int64_t position) { return (double)position / renderengine->get_edl()->session->frame_rate; }
triceratops1/cinelerra
cinelerra-4.6/cinelerra-4.6.mod/cinelerra/vrender.C
C++
gpl-2.0
13,523
import os from core import aleinst CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) class Formula(): def __init__(self, request): self.request = request def search(self): package = aleinst.Aleinst(request=self.request[0:]) package.search() def main(self): self.search()
darker0n/ale
core/Formula/install.py
Python
gpl-2.0
326
package com.austinv11.peripheralsplusplus.capabilities.nano; import net.minecraft.entity.Entity; import javax.annotation.Nullable; import java.util.UUID; /** * Capability interface for entities that will hold nano bots */ public interface NanoBotHolder { /** * Get the bots the entity is infested with * @return number of bots on entity */ int getBots(); /** * Set the bots on an entity * @param bots number of bots to set on the entity */ void setBots(int bots); /** * Set the antenna UUID the item is registered to * @param antennaIdentifier antenna UUID */ void setAntenna(UUID antennaIdentifier); /** * Get the registered antenna id * @return antenna UUID */ @Nullable UUID getAntenna(); /** * Get the entity that this capability is handling * @return the entity that the bots are attached to */ @Nullable Entity getEntity(); /** * Sets the entity that the bots are attached to * If there is no entity set the entity will not be registered with the antenna registry on (re)load. * This should be set on the {@link net.minecraftforge.event.AttachCapabilitiesEvent<Entity>} event * @param entity entity the bots are on */ void setEntity(Entity entity); }
rolandoislas/PeripheralsPlusPlus
src/main/java/com/austinv11/peripheralsplusplus/capabilities/nano/NanoBotHolder.java
Java
gpl-2.0
1,324
package impl; public class StopWordsFilter { private static String stopWordsList[] = { "的", "我们", "要", "自己", "之", "将", "“", "”", ",", "(", ")", "后", "应", "到", "某", "后", "个", "是", "位", "新", "一", "两", "在", "中", "或", "有", "更", "好", "" };// 常用停用词 public static boolean IsStopWord(String word) { for (int i = 0; i < stopWordsList.length; ++i) { if (word.equalsIgnoreCase(stopWordsList[i])) return true; } return false; } }
kevin-ww/text.classfication
src/main/java/impl/StopWordsFilter.java
Java
gpl-2.0
536
# -*- coding: utf-8 -*- # # papyon - a python client library for Msn # # Copyright (C) 2009 Collabora Ltd. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class MediaRelay(object): def __init__(self): self.username = None self.password = None self.ip = "" self.port = 0 def __repr__(self): return "<Media Relay: %s %i username=\"%s\" password=\"%s\">" % (self.ip, self.port, self.username, self.password)
Kjir/papyon
papyon/media/relay.py
Python
gpl-2.0
1,127
/*************************************************************************** main.cpp (c) 2000-2013 Benoît Minisini <gambas@users.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, 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. ***************************************************************************/ #define __MAIN_CPP #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <ctype.h> #include "gb_common.h" #include "c_clipper.h" #include "main.h" extern "C" { GB_INTERFACE GB EXPORT; GEOM_INTERFACE GEOM EXPORT; GB_DESC *GB_CLASSES [] EXPORT = { PolygonDesc, ClipperDesc, NULL }; const char *GB_INCLUDE EXPORT = "gb.geom"; int EXPORT GB_INIT(void) { GB.Component.Load("gb.geom"); GB.GetInterface("gb.geom", GEOM_INTERFACE_VERSION, &GEOM); return 0; } void EXPORT GB_EXIT() { } }
justlostintime/gambas
main/lib/clipper/main.cpp
C++
gpl-2.0
1,456
using UnityEngine; using System.Collections; public class AIController : MonoBehaviour { Transform lineStart, lineEnd; GameObject healthBar; float health = 250; float maxHealth = 250; GameObject character; Stats stats; Animator animateState; // Use this for initialization void Start () { animateState = transform.gameObject.GetComponent<Animator> (); character = GameObject.Find ("Character"); stats = GameObject.Find ("Canvas").GetComponent<Stats> (); lineStart = transform.FindChild ("Start").gameObject.transform; lineEnd = transform.FindChild ("End").gameObject.transform; healthBar = new GameObject ("HealthBar"); healthBar.AddComponent<SpriteRenderer> (); healthBar.GetComponent<SpriteRenderer> ().sprite = Resources.Load ("HealthBarVisual", typeof(Sprite)) as Sprite; healthBar.transform.parent = this.transform; healthBar.transform.position = new Vector2 (transform.position.x, transform.position.y + .75f); if (transform.FindChild ("AttackSpawn") != null) { //this is a caster health = 100; maxHealth = 100; InvokeRepeating ("FireWeapon", 0, .75f); } else { //this is a knight InvokeRepeating ("Attack", 0, .75f); } } // Update is called once per frame void Update () { //if there is a character in front of this entity if (Physics2D.Linecast (lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer ("Player")) || Physics2D.Linecast (lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer ("Enemy"))) { GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, GetComponent<Rigidbody2D> ().velocity.y); } else if (Physics2D.Linecast (lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer ("Ground"))) { GetComponent<Rigidbody2D> ().velocity = new Vector2 (GetComponent<Rigidbody2D> ().velocity.x, 8); } else if (transform.tag == "Enemy") { GetComponent<Rigidbody2D> ().velocity = new Vector2 (-2, GetComponent<Rigidbody2D> ().velocity.y); } else { GetComponent<Rigidbody2D> ().velocity = new Vector2 (2, GetComponent<Rigidbody2D> ().velocity.y); } } public void RemoveHealth(float amount) { health -= amount; healthBar.transform.localScale = new Vector3 (health / maxHealth, 1, 1); if (health <= 0 && transform.tag == "Enemy") { stats.ChangeXP (10); stats.ChangeGold (25); GameObject gold = Instantiate (Resources.Load ("gold")) as GameObject; gold.transform.position = new Vector2 (transform.position.x, transform.position.y + .3f); GameObject xp = Instantiate (Resources.Load ("xp")) as GameObject; xp.transform.position = new Vector2 (transform.position.x, transform.position.y + .5f); Destroy (this.gameObject); } else if (health <= 0) { Destroy (this.gameObject); } } void Attack() { RaycastHit2D hit = Physics2D.Linecast (lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer ("Player")); if (transform.tag == "Enemy" && Physics2D.Linecast (lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer ("Player")) && hit.collider.transform.name == "Character") { hit.collider.transform.gameObject.GetComponent<CharacterController>().RemoveHealth(20); animateState.SetBool ("isAttacking", true); } else if (transform.tag == "Enemy" && Physics2D.Linecast (lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer ("Player"))) { hit.collider.transform.gameObject.GetComponent<AIController>().RemoveHealth(20); animateState.SetBool ("isAttacking", true); } else if (transform.tag == "Player" && Physics2D.Linecast (lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer ("Enemy"))) { hit = Physics2D.Linecast (lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer ("Enemy")); hit.collider.transform.gameObject.GetComponent<AIController>().RemoveHealth(20); animateState.SetBool ("isAttacking", true); } else { animateState.SetBool ("isAttacking", false); } } void FireWeapon() { if (transform.tag == "Enemy") { float distance = 100; Transform target = transform; bool targetFound = false; if (Vector2.Distance (this.transform.position, character.transform.position) < 10) { target = character.transform; targetFound = true; } if (!targetFound) { for(int i = 0; i < GameObject.Find ("AllySpawnLocation").transform.childCount; i++) { if (Vector2.Distance (this.transform.position, GameObject.Find ("AllySpawnLocation").transform.GetChild(i).transform.position) < 10) { if (Vector2.Distance (this.transform.position, GameObject.Find ("AllySpawnLocation").transform.GetChild(i).transform.position) < distance) { distance = Vector2.Distance (this.transform.position, GameObject.Find ("AllySpawnLocation").transform.GetChild(i).transform.position); target = GameObject.Find ("AllySpawnLocation").transform.GetChild(i).transform; targetFound = true; } } } } if (targetFound) { GameObject IceBall = Instantiate(Resources.Load("Iceball")) as GameObject; IceBall.GetComponent<IceBolt>().SetTarget = target; IceBall.transform.position = transform.FindChild ("AttackSpawn").transform.position; Vector2 direction = new Vector2 (target.position.x - IceBall.transform.position.x, target.position.y - IceBall.transform.position.y); direction.Normalize (); IceBall.GetComponent<Rigidbody2D> ().velocity = direction * 10; } } else if (transform.tag == "Player") { float distance = 100; Transform target = transform; bool targetFound = false; for(int i = 0; i < GameObject.Find ("EnemySpawnLocation").transform.childCount; i++) { if (Vector2.Distance (this.transform.position, GameObject.Find ("EnemySpawnLocation").transform.GetChild(i).transform.position) < 10) { if (Vector2.Distance (this.transform.position, GameObject.Find ("EnemySpawnLocation").transform.GetChild(i).transform.position) < distance) { distance = Vector2.Distance (this.transform.position, GameObject.Find ("EnemySpawnLocation").transform.GetChild(i).transform.position); target = GameObject.Find ("EnemySpawnLocation").transform.GetChild(i).transform; targetFound = true; } } } if (targetFound) { GameObject IceBall = Instantiate(Resources.Load("Iceball")) as GameObject; IceBall.GetComponent<IceBolt>().SetTarget = target; IceBall.transform.position = transform.FindChild ("AttackSpawn").transform.position; Vector2 direction = new Vector2 (target.position.x - IceBall.transform.position.x, target.position.y - IceBall.transform.position.y); direction.Normalize (); IceBall.GetComponent<Rigidbody2D> ().velocity = direction * 10; } } // if (Vector2.Distance (character.transform.position, transform.position) < 10) { // //attack player // GameObject IceBall = Instantiate(Resources.Load("Iceball")) as GameObject; // IceBall.GetComponent<IceBolt>().SetTarget = "Player"; // IceBall.transform.position = transform.FindChild ("AttackSpawn").transform.position; // Vector2 direction = new Vector2 (character.transform.position.x - IceBall.transform.position.x, character.transform.position.y - IceBall.transform.position.y); // direction.Normalize (); // IceBall.GetComponent<Rigidbody2D> ().velocity = direction * 10; // } } }
UCCS-GDD/CS3350-ChampionOfTheNine
ChampionsOfTheNinePrototype/Assets/Scripts/AIController.cs
C#
gpl-2.0
7,286
<?php set_include_path(get_include_path().PATH_SEPARATOR.realpath('../../includes').PATH_SEPARATOR.realpath('../../').PATH_SEPARATOR.realpath('../').PATH_SEPARATOR); $dir = realpath(getcwd()); chdir("../../"); require_once ( 'WebStart.php'); require_once( 'Wiki.php' ); chdir($dir); $userRun = $wgUser; #The user that runs this script $user1 = User::newFromName("ThomasKelder"); $user2 = User::newFromName("TestUser"); $admin = User::newFromName("Thomas"); $anon = User::newFromId(0); $page_id = Title::newFromText('WP4', NS_PATHWAY)->getArticleId(); $title = Title::newFromId($page_id); $mgr = new PermissionManager($page_id); Test::echoStart("No permissions set"); #Remove all permissions from page $mgr->clearPermissions(); ##* can read $wgUser = $anon; $can = $title->userCan("read"); Test::assert("anonymous can read", $can, true); ##* can't edit $wgUser = $anon; $can = $title->userCan('edit'); Test::assert("anonymous can't edit", $can, false); ##users can read/edit $wgUser = $user1; $can = $title->userCan("read"); Test::assert("Users can read", $can, true); $can = $title->userCan('edit'); Test::assert("Users can edit", $can, true); #Set private for user1 Test::echoStart("Setting page private for user1"); $pms = new PagePermissions($page_id); $pms->addReadWrite($user1->getId()); $pms->addManage($user1->getId()); $mgr->setPermissions($pms); ##user1 can read/write/manage $wgUser = $user1; $can = $title->userCan("read"); Test::assert("User1 can read", $can, true); $can = $title->userCan('edit'); Test::assert("User1 can edit", $can, true); $can = $title->userCan(PermissionManager::$ACTION_MANAGE); Test::assert("User1 can manage", $can, true); ##admin can read/write/manage $wgUser = $admin; $can = $title->userCan("read"); Test::assert("User1 can read", $can, true); $can = $title->userCan('edit'); Test::assert("User1 can edit", $can, true); $can = $title->userCan(PermissionManager::$ACTION_MANAGE); Test::assert("User1 can manage", $can, true); ##user2 cannot read/write/manage $wgUser = $user2; $can = $title->userCan("read"); Test::assert("User2 can't read", $can, false); $can = $title->userCan('edit'); Test::assert("User2 can't read", $can, false); $can = $title->userCan(PermissionManager::$ACTION_MANAGE); Test::assert("User2 can't manage", $can, false); ##anonymous cannot read/write/manage $wgUser = $anon; $can = $title->userCan("read"); Test::assert("Anonymous can't read", $can, false); $can = $title->userCan('edit'); Test::assert("Anonymous can't edit", $can, false); #Add user2 Test::echoStart("Add user2 to read/write users"); $wgUser = $userRun; $pms->addReadWrite($user2->getId()); $mgr->setPermissions($pms); ##user2 can read/write/manage $wgUser = $user2; $can = $title->userCan("read"); Test::assert("User2 can read", $can, true); $can = $title->userCan('edit'); Test::assert("User1 can edit", $can, true); ##user1 can still read/write/manage $wgUser = $user1; $can = $title->userCan("read"); Test::assert("User1 can still read", $can, true); $can = $title->userCan('edit'); Test::assert("User1 can still edit", $can, true); #Remove read/write permissions for user2 Test::echoStart("Setting page private for user1"); $pms->clearPermissions($user2->getId()); $mgr->setPermissions($pms); ##user1 can read/write/manage $wgUser = $user1; $can = $title->userCan("read"); Test::assert("User1 can read", $can, true); $can = $title->userCan('edit'); Test::assert("User1 can edit", $can, true); ##user2 cannot read/write/manage $wgUser = $user2; $can = $title->userCan("read"); Test::assert("User2 can't read", $can, false); $can = $title->userCan('edit'); Test::assert("User2 can't read", $can, false); #Set expiration date to past ##permissions should be removed Test::echoStart("Simulating expiration"); $wgUser = $userRun; $pms->setExpires(wfTimestamp(TS_MW) - 1); $mgr->setPermissions($pms); ##user2 can read/edit again $wgUser = $user2; $can = $title->userCan("read"); Test::assert("User2 can read again", $can, true); $can = $title->userCan('edit'); Test::assert("User2 can edit again", $can, true); class Test { static function assert($test, $value, $expected) { echo("$test: "); if($value != $expected) { $e = new Exception(); echo("\t<font color='red'>Fail!</font>: value '$value' doesn't equal expected: '$expected'" . "<BR>\n" . $e->getTraceAsString() . "<BR>\n"); } else { echo("\t<font color='green'>Pass!</font><BR>\n"); } } static function echoStart($case) { echo("<h3>Testing $case</h3>\n"); } }
hexmode/wikipathways.org
wpi/test/testPrivatePathways.php
PHP
gpl-2.0
4,499
# ==Paramerer Controller # This manages the display of a parameter # # == Copyright # Copyright © 2006 Robert Shell, Alces Ltd All Rights Reserved # See license agreement for additional rights # # class Organize::ParametersController < ApplicationController use_authorization :organization, :use => [:list,:show,:new,:create,:edit,:update,:destroy] def index list render :action => 'list' end def list @assay = Assay.load(params[:id]) @report = Biorails::ReportLibrary.parameter_list("ParameterList") end def show @parameter = Parameter.find(params[:id]) end end
rshell/biorails
app/controllers/organize/parameters_controller.rb
Ruby
gpl-2.0
632
using System.Drawing; using System.Threading.Tasks; namespace GoF_TryOut.Proxy.Straight { public class Client { public Client() { var myImage = new MyImage(""); var bitmap = myImage.GetImage() ?? myImage.GetPreview(); } } public class MyImage { private readonly string path; private readonly Bitmap preview; private Bitmap fullImage; private Task<Bitmap> task; public MyImage(string path) { this.path = path; preview = new Bitmap(path); } private Bitmap LoadImage() { return new Bitmap(path); } public Bitmap GetPreview() { return preview; } public Bitmap GetImage() { task = new Task<Bitmap>(LoadImage); task.Start(); if (task.IsCompleted) { if (fullImage == null) { fullImage = task.Result; return fullImage; } return fullImage; } return preview; } } }
VioletTape/Trainings
DEV-001_GoF/GoF_TryOut/GoF_TryOut/Proxy/Straight/Client.cs
C#
gpl-2.0
1,114
package core import ( "github.com/justinsb/gova/log" ) type CleanupOldMachines struct { huddle *Huddle state map[string]int deleteThreshold int } func (self *CleanupOldMachines) Run() error { state, err := self.huddle.cleanupOldMachines(self.state, self.deleteThreshold) if err != nil { log.Warn("Error cleaning up old machines", err) return err } self.state = state return nil } func (self *CleanupOldMachines) String() string { return "CleanupOldMachines" }
jxaas/jxaas
core/scheduled_machine_cleanup.go
GO
gpl-2.0
490
<?php /** * @version $Id: AbstractItem.php 30067 2016-03-08 13:44:25Z matias $ * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2016 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only */ abstract class RokCommon_Form_AbstractItem implements RokCommon_Form_IItem { /** * @var RokCommon_Service_Container */ protected $container; /** * The JForm object of the form attached to the form field. * * @var object * @since 1.6 */ protected $form; /** * The form control prefix for field names from the JForm object attached to the form field. * * @var string * @since 1.6 */ protected $formControl; /** * The hidden state for the form field. * * @var boolean * @since 1.6 */ protected $hidden = false; /** * True to translate the field label string. * True to translate the field label string. * * @var boolean * @since 1.6 */ protected $translateLabel = true; /** * True to translate the field description string. * * @var boolean * @since 1.6 */ protected $translateDescription = true; /** * The JXMLElement object of the <field /> XML element that describes the form field. * * @var object * @since 1.6 */ protected $element; /** * The document id for the form field. * * @var string * @since 1.6 */ protected $id; /** * The input for the form field. * * @var string * @since 1.6 */ protected $input; /** * The label for the form field. * * @var string * @since 1.6 */ protected $label; /** * The name of the form field. * * @var string * @since 1.6 */ protected $name; /** * The name of the field. * * @var string * @since 1.6 */ protected $fieldname; /** * The group of the field. * * @var string * @since 1.6 */ protected $group; /** * The form field type. * * @var string * @since 1.6 */ protected $type; protected $basetype; /** * The value of the form field. * * @var mixed * @since 1.6 */ protected $value; /** * @var string */ protected $panel_position = 'left'; /** * @var bool */ protected $show_label = true; /** * @var mixed */ protected $base_value; /** * @var bool */ protected $customized = false; /** * @var bool */ protected $setinoverride = true; /** * @var string */ protected $class; /** * @var bool */ protected $detached; /** * @var mixed */ protected $default; protected $assets_content; /** * Method to instantiate the form field object. * * @param object $form The form to attach to the form field object. * * @return void * @since 1.6 */ public function __construct(RokCommon_Form $form = null) { $this->container = RokCommon_Service::getContainer(); // If there is a form passed into the constructor set the form and form control properties. if ($form instanceof RokCommon_Form) { $this->form = $form; $this->formControl = $form->getFormControl(); } } /** * @param $name * @param $value * * @return void */ public function __set($name, $value) { if (property_exists($this, $name)) { $this->{$name} = $value; } } /** * Method to get the field title. * * @return string The field title. * @since 11.1 */ public function getTitle() { // Initialise variables. $title = ''; if ($this->hidden) { return $title; } // Get the label text from the XML element, defaulting to the element name. $title = $this->element['label'] ? (string)$this->element['label'] : (string)$this->element['name']; $title = $this->translateLabel ? JText::_($title) : $title; return $title; } /** * Method to get the field label markup. * * @return string The field label markup. * @since 1.6 */ public function getLabel() { // Initialise variables. $label = ''; if ($this->hidden) { return $label; } // Get the label text from the XML element, defaulting to the element name. $text = $this->element['label'] ? (string)$this->element['label'] : (string)$this->element['name']; $text = $this->translateLabel ? JText::_($text) : $text; // Build the class for the label. $class = !empty($this->description) ? 'hasTip' : ''; $class = $this->required == true ? $class . ' required' : $class; // Add the opening label tag and main attributes attributes. $label .= '<label id="' . $this->id . '-lbl" for="' . $this->id . '" class="' . $class . '"'; // If a description is specified, use it to build a tooltip. if (!empty($this->description)) { $label .= ' title="' . htmlspecialchars(trim($text, ':') . '::' . ($this->translateDescription ? JText::_($this->description) : $this->description), ENT_COMPAT, 'UTF-8') . '"'; } // Add the label text and closing tag. $label .= '>' . $text . '</label>'; return $label; } /** * Method to attach a JForm object to the field. * * @param \RokCommon_Form $form The JForm object to attach to the form field. * * @return object The form field object so that the method can be used in a chain. * @since 1.6 */ public function setForm(RokCommon_Form $form) { $this->form = $form; $this->formControl = $form->getFormControl(); return $this; } /** * Method to get the name used for the field input tag. * * @param string $fieldName The field element name. * * @return string The name to be used for the field input tag. * * @since 11.1 */ public function getName($fieldName) { /** @var $namehandler RokCommon_Form_IItemNameHandler */ $namehandler = $this->container->getService('form.namehandler'); return $namehandler->getName($fieldName, $this->group, $this->formControl, false); } /** * Method to get the id used for the field input tag. * * @param string $fieldId The field element id. * @param string $fieldName The field element name. * * @return string The id to be used for the field input tag. * @since 1.6 */ public function getId($fieldId, $fieldName) { /** @var $namehandler RokCommon_Form_IItemNameHandler */ $namehandler = $this->container->getService('form.namehandler'); return $namehandler->getId($fieldName, $fieldId, $this->group, $this->formControl, false); } /** * Method to get certain otherwise inaccessible properties from the form field object. * * @param string $name The property name for which to the the value. * * @return mixed|null The property value or null. * @since 1.6 */ public function __get($name) { switch ($name) { case 'input': // If the input hasn't yet been generated, generate it. if (empty($this->input)) { $this->input = $this->getInput(); } return $this->input; break; case 'label': // If the label hasn't yet been generated, generate it. if (empty($this->label)) { $this->label = $this->getLabel(); } return $this->label; break; case 'title': return $this->getTitle(); break; default : if (property_exists($this, $name) && isset($this->{$name})) { return $this->{$name}; } elseif (method_exists($this, 'get' . ucfirst($name))) { return call_user_func(array($this, 'get' . ucfirst($name))); } elseif (property_exists($this, $name)) { return $this->{$name}; } elseif (isset($this->element[$name])) { return (string)$this->element[$name]; } else { return null; } break; } } /** * Method to attach a JForm object to the field. * * @param object $element The JXMLElement object representing the <field /> tag for the * form field object. * @param mixed $value The form field default value for display. * @param string $group The field name group control value. This acts as as an array * container for the field. For example if the field has name="foo" * and the group value is set to "bar" then the full field name * would end up being "bar[foo]". * * @return boolean True on success. * @since 1.6 */ public function setup(& $element, $value, $group = null) { global $gantry; // Make sure there is a valid JFormField XML element. if (!($element instanceof RokCommon_XMLElement)) { return false; } // Reset the input and label values. $this->input = null; $this->label = null; // Set the xml element object. $this->element = $element; // Get some important attributes from the form field element. $class = (string)$element['class']; $id = (string)$element['id']; $name = (string)$element['name']; $type = (string)$element['type']; $panel_position = (string)$element['panel_position']; $this->show_label = ((string)$element['show_label'] == 'false') ? false : true; $this->setinoverride = ((string)$element['setinoverride'] == 'false') ? false : true; $default = (string)$element['default']; // if (!empty($name)) { // if (empty($group)) { // $gantry_name = $name; // } else { // $groups = explode('.', $group); // if (count($groups > 0)) { // //array_shift($groups); // $groups[] = $name; // $gantry_name = implode('-', $groups); // } // } // // TODO set this up to get for Default not for RokCommon param value // //$this->base_value = $gantry->get($gantry_name, null); // } // Set the field description text. $this->description = (string)$element['description']; // Set the visibility. $this->hidden = ((string)$element['type'] == 'hidden' || (string)$element['hidden'] == 'true'); // Determine whether to translate the field label and/or description. $this->translateLabel = !((string)$this->element['translate_label'] == 'false' || (string)$this->element['translate_label'] == '0'); $this->translateDescription = !((string)$this->element['translate_description'] == 'false' || (string)$this->element['translate_description'] == '0'); // Set the group of the field. $this->group = $group; // Set the field name and id. $this->fieldname = $name; $this->name = $this->getName($name, $group); $this->id = $this->getId($id, $name, $group); $this->type = $type; $this->class = $class; if ($panel_position != null) $this->panel_position = $panel_position; // Set the field default value. $this->value = $value; if (null != $this->default && $this->default != $this->value) $this->customized = true; return true; } /** * @static * @return void */ public static function initialize() { } /** * @static * @return void */ public static function finalize() { } /** * @param $callback * * @return mixed */ public function render($callback) { return call_user_func_array($callback, array($this)); } }
bmacenbacher/multison
libraries/rokcommon/RokCommon/Form/AbstractItem.php
PHP
gpl-2.0
11,359
/* Copyright (C) 2006 - 2011 ScriptDev2 <http://www.scriptdev2.com/> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Instance_Dark_Portal SD%Complete: 50 SDComment: Quest support: 9836, 10297. Currently in progress. SDCategory: Caverns of Time, The Dark Portal EndScriptData */ #include "precompiled.h" #include "dark_portal.h" inline uint32 RandRiftBoss() { return (urand(0, 1) ? NPC_RKEEP : NPC_RLORD); } float PortalLocation[4][4]= { {-2041.06f, 7042.08f, 29.99f, 1.30f}, {-1968.18f, 7042.11f, 21.93f, 2.12f}, {-1885.82f, 7107.36f, 22.32f, 3.07f}, {-1928.11f, 7175.95f, 22.11f, 3.44f} }; struct Wave { uint32 PortalBoss; // protector of current portal uint32 NextPortalTime; // time to next portal, or 0 if portal boss need to be killed }; static Wave RiftWaves[]= { {RIFT_BOSS, 0}, {NPC_DEJA, 0}, {RIFT_BOSS, 120000}, {NPC_TEMPO, 140000}, {RIFT_BOSS, 120000}, {NPC_AEONUS, 0} }; struct MANGOS_DLL_DECL instance_dark_portal : public ScriptedInstance { instance_dark_portal(Map* pMap) : ScriptedInstance(pMap) {Initialize();}; uint32 m_auiEncounter[MAX_ENCOUNTER]; uint32 m_uiRiftPortalCount; uint32 m_uiShieldPercent; uint8 m_uiRiftWaveCount; uint8 m_uiRiftWaveId; uint32 m_uiNextPortal_Timer; uint64 m_uiMedivhGUID; uint8 m_uiCurrentRiftId; void Initialize() { m_uiMedivhGUID = 0; Clear(); } void Clear() { memset(&m_auiEncounter, 0, sizeof(m_auiEncounter)); m_uiRiftPortalCount = 0; m_uiShieldPercent = 100; m_uiRiftWaveCount = 0; m_uiRiftWaveId = 0; m_uiCurrentRiftId = 0; m_uiNextPortal_Timer = 0; } void InitWorldState(bool Enable = true) { DoUpdateWorldState(WORLD_STATE_BM,Enable ? 1 : 0); DoUpdateWorldState(WORLD_STATE_BM_SHIELD, 100); DoUpdateWorldState(WORLD_STATE_BM_RIFT, 0); } bool IsEncounterInProgress() const { if (m_auiEncounter[0] == IN_PROGRESS) return true; return false; } void OnPlayerEnter(Player* pPlayer) { if (m_auiEncounter[0] == IN_PROGRESS) return; pPlayer->SendUpdateWorldState(WORLD_STATE_BM, 0); } void OnCreatureCreate(Creature* pCreature) { if (pCreature->GetEntry() == NPC_MEDIVH) m_uiMedivhGUID = pCreature->GetGUID(); } // what other conditions to check? bool CanProgressEvent() { if (instance->GetPlayers().isEmpty()) return false; return true; } uint8 GetRiftWaveId() { switch(m_uiRiftPortalCount) { case 6: m_uiRiftWaveId = 2; return 1; case 12: m_uiRiftWaveId = 4; return 3; case 18: return 5; default: return m_uiRiftWaveId; } } void SetData(uint32 uiType, uint32 uiData) { switch(uiType) { case TYPE_MEDIVH: if (uiData == SPECIAL && m_auiEncounter[0] == IN_PROGRESS) { --m_uiShieldPercent; DoUpdateWorldState(WORLD_STATE_BM_SHIELD, m_uiShieldPercent); if (!m_uiShieldPercent) { if (Creature* pMedivh = instance->GetCreature(m_uiMedivhGUID)) { if (pMedivh->isAlive()) { pMedivh->DealDamage(pMedivh, pMedivh->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); m_auiEncounter[0] = FAIL; m_auiEncounter[1] = NOT_STARTED; } } } } else { if (uiData == IN_PROGRESS) { debug_log("½Å±¾¿â£º Instance Dark Portal: Starting event."); InitWorldState(); m_auiEncounter[1] = IN_PROGRESS; m_uiNextPortal_Timer = 15000; } if (uiData == DONE) { // this may be completed further out in the post-event debug_log("½Å±¾¿â£º Instance Dark Portal: Event completed."); Map::PlayerList const& players = instance->GetPlayers(); if (!players.isEmpty()) { for(Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) { if (Player* pPlayer = itr->getSource()) { if (pPlayer->GetQuestStatus(QUEST_OPENING_PORTAL) == QUEST_STATUS_INCOMPLETE) pPlayer->AreaExploredOrEventHappens(QUEST_OPENING_PORTAL); if (pPlayer->GetQuestStatus(QUEST_MASTER_TOUCH) == QUEST_STATUS_INCOMPLETE) pPlayer->AreaExploredOrEventHappens(QUEST_MASTER_TOUCH); } } } } m_auiEncounter[0] = uiData; } break; case TYPE_RIFT: if (uiData == SPECIAL) { if (m_uiRiftPortalCount < 7) m_uiNextPortal_Timer = 5000; } else m_auiEncounter[1] = uiData; break; } } uint32 GetData(uint32 uiType) { switch(uiType) { case TYPE_MEDIVH: return m_auiEncounter[0]; case TYPE_RIFT: return m_auiEncounter[1]; case DATA_PORTAL_COUNT: return m_uiRiftPortalCount; case DATA_SHIELD: return m_uiShieldPercent; } return 0; } uint64 GetData64(uint32 uiData) { if (uiData == DATA_MEDIVH) return m_uiMedivhGUID; return 0; } Creature* SummonedPortalBoss(Creature* pSource) { uint32 uiEntry = RiftWaves[GetRiftWaveId()].PortalBoss; if (uiEntry == RIFT_BOSS) uiEntry = RandRiftBoss(); float x, y, z; pSource->GetRandomPoint(pSource->GetPositionX(), pSource->GetPositionY(), pSource->GetPositionZ(), 10.0f, x, y, z); // uncomment the following if something doesn't work correctly, otherwise just delete // pSource->UpdateAllowedPositionZ(x, y, z); debug_log("½Å±¾¿â£º Instance Dark Portal: Summoning rift boss uiEntry %u.", uiEntry); if (Creature* pSummoned = pSource->SummonCreature(uiEntry, x, y, z, pSource->GetOrientation(), TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 600000)) return pSummoned; debug_log("½Å±¾¿â£º Instance Dark Portal: what just happened there? No boss, no loot, no fun..."); return NULL; } void DoSpawnPortal() { if (Creature* pMedivh = instance->GetCreature(m_uiMedivhGUID)) { uint8 uiTmp = urand(0, 2); if (uiTmp >= m_uiCurrentRiftId) ++uiTmp; debug_log("½Å±¾¿â£º Instance Dark Portal: Creating Time Rift at locationId %i (old locationId was %u).", uiTmp, m_uiCurrentRiftId); m_uiCurrentRiftId = uiTmp; if (Creature* pTemp = pMedivh->SummonCreature(NPC_TIME_RIFT, PortalLocation[uiTmp][0], PortalLocation[uiTmp][1], PortalLocation[uiTmp][2], PortalLocation[uiTmp][3], TEMPSUMMON_CORPSE_DESPAWN, 0)) { pTemp->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); pTemp->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); if (Creature* pBoss = SummonedPortalBoss(pTemp)) { if (pBoss->GetEntry() == NPC_AEONUS) pBoss->AddThreat(pMedivh); else { pBoss->AddThreat(pTemp); pTemp->CastSpell(pBoss, SPELL_RIFT_CHANNEL, false); } } } } } void Update(uint32 uiDiff) { if (m_auiEncounter[1] != IN_PROGRESS) return; //add delay timer? if (!CanProgressEvent()) { Clear(); return; } if (m_uiNextPortal_Timer) { if (m_uiNextPortal_Timer <= uiDiff) { ++m_uiRiftPortalCount; DoUpdateWorldState(WORLD_STATE_BM_RIFT, m_uiRiftPortalCount); DoSpawnPortal(); m_uiNextPortal_Timer = RiftWaves[GetRiftWaveId()].NextPortalTime; } else m_uiNextPortal_Timer -= uiDiff; } } }; InstanceData* GetInstanceData_instance_dark_portal(Map* pMap) { return new instance_dark_portal(pMap); } void AddSC_instance_dark_portal() { Script* newscript; newscript = new Script; newscript->Name = "instance_dark_portal"; newscript->GetInstanceData = &GetInstanceData_instance_dark_portal; newscript->RegisterSelf(); }
gelu/ChgSD2
scripts/kalimdor/caverns_of_time/dark_portal/instance_dark_portal.cpp
C++
gpl-2.0
10,305
package com.github.randoapp.api.listeners; import com.github.randoapp.db.model.Rando; public interface UploadRandoListener { void onUpload(Rando rando); }
RandoApp/Rando-android
src/main/java/com/github/randoapp/api/listeners/UploadRandoListener.java
Java
gpl-2.0
162
<?php /** * Copyright (c) 2007-2011, Servigistics, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of Servigistics, Inc. nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @copyright Copyright 2007-2011 Servigistics, Inc. (http://servigistics.com) * @license http://solr-php-client.googlecode.com/svn/trunk/COPYING New BSD * @version $Id: Service.php 59 2011-02-08 20:38:59Z donovan.jimenez $ * * @package Apache * @subpackage Solr * @author Donovan Jimenez <djimenez@conduit-it.com> */ // See Issue #1 (http://code.google.com/p/solr-php-client/issues/detail?id=1) // Doesn't follow typical include path conventions, but is more convenient for users require_once(dirname(__FILE__) . '/Exception.php'); require_once(dirname(__FILE__) . '/HttpTransportException.php'); require_once(dirname(__FILE__) . '/InvalidArgumentException.php'); require_once(dirname(__FILE__) . '/Document.php'); require_once(dirname(__FILE__) . '/Response.php'); require_once(dirname(__FILE__) . '/HttpTransport/Interface.php'); /** * Starting point for the Solr API. Represents a Solr server resource and has * methods for pinging, adding, deleting, committing, optimizing and searching. * * Example Usage: * <code> * ... * $solr = new Apache_Solr_Service(); //or explicitly new Apache_Solr_Service('localhost', 8180, '/solr') * * if ($solr->ping()) * { * $solr->deleteByQuery('*:*'); //deletes ALL documents - be careful :) * * $document = new Apache_Solr_Document(); * $document->id = uniqid(); //or something else suitably unique * * $document->title = 'Some Title'; * $document->content = 'Some content for this wonderful document. Blah blah blah.'; * * $solr->addDocument($document); //if you're going to be adding documents in bulk using addDocuments * //with an array of documents is faster * * $solr->commit(); //commit to see the deletes and the document * $solr->optimize(); //merges multiple segments into one * * //and the one we all care about, search! * //any other common or custom parameters to the request handler can go in the * //optional 4th array argument. * $solr->search('content:blah', 0, 10, array('sort' => 'timestamp desc')); * } * ... * </code> * * @todo Investigate using other HTTP clients other than file_get_contents built-in handler. Could provide performance * improvements when dealing with multiple requests by using HTTP's keep alive functionality */ class Apache_Solr_Service { /** * SVN Revision meta data for this class */ const SVN_REVISION = '$Revision: 59 $'; /** * SVN ID meta data for this class */ const SVN_ID = '$Id: Service.php 59 2011-02-08 20:38:59Z donovan.jimenez $'; /** * Response writer we'll request - JSON. See http://code.google.com/p/solr-php-client/issues/detail?id=6#c1 for reasoning */ const SOLR_WRITER = 'json'; /** * NamedList Treatment constants */ const NAMED_LIST_FLAT = 'flat'; const NAMED_LIST_MAP = 'map'; /** * Search HTTP Methods */ const METHOD_GET = 'GET'; const METHOD_POST = 'POST'; /** * Servlet mappings */ const PING_SERVLET = 'admin/ping'; const UPDATE_SERVLET = 'update'; const SEARCH_SERVLET = 'select'; const THREADS_SERVLET = 'admin/threads'; const EXTRACT_SERVLET = 'update/extract'; /** * Server identification strings * * @var string */ protected $_host, $_port, $_path; /** * Whether {@link Apache_Solr_Response} objects should create {@link Apache_Solr_Document}s in * the returned parsed data * * @var boolean */ protected $_createDocuments = true; /** * Whether {@link Apache_Solr_Response} objects should have multivalue fields with only a single value * collapsed to appear as a single value would. * * @var boolean */ protected $_collapseSingleValueArrays = true; /** * How NamedLists should be formatted in the output. This specifically effects facet counts. Valid values * are {@link Apache_Solr_Service::NAMED_LIST_MAP} (default) or {@link Apache_Solr_Service::NAMED_LIST_FLAT}. * * @var string */ protected $_namedListTreatment = self::NAMED_LIST_MAP; /** * Query delimiters. Someone might want to be able to change * these (to use &amp; instead of & for example), so I've provided them. * * @var string */ protected $_queryDelimiter = '?', $_queryStringDelimiter = '&', $_queryBracketsEscaped = true; /** * Constructed servlet full path URLs * * @var string */ protected $_pingUrl, $_updateUrl, $_searchUrl, $_threadsUrl; /** * Keep track of whether our URLs have been constructed * * @var boolean */ protected $_urlsInited = false; /** * HTTP Transport implementation (pluggable) * * @var Apache_Solr_HttpTransport_Interface */ protected $_httpTransport = false; /** * Escape a value for special query characters such as ':', '(', ')', '*', '?', etc. * * NOTE: inside a phrase fewer characters need escaped, use {@link Apache_Solr_Service::escapePhrase()} instead * * @param string $value * @return string */ static public function escape($value) { //list taken from http://lucene.apache.org/java/docs/queryparsersyntax.html#Escaping%20Special%20Characters $pattern = '/(\+|-|&&|\|\||!|\(|\)|\{|}|\[|]|\^|"|~|\*|\?|:|\\\)/'; $replace = '\\\$1'; return preg_replace($pattern, $replace, $value); } /** * Escape a value meant to be contained in a phrase for special query characters * * @param string $value * @return string */ static public function escapePhrase($value) { $pattern = '/("|\\\)/'; $replace = '\\\$1'; return preg_replace($pattern, $replace, $value); } /** * Convenience function for creating phrase syntax from a value * * @param string $value * @return string */ static public function phrase($value) { return '"' . self::escapePhrase($value) . '"'; } /** * Constructor. All parameters are optional and will take on default values * if not specified. * * @param string $host * @param string $port * @param string $path * @param Apache_Solr_HttpTransport_Interface $httpTransport */ public function __construct($host = 'localhost', $port = 8180, $path = '/solr/', $httpTransport = false) { $this->setHost($host); $this->setPort($port); $this->setPath($path); $this->_initUrls(); if ($httpTransport) { $this->setHttpTransport($httpTransport); } // check that our php version is >= 5.1.3 so we can correct for http_build_query behavior later $this->_queryBracketsEscaped = version_compare(phpversion(), '5.1.3', '>='); } /** * Return a valid http URL given this server's host, port and path and a provided servlet name * * @param string $servlet * @return string */ protected function _constructUrl($servlet, $params = array()) { if (count($params)) { //escape all parameters appropriately for inclusion in the query string $escapedParams = array(); foreach ($params as $key => $value) { $escapedParams[] = urlencode($key) . '=' . urlencode($value); } $queryString = $this->_queryDelimiter . implode($this->_queryStringDelimiter, $escapedParams); } else { $queryString = ''; } return 'http://' . $this->_host . ':' . $this->_port . $this->_path . $servlet . $queryString; } /** * Construct the Full URLs for the three servlets we reference */ protected function _initUrls() { //Initialize our full servlet URLs now that we have server information $this->_extractUrl = $this->_constructUrl(self::EXTRACT_SERVLET); $this->_pingUrl = $this->_constructUrl(self::PING_SERVLET); $this->_searchUrl = $this->_constructUrl(self::SEARCH_SERVLET); $this->_threadsUrl = $this->_constructUrl(self::THREADS_SERVLET, array('wt' => self::SOLR_WRITER )); $this->_updateUrl = $this->_constructUrl(self::UPDATE_SERVLET, array('wt' => self::SOLR_WRITER )); $this->_urlsInited = true; } protected function _generateQueryString($params) { // use http_build_query to encode our arguments because its faster // than urlencoding all the parts ourselves in a loop // // because http_build_query treats arrays differently than we want to, correct the query // string by changing foo[#]=bar (# being an actual number) parameter strings to just // multiple foo=bar strings. This regex should always work since '=' will be urlencoded // anywhere else the regex isn't expecting it // // NOTE: before php 5.1.3 brackets were not url encoded by http_build query - we've checked // the php version in the constructor and put the results in the instance variable. Also, before // 5.1.2 the arg_separator parameter was not available, so don't use it if ($this->_queryBracketsEscaped) { $queryString = http_build_query($params, null, $this->_queryStringDelimiter); return preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $queryString); } else { $queryString = http_build_query($params); return preg_replace('/\\[(?:[0-9]|[1-9][0-9]+)\\]=/', '=', $queryString); } } /** * Central method for making a get operation against this Solr Server * * @param string $url * @param float $timeout Read timeout in seconds * @return Apache_Solr_Response * * @throws Apache_Solr_HttpTransportException If a non 200 response status is returned */ protected function _sendRawGet($url, $timeout = FALSE) { $httpTransport = $this->getHttpTransport(); $httpResponse = $httpTransport->performGetRequest($url, $timeout); $solrResponse = new Apache_Solr_Response($httpResponse, $this->_createDocuments, $this->_collapseSingleValueArrays); if ($solrResponse->getHttpStatus() != 200) { throw new Apache_Solr_HttpTransportException($solrResponse); } return $solrResponse; } /** * Central method for making a post operation against this Solr Server * * @param string $url * @param string $rawPost * @param float $timeout Read timeout in seconds * @param string $contentType * @return Apache_Solr_Response * * @throws Apache_Solr_HttpTransportException If a non 200 response status is returned */ protected function _sendRawPost($url, $rawPost, $timeout = FALSE, $contentType = 'text/xml; charset=UTF-8') { $httpTransport = $this->getHttpTransport(); $httpResponse = $httpTransport->performPostRequest($url, $rawPost, $contentType, $timeout); $solrResponse = new Apache_Solr_Response($httpResponse, $this->_createDocuments, $this->_collapseSingleValueArrays); if ($solrResponse->getHttpStatus() != 200) { throw new Apache_Solr_HttpTransportException($solrResponse); } return $solrResponse; } /** * Returns the set host * * @return string */ public function getHost() { return $this->_host; } /** * Set the host used. If empty will fallback to constants * * @param string $host * * @throws Apache_Solr_InvalidArgumentException If the host parameter is empty */ public function setHost($host) { //Use the provided host or use the default if (empty($host)) { throw new Apache_Solr_InvalidArgumentException('Host parameter is empty'); } else { $this->_host = $host; } if ($this->_urlsInited) { $this->_initUrls(); } } /** * Get the set port * * @return integer */ public function getPort() { return $this->_port; } /** * Set the port used. If empty will fallback to constants * * @param integer $port * * @throws Apache_Solr_InvalidArgumentException If the port parameter is empty */ public function setPort($port) { //Use the provided port or use the default $port = (int) $port; if ($port <= 0) { throw new Apache_Solr_InvalidArgumentException('Port is not a valid port number'); } else { $this->_port = $port; } if ($this->_urlsInited) { $this->_initUrls(); } } /** * Get the set path. * * @return string */ public function getPath() { return $this->_path; } /** * Set the path used. If empty will fallback to constants * * @param string $path */ public function setPath($path) { $path = trim($path, '/'); $this->_path = '/' . $path . '/'; if ($this->_urlsInited) { $this->_initUrls(); } } /** * Get the current configured HTTP Transport * * @return HttpTransportInterface */ public function getHttpTransport() { // lazy load a default if one has not be set if ($this->_httpTransport === false) { require_once(dirname(__FILE__) . '/HttpTransport/FileGetContents.php'); $this->_httpTransport = new Apache_Solr_HttpTransport_FileGetContents(); } return $this->_httpTransport; } /** * Set the HTTP Transport implemenation that will be used for all HTTP requests * * @param Apache_Solr_HttpTransport_Interface */ public function setHttpTransport(Apache_Solr_HttpTransport_Interface $httpTransport) { $this->_httpTransport = $httpTransport; } /** * Set the create documents flag. This determines whether {@link Apache_Solr_Response} objects will * parse the response and create {@link Apache_Solr_Document} instances in place. * * @param boolean $createDocuments */ public function setCreateDocuments($createDocuments) { $this->_createDocuments = (bool) $createDocuments; } /** * Get the current state of teh create documents flag. * * @return boolean */ public function getCreateDocuments() { return $this->_createDocuments; } /** * Set the collapse single value arrays flag. * * @param boolean $collapseSingleValueArrays */ public function setCollapseSingleValueArrays($collapseSingleValueArrays) { $this->_collapseSingleValueArrays = (bool) $collapseSingleValueArrays; } /** * Get the current state of the collapse single value arrays flag. * * @return boolean */ public function getCollapseSingleValueArrays() { return $this->_collapseSingleValueArrays; } /** * Get the current default timeout setting (initially the default_socket_timeout ini setting) * in seconds * * @return float * * @deprecated Use the getDefaultTimeout method on the HTTP transport implementation */ public function getDefaultTimeout() { return $this->getHttpTransport()->getDefaultTimeout(); } /** * Set the default timeout for all calls that aren't passed a specific timeout * * @param float $timeout Timeout value in seconds * * @deprecated Use the setDefaultTimeout method on the HTTP transport implementation */ public function setDefaultTimeout($timeout) { $this->getHttpTransport()->setDefaultTimeout($timeout); } /** * Set how NamedLists should be formatted in the response data. This mainly effects * the facet counts format. * * @param string $namedListTreatment * @throws Apache_Solr_InvalidArgumentException If invalid option is set */ public function setNamedListTreatment($namedListTreatment) { switch ((string) $namedListTreatment) { case Apache_Solr_Service::NAMED_LIST_FLAT: $this->_namedListTreatment = Apache_Solr_Service::NAMED_LIST_FLAT; break; case Apache_Solr_Service::NAMED_LIST_MAP: $this->_namedListTreatment = Apache_Solr_Service::NAMED_LIST_MAP; break; default: throw new Apache_Solr_InvalidArgumentException('Not a valid named list treatement option'); } } /** * Get the current setting for named list treatment. * * @return string */ public function getNamedListTreatment() { return $this->_namedListTreatment; } /** * Set the string used to separate the path form the query string. * Defaulted to '?' * * @param string $queryDelimiter */ public function setQueryDelimiter($queryDelimiter) { $this->_queryDelimiter = $queryDelimiter; } /** * Set the string used to separate the parameters in thequery string * Defaulted to '&' * * @param string $queryStringDelimiter */ public function setQueryStringDelimiter($queryStringDelimiter) { $this->_queryStringDelimiter = $queryStringDelimiter; } /** * Call the /admin/ping servlet, can be used to quickly tell if a connection to the * server is able to be made. * * @param float $timeout maximum time to wait for ping in seconds, -1 for unlimited (default is 2) * @return float Actual time taken to ping the server, FALSE if timeout or HTTP error status occurs */ public function ping($timeout = 2) { $start = microtime(true); $httpTransport = $this->getHttpTransport(); $httpResponse = $httpTransport->performHeadRequest($this->_pingUrl, $timeout); $solrResponse = new Apache_Solr_Response($httpResponse, $this->_createDocuments, $this->_collapseSingleValueArrays); if ($solrResponse->getHttpStatus() == 200) { return microtime(true) - $start; } else { return false; } } /** * Call the /admin/threads servlet and retrieve information about all threads in the * Solr servlet's thread group. Useful for diagnostics. * * @return Apache_Solr_Response * * @throws Apache_Solr_HttpTransportException If an error occurs during the service call */ public function threads() { return $this->_sendRawGet($this->_threadsUrl); } /** * Raw Add Method. Takes a raw post body and sends it to the update service. Post body * should be a complete and well formed "add" xml document. * * @param string $rawPost * @return Apache_Solr_Response * * @throws Apache_Solr_HttpTransportException If an error occurs during the service call */ public function add($rawPost) { return $this->_sendRawPost($this->_updateUrl, $rawPost); } /** * Add a Solr Document to the index * * @param Apache_Solr_Document $document * @param boolean $allowDups * @param boolean $overwritePending * @param boolean $overwriteCommitted * @param integer $commitWithin The number of milliseconds that a document must be committed within, see @{link http://wiki.apache.org/solr/UpdateXmlMessages#The_Update_Schema} for details. If left empty this property will not be set in the request. * @return Apache_Solr_Response * * @throws Apache_Solr_HttpTransportException If an error occurs during the service call */ public function addDocument(Apache_Solr_Document $document, $allowDups = false, $overwritePending = true, $overwriteCommitted = true, $commitWithin = 0) { $dupValue = $allowDups ? 'true' : 'false'; $pendingValue = $overwritePending ? 'true' : 'false'; $committedValue = $overwriteCommitted ? 'true' : 'false'; $commitWithin = (int) $commitWithin; $commitWithinString = $commitWithin > 0 ? " commitWithin=\"{$commitWithin}\"" : ''; $rawPost = "<add{$commitWithinString}>"; $rawPost .= $this->_documentToXmlFragment($document); $rawPost .= '</add>'; return $this->add($rawPost); } /** * Add an array of Solr Documents to the index all at once * * @param array $documents Should be an array of Apache_Solr_Document instances * @param boolean $allowDups * @param boolean $overwritePending * @param boolean $overwriteCommitted * @param integer $commitWithin The number of milliseconds that a document must be committed within, see @{link http://wiki.apache.org/solr/UpdateXmlMessages#The_Update_Schema} for details. If left empty this property will not be set in the request. * @return Apache_Solr_Response * * @throws Apache_Solr_HttpTransportException If an error occurs during the service call */ public function addDocuments($documents, $allowDups = false, $overwritePending = true, $overwriteCommitted = true, $commitWithin = 0) { $dupValue = $allowDups ? 'true' : 'false'; $pendingValue = $overwritePending ? 'true' : 'false'; $committedValue = $overwriteCommitted ? 'true' : 'false'; $commitWithin = (int) $commitWithin; $commitWithinString = $commitWithin > 0 ? " commitWithin=\"{$commitWithin}\"" : ''; $rawPost = "<add{$commitWithinString}>"; foreach ($documents as $document) { if ($document instanceof Apache_Solr_Document) { $rawPost .= $this->_documentToXmlFragment($document); } } $rawPost .= '</add>'; return $this->add($rawPost); } /** * Create an XML fragment from a {@link Apache_Solr_Document} instance appropriate for use inside a Solr add call * * @return string */ protected function _documentToXmlFragment(Apache_Solr_Document $document) { $xml = '<doc'; if ($document->getBoost() !== false) { $xml .= ' boost="' . $document->getBoost() . '"'; } $xml .= '>'; foreach ($document as $key => $value) { $key = htmlspecialchars($key, ENT_QUOTES, 'UTF-8'); $fieldBoost = $document->getFieldBoost($key); if (is_array($value)) { foreach ($value as $multivalue) { $xml .= '<field name="' . $key . '"'; if ($fieldBoost !== false) { $xml .= ' boost="' . $fieldBoost . '"'; // only set the boost for the first field in the set $fieldBoost = false; } $multivalue = htmlspecialchars($multivalue, ENT_NOQUOTES, 'UTF-8'); $xml .= '>' . $multivalue . '</field>'; } } else { $xml .= '<field name="' . $key . '"'; if ($fieldBoost !== false) { $xml .= ' boost="' . $fieldBoost . '"'; } $value = htmlspecialchars($value, ENT_NOQUOTES, 'UTF-8'); $xml .= '>' . $value . '</field>'; } } $xml .= '</doc>'; // replace any control characters to avoid Solr XML parser exception return $this->_stripCtrlChars($xml); } /** * Replace control (non-printable) characters from string that are invalid to Solr's XML parser with a space. * * @param string $string * @return string */ protected function _stripCtrlChars($string) { // See: http://w3.org/International/questions/qa-forms-utf-8.html // Printable utf-8 does not include any of these chars below x7F return preg_replace('@[\x00-\x08\x0B\x0C\x0E-\x1F]@', ' ', $string); } /** * Send a commit command. Will be synchronous unless both wait parameters are set to false. * * @param boolean $expungeDeletes Defaults to false, merge segments with deletes away * @param boolean $waitFlush Defaults to true, block until index changes are flushed to disk * @param boolean $waitSearcher Defaults to true, block until a new searcher is opened and registered as the main query searcher, making the changes visible * @param float $timeout Maximum expected duration (in seconds) of the commit operation on the server (otherwise, will throw a communication exception). Defaults to 1 hour * @return Apache_Solr_Response * * @throws Apache_Solr_HttpTransportException If an error occurs during the service call */ public function commit($expungeDeletes = false, $waitFlush = true, $waitSearcher = true, $timeout = 3600) { $expungeValue = $expungeDeletes ? 'true' : 'false'; $flushValue = $waitFlush ? 'true' : 'false'; $searcherValue = $waitSearcher ? 'true' : 'false'; $rawPost = '<commit expungeDeletes="' . $expungeValue . '" waitSearcher="' . $searcherValue . '" />'; return $this->_sendRawPost($this->_updateUrl, $rawPost, $timeout); } /** * Raw Delete Method. Takes a raw post body and sends it to the update service. Body should be * a complete and well formed "delete" xml document * * @param string $rawPost Expected to be utf-8 encoded xml document * @param float $timeout Maximum expected duration of the delete operation on the server (otherwise, will throw a communication exception) * @return Apache_Solr_Response * * @throws Apache_Solr_HttpTransportException If an error occurs during the service call */ public function delete($rawPost, $timeout = 3600) { return $this->_sendRawPost($this->_updateUrl, $rawPost, $timeout); } /** * Create a delete document based on document ID * * @param string $id Expected to be utf-8 encoded * @param boolean $fromPending * @param boolean $fromCommitted * @param float $timeout Maximum expected duration of the delete operation on the server (otherwise, will throw a communication exception) * @return Apache_Solr_Response * * @throws Apache_Solr_HttpTransportException If an error occurs during the service call */ public function deleteById($id, $fromPending = true, $fromCommitted = true, $timeout = 3600) { $pendingValue = $fromPending ? 'true' : 'false'; $committedValue = $fromCommitted ? 'true' : 'false'; //escape special xml characters $id = htmlspecialchars($id, ENT_NOQUOTES, 'UTF-8'); $rawPost = '<delete fromPending="' . $pendingValue . '" fromCommitted="' . $committedValue . '"><id>' . $id . '</id></delete>'; return $this->delete($rawPost, $timeout); } /** * Create and post a delete document based on multiple document IDs. * * @param array $ids Expected to be utf-8 encoded strings * @param boolean $fromPending * @param boolean $fromCommitted * @param float $timeout Maximum expected duration of the delete operation on the server (otherwise, will throw a communication exception) * @return Apache_Solr_Response * * @throws Apache_Solr_HttpTransportException If an error occurs during the service call */ public function deleteByMultipleIds($ids, $fromPending = true, $fromCommitted = true, $timeout = 3600) { $pendingValue = $fromPending ? 'true' : 'false'; $committedValue = $fromCommitted ? 'true' : 'false'; $rawPost = '<delete fromPending="' . $pendingValue . '" fromCommitted="' . $committedValue . '">'; foreach ($ids as $id) { //escape special xml characters $id = htmlspecialchars($id, ENT_NOQUOTES, 'UTF-8'); $rawPost .= '<id>' . $id . '</id>'; } $rawPost .= '</delete>'; return $this->delete($rawPost, $timeout); } /** * Create a delete document based on a query and submit it * * @param string $rawQuery Expected to be utf-8 encoded * @param boolean $fromPending * @param boolean $fromCommitted * @param float $timeout Maximum expected duration of the delete operation on the server (otherwise, will throw a communication exception) * @return Apache_Solr_Response * * @throws Apache_Solr_HttpTransportException If an error occurs during the service call */ public function deleteByQuery($rawQuery, $fromPending = true, $fromCommitted = true, $timeout = 3600) { $pendingValue = $fromPending ? 'true' : 'false'; $committedValue = $fromCommitted ? 'true' : 'false'; // escape special xml characters $rawQuery = htmlspecialchars($rawQuery, ENT_NOQUOTES, 'UTF-8'); $rawPost = '<delete fromPending="' . $pendingValue . '" fromCommitted="' . $committedValue . '"><query>' . $rawQuery . '</query></delete>'; return $this->delete($rawPost, $timeout); } /** * Use Solr Cell to extract document contents. See {@link http://wiki.apache.org/solr/ExtractingRequestHandler} for information on how * to use Solr Cell and what parameters are available. * * NOTE: when passing an Apache_Solr_Document instance, field names and boosts will automatically be prepended by "literal." and "boost." * as appropriate. Any keys from the $params array will NOT be treated this way. Any mappings from the document will overwrite key / value * pairs in the params array if they have the same name (e.g. you pass a "literal.id" key and value in your $params array but you also * pass in a document isntance with an "id" field" - the document's value(s) will take precedence). * * @param string $file Path to file to extract data from * @param array $params optional array of key value pairs that will be sent with the post (see Solr Cell documentation) * @param Apache_Solr_Document $document optional document that will be used to generate post parameters (literal.* and boost.* params) * @param string $mimetype optional mimetype specification (for the file being extracted) * * @return Apache_Solr_Response * * @throws Apache_Solr_InvalidArgumentException if $file, $params, or $document are invalid. */ public function extract($file, $params = array(), $document = null, $mimetype = 'application/octet-stream') { // check if $params is an array (allow null for default empty array) if (!is_null($params)) { if (!is_array($params)) { throw new Apache_Solr_InvalidArgumentException("\$params must be a valid array or null"); } } else { $params = array(); } // if $file is an http request, defer to extractFromUrl instead if (substr($file, 0, 7) == 'http://' || substr($file, 0, 8) == 'https://') { return $this->extractFromUrl($file, $params, $document, $mimetype); } // read the contents of the file $contents = @file_get_contents($file); if ($contents !== false) { // add the resource.name parameter if not specified if (!isset($params['resource.name'])) { $params['resource.name'] = basename($file); } // delegate the rest to extractFromString return $this->extractFromString($contents, $params, $document, $mimetype); } else { throw new Apache_Solr_InvalidArgumentException("File '{$file}' is empty or could not be read"); } } /** * Use Solr Cell to extract document contents. See {@link http://wiki.apache.org/solr/ExtractingRequestHandler} for information on how * to use Solr Cell and what parameters are available. * * NOTE: when passing an Apache_Solr_Document instance, field names and boosts will automatically be prepended by "literal." and "boost." * as appropriate. Any keys from the $params array will NOT be treated this way. Any mappings from the document will overwrite key / value * pairs in the params array if they have the same name (e.g. you pass a "literal.id" key and value in your $params array but you also * pass in a document isntance with an "id" field" - the document's value(s) will take precedence). * * @param string $data Data that will be passed to Solr Cell * @param array $params optional array of key value pairs that will be sent with the post (see Solr Cell documentation) * @param Apache_Solr_Document $document optional document that will be used to generate post parameters (literal.* and boost.* params) * @param string $mimetype optional mimetype specification (for the file being extracted) * * @return Apache_Solr_Response * * @throws Apache_Solr_InvalidArgumentException if $file, $params, or $document are invalid. * * @todo Should be using multipart/form-data to post parameter values, but I could not get my implementation to work. Needs revisisted. */ public function extractFromString($data, $params = array(), $document = null, $mimetype = 'application/octet-stream') { // check if $params is an array (allow null for default empty array) if (!is_null($params)) { if (!is_array($params)) { throw new Apache_Solr_InvalidArgumentException("\$params must be a valid array or null"); } } else { $params = array(); } // make sure we receive our response in JSON and have proper name list treatment $params['wt'] = self::SOLR_WRITER; $params['json.nl'] = $this->_namedListTreatment; // check if $document is an Apache_Solr_Document instance if (!is_null($document) && $document instanceof Apache_Solr_Document) { // iterate document, adding literal.* and boost.* fields to $params as appropriate foreach ($document as $field => $fieldValue) { // check if we need to add a boost.* parameters $fieldBoost = $document->getFieldBoost($field); if ($fieldBoost !== false) { $params["boost.{$field}"] = $fieldBoost; } // add the literal.* parameter $params["literal.{$field}"] = $fieldValue; } } // params will be sent to SOLR in the QUERY STRING $queryString = $this->_generateQueryString($params); // the file contents will be sent to SOLR as the POST BODY - we use application/octect-stream as default mimetype return $this->_sendRawPost($this->_extractUrl . $this->_queryDelimiter . $queryString, $data, false, $mimetype); } /** * Use Solr Cell to extract document contents. See {@link http://wiki.apache.org/solr/ExtractingRequestHandler} for information on how * to use Solr Cell and what parameters are available. * * NOTE: when passing an Apache_Solr_Document instance, field names and boosts will automatically be prepended by "literal." and "boost." * as appropriate. Any keys from the $params array will NOT be treated this way. Any mappings from the document will overwrite key / value * pairs in the params array if they have the same name (e.g. you pass a "literal.id" key and value in your $params array but you also * pass in a document isntance with an "id" field" - the document's value(s) will take precedence). * * @param string $url URL * @param array $params optional array of key value pairs that will be sent with the post (see Solr Cell documentation) * @param Apache_Solr_Document $document optional document that will be used to generate post parameters (literal.* and boost.* params) * @param string $mimetype optional mimetype specification (for the file being extracted) * * @return Apache_Solr_Response * * @throws Apache_Solr_InvalidArgumentException if $url, $params, or $document are invalid. */ public function extractFromUrl($url, $params = array(), $document = null, $mimetype = 'application/octet-stream') { // check if $params is an array (allow null for default empty array) if (!is_null($params)) { if (!is_array($params)) { throw new Apache_Solr_InvalidArgumentException("\$params must be a valid array or null"); } } else { $params = array(); } $httpTransport = $this->getHttpTransport(); // read the contents of the URL using our configured Http Transport and default timeout $httpResponse = $httpTransport->performGetRequest($url); // check that its a 200 response if ($httpResponse->getStatusCode() == 200) { // add the resource.name parameter if not specified if (!isset($params['resource.name'])) { $params['resource.name'] = $url; } // delegate the rest to extractFromString return $this->extractFromString($httpResponse->getBody(), $params, $document, $mimetype); } else { throw new Apache_Solr_InvalidArgumentException("URL '{$url}' returned non 200 response code"); } } /** * Send an optimize command. Will be synchronous unless both wait parameters are set * to false. * * @param boolean $waitFlush * @param boolean $waitSearcher * @param float $timeout Maximum expected duration of the commit operation on the server (otherwise, will throw a communication exception) * @return Apache_Solr_Response * * @throws Apache_Solr_HttpTransportException If an error occurs during the service call */ public function optimize($waitFlush = true, $waitSearcher = true, $timeout = 3600) { $flushValue = $waitFlush ? 'true' : 'false'; $searcherValue = $waitSearcher ? 'true' : 'false'; $rawPost = '<optimize waitSearcher="' . $searcherValue . '" />'; return $this->_sendRawPost($this->_updateUrl, $rawPost, $timeout); } /** * Simple Search interface * * @param string $query The raw query string * @param int $offset The starting offset for result documents * @param int $limit The maximum number of result documents to return * @param array $params key / value pairs for other query parameters (see Solr documentation), use arrays for parameter keys used more than once (e.g. facet.field) * @param string $method The HTTP method (Apache_Solr_Service::METHOD_GET or Apache_Solr_Service::METHOD::POST) * @return Apache_Solr_Response * * @throws Apache_Solr_HttpTransportException If an error occurs during the service call * @throws Apache_Solr_InvalidArgumentException If an invalid HTTP method is used */ public function search($query, $offset = 0, $limit = 10, $params = array(), $method = self::METHOD_GET) { // ensure params is an array if (!is_null($params)) { if (!is_array($params)) { // params was specified but was not an array - invalid throw new Apache_Solr_InvalidArgumentException("\$params must be a valid array or null"); } } else { $params = array(); } // construct our full parameters // common parameters in this interface $params['wt'] = self::SOLR_WRITER; $params['json.nl'] = $this->_namedListTreatment; $params['q'] = $query; $params['start'] = $offset; $params['rows'] = $limit; $queryString = $this->_generateQueryString($params); if ($method == self::METHOD_GET) { return $this->_sendRawGet($this->_searchUrl . $this->_queryDelimiter . $queryString); } else if ($method == self::METHOD_POST) { return $this->_sendRawPost($this->_searchUrl, $queryString, FALSE, 'application/x-www-form-urlencoded; charset=UTF-8'); } else { throw new Apache_Solr_InvalidArgumentException("Unsupported method '$method', please use the Apache_Solr_Service::METHOD_* constants"); } } }
ekilfeather/open-storyscope
profiles/storyscope/libraries/SolrPhpClient/Apache/Solr/Service.php
PHP
gpl-2.0
39,313
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tesisweb.controller.general; /** * * @author root */ /* ******************************************* // Copyright 2010-2012, Anthony Hand // // File version date: January 21, 2012 // Update: // - Moved Windows Phone 7 to the iPhone Tier. WP7.5's IE 9-based browser is good enough now. // - Added a new variable for 2 versions of the new BlackBerry Bold Touch (9900 and 9930): deviceBBBoldTouch. // - Updated DetectBlackBerryTouch() to support the 2 versions of the new BlackBerry Bold Touch (9900 and 9930). // - Updated DetectKindle() to focus on eInk devices only. The Kindle Fire should be detected as a regular Android device. // // File version date: August 22, 2011 // Update: // - Updated DetectAndroidTablet() to fix a bug I introduced in the last fix! // // File version date: August 16, 2011 // Update: // - Updated DetectAndroidTablet() to exclude Opera Mini, which was falsely reporting as running on a tablet device when on a phone. // // File version date: August 7, 2011 // Update: // - The Opera for Android browser doesn't follow Google's recommended useragent string guidelines, so some fixes were needed. // - Updated DetectAndroidPhone() and DetectAndroidTablet() to properly detect devices running Opera Mobile. // - Created 2 new methods: DetectOperaAndroidPhone() and DetectOperaAndroidTablet(). // - Updated DetectTierIphone(). Removed the call to DetectMaemoTablet(), an obsolete mobile OS. // // // LICENSE INFORMATION // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific // language governing permissions and limitations under the License. // // // ABOUT THIS PROJECT // Project Owner: Anthony Hand // Email: anthony.hand@gmail.com // Web Site: http://www.mobileesp.com // Source Files: http://code.google.com/p/mobileesp/ // // Versions of this code are available for: // PHP, JavaScript, Java, ASP.NET (C#), and Ruby // // ******************************************* */ /** * The DetectSmartPhone class encapsulates information about * a browser's connection to your web site. * You can use it to find out whether the browser asking for * your site's content is probably running on a mobile device. * The methods were written so you can be as granular as you want. * For example, enquiring whether it's as specific as an iPod Touch or * as general as a smartphone class device. * The object's methods return true, or false. */ public class UserAgentInfo { // User-Agent and Accept HTTP request headers private String userAgent = ""; private String httpAccept = ""; // Let's store values for quickly accessing the same info multiple times. public boolean isIphone = false; public boolean isAndroidPhone = false; public boolean isTierTablet = false; public boolean isTierIphone = false; public boolean isTierRichCss = false; public boolean isTierGenericMobile = false; // Initialize some initial smartphone string variables. public static final String engineWebKit = "webkit"; public static final String deviceIphone = "iphone"; public static final String deviceIpod = "ipod"; public static final String deviceIpad = "ipad"; public static final String deviceMacPpc = "macintosh"; //Used for disambiguation public static final String deviceAndroid = "android"; public static final String deviceGoogleTV = "googletv"; public static final String deviceXoom = "xoom"; //Motorola Xoom public static final String deviceHtcFlyer = "htc_flyer"; //HTC Flyer public static final String deviceSymbian = "symbian"; public static final String deviceS60 = "series60"; public static final String deviceS70 = "series70"; public static final String deviceS80 = "series80"; public static final String deviceS90 = "series90"; public static final String deviceWinPhone7 = "windows phone os 7"; public static final String deviceWinMob = "windows ce"; public static final String deviceWindows = "windows"; public static final String deviceIeMob = "iemobile"; public static final String devicePpc = "ppc"; //Stands for PocketPC public static final String enginePie = "wm5 pie"; //An old Windows Mobile public static final String deviceBB = "blackberry"; public static final String vndRIM = "vnd.rim"; //Detectable when BB devices emulate IE or Firefox public static final String deviceBBStorm = "blackberry95"; //Storm 1 and 2 public static final String deviceBBBold = "blackberry97"; //Bold 97x0 (non-touch) public static final String deviceBBBoldTouch = "blackberry 99"; //Bold 99x0 (touchscreen) public static final String deviceBBTour = "blackberry96"; //Tour public static final String deviceBBCurve = "blackberry89"; //Curve 2 public static final String deviceBBTorch = "blackberry 98"; //Torch public static final String deviceBBPlaybook = "playbook"; //PlayBook tablet public static final String devicePalm = "palm"; public static final String deviceWebOS = "webos"; //For Palm's line of WebOS devices public static final String deviceWebOShp = "hpwos"; //For HP's line of WebOS devices public static final String engineBlazer = "blazer"; //Old Palm public static final String engineXiino = "xiino"; //Another old Palm public static final String deviceKindle = "kindle"; //Amazon Kindle, eInk one. public static final String deviceNuvifone = "nuvifone"; //Garmin Nuvifone //Initialize variables for mobile-specific content. public static final String vndwap = "vnd.wap"; public static final String wml = "wml"; //Initialize variables for other random devices and mobile browsers. public static final String deviceTablet = "tablet"; //Generic term for slate and tablet devices public static final String deviceBrew = "brew"; public static final String deviceDanger = "danger"; public static final String deviceHiptop = "hiptop"; public static final String devicePlaystation = "playstation"; public static final String deviceNintendoDs = "nitro"; public static final String deviceNintendo = "nintendo"; public static final String deviceWii = "wii"; public static final String deviceXbox = "xbox"; public static final String deviceArchos = "archos"; public static final String engineOpera = "opera"; //Popular browser public static final String engineNetfront = "netfront"; //Common embedded OS browser public static final String engineUpBrowser = "up.browser"; //common on some phones public static final String engineOpenWeb = "openweb"; //Transcoding by OpenWave server public static final String deviceMidp = "midp"; //a mobile Java technology public static final String uplink = "up.link"; public static final String engineTelecaQ = "teleca q"; //a modern feature phone browser public static final String devicePda = "pda"; //some devices report themselves as PDAs public static final String mini = "mini"; //Some mobile browsers put "mini" in their names. public static final String mobile = "mobile"; //Some mobile browsers put "mobile" in their user agent strings. public static final String mobi = "mobi"; //Some mobile browsers put "mobi" in their user agent strings. //Use Maemo, Tablet, and Linux to test for Nokia"s Internet Tablets. public static final String maemo = "maemo"; public static final String linux = "linux"; public static final String qtembedded = "qt embedded"; //for Sony Mylo public static final String mylocom2 = "com2"; //for Sony Mylo also //In some UserAgents, the only clue is the manufacturer. public static final String manuSonyEricsson = "sonyericsson"; public static final String manuericsson = "ericsson"; public static final String manuSamsung1 = "sec-sgh"; public static final String manuSony = "sony"; public static final String manuHtc = "htc"; //Popular Android and WinMo manufacturer //In some UserAgents, the only clue is the operator. public static final String svcDocomo = "docomo"; public static final String svcKddi = "kddi"; public static final String svcVodafone = "vodafone"; //Disambiguation strings. public static final String disUpdate = "update"; //pda vs. update /** * Initialize the userAgent and httpAccept variables * * @param userAgent the User-Agent header * @param httpAccept the Accept header */ public UserAgentInfo(String userAgent, String httpAccept) { if (userAgent != null) { this.userAgent = userAgent.toLowerCase(); } if (httpAccept != null) { this.httpAccept = httpAccept.toLowerCase(); } //Intialize key stored values. initDeviceScan(); } /** * Is the device is any Mobile Device (in list of course) * @return */ public boolean isMobileDevice(){ if(isIphone || isAndroidPhone || isTierTablet || isTierIphone || isTierRichCss || isTierGenericMobile) return true; return false; } /** * Return the lower case HTTP_USER_AGENT * @return userAgent */ public String getUserAgent() { return userAgent; } /** * Return the lower case HTTP_ACCEPT * @return httpAccept */ public String getHttpAccept() { return httpAccept; } /** * Return whether the device is an Iphone or iPod Touch * @return isIphone */ public boolean getIsIphone() { return isIphone; } /** * Return whether the device is in the Tablet Tier. * @return isTierTablet */ public boolean getIsTierTablet() { return isTierTablet; } /** * Return whether the device is in the Iphone Tier. * @return isTierIphone */ public boolean getIsTierIphone() { return isTierIphone; } /** * Return whether the device is in the 'Rich CSS' tier of mobile devices. * @return isTierRichCss */ public boolean getIsTierRichCss() { return isTierRichCss; } /** * Return whether the device is a generic, less-capable mobile device. * @return isTierGenericMobile */ public boolean getIsTierGenericMobile() { return isTierGenericMobile; } /** * Initialize Key Stored Values. */ public void initDeviceScan() { this.isIphone = detectIphoneOrIpod(); this.isAndroidPhone = detectAndroidPhone(); this.isTierTablet = detectTierTablet(); this.isTierIphone = detectTierIphone(); this.isTierRichCss = detectTierRichCss(); this.isTierGenericMobile = detectTierOtherPhones(); } /** * Detects if the current device is an iPhone. * @return detection of an iPhone */ public boolean detectIphone() { // The iPad and iPod touch say they're an iPhone! So let's disambiguate. if (userAgent.indexOf(deviceIphone) != -1 && !detectIpad() && !detectIpod()) { return true; } return false; } /** * Detects if the current device is an iPod Touch. * @return detection of an iPod Touch */ public boolean detectIpod() { if (userAgent.indexOf(deviceIpod) != -1) { return true; } return false; } /** * Detects if the current device is an iPad tablet. * @return detection of an iPad */ public boolean detectIpad() { if (userAgent.indexOf(deviceIpad) != -1 && detectWebkit()) { return true; } return false; } /** * Detects if the current device is an iPhone or iPod Touch. * @return detection of an iPhone or iPod Touch */ public boolean detectIphoneOrIpod() { //We repeat the searches here because some iPods may report themselves as an iPhone, which would be okay. if (userAgent.indexOf(deviceIphone) != -1 || userAgent.indexOf(deviceIpod) != -1) { return true; } return false; } /** * Detects *any* iOS device: iPhone, iPod Touch, iPad. * @return detection of an Apple iOS device */ public boolean detectIos() { if (detectIphoneOrIpod() || detectIpad()) { return true; } return false; } /** * Detects *any* Android OS-based device: phone, tablet, and multi-media player. * Also detects Google TV. * @return detection of an Android device */ public boolean detectAndroid() { if ((userAgent.indexOf(deviceAndroid) != -1) || detectGoogleTV()) return true; //Special check for the HTC Flyer 7" tablet. It should report here. if (userAgent.indexOf(deviceHtcFlyer) != -1) return true; return false; } /** * Detects if the current device is a (small-ish) Android OS-based device * used for calling and/or multi-media (like a Samsung Galaxy Player). * Google says these devices will have 'Android' AND 'mobile' in user agent. * Ignores tablets (Honeycomb and later). * @return detection of an Android phone */ public boolean detectAndroidPhone() { if (detectAndroid() && (userAgent.indexOf(mobile) != -1)) return true; //Special check for Android phones with Opera Mobile. They should report here. if (detectOperaAndroidPhone()) return true; //Special check for the HTC Flyer 7" tablet. It should report here. if (userAgent.indexOf(deviceHtcFlyer) != -1) return true; return false; } /** * Detects if the current device is a (self-reported) Android tablet. * Google says these devices will have 'Android' and NOT 'mobile' in their user agent. * @return detection of an Android tablet */ public boolean detectAndroidTablet() { //First, let's make sure we're on an Android device. if (!detectAndroid()) return false; //Special check for Opera Android Phones. They should NOT report here. if (detectOperaMobile()) return false; //Special check for the HTC Flyer 7" tablet. It should NOT report here. if (userAgent.indexOf(deviceHtcFlyer) != -1) return false; //Otherwise, if it's Android and does NOT have 'mobile' in it, Google says it's a tablet. if ((userAgent.indexOf(mobile) > -1)) return false; else return true; } /** * Detects if the current device is an Android OS-based device and * the browser is based on WebKit. * @return detection of an Android WebKit browser */ public boolean detectAndroidWebKit() { if (detectAndroid() && detectWebkit()) { return true; } return false; } /** * Detects if the current device is a GoogleTV. * @return detection of GoogleTV */ public boolean detectGoogleTV() { if (userAgent.indexOf(deviceGoogleTV) != -1) { return true; } return false; } /** * Detects if the current browser is based on WebKit. * @return detection of a WebKit browser */ public boolean detectWebkit() { if (userAgent.indexOf(engineWebKit) != -1) { return true; } return false; } /** * Detects if the current browser is the Symbian S60 Open Source Browser. * @return detection of Symbian S60 Browser */ public boolean detectS60OssBrowser() { //First, test for WebKit, then make sure it's either Symbian or S60. if (detectWebkit() && (userAgent.indexOf(deviceSymbian) != -1 || userAgent.indexOf(deviceS60) != -1)) { return true; } return false; } /** * * Detects if the current device is any Symbian OS-based device, * including older S60, Series 70, Series 80, Series 90, and UIQ, * or other browsers running on these devices. * @return detection of SymbianOS */ public boolean detectSymbianOS() { if (userAgent.indexOf(deviceSymbian) != -1 || userAgent.indexOf(deviceS60) != -1 || userAgent.indexOf(deviceS70) != -1 || userAgent.indexOf(deviceS80) != -1 || userAgent.indexOf(deviceS90) != -1) { return true; } return false; } /** * Detects if the current browser is a * Windows Phone 7 device. * @return detection of Windows Phone 7 */ public boolean detectWindowsPhone7() { if (userAgent.indexOf(deviceWinPhone7) != -1) { return true; } return false; } /** * Detects if the current browser is a Windows Mobile device. * Excludes Windows Phone 7 devices. * Focuses on Windows Mobile 6.xx and earlier. * @return detection of Windows Mobile */ public boolean detectWindowsMobile() { //Exclude new Windows Phone 7. if (detectWindowsPhone7()) { return false; } //Most devices use 'Windows CE', but some report 'iemobile' // and some older ones report as 'PIE' for Pocket IE. // We also look for instances of HTC and Windows for many of their WinMo devices. if (userAgent.indexOf(deviceWinMob) != -1 || userAgent.indexOf(deviceWinMob) != -1 || userAgent.indexOf(deviceIeMob) != -1 || userAgent.indexOf(enginePie) != -1 || (userAgent.indexOf(manuHtc) != -1 && userAgent.indexOf(deviceWindows) != -1) || (detectWapWml() && userAgent.indexOf(deviceWindows) != -1)) { return true; } //Test for Windows Mobile PPC but not old Macintosh PowerPC. if (userAgent.indexOf(devicePpc) != -1 && !(userAgent.indexOf(deviceMacPpc) != -1)) return true; return false; } /** * Detects if the current browser is any BlackBerry. * Includes the PlayBook. * @return detection of Blackberry */ public boolean detectBlackBerry() { if (userAgent.indexOf(deviceBB) != -1 || httpAccept.indexOf(vndRIM) != -1) { return true; } return false; } /** * Detects if the current browser is on a BlackBerry tablet device. * Example: PlayBook * @return detection of a Blackberry Tablet */ public boolean detectBlackBerryTablet() { if (userAgent.indexOf(deviceBBPlaybook) != -1) { return true; } return false; } /** * Detects if the current browser is a BlackBerry device AND uses a * WebKit-based browser. These are signatures for the new BlackBerry OS 6. * Examples: Torch. Includes the Playbook. * @return detection of a Blackberry device with WebKit browser */ public boolean detectBlackBerryWebKit() { if (detectBlackBerry() && userAgent.indexOf(engineWebKit) != -1) { return true; } return false; } /** * Detects if the current browser is a BlackBerry Touch * device, such as the Storm, Torch, and Bold Touch. Excludes the Playbook. * @return detection of a Blackberry touchscreen device */ public boolean detectBlackBerryTouch() { if (detectBlackBerry() && (userAgent.indexOf(deviceBBStorm) != -1 || userAgent.indexOf(deviceBBTorch) != -1 || userAgent.indexOf(deviceBBBoldTouch) != -1)) { return true; } return false; } /** * Detects if the current browser is a BlackBerry device AND * has a more capable recent browser. Excludes the Playbook. * Examples, Storm, Bold, Tour, Curve2 * Excludes the new BlackBerry OS 6 and 7 browser!! * @return detection of a Blackberry device with a better browser */ public boolean detectBlackBerryHigh() { //Disambiguate for BlackBerry OS 6 or 7 (WebKit) browser if (detectBlackBerryWebKit()) return false; if (detectBlackBerry()) { if (detectBlackBerryTouch() || userAgent.indexOf(deviceBBBold) != -1 || userAgent.indexOf(deviceBBTour) != -1 || userAgent.indexOf(deviceBBCurve) != -1) { return true; } else { return false; } } else { return false; } } /** * Detects if the current browser is a BlackBerry device AND * has an older, less capable browser. * Examples: Pearl, 8800, Curve1 * @return detection of a Blackberry device with a poorer browser */ public boolean detectBlackBerryLow() { if (detectBlackBerry()) { //Assume that if it's not in the High tier, then it's Low if (detectBlackBerryHigh() || detectBlackBerryWebKit()) { return false; } else { return true; } } else { return false; } } /** * Detects if the current browser is on a PalmOS device. * @return detection of a PalmOS device */ public boolean detectPalmOS() { //Most devices nowadays report as 'Palm', but some older ones reported as Blazer or Xiino. if (userAgent.indexOf(devicePalm) != -1 || userAgent.indexOf(engineBlazer) != -1 || userAgent.indexOf(engineXiino) != -1) { //Make sure it's not WebOS first if (detectPalmWebOS()) { return false; } else { return true; } } return false; } /** * Detects if the current browser is on a Palm device * running the new WebOS. * @return detection of a Palm WebOS device */ public boolean detectPalmWebOS() { if (userAgent.indexOf(deviceWebOS) != -1) { return true; } return false; } /** * Detects if the current browser is on an HP tablet running WebOS. * @return detection of an HP WebOS tablet */ public boolean detectWebOSTablet() { if (userAgent.indexOf(deviceWebOShp) != -1 && userAgent.indexOf(deviceTablet) != -1) { return true; } return false; } /** * Detects if the current browser is a * Garmin Nuvifone. * @return detection of a Garmin Nuvifone */ public boolean detectGarminNuvifone() { if (userAgent.indexOf(deviceNuvifone) != -1) { return true; } return false; } /** * Check to see whether the device is any device * in the 'smartphone' category. * @return detection of a general smartphone device */ public boolean detectSmartphone() { return (isIphone || isAndroidPhone || isTierIphone || detectS60OssBrowser() || detectSymbianOS() || detectWindowsMobile() || detectWindowsPhone7() || detectBlackBerry() || detectPalmWebOS() || detectPalmOS() || detectGarminNuvifone()); } /** * Detects whether the device is a Brew-powered device. * @return detection of a Brew device */ public boolean detectBrewDevice() { if (userAgent.indexOf(deviceBrew) != -1) { return true; } return false; } /** * Detects the Danger Hiptop device. * @return detection of a Danger Hiptop */ public boolean detectDangerHiptop() { if (userAgent.indexOf(deviceDanger) != -1 || userAgent.indexOf(deviceHiptop) != -1) { return true; } return false; } /** * Detects Opera Mobile or Opera Mini. * @return detection of an Opera browser for a mobile device */ public boolean detectOperaMobile() { if (userAgent.indexOf(engineOpera) != -1 && (userAgent.indexOf(mini) != -1 || userAgent.indexOf(mobi) != -1)) { return true; } return false; } /** * Detects Opera Mobile on an Android phone. * @return detection of an Opera browser on an Android phone */ public boolean detectOperaAndroidPhone() { if (userAgent.indexOf(engineOpera) != -1 && (userAgent.indexOf(deviceAndroid) != -1 && userAgent.indexOf(mobi) != -1)) { return true; } return false; } /** * Detects Opera Mobile on an Android tablet. * @return detection of an Opera browser on an Android tablet */ public boolean detectOperaAndroidTablet() { if (userAgent.indexOf(engineOpera) != -1 && (userAgent.indexOf(deviceAndroid) != -1 && userAgent.indexOf(deviceTablet) != -1)) { return true; } return false; } /** * Detects whether the device supports WAP or WML. * @return detection of a WAP- or WML-capable device */ public boolean detectWapWml() { if (httpAccept.indexOf(vndwap) != -1 || httpAccept.indexOf(wml) != -1) { return true; } return false; } /** * Detects if the current device is an Amazon Kindle (eInk devices only). * Note: For the Kindle Fire, use the normal Android methods. * @return detection of a Kindle */ public boolean detectKindle() { if (userAgent.indexOf(deviceKindle)!= -1 && !detectAndroid()) { return true; } return false; } /** * Detects if the current device is a mobile device. * This method catches most of the popular modern devices. * Excludes Apple iPads and other modern tablets. * @return detection of any mobile device using the quicker method */ public boolean detectMobileQuick() { //Let's exclude tablets if (isTierTablet) { return false; } //Most mobile browsing is done on smartphones if (detectSmartphone()) { return true; } if (detectWapWml() || detectBrewDevice() || detectOperaMobile()) { return true; } if ((userAgent.indexOf(engineNetfront) != -1) || (userAgent.indexOf(engineUpBrowser) != -1) || (userAgent.indexOf(engineOpenWeb) != -1)) { return true; } if (detectDangerHiptop() || detectMidpCapable() || detectMaemoTablet() || detectArchos()) { return true; } if ((userAgent.indexOf(devicePda) != -1) && (userAgent.indexOf(disUpdate) < 0)) //no index found { return true; } if (userAgent.indexOf(mobile) != -1) { return true; } return false; } /** * Detects if the current device is a Sony Playstation. * @return detection of Sony Playstation */ public boolean detectSonyPlaystation() { if (userAgent.indexOf(devicePlaystation) != -1) { return true; } return false; } /** * Detects if the current device is a Nintendo game device. * @return detection of Nintendo */ public boolean detectNintendo() { if (userAgent.indexOf(deviceNintendo) != -1 || userAgent.indexOf(deviceWii) != -1 || userAgent.indexOf(deviceNintendoDs) != -1) { return true; } return false; } /** * Detects if the current device is a Microsoft Xbox. * @return detection of Xbox */ public boolean detectXbox() { if (userAgent.indexOf(deviceXbox) != -1) { return true; } return false; } /** * Detects if the current device is an Internet-capable game console. * @return detection of any Game Console */ public boolean detectGameConsole() { if (detectSonyPlaystation() || detectNintendo() || detectXbox()) { return true; } return false; } /** * Detects if the current device supports MIDP, a mobile Java technology. * @return detection of a MIDP mobile Java-capable device */ public boolean detectMidpCapable() { if (userAgent.indexOf(deviceMidp) != -1 || httpAccept.indexOf(deviceMidp) != -1) { return true; } return false; } /** * Detects if the current device is on one of the Maemo-based Nokia Internet Tablets. * @return detection of a Maemo OS tablet */ public boolean detectMaemoTablet() { if (userAgent.indexOf(maemo) != -1) { return true; } else if (userAgent.indexOf(linux) != -1 && userAgent.indexOf(deviceTablet) != -1 && !detectWebOSTablet() && !detectAndroid()) { return true; } return false; } /** * Detects if the current device is an Archos media player/Internet tablet. * @return detection of an Archos media player */ public boolean detectArchos() { if (userAgent.indexOf(deviceArchos) != -1) { return true; } return false; } /** * Detects if the current browser is a Sony Mylo device. * @return detection of a Sony Mylo device */ public boolean detectSonyMylo() { if (userAgent.indexOf(manuSony) != -1 && (userAgent.indexOf(qtembedded) != -1 || userAgent.indexOf(mylocom2) != -1)) { return true; } return false; } /** * The longer and more thorough way to detect for a mobile device. * Will probably detect most feature phones, * smartphone-class devices, Internet Tablets, * Internet-enabled game consoles, etc. * This ought to catch a lot of the more obscure and older devices, also -- * but no promises on thoroughness! * @return detection of any mobile device using the more thorough method */ public boolean detectMobileLong() { if (detectMobileQuick() || detectGameConsole() || detectSonyMylo()) { return true; } //detect older phones from certain manufacturers and operators. if (userAgent.indexOf(uplink) != -1) { return true; } if (userAgent.indexOf(manuSonyEricsson) != -1) { return true; } if (userAgent.indexOf(manuericsson) != -1) { return true; } if (userAgent.indexOf(manuSamsung1) != -1) { return true; } if (userAgent.indexOf(svcDocomo) != -1) { return true; } if (userAgent.indexOf(svcKddi) != -1) { return true; } if (userAgent.indexOf(svcVodafone) != -1) { return true; } return false; } //***************************** // For Mobile Web Site Design //***************************** /** * The quick way to detect for a tier of devices. * This method detects for the new generation of * HTML 5 capable, larger screen tablets. * Includes iPad, Android (e.g., Xoom), BB Playbook, WebOS, etc. * @return detection of any device in the Tablet Tier */ public boolean detectTierTablet() { if (detectIpad() || detectAndroidTablet() || detectBlackBerryTablet() || detectWebOSTablet()) { return true; } return false; } /** * The quick way to detect for a tier of devices. * This method detects for devices which can * display iPhone-optimized web content. * Includes iPhone, iPod Touch, Android, Windows Phone 7, Palm WebOS, etc. * @return detection of any device in the iPhone/Android/WP7/WebOS Tier */ public boolean detectTierIphone() { if (isIphone || isAndroidPhone || (detectBlackBerryWebKit() && detectBlackBerryTouch()) || detectWindowsPhone7() || detectPalmWebOS() || detectGarminNuvifone()) { return true; } return false; } /** * The quick way to detect for a tier of devices. * This method detects for devices which are likely to be capable * of viewing CSS content optimized for the iPhone, * but may not necessarily support JavaScript. * Excludes all iPhone Tier devices. * @return detection of any device in the 'Rich CSS' Tier */ public boolean detectTierRichCss() { boolean result = false; //The following devices are explicitly ok. //Note: 'High' BlackBerry devices ONLY if (detectMobileQuick()) { if (!detectTierIphone()) { //The following devices are explicitly ok. //Note: 'High' BlackBerry devices ONLY //Older Windows 'Mobile' isn't good enough for iPhone Tier. if (detectWebkit() || detectS60OssBrowser() || detectBlackBerryHigh() || detectWindowsMobile() || userAgent.indexOf(engineTelecaQ) != -1) { result= true; } // if detectWebkit() } //if !detectTierIphone() } //if detectMobileQuick() return result; } /** * The quick way to detect for a tier of devices. * This method detects for all other types of phones, * but excludes the iPhone and RichCSS Tier devices. * @return detection of a mobile device in the less capable tier */ public boolean detectTierOtherPhones() { //Exclude devices in the other 2 categories if (detectMobileLong() && !detectTierIphone() && !detectTierRichCss()) { return true; } return false; } }
ferremarce/TEST_USABILIDAD
src/main/java/tesisweb/controller/general/UserAgentInfo.java
Java
gpl-2.0
35,267
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Reports\Block\Adminhtml\Sales; /** * Adminhtml invoiced report page content block * * @api * @author Magento Core Team <core@magentocommerce.com> * @since 100.0.2 */ class Invoiced extends \Magento\Backend\Block\Widget\Grid\Container { /** * Template file * * @var string */ protected $_template = 'Magento_Reports::report/grid/container.phtml'; /** * {@inheritdoc} */ protected function _construct() { $this->_blockGroup = 'Magento_Reports'; $this->_controller = 'adminhtml_sales_invoiced'; $this->_headerText = __('Total Invoiced vs. Paid Report'); parent::_construct(); $this->buttonList->remove('add'); $this->addButton( 'filter_form_submit', ['label' => __('Show Report'), 'onclick' => 'filterFormSubmit()', 'class' => 'primary'] ); } /** * Get filter URL * * @return string */ public function getFilterUrl() { $this->getRequest()->setParam('filter', null); return $this->getUrl('*/*/invoiced', ['_current' => true]); } }
kunj1988/Magento2
app/code/Magento/Reports/Block/Adminhtml/Sales/Invoiced.php
PHP
gpl-2.0
1,251
<?php $contents="<html> <head> <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js' type='text/javascript' charset='utf-8'></script> <script src='js/jquery.uniform.min.js' type='text/javascript' charset='utf-8'></script> <script type='text/javascript' charset='utf-8'> $(function(){ $('input, textarea, select, button').uniform(); }); </script> <link rel='stylesheet' href='css/uniform.default.css' type='text/css' media='screen'> <style type='text/css' media='screen'> body { font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; color: #666; padding: 40px; } h1 { margin-top: 0; } ul { list-style: none; padding: 0; margin: 0; } li { margin-bottom: 20px; clear: both; } label { font-size: 10px; font-weight: bold; text-transform: uppercase; display: block; margin-bottom: 3px; clear: both; } </style> </head> "; include('../openinviter.php'); $inviter=new OpenInviter(); $oi_services=$inviter->getPlugins(); $pluginContent=""; if (isset($_POST['provider_box'])) { if (isset($oi_services['email'][$_POST['provider_box']])) $plugType='email'; elseif (isset($oi_services['social'][$_POST['provider_box']])) $plugType='social'; else $plugType=''; if ($plugType) $pluginContent=createPluginContent($_POST['provider_box']); } elseif(!empty($_GET['provider_box'])) { if (isset($oi_services['email'][$_GET['provider_box']])) $plugType='email'; elseif (isset($oi_services['social'][$_GET['provider_box']])) $plugType='social'; else $plugType=''; if($plugType) { $_POST['provider_box']=$_GET['provider_box']; $pluginContent=createPluginContent($_GET['provider_box']); } } else { $plugType = ''; $_POST['provider_box']=''; } function ers($ers) { if (!empty($ers)) { $contents="<table cellspacing='0' cellpadding='0' style='border:1px solid red;' align='center'><tr><td valign='middle' style='padding:3px' valign='middle'><img src='imgs/ers.gif'></td><td valign='middle' style='color:red;padding:5px;'>"; foreach ($ers as $key=>$error) $contents.="{$error}<br >"; $contents.="</td></tr></table><br >"; return $contents; } } function oks($oks) { if (!empty($oks)) { $contents="<table border='0' cellspacing='0' cellpadding='10' style='border:1px solid #5897FE;' align='center'><tr><td valign='middle' valign='middle'><img src='imgs/oks.gif' ></td><td valign='middle' style='color:#5897FE;padding:5px;'> "; foreach ($oks as $key=>$msg) $contents.="{$msg}<br >"; $contents.="</td></tr></table><br >"; return $contents; } } if (!empty($_POST['step'])) $step=$_POST['step']; else $step='get_contacts'; $ers=array();$oks=array();$import_ok=false;$done=false; if ($_SERVER['REQUEST_METHOD']=='POST') { if ($step=='get_contacts') { if (empty($_POST['email_box'])) $ers['email']="Email missing !"; if (empty($_POST['password_box'])) $ers['password']="Password missing !"; if (empty($_POST['provider_box'])) $ers['provide']='Provider missing!'; if (count($ers)==0) { $inviter->startPlugin($_POST['provider_box']); $internal=$inviter->getInternalError(); if ($internal) $ers['inviter']=$internal; elseif (!$inviter->login($_POST['email_box'],$_POST['password_box'])) { $internal=$inviter->getInternalError(); $ers['login']=($internal?$internal:"Login failed. Please check the email and password you have provided and try again later !"); } elseif (false===$contacts=$inviter->getMyContacts()) $ers['contacts']="Unable to get contacts !"; else { $import_ok=true; $step='send_invites'; $_POST['oi_session_id']=$inviter->plugin->getSessionID(); $_POST['message_box']=''; } } } elseif ($step=='send_invites') { if (empty($_POST['provider_box'])) $ers['provider']='Provider missing !'; else { $inviter->startPlugin($_POST['provider_box']); $internal=$inviter->getInternalError(); if ($internal) $ers['internal']=$internal; else { if (empty($_POST['email_box'])) $ers['inviter']='Inviter information missing !'; if (empty($_POST['oi_session_id'])) $ers['session_id']='No active session !'; if (empty($_POST['message_box'])) $ers['message_body']='Message missing !'; else $_POST['message_box']=strip_tags($_POST['message_box']); $selected_contacts=array();$contacts=array(); $message=array('subject'=>$inviter->settings['message_subject'],'body'=>$inviter->settings['message_body'],'attachment'=>"\n\rAttached message: \n\r".$_POST['message_box']); if ($inviter->showContacts()) { foreach ($_POST as $key=>$val) if (strpos($key,'check_')!==false) $selected_contacts[$_POST['email_'.$val]]=$_POST['name_'.$val]; elseif (strpos($key,'email_')!==false) { $temp=explode('_',$key);$counter=$temp[1]; if (is_numeric($temp[1])) $contacts[$val]=$_POST['name_'.$temp[1]]; } if (count($selected_contacts)==0) $ers['contacts']="You haven't selected any contacts to invite !"; } } } if (count($ers)==0) { $sendMessage=$inviter->sendMessage($_POST['oi_session_id'],$message,$selected_contacts); $inviter->logout(); if ($sendMessage===-1) { $message_footer="\r\n\r\nThis invite was sent using OpenInviter technology."; $message_subject=$_POST['email_box'].$message['subject']; $message_body=$message['body'].$message['attachment'].$message_footer; $headers="From: {$_POST['email_box']}"; foreach ($selected_contacts as $email=>$name) mail($email,$message_subject,$message_body,$headers); $oks['mails']="Mails sent successfully"; } elseif ($sendMessage===false) { $internal=$inviter->getInternalError(); $ers['internal']=($internal?$internal:"There were errors while sending your invites.<br>Please try again later!"); } else $oks['internal']="Invites sent successfully!"; $done=true; } } } else { $_POST['email_box']=''; $_POST['password_box']=''; } $contents.="<script type='text/javascript'> function toggleAll(element) { var form = document.forms.openinviter, z = 0; for(z=0; z<form.length;z++) { if(form[z].type == 'checkbox') form[z].checked = element.checked; } } </script>"; $contents.="<form action='' method='POST' name='openinviter'>".ers($ers).oks($oks); if (!$done) { if ($step=='get_contacts') { $contents.="<table align='center' class='thTable' cellspacing='2' cellpadding='0' style='border:none;'> <tr><td align='right'><label for='email_box'>Email</label></td><td><input type='text' name='email_box' value='{$_POST['email_box']}'></td></tr> <tr><td align='right'><label for='password_box'>Password</label></td><td><input type='password' name='password_box' value='{$_POST['password_box']}'></td></tr> <tr><td colspan='2' align='center'><input type='submit' name='import' value='Import Contacts'></td></tr> </table><input type='hidden' name='provider_box' value='{$_POST['provider_box']}'><input type='hidden' name='step' value='get_contacts'>"; } else $contents.="<table class='thTable' cellspacing='0' cellpadding='0' style='border:none;'> <tr><td align='center' valign='top'><label for='message_box'>Message</label></td><td><textarea rows='5' cols='50' name='message_box' style='width:300px;'>{$_POST['message_box']}</textarea></td></tr> <tr><td align='center' colspan='2'><input type='submit' name='send' value='Send Invites' ></td></tr> </table>"; } $contents.="<center>{$pluginContent}</center>"; if (!$done) { if ($step=='send_invites') { if ($inviter->showContacts()) { $contents.="<table align='center' cellspacing='0' cellpadding='0'><tr><td colspan='".($plugType=='email'? "3":"2")."'>Your contacts</td></tr>"; if (count($contacts)==0) $contents.="<tr><td align='center' style='padding:20px;' colspan='".($plugType=='email'? "3":"2")."'>You do not have any contacts in your address book.</td></tr>"; else { $contents.="<tr><td><input type='checkbox' onChange='toggleAll(this)' name='toggle_all' title='Select/Deselect all' checked>Invite?</td><td>Name</td>".($plugType == 'email' ?"<td>E-mail</td>":"")."</tr>"; $counter=0; foreach ($contacts as $email=>$name) { $counter++; $contents.="<tr><td><input name='check_{$counter}' value='{$counter}' type='checkbox' checked><input type='hidden' name='email_{$counter}' value='{$email}'><input type='hidden' name='name_{$counter}' value='{$name}'></td><td>{$name}</td>".($plugType == 'email' ?"<td>{$email}</td>":"")."</tr>"; } $contents.="<tr><td colspan='".($plugType=='email'? "3":"2")."' style='padding:3px;'><input type='submit' name='send' value='Send invites'></td></tr>"; } $contents.="</table>"; } $contents.="<input type='hidden' name='step' value='send_invites'> <input type='hidden' name='provider_box' value='{$_POST['provider_box']}'> <input type='hidden' name='email_box' value='{$_POST['email_box']}'> <input type='hidden' name='oi_session_id' value='{$_POST['oi_session_id']}'>"; $contents.="<script>self.parent.$.fancybox.resize();</script>"; } } $contents.="</form>"; echo $contents; function createPluginContent($pr) { global $oi_services,$plugType; $a=array_keys($oi_services[$plugType]); foreach($a as $r=>$sv) if ($sv==$pr) break; return $contentPlugin="<div style='border:none; display:block; height:60px; margin:0; padding:0; width:130px; background-position: 0px ".(-60*$r)."px; background-image:url(\"imgs/{$plugType}_services.png\");'></div>"; } ?>
berryjace/www
crm/library/ThirdParty/OpenInviter/more_examples/get_contacts.php
PHP
gpl-2.0
9,479
import React from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { UncontrolledDropdown, DropdownToggle, DropdownMenu, DropdownItem, NavItem, NavLink } from 'reactstrap'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faCog, faExternalLinkAlt, faSignOutAlt } from '@fortawesome/free-solid-svg-icons'; import { useTranslation } from 'react-i18next'; import Avatar from 'components/Avatar'; import { openSettingsModal } from 'store/actions/settingsActions'; import { logOut } from 'store/actions/userActions'; import './UserDropdown.scss'; export default function UserDropdow() { const { t } = useTranslation(); const dispatch = useDispatch(); const user = useSelector((state) => state.user); return ( <React.Fragment> <UncontrolledDropdown data-cy="UserDropdown" nav inNavbar> <DropdownToggle nav caret className="ows-dropdown-user"> <Avatar user={user} alt={user.name} size="sm" /> <span className="ows-username" data-cy="UserDropdown-username"> {user.name} </span> </DropdownToggle> <DropdownMenu right> <DropdownItem href={user.url} target="_blank" rel="noopener" data-cy="UserDropdown-profileLink"> {t('viewProfile')} <FontAwesomeIcon className="ml-1" color="var(--gray)" icon={faExternalLinkAlt} /> </DropdownItem> <DropdownItem divider /> <DropdownItem onClick={openSettingsModal(dispatch)}> <FontAwesomeIcon icon={faCog} /> {t('settings')} </DropdownItem> <DropdownItem className="d-none d-md-block" onClick={logOut(dispatch)}> <FontAwesomeIcon icon={faSignOutAlt} /> {t('logOut')} </DropdownItem> </DropdownMenu> </UncontrolledDropdown> <NavItem className="d-block d-md-none"> <NavLink onClick={logOut(dispatch)}> <FontAwesomeIcon icon={faSignOutAlt} /> {t('logOut')} </NavLink> </NavItem> </React.Fragment> ); }
elamperti/OpenWebScrobbler
src/components/Navigation/partials/UserDropdown.js
JavaScript
gpl-2.0
2,071
/* * Copyright (C) 2005-2011 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "SpellMgr.h" #include "ObjectMgr.h" #include "SpellAuraDefines.h" #include "ProgressBar.h" #include "DBCStores.h" #include "World.h" #include "Chat.h" #include "Spell.h" #include "BattleGroundMgr.h" #include "MapManager.h" #include "Unit.h" SpellMgr::SpellMgr() { } SpellMgr::~SpellMgr() { } SpellMgr& SpellMgr::Instance() { static SpellMgr spellMgr; return spellMgr; } int32 GetSpellDuration(SpellEntry const *spellInfo) { if(!spellInfo) return 0; SpellDurationEntry const *du = sSpellDurationStore.LookupEntry(spellInfo->DurationIndex); if(!du) return 0; return (du->Duration[0] == -1) ? -1 : abs(du->Duration[0]); } int32 GetSpellMaxDuration(SpellEntry const *spellInfo) { if(!spellInfo) return 0; SpellDurationEntry const *du = sSpellDurationStore.LookupEntry(spellInfo->DurationIndex); if(!du) return 0; return (du->Duration[2] == -1) ? -1 : abs(du->Duration[2]); } int32 CalculateSpellDuration(SpellEntry const *spellInfo, Unit const* caster) { int32 duration = GetSpellDuration(spellInfo); if (duration != -1 && caster) { int32 maxduration = GetSpellMaxDuration(spellInfo); if (duration != maxduration && caster->GetTypeId() == TYPEID_PLAYER) duration += int32((maxduration - duration) * ((Player*)caster)->GetComboPoints() / 5); if (Player* modOwner = caster->GetSpellModOwner()) { modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_DURATION, duration); if (duration < 0) duration = 0; } } return duration; } uint32 GetSpellCastTime(SpellEntry const* spellInfo, Spell const* spell) { if (spell) { // some triggered spells have data only usable for client if (spell->IsTriggeredSpellWithRedundentData()) return 0; // spell targeted to non-trading trade slot item instant at trade success apply if (spell->GetCaster()->GetTypeId()==TYPEID_PLAYER) if (TradeData* my_trade = ((Player*)(spell->GetCaster()))->GetTradeData()) if (Item* nonTrade = my_trade->GetTraderData()->GetItem(TRADE_SLOT_NONTRADED)) if (nonTrade == spell->m_targets.getItemTarget()) return 0; } SpellCastTimesEntry const *spellCastTimeEntry = sSpellCastTimesStore.LookupEntry(spellInfo->CastingTimeIndex); // not all spells have cast time index and this is all is pasiive abilities if (!spellCastTimeEntry) return 0; int32 castTime = spellCastTimeEntry->CastTime; if (spell) { if (Player* modOwner = spell->GetCaster()->GetSpellModOwner()) modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CASTING_TIME, castTime, spell); if (!(spellInfo->Attributes & (SPELL_ATTR_UNK4|SPELL_ATTR_TRADESPELL))) castTime = int32(castTime * spell->GetCaster()->GetFloatValue(UNIT_MOD_CAST_SPEED)); else { if (spell->IsRangedSpell() && !spell->IsAutoRepeat()) castTime = int32(castTime * spell->GetCaster()->m_modAttackSpeedPct[RANGED_ATTACK]); } } if (spellInfo->Attributes & SPELL_ATTR_RANGED && (!spell || !spell->IsAutoRepeat())) castTime += 500; return (castTime > 0) ? uint32(castTime) : 0; } uint32 GetSpellCastTimeForBonus( SpellEntry const *spellProto, DamageEffectType damagetype ) { uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto); if (CastingTime > 7000) CastingTime = 7000; if (CastingTime < 1500) CastingTime = 1500; if(damagetype == DOT && !IsChanneledSpell(spellProto)) CastingTime = 3500; int32 overTime = 0; uint8 effects = 0; bool DirectDamage = false; bool AreaEffect = false; for (uint32 i = 0; i < MAX_EFFECT_INDEX; ++i) if (IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetA[i])) || IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetB[i]))) AreaEffect = true; for (uint32 i = 0; i < MAX_EFFECT_INDEX; ++i) { switch (spellProto->Effect[i]) { case SPELL_EFFECT_SCHOOL_DAMAGE: case SPELL_EFFECT_POWER_DRAIN: case SPELL_EFFECT_HEALTH_LEECH: case SPELL_EFFECT_ENVIRONMENTAL_DAMAGE: case SPELL_EFFECT_POWER_BURN: case SPELL_EFFECT_HEAL: DirectDamage = true; break; case SPELL_EFFECT_APPLY_AURA: switch (spellProto->EffectApplyAuraName[i]) { case SPELL_AURA_PERIODIC_DAMAGE: case SPELL_AURA_PERIODIC_HEAL: case SPELL_AURA_PERIODIC_LEECH: if ( GetSpellDuration(spellProto) ) overTime = GetSpellDuration(spellProto); break; // Penalty for additional effects case SPELL_AURA_DUMMY: ++effects; break; case SPELL_AURA_MOD_DECREASE_SPEED: ++effects; break; case SPELL_AURA_MOD_CONFUSE: case SPELL_AURA_MOD_STUN: case SPELL_AURA_MOD_ROOT: // -10% per effect effects += 2; break; default: break; } break; default: break; } } // Combined Spells with Both Over Time and Direct Damage if (overTime > 0 && CastingTime > 0 && DirectDamage) { // mainly for DoTs which are 3500 here otherwise uint32 OriginalCastTime = GetSpellCastTime(spellProto); if (OriginalCastTime > 7000) OriginalCastTime = 7000; if (OriginalCastTime < 1500) OriginalCastTime = 1500; // Portion to Over Time float PtOT = (overTime / 15000.0f) / ((overTime / 15000.0f) + (OriginalCastTime / 3500.0f)); if (damagetype == DOT) CastingTime = uint32(CastingTime * PtOT); else if (PtOT < 1.0f) CastingTime = uint32(CastingTime * (1 - PtOT)); else CastingTime = 0; } // Area Effect Spells receive only half of bonus if (AreaEffect) CastingTime /= 2; // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing for(int j = 0; j < MAX_EFFECT_INDEX; ++j) { if (spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH || (spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH)) { CastingTime /= 2; break; } } // -5% of total per any additional effect (multiplicative) for (int i = 0; i < effects; ++i) CastingTime *= 0.95f; return CastingTime; } uint16 GetSpellAuraMaxTicks(SpellEntry const* spellInfo) { int32 DotDuration = GetSpellDuration(spellInfo); if(DotDuration == 0) return 1; // 200% limit if(DotDuration > 30000) DotDuration = 30000; for (int j = 0; j < MAX_EFFECT_INDEX; ++j) { if (spellInfo->Effect[j] == SPELL_EFFECT_APPLY_AURA && ( spellInfo->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE || spellInfo->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_HEAL || spellInfo->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH) ) { if (spellInfo->EffectAmplitude[j] != 0) return DotDuration / spellInfo->EffectAmplitude[j]; break; } } return 6; } uint16 GetSpellAuraMaxTicks(uint32 spellId) { SpellEntry const* spellInfo = sSpellStore.LookupEntry(spellId); if (!spellInfo) { sLog.outError("GetSpellAuraMaxTicks: Spell %u not exist!", spellId); return 1; } return GetSpellAuraMaxTicks(spellInfo); } float CalculateDefaultCoefficient(SpellEntry const *spellProto, DamageEffectType const damagetype) { // Damage over Time spells bonus calculation float DotFactor = 1.0f; if (damagetype == DOT) { if (!IsChanneledSpell(spellProto)) DotFactor = GetSpellDuration(spellProto) / 15000.0f; if (uint16 DotTicks = GetSpellAuraMaxTicks(spellProto)) DotFactor /= DotTicks; } // Distribute Damage over multiple effects, reduce by AoE float coeff = GetSpellCastTimeForBonus(spellProto, damagetype) / 3500.0f; return coeff * DotFactor; } WeaponAttackType GetWeaponAttackType(SpellEntry const *spellInfo) { if(!spellInfo) return BASE_ATTACK; switch (spellInfo->DmgClass) { case SPELL_DAMAGE_CLASS_MELEE: if (spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_OFFHAND) return OFF_ATTACK; else return BASE_ATTACK; break; case SPELL_DAMAGE_CLASS_RANGED: return RANGED_ATTACK; break; default: // Wands if (spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG) return RANGED_ATTACK; else return BASE_ATTACK; break; } } bool IsPassiveSpell(uint32 spellId) { SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId); if (!spellInfo) return false; return IsPassiveSpell(spellInfo); } bool IsPassiveSpell(SpellEntry const *spellInfo) { return (spellInfo->Attributes & SPELL_ATTR_PASSIVE) != 0; } bool IsNoStackAuraDueToAura(uint32 spellId_1, uint32 spellId_2) { SpellEntry const *spellInfo_1 = sSpellStore.LookupEntry(spellId_1); SpellEntry const *spellInfo_2 = sSpellStore.LookupEntry(spellId_2); if(!spellInfo_1 || !spellInfo_2) return false; if(spellInfo_1->Id == spellId_2) return false; for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) { for (int32 j = 0; j < MAX_EFFECT_INDEX; ++j) { if (spellInfo_1->Effect[i] == spellInfo_2->Effect[j] && spellInfo_1->EffectApplyAuraName[i] == spellInfo_2->EffectApplyAuraName[j] && spellInfo_1->EffectMiscValue[i] == spellInfo_2->EffectMiscValue[j] && spellInfo_1->EffectItemType[i] == spellInfo_2->EffectItemType[j] && (spellInfo_1->Effect[i] != 0 || spellInfo_1->EffectApplyAuraName[i] != 0 || spellInfo_1->EffectMiscValue[i] != 0 || spellInfo_1->EffectItemType[i] != 0)) return true; } } return false; } int32 CompareAuraRanks(uint32 spellId_1, uint32 spellId_2) { SpellEntry const*spellInfo_1 = sSpellStore.LookupEntry(spellId_1); SpellEntry const*spellInfo_2 = sSpellStore.LookupEntry(spellId_2); if(!spellInfo_1 || !spellInfo_2) return 0; if (spellId_1 == spellId_2) return 0; for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) { if (spellInfo_1->Effect[i] != 0 && spellInfo_2->Effect[i] != 0 && spellInfo_1->Effect[i] == spellInfo_2->Effect[i]) { int32 diff = spellInfo_1->EffectBasePoints[i] - spellInfo_2->EffectBasePoints[i]; if (spellInfo_1->CalculateSimpleValue(SpellEffectIndex(i)) < 0 && spellInfo_2->CalculateSimpleValue(SpellEffectIndex(i)) < 0) return -diff; else return diff; } } return 0; } SpellSpecific GetSpellSpecific(uint32 spellId) { SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId); if(!spellInfo) return SPELL_NORMAL; switch(spellInfo->SpellFamilyName) { case SPELLFAMILY_GENERIC: { // Food / Drinks (mostly) if (spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) { bool food = false; bool drink = false; for(int i = 0; i < MAX_EFFECT_INDEX; ++i) { switch(spellInfo->EffectApplyAuraName[i]) { // Food case SPELL_AURA_MOD_REGEN: case SPELL_AURA_OBS_MOD_HEALTH: food = true; break; // Drink case SPELL_AURA_MOD_POWER_REGEN: case SPELL_AURA_OBS_MOD_MANA: drink = true; break; default: break; } } if (food && drink) return SPELL_FOOD_AND_DRINK; else if (food) return SPELL_FOOD; else if (drink) return SPELL_DRINK; } else { // Well Fed buffs (must be exclusive with Food / Drink replenishment effects, or else Well Fed will cause them to be removed) // SpellIcon 2560 is Spell 46687, does not have this flag if ((spellInfo->AttributesEx2 & SPELL_ATTR_EX2_FOOD_BUFF) || spellInfo->SpellIconID == 2560) return SPELL_WELL_FED; else if (spellInfo->EffectApplyAuraName[EFFECT_INDEX_0] == SPELL_AURA_MOD_STAT && spellInfo->Attributes & SPELL_ATTR_NOT_SHAPESHIFT && spellInfo->SchoolMask & SPELL_SCHOOL_MASK_NATURE && spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE) return SPELL_SCROLL; } break; } case SPELLFAMILY_MAGE: { // family flags 18(Molten), 25(Frost/Ice), 28(Mage) if (spellInfo->SpellFamilyFlags & UI64LIT(0x12040000)) return SPELL_MAGE_ARMOR; if ((spellInfo->SpellFamilyFlags & UI64LIT(0x1000000)) && spellInfo->EffectApplyAuraName[EFFECT_INDEX_0] == SPELL_AURA_MOD_CONFUSE) return SPELL_MAGE_POLYMORPH; break; } case SPELLFAMILY_WARRIOR: { if (spellInfo->SpellFamilyFlags & UI64LIT(0x00008000010000)) return SPELL_POSITIVE_SHOUT; break; } case SPELLFAMILY_WARLOCK: { // only warlock curses have this if (spellInfo->Dispel == DISPEL_CURSE) return SPELL_CURSE; // Warlock (Demon Armor | Demon Skin | Fel Armor) if (spellInfo->IsFitToFamilyMask(UI64LIT(0x2000002000000000), 0x00000010)) return SPELL_WARLOCK_ARMOR; // Unstable Affliction | Immolate if (spellInfo->IsFitToFamilyMask(UI64LIT(0x0000010000000004))) return SPELL_UA_IMMOLATE; break; } case SPELLFAMILY_PRIEST: { // "Well Fed" buff from Blessed Sunfruit, Blessed Sunfruit Juice, Alterac Spring Water if ((spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_SITTING) && (spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_AUTOATTACK) && (spellInfo->SpellIconID == 52 || spellInfo->SpellIconID == 79)) return SPELL_WELL_FED; break; } case SPELLFAMILY_HUNTER: { // only hunter stings have this if (spellInfo->Dispel == DISPEL_POISON) return SPELL_STING; // only hunter aspects have this if (spellInfo->IsFitToFamilyMask(UI64LIT(0x0044000000380000), 0x00001010)) return SPELL_ASPECT; break; } case SPELLFAMILY_PALADIN: { if (IsSealSpell(spellInfo)) return SPELL_SEAL; if (spellInfo->IsFitToFamilyMask(UI64LIT(0x0000000011010002))) return SPELL_BLESSING; if (spellInfo->IsFitToFamilyMask(UI64LIT(0x0000000000002190))) return SPELL_HAND; // skip Heart of the Crusader that have also same spell family mask if (spellInfo->IsFitToFamilyMask(UI64LIT(0x00000820180400)) && (spellInfo->AttributesEx3 & 0x200) && (spellInfo->SpellIconID != 237)) return SPELL_JUDGEMENT; // only paladin auras have this (for palaldin class family) if (spellInfo->IsFitToFamilyMask(UI64LIT(0x0000000000000000), 0x00000020)) return SPELL_AURA; break; } case SPELLFAMILY_SHAMAN: { if (IsElementalShield(spellInfo)) return SPELL_ELEMENTAL_SHIELD; break; } case SPELLFAMILY_POTION: return sSpellMgr.GetSpellElixirSpecific(spellInfo->Id); case SPELLFAMILY_DEATHKNIGHT: if (spellInfo->Category == 47) return SPELL_PRESENCE; break; } // Tracking spells (exclude Well Fed, some other always allowed cases) if ((IsSpellHaveAura(spellInfo, SPELL_AURA_TRACK_CREATURES) || IsSpellHaveAura(spellInfo, SPELL_AURA_TRACK_RESOURCES) || IsSpellHaveAura(spellInfo, SPELL_AURA_TRACK_STEALTHED)) && ((spellInfo->AttributesEx & SPELL_ATTR_EX_UNK17) || (spellInfo->AttributesEx6 & SPELL_ATTR_EX6_UNK12))) return SPELL_TRACKER; // elixirs can have different families, but potion most ofc. if (SpellSpecific sp = sSpellMgr.GetSpellElixirSpecific(spellInfo->Id)) return sp; return SPELL_NORMAL; } // target not allow have more one spell specific from same caster bool IsSingleFromSpellSpecificPerTargetPerCaster(SpellSpecific spellSpec1,SpellSpecific spellSpec2) { switch(spellSpec1) { case SPELL_BLESSING: case SPELL_AURA: case SPELL_STING: case SPELL_CURSE: case SPELL_ASPECT: case SPELL_POSITIVE_SHOUT: case SPELL_JUDGEMENT: case SPELL_HAND: case SPELL_UA_IMMOLATE: return spellSpec1==spellSpec2; default: return false; } } // target not allow have more one ranks from spell from spell specific per target bool IsSingleFromSpellSpecificSpellRanksPerTarget(SpellSpecific spellSpec1,SpellSpecific spellSpec2) { switch(spellSpec1) { case SPELL_BLESSING: case SPELL_AURA: case SPELL_CURSE: case SPELL_ASPECT: case SPELL_HAND: return spellSpec1==spellSpec2; default: return false; } } // target not allow have more one spell specific per target from any caster bool IsSingleFromSpellSpecificPerTarget(SpellSpecific spellSpec1,SpellSpecific spellSpec2) { switch(spellSpec1) { case SPELL_SEAL: case SPELL_TRACKER: case SPELL_WARLOCK_ARMOR: case SPELL_MAGE_ARMOR: case SPELL_ELEMENTAL_SHIELD: case SPELL_MAGE_POLYMORPH: case SPELL_PRESENCE: case SPELL_WELL_FED: return spellSpec1==spellSpec2; case SPELL_BATTLE_ELIXIR: return spellSpec2==SPELL_BATTLE_ELIXIR || spellSpec2==SPELL_FLASK_ELIXIR; case SPELL_GUARDIAN_ELIXIR: return spellSpec2==SPELL_GUARDIAN_ELIXIR || spellSpec2==SPELL_FLASK_ELIXIR; case SPELL_FLASK_ELIXIR: return spellSpec2==SPELL_BATTLE_ELIXIR || spellSpec2==SPELL_GUARDIAN_ELIXIR || spellSpec2==SPELL_FLASK_ELIXIR; case SPELL_FOOD: return spellSpec2==SPELL_FOOD || spellSpec2==SPELL_FOOD_AND_DRINK; case SPELL_DRINK: return spellSpec2==SPELL_DRINK || spellSpec2==SPELL_FOOD_AND_DRINK; case SPELL_FOOD_AND_DRINK: return spellSpec2==SPELL_FOOD || spellSpec2==SPELL_DRINK || spellSpec2==SPELL_FOOD_AND_DRINK; default: return false; } } bool IsPositiveTarget(uint32 targetA, uint32 targetB) { switch(targetA) { // non-positive targets case TARGET_CHAIN_DAMAGE: case TARGET_ALL_ENEMY_IN_AREA: case TARGET_ALL_ENEMY_IN_AREA_INSTANT: case TARGET_IN_FRONT_OF_CASTER: case TARGET_ALL_ENEMY_IN_AREA_CHANNELED: case TARGET_CURRENT_ENEMY_COORDINATES: case TARGET_SINGLE_ENEMY: case TARGET_IN_FRONT_OF_CASTER_30: return false; // positive or dependent case TARGET_CASTER_COORDINATES: return (targetB == TARGET_ALL_PARTY || targetB == TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER); default: break; } if (targetB) return IsPositiveTarget(targetB, 0); return true; } bool IsExplicitPositiveTarget(uint32 targetA) { // positive targets that in target selection code expect target in m_targers, so not that auto-select target by spell data by m_caster and etc switch(targetA) { case TARGET_SINGLE_FRIEND: case TARGET_SINGLE_PARTY: case TARGET_CHAIN_HEAL: case TARGET_SINGLE_FRIEND_2: case TARGET_AREAEFFECT_PARTY_AND_CLASS: return true; default: break; } return false; } bool IsExplicitNegativeTarget(uint32 targetA) { // non-positive targets that in target selection code expect target in m_targers, so not that auto-select target by spell data by m_caster and etc switch(targetA) { case TARGET_CHAIN_DAMAGE: case TARGET_CURRENT_ENEMY_COORDINATES: case TARGET_SINGLE_ENEMY: return true; default: break; } return false; } bool IsPositiveEffect(SpellEntry const *spellproto, SpellEffectIndex effIndex) { // FG: temp fix, that they are not cancelable switch(spellproto->Id) { case 37675: // Chaos Blast case 36810: // rotting puterescence case 36809: // overpowering sickness case 48323: // indisposed return false; } switch(spellproto->Effect[effIndex]) { case SPELL_EFFECT_DUMMY: // some explicitly required dummy effect sets switch(spellproto->Id) { case 28441: // AB Effect 000 return false; case 49634: // Sergeant's Flare case 54530: // Opening case 62105: // To'kini's Blowgun return true; default: break; } break; // always positive effects (check before target checks that provided non-positive result in some case for positive effects) case SPELL_EFFECT_HEAL: case SPELL_EFFECT_LEARN_SPELL: case SPELL_EFFECT_SKILL_STEP: case SPELL_EFFECT_HEAL_PCT: case SPELL_EFFECT_ENERGIZE_PCT: return true; // non-positive aura use case SPELL_EFFECT_APPLY_AURA: case SPELL_EFFECT_APPLY_AREA_AURA_FRIEND: { switch(spellproto->EffectApplyAuraName[effIndex]) { case SPELL_AURA_DUMMY: { // dummy aura can be positive or negative dependent from casted spell switch(spellproto->Id) { case 13139: // net-o-matic special effect case 23445: // evil twin case 35679: // Protectorate Demolitionist case 38637: // Nether Exhaustion (red) case 38638: // Nether Exhaustion (green) case 38639: // Nether Exhaustion (blue) case 11196: // Recently Bandaged case 44689: // Relay Race Accept Hidden Debuff - DND case 58600: // Restricted Flight Area return false; // some spells have unclear target modes for selection, so just make effect positive case 27184: case 27190: case 27191: case 27201: case 27202: case 27203: return true; default: break; } } break; case SPELL_AURA_MOD_DAMAGE_DONE: // dependent from base point sign (negative -> negative) case SPELL_AURA_MOD_RESISTANCE: case SPELL_AURA_MOD_STAT: case SPELL_AURA_MOD_SKILL: case SPELL_AURA_MOD_DODGE_PERCENT: case SPELL_AURA_MOD_HEALING_PCT: case SPELL_AURA_MOD_HEALING_DONE: if(spellproto->CalculateSimpleValue(effIndex) < 0) return false; break; case SPELL_AURA_MOD_DAMAGE_TAKEN: // dependent from bas point sign (positive -> negative) if (spellproto->CalculateSimpleValue(effIndex) < 0) return true; // let check by target modes (for Amplify Magic cases/etc) break; case SPELL_AURA_MOD_SPELL_CRIT_CHANCE: case SPELL_AURA_MOD_INCREASE_HEALTH_PERCENT: case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: if(spellproto->CalculateSimpleValue(effIndex) > 0) return true; // some expected positive spells have SPELL_ATTR_EX_NEGATIVE or unclear target modes break; case SPELL_AURA_ADD_TARGET_TRIGGER: return true; case SPELL_AURA_PERIODIC_TRIGGER_SPELL: if (spellproto->Id != spellproto->EffectTriggerSpell[effIndex]) { uint32 spellTriggeredId = spellproto->EffectTriggerSpell[effIndex]; SpellEntry const *spellTriggeredProto = sSpellStore.LookupEntry(spellTriggeredId); if (spellTriggeredProto) { // non-positive targets of main spell return early for(int i = 0; i < MAX_EFFECT_INDEX; ++i) { // if non-positive trigger cast targeted to positive target this main cast is non-positive // this will place this spell auras as debuffs if (spellTriggeredProto->Effect[i] && IsPositiveTarget(spellTriggeredProto->EffectImplicitTargetA[i], spellTriggeredProto->EffectImplicitTargetB[i]) && !IsPositiveEffect(spellTriggeredProto, SpellEffectIndex(i))) return false; } } } break; case SPELL_AURA_PROC_TRIGGER_SPELL: // many positive auras have negative triggered spells at damage for example and this not make it negative (it can be canceled for example) break; case SPELL_AURA_MOD_STUN: //have positive and negative spells, we can't sort its correctly at this moment. if (effIndex == EFFECT_INDEX_0 && spellproto->Effect[EFFECT_INDEX_1] == 0 && spellproto->Effect[EFFECT_INDEX_2] == 0) return false; // but all single stun aura spells is negative // Petrification if(spellproto->Id == 17624) return false; break; case SPELL_AURA_MOD_PACIFY_SILENCE: switch(spellproto->Id) { case 24740: // Wisp Costume case 47585: // Dispersion return true; default: break; } return false; case SPELL_AURA_MOD_ROOT: case SPELL_AURA_MOD_SILENCE: case SPELL_AURA_GHOST: case SPELL_AURA_PERIODIC_LEECH: case SPELL_AURA_MOD_STALKED: case SPELL_AURA_PERIODIC_DAMAGE_PERCENT: return false; case SPELL_AURA_PERIODIC_DAMAGE: // used in positive spells also. // part of negative spell if casted at self (prevent cancel) if (spellproto->EffectImplicitTargetA[effIndex] == TARGET_SELF || spellproto->EffectImplicitTargetA[effIndex] == TARGET_SELF2) return false; break; case SPELL_AURA_MOD_DECREASE_SPEED: // used in positive spells also // part of positive spell if casted at self if ((spellproto->EffectImplicitTargetA[effIndex] == TARGET_SELF || spellproto->EffectImplicitTargetA[effIndex] == TARGET_SELF2) && spellproto->SpellFamilyName == SPELLFAMILY_GENERIC) return false; // but not this if this first effect (don't found better check) if (spellproto->Attributes & 0x4000000 && effIndex == EFFECT_INDEX_0) return false; break; case SPELL_AURA_TRANSFORM: // some spells negative switch(spellproto->Id) { case 36897: // Transporter Malfunction (race mutation to horde) case 36899: // Transporter Malfunction (race mutation to alliance) return false; } break; case SPELL_AURA_MOD_SCALE: // some spells negative switch(spellproto->Id) { case 802: // Mutate Bug, wrongly negative by target modes return true; case 36900: // Soul Split: Evil! case 36901: // Soul Split: Good case 36893: // Transporter Malfunction (decrease size case) case 36895: // Transporter Malfunction (increase size case) return false; } break; case SPELL_AURA_MECHANIC_IMMUNITY: { // non-positive immunities switch(spellproto->EffectMiscValue[effIndex]) { case MECHANIC_BANDAGE: case MECHANIC_SHIELD: case MECHANIC_MOUNT: case MECHANIC_INVULNERABILITY: return false; default: break; } } break; case SPELL_AURA_ADD_FLAT_MODIFIER: // mods case SPELL_AURA_ADD_PCT_MODIFIER: { // non-positive mods switch(spellproto->EffectMiscValue[effIndex]) { case SPELLMOD_COST: // dependent from bas point sign (negative -> positive) if(spellproto->CalculateSimpleValue(effIndex) > 0) return false; break; default: break; } } break; case SPELL_AURA_FORCE_REACTION: { switch (spellproto->Id) { case 42792: // Recently Dropped Flag (prevent cancel) case 46221: // Animal Blood return false; default: break; } break; } default: break; } break; } default: break; } // non-positive targets if(!IsPositiveTarget(spellproto->EffectImplicitTargetA[effIndex],spellproto->EffectImplicitTargetB[effIndex])) return false; // AttributesEx check if(spellproto->AttributesEx & SPELL_ATTR_EX_NEGATIVE) return false; // ok, positive return true; } bool IsPositiveSpell(uint32 spellId) { SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId); if (!spellproto) return false; return IsPositiveSpell(spellproto); } bool IsPositiveSpell(SpellEntry const *spellproto) { // spells with at least one negative effect are considered negative // some self-applied spells have negative effects but in self casting case negative check ignored. for (int i = 0; i < MAX_EFFECT_INDEX; ++i) if (spellproto->Effect[i] && !IsPositiveEffect(spellproto, SpellEffectIndex(i))) return false; return true; } bool IsSingleTargetSpell(SpellEntry const *spellInfo) { // all other single target spells have if it has AttributesEx5 if ( spellInfo->AttributesEx5 & SPELL_ATTR_EX5_SINGLE_TARGET_SPELL ) return true; // TODO - need found Judgements rule switch(GetSpellSpecific(spellInfo->Id)) { case SPELL_JUDGEMENT: return true; default: break; } // single target triggered spell. // Not real client side single target spell, but it' not triggered until prev. aura expired. // This is allow store it in single target spells list for caster for spell proc checking if(spellInfo->Id==38324) // Regeneration (triggered by 38299 (HoTs on Heals)) return true; return false; } bool IsSingleTargetSpells(SpellEntry const *spellInfo1, SpellEntry const *spellInfo2) { // TODO - need better check // Equal icon and spellfamily if( spellInfo1->SpellFamilyName == spellInfo2->SpellFamilyName && spellInfo1->SpellIconID == spellInfo2->SpellIconID ) return true; // TODO - need found Judgements rule SpellSpecific spec1 = GetSpellSpecific(spellInfo1->Id); // spell with single target specific types switch(spec1) { case SPELL_JUDGEMENT: case SPELL_MAGE_POLYMORPH: if(GetSpellSpecific(spellInfo2->Id) == spec1) return true; break; default: break; } return false; } SpellCastResult GetErrorAtShapeshiftedCast (SpellEntry const *spellInfo, uint32 form) { // talents that learn spells can have stance requirements that need ignore // (this requirement only for client-side stance show in talent description) if( GetTalentSpellCost(spellInfo->Id) > 0 && (spellInfo->Effect[EFFECT_INDEX_0] == SPELL_EFFECT_LEARN_SPELL || spellInfo->Effect[EFFECT_INDEX_1] == SPELL_EFFECT_LEARN_SPELL || spellInfo->Effect[EFFECT_INDEX_2] == SPELL_EFFECT_LEARN_SPELL) ) return SPELL_CAST_OK; uint32 stanceMask = (form ? 1 << (form - 1) : 0); if (stanceMask & spellInfo->StancesNot) // can explicitly not be casted in this stance return SPELL_FAILED_NOT_SHAPESHIFT; if (stanceMask & spellInfo->Stances) // can explicitly be casted in this stance return SPELL_CAST_OK; bool actAsShifted = false; if (form > 0) { SpellShapeshiftFormEntry const *shapeInfo = sSpellShapeshiftFormStore.LookupEntry(form); if (!shapeInfo) { sLog.outError("GetErrorAtShapeshiftedCast: unknown shapeshift %u", form); return SPELL_CAST_OK; } actAsShifted = !(shapeInfo->flags1 & 1); // shapeshift acts as normal form for spells } if(actAsShifted) { if (spellInfo->Attributes & SPELL_ATTR_NOT_SHAPESHIFT) // not while shapeshifted { //but we must allow cast of Berserk+modifier from any form... where for the hell should we do it? if (!(spellInfo->SpellIconID == 1680 && (spellInfo->AttributesEx & 0x8000))) return SPELL_FAILED_NOT_SHAPESHIFT; } else if (spellInfo->Stances != 0) // needs other shapeshift return SPELL_FAILED_ONLY_SHAPESHIFT; } else { // needs shapeshift if(!(spellInfo->AttributesEx2 & SPELL_ATTR_EX2_NOT_NEED_SHAPESHIFT) && spellInfo->Stances != 0) return SPELL_FAILED_ONLY_SHAPESHIFT; } return SPELL_CAST_OK; } void SpellMgr::LoadSpellTargetPositions() { mSpellTargetPositions.clear(); // need for reload case uint32 count = 0; // 0 1 2 3 4 5 QueryResult *result = WorldDatabase.Query("SELECT id, target_map, target_position_x, target_position_y, target_position_z, target_orientation FROM spell_target_position"); if (!result) { BarGoLink bar(1); bar.step(); sLog.outString(); sLog.outString(">> Loaded %u spell target destination coordinates", count); return; } BarGoLink bar(result->GetRowCount()); do { Field *fields = result->Fetch(); bar.step(); uint32 Spell_ID = fields[0].GetUInt32(); SpellTargetPosition st; st.target_mapId = fields[1].GetUInt32(); st.target_X = fields[2].GetFloat(); st.target_Y = fields[3].GetFloat(); st.target_Z = fields[4].GetFloat(); st.target_Orientation = fields[5].GetFloat(); MapEntry const* mapEntry = sMapStore.LookupEntry(st.target_mapId); if (!mapEntry) { sLog.outErrorDb("Spell (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Spell_ID,st.target_mapId); continue; } if (st.target_X==0 && st.target_Y==0 && st.target_Z==0) { sLog.outErrorDb("Spell (ID:%u) target coordinates not provided.",Spell_ID); continue; } SpellEntry const* spellInfo = sSpellStore.LookupEntry(Spell_ID); if (!spellInfo) { sLog.outErrorDb("Spell (ID:%u) listed in `spell_target_position` does not exist.",Spell_ID); continue; } bool found = false; for(int i = 0; i < MAX_EFFECT_INDEX; ++i) { if (spellInfo->EffectImplicitTargetA[i]==TARGET_TABLE_X_Y_Z_COORDINATES || spellInfo->EffectImplicitTargetB[i]==TARGET_TABLE_X_Y_Z_COORDINATES) { // additional requirements if (spellInfo->Effect[i]==SPELL_EFFECT_BIND && spellInfo->EffectMiscValue[i]) { uint32 zone_id = sTerrainMgr.GetAreaId(st.target_mapId, st.target_X, st.target_Y, st.target_Z); if (int32(zone_id) != spellInfo->EffectMiscValue[i]) { sLog.outErrorDb("Spell (Id: %u) listed in `spell_target_position` expected point to zone %u bit point to zone %u.",Spell_ID, spellInfo->EffectMiscValue[i], zone_id); break; } } found = true; break; } } if (!found) { sLog.outErrorDb("Spell (Id: %u) listed in `spell_target_position` does not have target TARGET_TABLE_X_Y_Z_COORDINATES (17).",Spell_ID); continue; } mSpellTargetPositions[Spell_ID] = st; ++count; } while( result->NextRow() ); delete result; sLog.outString(); sLog.outString(">> Loaded %u spell target destination coordinates", count); } template <typename EntryType, typename WorkerType, typename StorageType> struct SpellRankHelper { SpellRankHelper(SpellMgr &_mgr, StorageType &_storage): mgr(_mgr), worker(_storage), customRank(0) {} void RecordRank(EntryType &entry, uint32 spell_id) { const SpellEntry *spell = sSpellStore.LookupEntry(spell_id); if (!spell) { sLog.outErrorDb("Spell %u listed in `%s` does not exist", spell_id, worker.TableName()); return; } uint32 first_id = mgr.GetFirstSpellInChain(spell_id); // most spell ranks expected same data if(first_id) { firstRankSpells.insert(first_id); if (first_id != spell_id) { if (!worker.IsValidCustomRank(entry, spell_id, first_id)) return; // for later check that first rank also added else { firstRankSpellsWithCustomRanks.insert(first_id); ++customRank; } } } worker.AddEntry(entry, spell); } void FillHigherRanks() { // check that first rank added for custom ranks for (std::set<uint32>::const_iterator itr = firstRankSpellsWithCustomRanks.begin(); itr != firstRankSpellsWithCustomRanks.end(); ++itr) if (!worker.HasEntry(*itr)) sLog.outErrorDb("Spell %u must be listed in `%s` as first rank for listed custom ranks of spell but not found!", *itr, worker.TableName()); // fill absent non first ranks data base at first rank data for (std::set<uint32>::const_iterator itr = firstRankSpells.begin(); itr != firstRankSpells.end(); ++itr) { if (worker.SetStateToEntry(*itr)) mgr.doForHighRanks(*itr, worker); } } std::set<uint32> firstRankSpells; std::set<uint32> firstRankSpellsWithCustomRanks; SpellMgr &mgr; WorkerType worker; uint32 customRank; }; struct DoSpellProcEvent { DoSpellProcEvent(SpellProcEventMap& _spe_map) : spe_map(_spe_map), customProc(0), count(0) {} void operator() (uint32 spell_id) { SpellProcEventEntry const& spe = state->second; // add ranks only for not filled data (some ranks have ppm data different for ranks for example) SpellProcEventMap::const_iterator spellItr = spe_map.find(spell_id); if (spellItr == spe_map.end()) spe_map[spell_id] = spe; // if custom rank data added then it must be same except ppm else { SpellProcEventEntry const& r_spe = spellItr->second; if (spe.schoolMask != r_spe.schoolMask) sLog.outErrorDb("Spell %u listed in `spell_proc_event` as custom rank have different schoolMask from first rank in chain", spell_id); if (spe.spellFamilyName != r_spe.spellFamilyName) sLog.outErrorDb("Spell %u listed in `spell_proc_event` as custom rank have different spellFamilyName from first rank in chain", spell_id); for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) { if (spe.spellFamilyMask[i] != r_spe.spellFamilyMask[i]) { sLog.outErrorDb("Spell %u listed in `spell_proc_event` as custom rank have different spellFamilyMask/spellFamilyMask2 from first rank in chain", spell_id); break; } } if (spe.procFlags != r_spe.procFlags) sLog.outErrorDb("Spell %u listed in `spell_proc_event` as custom rank have different procFlags from first rank in chain", spell_id); if (spe.procEx != r_spe.procEx) sLog.outErrorDb("Spell %u listed in `spell_proc_event` as custom rank have different procEx from first rank in chain", spell_id); // only ppm allowed has been different from first rank if (spe.customChance != r_spe.customChance) sLog.outErrorDb("Spell %u listed in `spell_proc_event` as custom rank have different customChance from first rank in chain", spell_id); if (spe.cooldown != r_spe.cooldown) sLog.outErrorDb("Spell %u listed in `spell_proc_event` as custom rank have different cooldown from first rank in chain", spell_id); } } const char* TableName() { return "spell_proc_event"; } bool IsValidCustomRank(SpellProcEventEntry const &spe, uint32 entry, uint32 first_id) { // let have independent data in table for spells with ppm rates (exist rank dependent ppm rate spells) if (!spe.ppmRate) { sLog.outErrorDb("Spell %u listed in `spell_proc_event` is not first rank (%u) in chain", entry, first_id); // prevent loading since it won't have an effect anyway return false; } return true; } void AddEntry(SpellProcEventEntry const &spe, SpellEntry const *spell) { spe_map[spell->Id] = spe; bool isCustom = false; if (spe.procFlags == 0) { if (spell->procFlags==0) sLog.outErrorDb("Spell %u listed in `spell_proc_event` probally not triggered spell (no proc flags)", spell->Id); } else { if (spell->procFlags==spe.procFlags) sLog.outErrorDb("Spell %u listed in `spell_proc_event` has exactly same proc flags as in spell.dbc, field value redundant", spell->Id); else isCustom = true; } if (spe.customChance == 0) { /* enable for re-check cases, 0 chance ok for some cases because in some cases it set by another spell/talent spellmod) if (spell->procChance==0 && !spe.ppmRate) sLog.outErrorDb("Spell %u listed in `spell_proc_event` probally not triggered spell (no chance or ppm)", spell->Id); */ } else { if (spell->procChance==spe.customChance) sLog.outErrorDb("Spell %u listed in `spell_proc_event` has exactly same custom chance as in spell.dbc, field value redundant", spell->Id); else isCustom = true; } // totally redundant record if (!spe.schoolMask && !spe.procFlags && !spe.procEx && !spe.ppmRate && !spe.customChance && !spe.cooldown) { bool empty = !spe.spellFamilyName ? true : false; for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) { if (spe.spellFamilyMask[i]) { empty = false; ClassFamilyMask const& mask = spell->GetEffectSpellClassMask(SpellEffectIndex(i)); if (mask == spe.spellFamilyMask[i]) sLog.outErrorDb("Spell %u listed in `spell_proc_event` has same class mask as in Spell.dbc (EffectIndex %u) and doesn't have any other data", spell->Id, i); } } if (empty) sLog.outErrorDb("Spell %u listed in `spell_proc_event` doesn't have any useful data", spell->Id); } if (isCustom) ++customProc; else ++count; } bool HasEntry(uint32 spellId) { return spe_map.count(spellId) > 0; } bool SetStateToEntry(uint32 spellId) { return (state = spe_map.find(spellId)) != spe_map.end(); } SpellProcEventMap& spe_map; SpellProcEventMap::const_iterator state; uint32 customProc; uint32 count; }; void SpellMgr::LoadSpellProcEvents() { mSpellProcEventMap.clear(); // need for reload case // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 QueryResult *result = WorldDatabase.Query("SELECT entry, SchoolMask, SpellFamilyName, SpellFamilyMaskA0, SpellFamilyMaskA1, SpellFamilyMaskA2, SpellFamilyMaskB0, SpellFamilyMaskB1, SpellFamilyMaskB2, SpellFamilyMaskC0, SpellFamilyMaskC1, SpellFamilyMaskC2, procFlags, procEx, ppmRate, CustomChance, Cooldown FROM spell_proc_event"); if (!result) { BarGoLink bar(1); bar.step(); sLog.outString(); sLog.outString(">> No spell proc event conditions loaded"); return; } SpellRankHelper<SpellProcEventEntry, DoSpellProcEvent, SpellProcEventMap> rankHelper(*this, mSpellProcEventMap); BarGoLink bar(result->GetRowCount()); do { Field *fields = result->Fetch(); bar.step(); uint32 entry = fields[0].GetUInt32(); SpellProcEventEntry spe; spe.schoolMask = fields[1].GetUInt32(); spe.spellFamilyName = fields[2].GetUInt32(); for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) { spe.spellFamilyMask[i] = ClassFamilyMask( (uint64)fields[i+3].GetUInt32() | ((uint64)fields[i+6].GetUInt32()<<32), fields[i+9].GetUInt32()); } spe.procFlags = fields[12].GetUInt32(); spe.procEx = fields[13].GetUInt32(); spe.ppmRate = fields[14].GetFloat(); spe.customChance = fields[15].GetFloat(); spe.cooldown = fields[16].GetUInt32(); rankHelper.RecordRank(spe, entry); } while (result->NextRow()); rankHelper.FillHigherRanks(); delete result; sLog.outString(); sLog.outString( ">> Loaded %u extra spell proc event conditions +%u custom proc (inc. +%u custom ranks)", rankHelper.worker.count, rankHelper.worker.customProc, rankHelper.customRank); } struct DoSpellProcItemEnchant { DoSpellProcItemEnchant(SpellProcItemEnchantMap& _procMap, float _ppm) : procMap(_procMap), ppm(_ppm) {} void operator() (uint32 spell_id) { procMap[spell_id] = ppm; } SpellProcItemEnchantMap& procMap; float ppm; }; void SpellMgr::LoadSpellProcItemEnchant() { mSpellProcItemEnchantMap.clear(); // need for reload case uint32 count = 0; // 0 1 QueryResult *result = WorldDatabase.Query("SELECT entry, ppmRate FROM spell_proc_item_enchant"); if (!result) { BarGoLink bar(1); bar.step(); sLog.outString(); sLog.outString(">> Loaded %u proc item enchant definitions", count); return; } BarGoLink bar(result->GetRowCount()); do { Field *fields = result->Fetch(); bar.step(); uint32 entry = fields[0].GetUInt32(); float ppmRate = fields[1].GetFloat(); SpellEntry const* spellInfo = sSpellStore.LookupEntry(entry); if (!spellInfo) { sLog.outErrorDb("Spell %u listed in `spell_proc_item_enchant` does not exist", entry); continue; } uint32 first_id = GetFirstSpellInChain(entry); if ( first_id != entry ) { sLog.outErrorDb("Spell %u listed in `spell_proc_item_enchant` is not first rank (%u) in chain", entry, first_id); // prevent loading since it won't have an effect anyway continue; } mSpellProcItemEnchantMap[entry] = ppmRate; // also add to high ranks DoSpellProcItemEnchant worker(mSpellProcItemEnchantMap, ppmRate); doForHighRanks(entry,worker); ++count; } while( result->NextRow() ); delete result; sLog.outString(); sLog.outString( ">> Loaded %u proc item enchant definitions", count ); } struct DoSpellBonuses { DoSpellBonuses(SpellBonusMap& _spellBonusMap, SpellBonusEntry const& _spellBonus) : spellBonusMap(_spellBonusMap), spellBonus(_spellBonus) {} void operator() (uint32 spell_id) { spellBonusMap[spell_id] = spellBonus; } SpellBonusMap& spellBonusMap; SpellBonusEntry const& spellBonus; }; void SpellMgr::LoadSpellBonuses() { mSpellBonusMap.clear(); // need for reload case uint32 count = 0; // 0 1 2 3 QueryResult *result = WorldDatabase.Query("SELECT entry, direct_bonus, dot_bonus, ap_bonus, ap_dot_bonus FROM spell_bonus_data"); if (!result) { BarGoLink bar(1); bar.step(); sLog.outString(); sLog.outString(">> Loaded %u spell bonus data", count); return; } BarGoLink bar(result->GetRowCount()); do { Field *fields = result->Fetch(); bar.step(); uint32 entry = fields[0].GetUInt32(); SpellEntry const* spell = sSpellStore.LookupEntry(entry); if (!spell) { sLog.outErrorDb("Spell %u listed in `spell_bonus_data` does not exist", entry); continue; } uint32 first_id = GetFirstSpellInChain(entry); if ( first_id != entry ) { sLog.outErrorDb("Spell %u listed in `spell_bonus_data` is not first rank (%u) in chain", entry, first_id); // prevent loading since it won't have an effect anyway continue; } SpellBonusEntry sbe; sbe.direct_damage = fields[1].GetFloat(); sbe.dot_damage = fields[2].GetFloat(); sbe.ap_bonus = fields[3].GetFloat(); sbe.ap_dot_bonus = fields[4].GetFloat(); bool need_dot = false; bool need_direct = false; uint32 x = 0; // count all, including empty, meaning: not all existing effect is DoTs/HoTs for(int i = 0; i < MAX_EFFECT_INDEX; ++i) { if (!spell->Effect[i]) { ++x; continue; } // DoTs/HoTs switch(spell->EffectApplyAuraName[i]) { case SPELL_AURA_PERIODIC_DAMAGE: case SPELL_AURA_PERIODIC_DAMAGE_PERCENT: case SPELL_AURA_PERIODIC_LEECH: case SPELL_AURA_PERIODIC_HEAL: case SPELL_AURA_OBS_MOD_HEALTH: case SPELL_AURA_PERIODIC_MANA_LEECH: case SPELL_AURA_OBS_MOD_MANA: case SPELL_AURA_POWER_BURN_MANA: need_dot = true; ++x; break; default: break; } } //TODO: maybe add explicit list possible direct damage spell effects... if (x < MAX_EFFECT_INDEX) need_direct = true; // Check if direct_bonus is needed in `spell_bonus_data` float direct_calc; float direct_diff = 1000.0f; // for have big diff if no DB field value if (sbe.direct_damage) { bool isHeal = false; for(int i = 0; i < 3; ++i) { // Heals (Also count Mana Shield and Absorb effects as heals) if (spell->Effect[i] == SPELL_EFFECT_HEAL || spell->Effect[i] == SPELL_EFFECT_HEAL_MAX_HEALTH || (spell->Effect[i] == SPELL_EFFECT_APPLY_AURA && (spell->EffectApplyAuraName[i] == SPELL_AURA_SCHOOL_ABSORB || spell->EffectApplyAuraName[i] == SPELL_AURA_PERIODIC_HEAL)) ) { isHeal = true; break; } } direct_calc = CalculateDefaultCoefficient(spell, SPELL_DIRECT_DAMAGE) * (isHeal ? 1.88f : 1.0f); direct_diff = std::abs(sbe.direct_damage - direct_calc); } // Check if dot_bonus is needed in `spell_bonus_data` float dot_calc; float dot_diff = 1000.0f; // for have big diff if no DB field value if (sbe.dot_damage) { bool isHeal = false; for(int i = 0; i < 3; ++i) { // Periodic Heals if (spell->Effect[i] == SPELL_EFFECT_APPLY_AURA && spell->EffectApplyAuraName[i] == SPELL_AURA_PERIODIC_HEAL) { isHeal = true; break; } } dot_calc = CalculateDefaultCoefficient(spell, DOT) * (isHeal ? 1.88f : 1.0f); dot_diff = std::abs(sbe.dot_damage - dot_calc); } if (direct_diff < 0.02f && !need_dot && !sbe.ap_bonus && !sbe.ap_dot_bonus) sLog.outErrorDb("`spell_bonus_data` entry for spell %u `direct_bonus` not needed (data from table: %f, calculated %f, difference of %f) and `dot_bonus` also not used", entry, sbe.direct_damage, direct_calc, direct_diff); else if (direct_diff < 0.02f && dot_diff < 0.02f && !sbe.ap_bonus && !sbe.ap_dot_bonus) { sLog.outErrorDb("`spell_bonus_data` entry for spell %u `direct_bonus` not needed (data from table: %f, calculated %f, difference of %f) and ", entry, sbe.direct_damage, direct_calc, direct_diff); sLog.outErrorDb(" ... `dot_bonus` not needed (data from table: %f, calculated %f, difference of %f)", sbe.dot_damage, dot_calc, dot_diff); } else if (!need_direct && dot_diff < 0.02f && !sbe.ap_bonus && !sbe.ap_dot_bonus) sLog.outErrorDb("`spell_bonus_data` entry for spell %u `dot_bonus` not needed (data from table: %f, calculated %f, difference of %f) and direct also not used", entry, sbe.dot_damage, dot_calc, dot_diff); else if (!need_direct && sbe.direct_damage) sLog.outErrorDb("`spell_bonus_data` entry for spell %u `direct_bonus` not used (spell not have non-periodic affects)", entry); else if (!need_dot && sbe.dot_damage) sLog.outErrorDb("`spell_bonus_data` entry for spell %u `dot_bonus` not used (spell not have periodic affects)", entry); if (!need_direct && sbe.ap_bonus) sLog.outErrorDb("`spell_bonus_data` entry for spell %u `ap_bonus` not used (spell not have non-periodic affects)", entry); else if (!need_dot && sbe.ap_dot_bonus) sLog.outErrorDb("`spell_bonus_data` entry for spell %u `ap_dot_bonus` not used (spell not have periodic affects)", entry); mSpellBonusMap[entry] = sbe; // also add to high ranks DoSpellBonuses worker(mSpellBonusMap, sbe); doForHighRanks(entry,worker); ++count; } while( result->NextRow() ); delete result; sLog.outString(); sLog.outString( ">> Loaded %u extra spell bonus data", count); } bool SpellMgr::IsSpellProcEventCanTriggeredBy(SpellProcEventEntry const * spellProcEvent, uint32 EventProcFlag, SpellEntry const * procSpell, uint32 procFlags, uint32 procExtra) { // No extra req need uint32 procEvent_procEx = PROC_EX_NONE; // check prockFlags for condition if((procFlags & EventProcFlag) == 0) return false; // Always trigger for this if (EventProcFlag & (PROC_FLAG_KILLED | PROC_FLAG_KILL | PROC_FLAG_ON_TRAP_ACTIVATION | PROC_FLAG_ON_DEATH)) return true; if (spellProcEvent) // Exist event data { // Store extra req procEvent_procEx = spellProcEvent->procEx; // For melee triggers if (procSpell == NULL) { // Check (if set) for school (melee attack have Normal school) if(spellProcEvent->schoolMask && (spellProcEvent->schoolMask & SPELL_SCHOOL_MASK_NORMAL) == 0) return false; } else // For spells need check school/spell family/family mask { // Check (if set) for school if(spellProcEvent->schoolMask && (spellProcEvent->schoolMask & procSpell->SchoolMask) == 0) return false; // Check (if set) for spellFamilyName if(spellProcEvent->spellFamilyName && (spellProcEvent->spellFamilyName != procSpell->SpellFamilyName)) return false; } } // Check for extra req (if none) and hit/crit if (procEvent_procEx == PROC_EX_NONE) { // Don't allow proc from periodic heal if no extra requirement is defined if (EventProcFlag & (PROC_FLAG_ON_DO_PERIODIC | PROC_FLAG_ON_TAKE_PERIODIC) && (procExtra & PROC_EX_PERIODIC_POSITIVE)) return false; // No extra req, so can trigger for (damage/healing present) and hit/crit if(procExtra & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) return true; } else // all spells hits here only if resist/reflect/immune/evade { // Exist req for PROC_EX_EX_TRIGGER_ALWAYS if (procEvent_procEx & PROC_EX_EX_TRIGGER_ALWAYS) return true; // Check Extra Requirement like (hit/crit/miss/resist/parry/dodge/block/immune/reflect/absorb and other) if (procEvent_procEx & procExtra) return true; } return false; } void SpellMgr::LoadSpellElixirs() { mSpellElixirs.clear(); // need for reload case uint32 count = 0; // 0 1 QueryResult *result = WorldDatabase.Query("SELECT entry, mask FROM spell_elixir"); if (!result) { BarGoLink bar(1); bar.step(); sLog.outString(); sLog.outString(">> Loaded %u spell elixir definitions", count); return; } BarGoLink bar(result->GetRowCount()); do { Field *fields = result->Fetch(); bar.step(); uint32 entry = fields[0].GetUInt32(); uint8 mask = fields[1].GetUInt8(); SpellEntry const* spellInfo = sSpellStore.LookupEntry(entry); if (!spellInfo) { sLog.outErrorDb("Spell %u listed in `spell_elixir` does not exist", entry); continue; } mSpellElixirs[entry] = mask; ++count; } while( result->NextRow() ); delete result; sLog.outString(); sLog.outString( ">> Loaded %u spell elixir definitions", count ); } struct DoSpellThreat { DoSpellThreat(SpellThreatMap& _threatMap) : threatMap(_threatMap), count(0) {} void operator() (uint32 spell_id) { SpellThreatEntry const &ste = state->second; // add ranks only for not filled data (spells adding flat threat are usually different for ranks) SpellThreatMap::const_iterator spellItr = threatMap.find(spell_id); if (spellItr == threatMap.end()) threatMap[spell_id] = ste; // just assert that entry is not redundant else { SpellThreatEntry const& r_ste = spellItr->second; if (ste.threat == r_ste.threat && ste.multiplier == r_ste.multiplier && ste.ap_bonus == r_ste.ap_bonus) sLog.outErrorDb("Spell %u listed in `spell_threat` as custom rank has same data as Rank 1, so redundant", spell_id); } } const char* TableName() { return "spell_threat"; } bool IsValidCustomRank(SpellThreatEntry const &ste, uint32 entry, uint32 first_id) { if (!ste.threat) { sLog.outErrorDb("Spell %u listed in `spell_threat` is not first rank (%u) in chain and has no threat", entry, first_id); // prevent loading unexpected data return false; } return true; } void AddEntry(SpellThreatEntry const &ste, SpellEntry const *spell) { threatMap[spell->Id] = ste; // flat threat bonus and attack power bonus currently only work properly when all // effects have same targets, otherwise, we'd need to seperate it by effect index if (ste.threat || ste.ap_bonus != 0.f) { const uint32 *targetA = spell->EffectImplicitTargetA; const uint32 *targetB = spell->EffectImplicitTargetB; if ((targetA[EFFECT_INDEX_1] && targetA[EFFECT_INDEX_1] != targetA[EFFECT_INDEX_0]) || (targetA[EFFECT_INDEX_2] && targetA[EFFECT_INDEX_2] != targetA[EFFECT_INDEX_0])) sLog.outErrorDb("Spell %u listed in `spell_threat` has effects with different targets, threat may be assigned incorrectly", spell->Id); } ++count; } bool HasEntry(uint32 spellId) { return threatMap.count(spellId) > 0; } bool SetStateToEntry(uint32 spellId) { return (state = threatMap.find(spellId)) != threatMap.end(); } SpellThreatMap& threatMap; SpellThreatMap::const_iterator state; uint32 count; }; void SpellMgr::LoadSpellThreats() { mSpellThreatMap.clear(); // need for reload case // 0 1 2 3 QueryResult *result = WorldDatabase.Query("SELECT entry, Threat, multiplier, ap_bonus FROM spell_threat"); if (!result) { BarGoLink bar(1); bar.step(); sLog.outString(); sLog.outString(">> No spell threat entries loaded."); return; } SpellRankHelper<SpellThreatEntry, DoSpellThreat, SpellThreatMap> rankHelper(*this, mSpellThreatMap); BarGoLink bar(result->GetRowCount()); do { Field *fields = result->Fetch(); bar.step(); uint32 entry = fields[0].GetUInt32(); SpellThreatEntry ste; ste.threat = fields[1].GetUInt16(); ste.multiplier = fields[2].GetFloat(); ste.ap_bonus = fields[3].GetFloat(); rankHelper.RecordRank(ste, entry); } while( result->NextRow() ); rankHelper.FillHigherRanks(); delete result; sLog.outString(); sLog.outString( ">> Loaded %u spell threat entries", rankHelper.worker.count ); } bool SpellMgr::IsRankSpellDueToSpell(SpellEntry const *spellInfo_1,uint32 spellId_2) const { SpellEntry const *spellInfo_2 = sSpellStore.LookupEntry(spellId_2); if(!spellInfo_1 || !spellInfo_2) return false; if(spellInfo_1->Id == spellId_2) return false; return GetFirstSpellInChain(spellInfo_1->Id)==GetFirstSpellInChain(spellId_2); } bool SpellMgr::canStackSpellRanksInSpellBook(SpellEntry const *spellInfo) const { if (IsPassiveSpell(spellInfo)) // ranked passive spell return false; if (spellInfo->powerType != POWER_MANA && spellInfo->powerType != POWER_HEALTH) return false; if (IsProfessionOrRidingSpell(spellInfo->Id)) return false; if (IsSkillBonusSpell(spellInfo->Id)) return false; // All stance spells. if any better way, change it. for (int i = 0; i < MAX_EFFECT_INDEX; ++i) { switch(spellInfo->SpellFamilyName) { case SPELLFAMILY_PALADIN: // Paladin aura Spell if (spellInfo->Effect[i]==SPELL_EFFECT_APPLY_AREA_AURA_RAID) return false; // Seal of Righteousness, 2 version of same rank if ((spellInfo->SpellFamilyFlags & UI64LIT(0x0000000008000000)) && spellInfo->SpellIconID == 25) return false; break; case SPELLFAMILY_DRUID: // Druid form Spell if (spellInfo->Effect[i]==SPELL_EFFECT_APPLY_AURA && spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT) return false; break; case SPELLFAMILY_ROGUE: // Rogue Stealth if (spellInfo->Effect[i]==SPELL_EFFECT_APPLY_AURA && spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT) return false; break; } } return true; } bool SpellMgr::IsNoStackSpellDueToSpell(uint32 spellId_1, uint32 spellId_2) const { SpellEntry const *spellInfo_1 = sSpellStore.LookupEntry(spellId_1); SpellEntry const *spellInfo_2 = sSpellStore.LookupEntry(spellId_2); if (!spellInfo_1 || !spellInfo_2) return false; if (spellId_1 == spellId_2) return false; // Resurrection sickness if ((spellInfo_1->Id == SPELL_ID_PASSIVE_RESURRECTION_SICKNESS) != (spellInfo_2->Id==SPELL_ID_PASSIVE_RESURRECTION_SICKNESS)) return false; // Allow stack passive and not passive spells if ((spellInfo_1->Attributes & SPELL_ATTR_PASSIVE)!=(spellInfo_2->Attributes & SPELL_ATTR_PASSIVE)) return false; // My rules! :D if (spellInfo_1->AttributesEx6 & SPELL_ATTR_EX6_UNK26 && spellInfo_2->AttributesEx6 & SPELL_ATTR_EX6_UNK26) { // Marks and Gifts of the Wild if (spellInfo_1->EffectApplyAuraName[EFFECT_INDEX_2] == SPELL_AURA_MOD_RESISTANCE_EXCLUSIVE && spellInfo_2->EffectApplyAuraName[EFFECT_INDEX_2] == SPELL_AURA_MOD_RESISTANCE_EXCLUSIVE) return true; // Blessings of Kings and Blessing of Forgotten Kings if (spellInfo_1->EffectApplyAuraName[EFFECT_INDEX_0] == SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE && spellInfo_2->EffectApplyAuraName[EFFECT_INDEX_0] == SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE) return true; } // Mangle and Trauma if (spellInfo_1->EffectApplyAuraName[EFFECT_INDEX_1] == SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT && spellInfo_1->EffectMiscValue[EFFECT_INDEX_1] == MECHANIC_BLEED && spellInfo_2->EffectApplyAuraName[EFFECT_INDEX_0] == SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT && spellInfo_2->EffectMiscValue[EFFECT_INDEX_0] == MECHANIC_BLEED || spellInfo_2->EffectApplyAuraName[EFFECT_INDEX_1] == SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT && spellInfo_2->EffectMiscValue[EFFECT_INDEX_1] == MECHANIC_BLEED && spellInfo_1->EffectApplyAuraName[EFFECT_INDEX_0] == SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT && spellInfo_1->EffectMiscValue[EFFECT_INDEX_0] == MECHANIC_BLEED ) return true; // Specific spell family spells switch(spellInfo_1->SpellFamilyName) { case SPELLFAMILY_GENERIC: switch(spellInfo_2->SpellFamilyName) { case SPELLFAMILY_GENERIC: // same family case { // Thunderfury if ((spellInfo_1->Id == 21992 && spellInfo_2->Id == 27648) || (spellInfo_2->Id == 21992 && spellInfo_1->Id == 27648)) return false; // Lightning Speed (Mongoose) and Fury of the Crashing Waves (Tsunami Talisman) if ((spellInfo_1->Id == 28093 && spellInfo_2->Id == 42084) || (spellInfo_2->Id == 28093 && spellInfo_1->Id == 42084)) return false; // Soulstone Resurrection and Twisting Nether (resurrector) if (spellInfo_1->SpellIconID == 92 && spellInfo_2->SpellIconID == 92 && ( (spellInfo_1->SpellVisual[0] == 99 && spellInfo_2->SpellVisual[0] == 0) || (spellInfo_2->SpellVisual[0] == 99 && spellInfo_1->SpellVisual[0] == 0))) return false; // Heart of the Wild, Agility and various Idol Triggers if (spellInfo_1->SpellIconID == 240 && spellInfo_2->SpellIconID == 240) return false; // Personalized Weather (thunder effect should overwrite rainy aura) if (spellInfo_1->SpellIconID == 2606 && spellInfo_2->SpellIconID == 2606) return false; // Brood Affliction: Bronze if ((spellInfo_1->Id == 23170 && spellInfo_2->Id == 23171) || (spellInfo_2->Id == 23170 && spellInfo_1->Id == 23171)) return false; // Male Shadowy Disguise if ((spellInfo_1->Id == 32756 && spellInfo_2->Id == 38080) || (spellInfo_2->Id == 32756 && spellInfo_1->Id == 38080)) return false; // Female Shadowy Disguise if ((spellInfo_1->Id == 32756 && spellInfo_2->Id == 38081) || (spellInfo_2->Id == 32756 && spellInfo_1->Id == 38081)) return false; // Cool Down (See PeriodicAuraTick()) if ((spellInfo_1->Id == 52441 && spellInfo_2->Id == 52443) || (spellInfo_2->Id == 52441 && spellInfo_1->Id == 52443)) return false; // See Chapel Invisibility and See Noth Invisibility if ((spellInfo_1->Id == 52950 && spellInfo_2->Id == 52707) || (spellInfo_2->Id == 52950 && spellInfo_1->Id == 52707)) return false; // Regular and Night Elf Ghost if ((spellInfo_1->Id == 8326 && spellInfo_2->Id == 20584) || (spellInfo_2->Id == 8326 && spellInfo_1->Id == 20584)) return false; // Aura of Despair auras if ((spellInfo_1->Id == 64848 && spellInfo_2->Id == 62692) || (spellInfo_2->Id == 64848 && spellInfo_1->Id == 62692)) return false; // Blood Fury and Rage of the Unraveller if (spellInfo_1->SpellIconID == 1662 && spellInfo_2->SpellIconID == 1662) return false; // Kindred Spirits if (spellInfo_1->SpellIconID == 3559 && spellInfo_2->SpellIconID == 3559) return false; // Vigilance and Damage Reduction (Vigilance triggered spell) if (spellInfo_1->SpellIconID == 2834 && spellInfo_2->SpellIconID == 2834) return false; // Unstable Sphere Timer and Unstable Sphere Passive if ((spellInfo_1->Id == 50758 && spellInfo_2->Id == 50756) || (spellInfo_2->Id == 50758 && spellInfo_1->Id == 50756)) return false; break; } case SPELLFAMILY_MAGE: // Arcane Intellect and Insight if (spellInfo_2->SpellIconID == 125 && spellInfo_1->Id == 18820) return false; break; case SPELLFAMILY_WARRIOR: { // Scroll of Protection and Defensive Stance (multi-family check) if (spellInfo_1->SpellIconID == 276 && spellInfo_1->SpellVisual[0] == 196 && spellInfo_2->Id == 71) return false; // Improved Hamstring -> Hamstring (multi-family check) if ((spellInfo_2->SpellFamilyFlags & UI64LIT(0x2)) && spellInfo_1->Id == 23694) return false; // Death Wish and Heart of a Dragon if (spellInfo_1->Id == 169 && spellInfo_2->SpellIconID == 169) return false; break; } case SPELLFAMILY_PRIEST: { // Berserking/Enrage PvE spells and Mind Trauma if(spellInfo_1->SpellIconID == 95 && spellInfo_2->Id == 48301) return false; break; // Frenzy (Grand Widow Faerlina) and Mind Trauma if( spellInfo_1->SpellIconID == 95 && spellInfo_2->SpellFamilyFlags & UI64LIT(0x84000000)) return false; // Runescroll of Fortitude and Power Word: Fortitude if( spellInfo_1->Id == 72590 && spellInfo_2->SpellFamilyFlags & UI64LIT(0x8)) return true; } case SPELLFAMILY_DRUID: { // Scroll of Stamina and Leader of the Pack (multi-family check) if (spellInfo_1->SpellIconID == 312 && spellInfo_1->SpellVisual[0] == 216 && spellInfo_2->Id == 24932) return false; // Dragonmaw Illusion (multi-family check) if (spellId_1 == 40216 && spellId_2 == 42016) return false; // Drums of the Wild and Gift of the Wild if( spellInfo_1->Id == 72588 && spellInfo_2->SpellFamilyFlags & UI64LIT(0x40000)) return true; // FG: Gift of the Wild (21849 and ranks) and Gift of the Wild (from Item: Drums of the Wild) if (spellInfo_1->Id == 72588 && spellInfo_2->SpellIconID == 2435) return true; // does not stack break; } case SPELLFAMILY_ROGUE: { // Garrote-Silence -> Garrote (multi-family check) if (spellInfo_1->SpellIconID == 498 && spellInfo_1->SpellVisual[0] == 0 && spellInfo_2->SpellIconID == 498) return false; // Honor Among Thieves dummy auras (multi-family check) if (spellId_1 == 51699 && spellId_2 == 52916) return false; break; } case SPELLFAMILY_HUNTER: { // Concussive Shot and Imp. Concussive Shot (multi-family check) if (spellInfo_1->Id == 19410 && spellInfo_2->Id == 5116) return false; // Improved Wing Clip -> Wing Clip (multi-family check) if ((spellInfo_2->SpellFamilyFlags & UI64LIT(0x40)) && spellInfo_1->Id == 19229) return false; break; } case SPELLFAMILY_PALADIN: { // Unstable Currents and other -> *Sanctity Aura (multi-family check) if (spellInfo_2->SpellIconID==502 && spellInfo_1->SpellIconID==502 && spellInfo_1->SpellVisual[0]==969) return false; // *Band of Eternal Champion and Seal of Command(multi-family check) if (spellId_1 == 35081 && spellInfo_2->SpellIconID==561 && spellInfo_2->SpellVisual[0]==7992) return false; // FG: Frostforged Champion and Seal of Command(multi-family check) if( spellId_1 == 72412 && spellInfo_2->SpellIconID==561 && spellInfo_2->SpellVisual[0]==7992) return false; // Blessing of Sanctuary (multi-family check, some from 16 spell icon spells) if (spellInfo_1->Id == 67480 && spellInfo_2->Id == 20911) return false; // Devotion Aura and Essence if Gossamer if (spellInfo_1->SpellIconID == 291 && spellInfo_2->SpellIconID == 291) return false; // FG: Greater Blessing of Kings and Blessing of Forgotten Kings if (spellId_1 == 72586 && spellId_2 == 25898) return true; // does not stack // Drums of Forgotten Kings and Blessing of Kings if( spellInfo_1->Id == 72586 && spellInfo_2->SpellFamilyFlags & UI64LIT(0x10000000)) return true; break; } } // Dragonmaw Illusion, Blood Elf Illusion, Human Illusion, Illidari Agent Illusion, Scarlet Crusade Disguise if(spellInfo_1->SpellIconID == 1691 && spellInfo_2->SpellIconID == 1691) return false; break; case SPELLFAMILY_MAGE: if( spellInfo_2->SpellFamilyName == SPELLFAMILY_MAGE ) { // Blizzard & Chilled (and some other stacked with blizzard spells if (((spellInfo_1->SpellFamilyFlags & UI64LIT(0x80)) && (spellInfo_2->SpellFamilyFlags & UI64LIT(0x100000))) || ((spellInfo_2->SpellFamilyFlags & UI64LIT(0x80)) && (spellInfo_1->SpellFamilyFlags & UI64LIT(0x100000)))) return false; // Blink & Improved Blink if (((spellInfo_1->SpellFamilyFlags & UI64LIT(0x0000000000010000)) && (spellInfo_2->SpellVisual[0] == 72 && spellInfo_2->SpellIconID == 1499)) || ((spellInfo_2->SpellFamilyFlags & UI64LIT(0x0000000000010000)) && (spellInfo_1->SpellVisual[0] == 72 && spellInfo_1->SpellIconID == 1499))) return false; // Fingers of Frost effects if (spellInfo_1->SpellIconID == 2947 && spellInfo_2->SpellIconID == 2947) return false; // Living Bomb & Ignite (Dots) if (((spellInfo_1->SpellFamilyFlags & UI64LIT(0x2000000000000)) && (spellInfo_2->SpellFamilyFlags & UI64LIT(0x8000000))) || ((spellInfo_2->SpellFamilyFlags & UI64LIT(0x2000000000000)) && (spellInfo_1->SpellFamilyFlags & UI64LIT(0x8000000)))) return false; // Fireball & Pyroblast (Dots) if (((spellInfo_1->SpellFamilyFlags & UI64LIT(0x1)) && (spellInfo_2->SpellFamilyFlags & UI64LIT(0x400000))) || ((spellInfo_2->SpellFamilyFlags & UI64LIT(0x1)) && (spellInfo_1->SpellFamilyFlags & UI64LIT(0x400000)))) return false; //Focus magic 30min buff and 10s proc if( (spellInfo_1->SpellIconID == 54648) && (spellInfo_2->SpellIconID == 54646) || (spellInfo_2->SpellIconID == 54648) && (spellInfo_1->SpellIconID == 54646) ) return false; //Improved scorch and Winter's Chill if( (spellInfo_1->Id == 22959) && (spellInfo_2->Id == 12579) || (spellInfo_2->Id == 22959) && (spellInfo_1->Id == 12579) ) return false; // FG: arcane intelligence, arcane brilliance, dalaran intelligence, dalaran brilliance if( spellInfo_1->SpellFamilyFlags.Flags == 1024 && spellInfo_2->SpellFamilyFlags.Flags == 1024) return true; // cant be stacked } // Detect Invisibility and Mana Shield (multi-family check) if (spellInfo_2->Id == 132 && spellInfo_1->SpellIconID == 209 && spellInfo_1->SpellVisual[0] == 968) return false; // Combustion and Fire Protection Aura (multi-family check) if (spellInfo_1->Id == 11129 && spellInfo_2->SpellIconID == 33 && spellInfo_2->SpellVisual[0] == 321) return false; // Arcane Intellect and Insight if (spellInfo_1->SpellIconID == 125 && spellInfo_2->Id == 18820) return false; break; case SPELLFAMILY_WARLOCK: if (spellInfo_2->SpellFamilyName == SPELLFAMILY_WARLOCK) { // Siphon Life and Drain Life if ((spellInfo_1->SpellIconID == 152 && spellInfo_2->SpellIconID == 546) || (spellInfo_2->SpellIconID == 152 && spellInfo_1->SpellIconID == 546)) return false; //Corruption & Seed of corruption if ((spellInfo_1->SpellIconID == 313 && spellInfo_2->SpellIconID == 1932) || (spellInfo_2->SpellIconID == 313 && spellInfo_1->SpellIconID == 1932)) if(spellInfo_1->SpellVisual[0] != 0 && spellInfo_2->SpellVisual[0] != 0) return true; // can't be stacked // Corruption and Unstable Affliction if ((spellInfo_1->SpellIconID == 313 && spellInfo_2->SpellIconID == 2039) || (spellInfo_2->SpellIconID == 313 && spellInfo_1->SpellIconID == 2039)) return false; // (Corruption or Unstable Affliction) and (Curse of Agony or Curse of Doom) if (((spellInfo_1->SpellIconID == 313 || spellInfo_1->SpellIconID == 2039) && (spellInfo_2->SpellIconID == 544 || spellInfo_2->SpellIconID == 91)) || ((spellInfo_2->SpellIconID == 313 || spellInfo_2->SpellIconID == 2039) && (spellInfo_1->SpellIconID == 544 || spellInfo_1->SpellIconID == 91))) return false; // Shadowflame and Curse of Agony if( spellInfo_1->SpellIconID == 544 && spellInfo_2->SpellIconID == 3317 || spellInfo_2->SpellIconID == 544 && spellInfo_1->SpellIconID == 3317 ) return false; // Shadowflame and Curse of Doom if( spellInfo_1->SpellIconID == 91 && spellInfo_2->SpellIconID == 3317 || spellInfo_2->SpellIconID == 91 && spellInfo_1->SpellIconID == 3317 ) return false; // Metamorphosis, diff effects if (spellInfo_1->SpellIconID == 3314 && spellInfo_2->SpellIconID == 3314) return false; // Shadowflame and Corruption if ( ( (spellInfo_1->SpellFamilyFlags.Flags2 & 0x00000002) && spellInfo_2->SpellIconID == 313 ) || ( (spellInfo_2->SpellFamilyFlags.Flags2 & 0x00000002) && spellInfo_1->SpellIconID == 313 ) ) return false; // Shadowflame and Curse of Agony if ( ( (spellInfo_1->SpellFamilyFlags.Flags2 & 0x00000002) && spellInfo_2->SpellIconID == 544 ) || ( (spellInfo_2->SpellFamilyFlags.Flags2 & 0x00000002) && spellInfo_1->SpellIconID == 544 ) ) return false; } // Detect Invisibility and Mana Shield (multi-family check) if (spellInfo_1->Id == 132 && spellInfo_2->SpellIconID == 209 && spellInfo_2->SpellVisual[0] == 968) return false; break; case SPELLFAMILY_WARRIOR: if (spellInfo_2->SpellFamilyName == SPELLFAMILY_WARRIOR) { // Rend and Deep Wound if (((spellInfo_1->SpellFamilyFlags & UI64LIT(0x20)) && (spellInfo_2->SpellFamilyFlags & UI64LIT(0x1000000000))) || ((spellInfo_2->SpellFamilyFlags & UI64LIT(0x20)) && (spellInfo_1->SpellFamilyFlags & UI64LIT(0x1000000000)))) return false; // Battle Shout and Rampage if ((spellInfo_1->SpellIconID == 456 && spellInfo_2->SpellIconID == 2006) || (spellInfo_2->SpellIconID == 456 && spellInfo_1->SpellIconID == 2006)) return false; // Glyph of Revenge (triggered), and Sword and Board (triggered) if ((spellInfo_1->SpellIconID == 856 && spellInfo_2->SpellIconID == 2780) || (spellInfo_2->SpellIconID == 856 && spellInfo_1->SpellIconID == 2780)) return false; // Defensive/Berserker/Battle stance aura can not stack (needed for dummy auras) if (((spellInfo_1->SpellFamilyFlags & UI64LIT(0x800000)) && (spellInfo_2->SpellFamilyFlags & UI64LIT(0x800000))) || ((spellInfo_2->SpellFamilyFlags & UI64LIT(0x800000)) && (spellInfo_1->SpellFamilyFlags & UI64LIT(0x800000)))) return true; // Taste of Blood and Sudden Death if( (spellInfo_1->Id == 52437 && spellInfo_2->Id == 60503) || (spellInfo_2->Id == 52437 && spellInfo_1->Id == 60503) ) return false; } else if (spellInfo_2->SpellFamilyName == SPELLFAMILY_ROGUE) { // Sunder Armor and Expose Armor if (spellInfo_1->EffectApplyAuraName[EFFECT_INDEX_0] == SPELL_AURA_MOD_RESISTANCE_PCT && spellInfo_2->EffectApplyAuraName[EFFECT_INDEX_0] == SPELL_AURA_MOD_RESISTANCE_PCT) return true; } // Hamstring -> Improved Hamstring (multi-family check) if ((spellInfo_1->SpellFamilyFlags & UI64LIT(0x2)) && spellInfo_2->Id == 23694) return false; // Defensive Stance and Scroll of Protection (multi-family check) if (spellInfo_1->Id == 71 && spellInfo_2->SpellIconID == 276 && spellInfo_2->SpellVisual[0] == 196) return false; // Bloodlust and Bloodthirst (multi-family check) if (spellInfo_2->Id == 2825 && spellInfo_1->SpellIconID == 38 && spellInfo_1->SpellVisual[0] == 0) return false; // Death Wish and Heart of a Dragon if (spellInfo_1->Id == 169 && spellInfo_2->SpellIconID == 169 && spellInfo_2->SpellFamilyName == SPELLFAMILY_GENERIC) return false; break; case SPELLFAMILY_PRIEST: if (spellInfo_2->SpellFamilyName == SPELLFAMILY_PRIEST) { //Devouring Plague and Shadow Vulnerability if (((spellInfo_1->SpellFamilyFlags & UI64LIT(0x2000000)) && (spellInfo_2->SpellFamilyFlags & UI64LIT(0x800000000))) || ((spellInfo_2->SpellFamilyFlags & UI64LIT(0x2000000)) && (spellInfo_1->SpellFamilyFlags & UI64LIT(0x800000000)))) return false; //StarShards and Shadow Word: Pain if (((spellInfo_1->SpellFamilyFlags & UI64LIT(0x200000)) && (spellInfo_2->SpellFamilyFlags & UI64LIT(0x8000))) || ((spellInfo_2->SpellFamilyFlags & UI64LIT(0x200000)) && (spellInfo_1->SpellFamilyFlags & UI64LIT(0x8000)))) return false; // Dispersion if ((spellInfo_1->Id == 47585 && spellInfo_2->Id == 60069) || (spellInfo_2->Id == 47585 && spellInfo_1->Id == 60069)) return false; // Power Word: Shield and Divine Aegis if ((spellInfo_1->SpellIconID == 566 && spellInfo_2->SpellIconID == 2820) || (spellInfo_2->SpellIconID == 566 && spellInfo_1->SpellIconID == 2820)) return false; // Inner Fire and Consecration if (spellInfo_1->SpellIconID == 51 && spellInfo_2->SpellIconID == 51 && spellInfo_2->SpellFamilyName == SPELLFAMILY_PALADIN) return false; // Prayer/PW Fortitude && Runescroll of Fortitude if (spellInfo_1->SpellVisual[0] == 278 && spellInfo_2->Id == 72590) return true; } // Power Word: Fortitude and Runescroll of Fortitude if( spellInfo_1->SpellFamilyFlags & UI64LIT(0x8) && spellInfo_2->Id == 72590 ) return true; break; case SPELLFAMILY_DRUID: if (spellInfo_2->SpellFamilyName == SPELLFAMILY_DRUID) { //Omen of Clarity and Blood Frenzy if (((spellInfo_1->SpellFamilyFlags == UI64LIT(0x0) && spellInfo_1->SpellIconID == 108) && (spellInfo_2->SpellFamilyFlags & UI64LIT(0x20000000000000))) || ((spellInfo_2->SpellFamilyFlags == UI64LIT(0x0) && spellInfo_2->SpellIconID == 108) && (spellInfo_1->SpellFamilyFlags & UI64LIT(0x20000000000000)))) return false; // Tree of Life (Shapeshift) and 34123 Tree of Life (Passive) if ((spellId_1 == 33891 && spellId_2 == 34123) || (spellId_2 == 33891 && spellId_1 == 34123)) return false; // Lifebloom and Wild Growth if ((spellInfo_1->SpellIconID == 2101 && spellInfo_2->SpellIconID == 2864) || (spellInfo_2->SpellIconID == 2101 && spellInfo_1->SpellIconID == 2864)) return false; // Innervate and Glyph of Innervate and some other spells if (spellInfo_1->SpellIconID == 62 && spellInfo_2->SpellIconID == 62) return false; // Wrath of Elune and Nature's Grace if ((spellInfo_1->Id == 16886 && spellInfo_2->Id == 46833) || (spellInfo_2->Id == 16886 && spellInfo_1->Id == 46833)) return false; // Bear Rage (Feral T4 (2)) and Omen of Clarity if ((spellInfo_1->Id == 16864 && spellInfo_2->Id == 37306) || (spellInfo_2->Id == 16864 && spellInfo_1->Id == 37306)) return false; // Cat Energy (Feral T4 (2)) and Omen of Clarity if ((spellInfo_1->Id == 16864 && spellInfo_2->Id == 37311) || (spellInfo_2->Id == 16864 && spellInfo_1->Id == 37311)) return false; // Survival Instincts and Survival Instincts if ((spellInfo_1->Id == 61336 && spellInfo_2->Id == 50322) || (spellInfo_2->Id == 61336 && spellInfo_1->Id == 50322)) return false; // Frenzied Regeneration and Savage Defense if( spellInfo_1->Id == 22842 && spellInfo_2->Id == 62606 || spellInfo_2->Id == 22842 && spellInfo_1->Id == 62606 ) return false; // Savage Roar and Savage Roar (triggered) if (spellInfo_1->SpellIconID == 2865 && spellInfo_2->SpellIconID == 2865) return false; // Frenzied Regeneration and Savage Defense if ((spellInfo_1->Id == 22842 && spellInfo_2->Id == 62606) || (spellInfo_2->Id == 22842 && spellInfo_1->Id == 62606)) return false; // FG: Moonfire and Lacerate if ((spellInfo_1->SpellIconID == 225 && spellInfo_2->SpellIconID == 2246) || (spellInfo_1->SpellIconID == 2246 && spellInfo_2->SpellIconID == 225)) return false; } // FG: Gift of the Wild (21849 and ranks) and Gift of the Wild (from Item: Drums of the Wild) if (spellInfo_1->SpellIconID == 2435 && spellId_2 == 72588) return true; // does not stack // Leader of the Pack and Scroll of Stamina (multi-family check) if (spellInfo_1->Id == 24932 && spellInfo_2->SpellIconID == 312 && spellInfo_2->SpellVisual[0] == 216) return false; // Dragonmaw Illusion (multi-family check) if (spellId_1 == 42016 && spellId_2 == 40216 ) return false; // Gift of the Wild and Drums of the Wild if( spellInfo_1->SpellFamilyFlags & UI64LIT(0x40000) && spellInfo_2->Id == 72588) return true; break; case SPELLFAMILY_ROGUE: if (spellInfo_2->SpellFamilyName == SPELLFAMILY_ROGUE) { // Master of Subtlety if ((spellId_1 == 31665 && spellId_2 == 31666) || (spellId_1 == 31666 && spellId_2 == 31665)) return false; // Sprint & Sprint (waterwalk) if (spellInfo_1->SpellIconID == 516 && spellInfo_2->SpellIconID == 516 && ((spellInfo_1->Category == 44 && spellInfo_2->Category == 0) || (spellInfo_2->Category == 44 && spellInfo_1->Category == 0))) return false; } else if (spellInfo_2->SpellFamilyName == SPELLFAMILY_GENERIC) { if (spellInfo_1->SpellIconID == 2903 && spellInfo_2->SpellIconID == 2903) return false; // Honor Among Thieves dummy auras (multi-family check) if (spellId_1 == 52916 && spellId_2 == 51699) return false; } else if (spellInfo_2->SpellFamilyName == SPELLFAMILY_WARRIOR) { // Sunder Armor and Expose Armor if (spellInfo_1->EffectApplyAuraName[EFFECT_INDEX_0] == SPELL_AURA_MOD_RESISTANCE_PCT && spellInfo_2->EffectApplyAuraName[EFFECT_INDEX_0] == SPELL_AURA_MOD_RESISTANCE_PCT) return true; } //Overkill if (spellInfo_1->SpellIconID == 2285 && spellInfo_2->SpellIconID == 2285) return false; // Garrote -> Garrote-Silence (multi-family check) if (spellInfo_1->SpellIconID == 498 && spellInfo_2->SpellIconID == 498 && spellInfo_2->SpellVisual[0] == 0) return false; break; case SPELLFAMILY_HUNTER: if (spellInfo_2->SpellFamilyName == SPELLFAMILY_HUNTER) { // Rapid Fire & Quick Shots if (((spellInfo_1->SpellFamilyFlags & UI64LIT(0x20)) && (spellInfo_2->SpellFamilyFlags & UI64LIT(0x20000000000))) || ((spellInfo_2->SpellFamilyFlags & UI64LIT(0x20)) && (spellInfo_1->SpellFamilyFlags & UI64LIT(0x20000000000))) ) return false; // Serpent Sting & (Immolation/Explosive Trap Effect) if (((spellInfo_1->SpellFamilyFlags & UI64LIT(0x4)) && (spellInfo_2->SpellFamilyFlags & UI64LIT(0x00000004000))) || ((spellInfo_2->SpellFamilyFlags & UI64LIT(0x4)) && (spellInfo_1->SpellFamilyFlags & UI64LIT(0x00000004000)))) return false; // Deterrence if (spellInfo_1->SpellIconID == 83 && spellInfo_2->SpellIconID == 83) return false; // Bestial Wrath if (spellInfo_1->SpellIconID == 1680 && spellInfo_2->SpellIconID == 1680) return false; // Aspect of the Viper & Vicious Viper if (spellInfo_1->SpellIconID == 2227 && spellInfo_2->SpellIconID == 2227) return false; } // Repentance and Track Humanoids if (spellInfo_2->SpellFamilyName == SPELLFAMILY_PALADIN && spellInfo_1->SpellIconID == 316 && spellInfo_2->SpellIconID == 316) return false; // Wing Clip -> Improved Wing Clip (multi-family check) if ((spellInfo_1->SpellFamilyFlags & UI64LIT(0x40)) && spellInfo_2->Id == 19229) return false; // Concussive Shot and Imp. Concussive Shot (multi-family check) if (spellInfo_2->Id == 19410 && spellInfo_1->Id == 5116) return false; break; case SPELLFAMILY_PALADIN: if (spellInfo_2->SpellFamilyName == SPELLFAMILY_PALADIN) { // Paladin Seals if (IsSealSpell(spellInfo_1) && IsSealSpell(spellInfo_2)) return true; //Blood Corruption, Holy Vengeance, Righteous Vengeance if ((spellInfo_1->SpellIconID == 2292 && spellInfo_2->SpellIconID == 3025) || (spellInfo_2->SpellIconID == 2292 && spellInfo_1->SpellIconID == 3025)) return false; // Swift Retribution / Improved Devotion Aura (talents) and Paladin Auras if ((spellInfo_1->IsFitToFamilyMask(UI64LIT(0x0), 0x00000020) && (spellInfo_2->SpellIconID == 291 || spellInfo_2->SpellIconID == 3028)) || (spellInfo_2->IsFitToFamilyMask(UI64LIT(0x0), 0x00000020) && (spellInfo_1->SpellIconID == 291 || spellInfo_1->SpellIconID == 3028))) return false; // Beacon of Light and Light's Beacon if ((spellInfo_1->SpellIconID == 3032) && (spellInfo_2->SpellIconID == 3032)) return false; // Concentration Aura and Improved Concentration Aura and Aura Mastery if ((spellInfo_1->SpellIconID == 1487) && (spellInfo_2->SpellIconID == 1487)) return false; // Seal of Corruption (caster/target parts stacking allow, other stacking checked by spell specs) if (spellInfo_1->SpellIconID == 2292 && spellInfo_2->SpellIconID == 2292) return false; // Divine Sacrifice and Divine Guardian if (spellInfo_1->SpellIconID == 3837 && spellInfo_2->SpellIconID == 3837) return false; // Blood Corruption, Holy Vengeance, Righteous Vengeance if ((spellInfo_1->SpellIconID == 2292 && spellInfo_2->SpellIconID == 3025) || (spellInfo_2->SpellIconID == 2292 && spellInfo_1->SpellIconID == 3025)) return false; // Sacred Shield and Blessing of Sanctuary if ((( spellInfo_1->SpellFamilyFlags & UI64LIT(0x0008000000000000)) && (spellInfo_2->Id == 25899 || spellInfo_2->Id == 20911)) || (( spellInfo_2->SpellFamilyFlags & UI64LIT(0x0008000000000000)) && (spellInfo_1->Id == 25899 || spellInfo_1->Id == 20911))) return false; // Seal of Corruption/Vengeance DoT and Righteouss Fury if ((spellInfo_1->SpellIconID == 3025 && spellInfo_2->SpellIconID == 2292) || (spellInfo_1->SpellIconID == 2292 && spellInfo_2->SpellIconID == 3025)) return false; } // Blessing of Sanctuary (multi-family check, some from 16 spell icon spells) if (spellInfo_2->Id == 67480 && spellInfo_1->Id == 20911) return false; // Combustion and Fire Protection Aura (multi-family check) if (spellInfo_2->Id == 11129 && spellInfo_1->SpellIconID == 33 && spellInfo_1->SpellVisual[0] == 321) return false; // *Sanctity Aura -> Unstable Currents and other (multi-family check) if (spellInfo_1->SpellIconID==502 && spellInfo_2->SpellFamilyName == SPELLFAMILY_GENERIC && spellInfo_2->SpellIconID==502 && spellInfo_2->SpellVisual[0]==969) return false; // *Seal of Command and Band of Eternal Champion (multi-family check) if (spellInfo_1->SpellIconID==561 && spellInfo_1->SpellVisual[0]==7992 && spellId_2 == 35081) return false; // Blessing of Kings and Drums of Forgotten Kings if( spellInfo_1->SpellFamilyFlags & UI64LIT(0x10000000) && spellInfo_2->Id == 72586) return true; break; // FG: Seal of Command and Frostforged Champion (multi-family check) if( spellInfo_1->SpellIconID==561 && spellInfo_1->SpellVisual[0]==7992 && spellId_2 == 72412) return false; // Devotion Aura and Essence of Gossamer if (spellInfo_1->SpellIconID == 291 && spellInfo_2->SpellIconID == 291 && spellInfo_2->SpellFamilyName == SPELLFAMILY_GENERIC) return false; // Inner Fire and Consecration if (spellInfo_1->SpellIconID == 51 && spellInfo_2->SpellIconID == 51 && spellInfo_2->SpellFamilyName == SPELLFAMILY_PRIEST) return false; // Repentance and Track Humanoids if (spellInfo_2->SpellFamilyName == SPELLFAMILY_HUNTER && spellInfo_1->SpellIconID == 316 && spellInfo_2->SpellIconID == 316) return false; // FG: Greater Blessing of Kings and Blessing of Forgotten Kings if (spellId_1 == 25898 && spellId_2 == 72586) return true; // does not stack break; case SPELLFAMILY_SHAMAN: if (spellInfo_2->SpellFamilyName == SPELLFAMILY_SHAMAN) { // Windfury weapon if (spellInfo_1->SpellIconID==220 && spellInfo_2->SpellIconID==220 && !spellInfo_1->IsFitToFamilyMask(spellInfo_2->SpellFamilyFlags)) return false; // Ghost Wolf if (spellInfo_1->SpellIconID == 67 && spellInfo_2->SpellIconID == 67) return false; // Totem of Wrath (positive/negative), ranks checked early if (spellInfo_1->SpellIconID == 2019 && spellInfo_2->SpellIconID == 2019) return false; } // Bloodlust and Bloodthirst (multi-family check) if (spellInfo_1->Id == 2825 && spellInfo_2->SpellIconID == 38 && spellInfo_2->SpellVisual[0] == 0) return false; break; case SPELLFAMILY_DEATHKNIGHT: if (spellInfo_2->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT) { // Lichborne and Lichborne (triggered) if (spellInfo_1->SpellIconID == 61 && spellInfo_2->SpellIconID == 61) return false; // Frost Presence and Frost Presence (triggered) if (spellInfo_1->SpellIconID == 2632 && spellInfo_2->SpellIconID == 2632) return false; // Unholy Presence and Unholy Presence (triggered) if (spellInfo_1->SpellIconID == 2633 && spellInfo_2->SpellIconID == 2633) return false; // Blood Presence and Blood Presence (triggered) if (spellInfo_1->SpellIconID == 2636 && spellInfo_2->SpellIconID == 2636) return false; } break; default: break; } // more generic checks if (spellInfo_1->SpellIconID == spellInfo_2->SpellIconID && spellInfo_1->SpellIconID != 0 && spellInfo_2->SpellIconID != 0) { bool isModifier = false; for (int i = 0; i < MAX_EFFECT_INDEX; ++i) { if (spellInfo_1->EffectApplyAuraName[i] == SPELL_AURA_ADD_FLAT_MODIFIER || spellInfo_1->EffectApplyAuraName[i] == SPELL_AURA_ADD_PCT_MODIFIER || spellInfo_2->EffectApplyAuraName[i] == SPELL_AURA_ADD_FLAT_MODIFIER || spellInfo_2->EffectApplyAuraName[i] == SPELL_AURA_ADD_PCT_MODIFIER ) isModifier = true; } if (!isModifier) return true; } if (IsRankSpellDueToSpell(spellInfo_1, spellId_2)) return true; if (spellInfo_1->SpellFamilyName == 0 || spellInfo_2->SpellFamilyName == 0) return false; if (spellInfo_1->SpellFamilyName != spellInfo_2->SpellFamilyName) return false; bool dummy_only = true; for (int i = 0; i < MAX_EFFECT_INDEX; ++i) { if (spellInfo_1->Effect[i] != spellInfo_2->Effect[i] || spellInfo_1->EffectItemType[i] != spellInfo_2->EffectItemType[i] || spellInfo_1->EffectMiscValue[i] != spellInfo_2->EffectMiscValue[i] || spellInfo_1->EffectApplyAuraName[i] != spellInfo_2->EffectApplyAuraName[i]) return false; // ignore dummy only spells if (spellInfo_1->Effect[i] && spellInfo_1->Effect[i] != SPELL_EFFECT_DUMMY && spellInfo_1->EffectApplyAuraName[i] != SPELL_AURA_DUMMY) dummy_only = false; } if (dummy_only) return false; return true; } bool SpellMgr::IsProfessionOrRidingSpell(uint32 spellId) { SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId); if(!spellInfo) return false; if (spellInfo->Effect[EFFECT_INDEX_1] != SPELL_EFFECT_SKILL) return false; uint32 skill = spellInfo->EffectMiscValue[EFFECT_INDEX_1]; return IsProfessionOrRidingSkill(skill); } bool SpellMgr::IsProfessionSpell(uint32 spellId) { SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId); if(!spellInfo) return false; if (spellInfo->Effect[EFFECT_INDEX_1] != SPELL_EFFECT_SKILL) return false; uint32 skill = spellInfo->EffectMiscValue[EFFECT_INDEX_1]; return IsProfessionSkill(skill); } bool SpellMgr::IsPrimaryProfessionSpell(uint32 spellId) { SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId); if(!spellInfo) return false; if (spellInfo->Effect[EFFECT_INDEX_1] != SPELL_EFFECT_SKILL) return false; uint32 skill = spellInfo->EffectMiscValue[EFFECT_INDEX_1]; return IsPrimaryProfessionSkill(skill); } uint32 SpellMgr::GetProfessionSpellMinLevel(uint32 spellId) { uint32 s2l[8][3] = { // 0 - gather 1 - non-gather 2 - fish /*0*/ { 0, 5, 5 }, /*1*/ { 0, 5, 5 }, /*2*/ { 0, 10, 10 }, /*3*/ { 10, 20, 10 }, /*4*/ { 25, 35, 10 }, /*5*/ { 40, 50, 10 }, /*6*/ { 55, 65, 10 }, /*7*/ { 75, 75, 10 }, }; uint32 rank = GetSpellRank(spellId); if (rank >= 8) return 0; SkillLineAbilityMapBounds bounds = GetSkillLineAbilityMapBounds(spellId); if (bounds.first == bounds.second) return 0; switch (bounds.first->second->skillId) { case SKILL_FISHING: return s2l[rank][2]; case SKILL_HERBALISM: case SKILL_MINING: case SKILL_SKINNING: return s2l[rank][0]; default: return s2l[rank][1]; } } bool SpellMgr::IsPrimaryProfessionFirstRankSpell(uint32 spellId) const { return IsPrimaryProfessionSpell(spellId) && GetSpellRank(spellId)==1; } bool SpellMgr::IsSkillBonusSpell(uint32 spellId) const { SkillLineAbilityMapBounds bounds = GetSkillLineAbilityMapBounds(spellId); for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx) { SkillLineAbilityEntry const *pAbility = _spell_idx->second; if (!pAbility || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL) continue; if (pAbility->req_skill_value > 0) return true; } return false; } SpellEntry const* SpellMgr::SelectAuraRankForLevel(SpellEntry const* spellInfo, uint32 level) const { // fast case if (level + 10 >= spellInfo->spellLevel) return spellInfo; // ignore selection for passive spells if (IsPassiveSpell(spellInfo)) return spellInfo; bool needRankSelection = false; for(int i = 0; i < MAX_EFFECT_INDEX; ++i) { // for simple aura in check apply to any non caster based targets, in rank search mode to any explicit targets if (((spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA && (IsExplicitPositiveTarget(spellInfo->EffectImplicitTargetA[i]) || IsAreaEffectPossitiveTarget(Targets(spellInfo->EffectImplicitTargetA[i])))) || spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_PARTY || spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_RAID) && IsPositiveEffect(spellInfo, SpellEffectIndex(i))) { needRankSelection = true; break; } } // not required (rank check more slow so check it here) if (!needRankSelection || GetSpellRank(spellInfo->Id) == 0) return spellInfo; for(uint32 nextSpellId = spellInfo->Id; nextSpellId != 0; nextSpellId = GetPrevSpellInChain(nextSpellId)) { SpellEntry const *nextSpellInfo = sSpellStore.LookupEntry(nextSpellId); if (!nextSpellInfo) break; // if found appropriate level if (level + 10 >= spellInfo->spellLevel) return nextSpellInfo; // one rank less then } // not found return NULL; } typedef UNORDERED_MAP<uint32,uint32> AbilitySpellPrevMap; static void LoadSpellChains_AbilityHelper(SpellChainMap& chainMap, AbilitySpellPrevMap const& prevRanks, uint32 spell_id, uint32 prev_id, uint32 deep = 30) { // spell already listed in chains store SpellChainMap::const_iterator chain_itr = chainMap.find(spell_id); if (chain_itr != chainMap.end()) { MANGOS_ASSERT(chain_itr->second.prev == prev_id && "LoadSpellChains_AbilityHelper: Conflicting data in talents or spell abilities dbc"); return; } // prev rank listed in main chain table (can fill correct data directly) SpellChainMap::const_iterator prev_chain_itr = chainMap.find(prev_id); if (prev_chain_itr != chainMap.end()) { SpellChainNode node; node.prev = prev_id; node.first = prev_chain_itr->second.first; node.rank = prev_chain_itr->second.rank+1; node.req = 0; chainMap[spell_id] = node; return; } // prev spell not listed in prev ranks store, so it first rank AbilitySpellPrevMap::const_iterator prev_itr = prevRanks.find(prev_id); if (prev_itr == prevRanks.end()) { SpellChainNode prev_node; prev_node.prev = 0; prev_node.first = prev_id; prev_node.rank = 1; prev_node.req = 0; chainMap[prev_id] = prev_node; SpellChainNode node; node.prev = prev_id; node.first = prev_id; node.rank = 2; node.req = 0; chainMap[spell_id] = node; return; } if (deep == 0) { MANGOS_ASSERT(false && "LoadSpellChains_AbilityHelper: Infinity cycle in spell ability data"); return; } // prev rank listed, so process it first LoadSpellChains_AbilityHelper(chainMap, prevRanks, prev_id, prev_itr->second, deep-1); // prev rank must be listed now prev_chain_itr = chainMap.find(prev_id); if (prev_chain_itr == chainMap.end()) return; SpellChainNode node; node.prev = prev_id; node.first = prev_chain_itr->second.first; node.rank = prev_chain_itr->second.rank+1; node.req = 0; chainMap[spell_id] = node; } void SpellMgr::LoadSpellChains() { mSpellChains.clear(); // need for reload case mSpellChainsNext.clear(); // need for reload case // load known data for talents for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i) { TalentEntry const *talentInfo = sTalentStore.LookupEntry(i); if (!talentInfo) continue; // not add ranks for 1 ranks talents (if exist non ranks spells then it will included in table data) if (!talentInfo->RankID[1]) continue; for (int j = 0; j < MAX_TALENT_RANK; j++) { uint32 spell_id = talentInfo->RankID[j]; if (!spell_id) continue; if (!sSpellStore.LookupEntry(spell_id)) { //sLog.outErrorDb("Talent %u not exist as spell",spell_id); continue; } SpellChainNode node; node.prev = (j > 0) ? talentInfo->RankID[j-1] : 0; node.first = talentInfo->RankID[0]; node.rank = j+1; node.req = 0; mSpellChains[spell_id] = node; } } // load known data from spell abilities { // we can calculate ranks only after full data generation AbilitySpellPrevMap prevRanks; for(SkillLineAbilityMap::const_iterator ab_itr = mSkillLineAbilityMap.begin(); ab_itr != mSkillLineAbilityMap.end(); ++ab_itr) { uint32 spell_id = ab_itr->first; // skip GM/test/internal spells.begin Its not have ranks anyway if (ab_itr->second->skillId == SKILL_INTERNAL) continue; // some forward spells not exist and can be ignored (some outdated data) SpellEntry const* spell_entry = sSpellStore.LookupEntry(spell_id); if (!spell_entry) // no cases continue; // ignore spell without forwards (non ranked or missing info in skill abilities) uint32 forward_id = ab_itr->second->forward_spellid; if (!forward_id) continue; // some forward spells not exist and can be ignored (some outdated data) SpellEntry const* forward_entry = sSpellStore.LookupEntry(forward_id); if (!forward_entry) continue; // some forward spells still exist but excluded from real use as ranks and not listed in skill abilities now SkillLineAbilityMapBounds bounds = mSkillLineAbilityMap.equal_range(forward_id); if (bounds.first == bounds.second) continue; // spell already listed in chains store SpellChainMap::const_iterator chain_itr = mSpellChains.find(forward_id); if (chain_itr != mSpellChains.end()) { MANGOS_ASSERT(chain_itr->second.prev == spell_id && "Conflicting data in talents or spell abilities dbc"); continue; } // spell already listed in prev ranks store AbilitySpellPrevMap::const_iterator prev_itr = prevRanks.find(forward_id); if (prev_itr != prevRanks.end()) { MANGOS_ASSERT(prev_itr->second == spell_id && "Conflicting data in talents or spell abilities dbc"); continue; } // prev rank listed in main chain table (can fill correct data directly) SpellChainMap::const_iterator prev_chain_itr = mSpellChains.find(spell_id); if (prev_chain_itr != mSpellChains.end()) { SpellChainNode node; node.prev = spell_id; node.first = prev_chain_itr->second.first; node.rank = prev_chain_itr->second.rank+1; node.req = 0; mSpellChains[forward_id] = node; continue; } // need temporary store for later rank calculation prevRanks[forward_id] = spell_id; } while (!prevRanks.empty()) { uint32 spell_id = prevRanks.begin()->first; uint32 prev_id = prevRanks.begin()->second; prevRanks.erase(prevRanks.begin()); LoadSpellChains_AbilityHelper(mSpellChains, prevRanks, spell_id, prev_id); } } // load custom case QueryResult *result = WorldDatabase.Query("SELECT spell_id, prev_spell, first_spell, rank, req_spell FROM spell_chain"); if (!result) { BarGoLink bar(1); bar.step(); sLog.outString(); sLog.outString(">> Loaded 0 spell chain records"); sLog.outErrorDb("`spell_chains` table is empty!"); return; } uint32 dbc_count = mSpellChains.size(); uint32 new_count = 0; uint32 req_count = 0; BarGoLink bar(result->GetRowCount()); do { bar.step(); Field *fields = result->Fetch(); uint32 spell_id = fields[0].GetUInt32(); SpellChainNode node; node.prev = fields[1].GetUInt32(); node.first = fields[2].GetUInt32(); node.rank = fields[3].GetUInt8(); node.req = fields[4].GetUInt32(); if (!sSpellStore.LookupEntry(spell_id)) { sLog.outErrorDb("Spell %u listed in `spell_chain` does not exist",spell_id); continue; } SpellChainMap::iterator chain_itr = mSpellChains.find(spell_id); if (chain_itr != mSpellChains.end()) { if (chain_itr->second.rank != node.rank) { sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` expected rank %u by DBC data.", spell_id,node.prev,node.first,node.rank,node.req,chain_itr->second.rank); continue; } if (chain_itr->second.prev != node.prev) { sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` expected prev %u by DBC data.", spell_id,node.prev,node.first,node.rank,node.req,chain_itr->second.prev); continue; } if (chain_itr->second.first != node.first) { sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` expected first %u by DBC data.", spell_id,node.prev,node.first,node.rank,node.req,chain_itr->second.first); continue; } // update req field by table data if (node.req) { chain_itr->second.req = node.req; ++req_count; continue; } // in other case redundant sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) already added (talent or spell ability with forward) and non need in `spell_chain`", spell_id,node.prev,node.first,node.rank,node.req); continue; } if (node.prev != 0 && !sSpellStore.LookupEntry(node.prev)) { sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has nonexistent previous rank spell.", spell_id,node.prev,node.first,node.rank,node.req); continue; } if(!sSpellStore.LookupEntry(node.first)) { sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has not existing first rank spell.", spell_id,node.prev,node.first,node.rank,node.req); continue; } // check basic spell chain data integrity (note: rank can be equal 0 or 1 for first/single spell) if( (spell_id == node.first) != (node.rank <= 1) || (spell_id == node.first) != (node.prev == 0) || (node.rank <= 1) != (node.prev == 0) ) { sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has not compatible chain data.", spell_id,node.prev,node.first,node.rank,node.req); continue; } if(node.req!=0 && !sSpellStore.LookupEntry(node.req)) { sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has not existing required spell.", spell_id,node.prev,node.first,node.rank,node.req); continue; } // talents not required data in spell chain for work, but must be checked if present for integrity if(TalentSpellPos const* pos = GetTalentSpellPos(spell_id)) { if(node.rank!=pos->rank+1) { sLog.outErrorDb("Talent %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has wrong rank.", spell_id,node.prev,node.first,node.rank,node.req); continue; } if(TalentEntry const* talentEntry = sTalentStore.LookupEntry(pos->talent_id)) { if(node.first!=talentEntry->RankID[0]) { sLog.outErrorDb("Talent %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has wrong first rank spell.", spell_id,node.prev,node.first,node.rank,node.req); continue; } if(node.rank > 1 && node.prev != talentEntry->RankID[node.rank-1-1]) { sLog.outErrorDb("Talent %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has wrong prev rank spell.", spell_id,node.prev,node.first,node.rank,node.req); continue; } /*if(node.req!=talentEntry->DependsOnSpell) { sLog.outErrorDb("Talent %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has wrong required spell.", spell_id,node.prev,node.first,node.rank,node.req); continue; }*/ } } // removed ranks often still listed as forward in skill abilities but not listed as spell in it if (node.prev) { bool skip = false; // some forward spells still exist but excluded from real use as ranks and not listed in skill abilities now SkillLineAbilityMapBounds bounds = mSkillLineAbilityMap.equal_range(spell_id); if (bounds.first == bounds.second) { SkillLineAbilityMapBounds prev_bounds = mSkillLineAbilityMap.equal_range(node.prev); for(SkillLineAbilityMap::const_iterator ab_itr = prev_bounds.first; ab_itr != prev_bounds.second; ++ab_itr) { // spell listed as forward and not listed as ability // this is marker for removed ranks if (ab_itr->second->forward_spellid == spell_id) { sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` is removed rank by DBC data.", spell_id, node.prev, node.first, node.rank, node.req); skip = true; break; } } } if (skip) continue; } mSpellChains[spell_id] = node; ++new_count; } while( result->NextRow() ); delete result; // additional integrity checks for(SpellChainMap::const_iterator i = mSpellChains.begin(); i != mSpellChains.end(); ++i) { if(i->second.prev) { SpellChainMap::const_iterator i_prev = mSpellChains.find(i->second.prev); if(i_prev == mSpellChains.end()) { sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has not found previous rank spell in table.", i->first,i->second.prev,i->second.first,i->second.rank,i->second.req); } else if( i_prev->second.first != i->second.first ) { sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has different first spell in chain compared to previous rank spell (prev: %u, first: %u, rank: %d, req: %u).", i->first,i->second.prev,i->second.first,i->second.rank,i->second.req, i_prev->second.prev,i_prev->second.first,i_prev->second.rank,i_prev->second.req); } else if( i_prev->second.rank+1 != i->second.rank ) { sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has different rank compared to previous rank spell (prev: %u, first: %u, rank: %d, req: %u).", i->first,i->second.prev,i->second.first,i->second.rank,i->second.req, i_prev->second.prev,i_prev->second.first,i_prev->second.rank,i_prev->second.req); } } if(i->second.req) { SpellChainMap::const_iterator i_req = mSpellChains.find(i->second.req); if(i_req == mSpellChains.end()) { sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has not found required rank spell in table.", i->first,i->second.prev,i->second.first,i->second.rank,i->second.req); } else if( i_req->second.first == i->second.first ) { sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has required rank spell from same spell chain (prev: %u, first: %u, rank: %d, req: %u).", i->first,i->second.prev,i->second.first,i->second.rank,i->second.req, i_req->second.prev,i_req->second.first,i_req->second.rank,i_req->second.req); } else if( i_req->second.req ) { sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has required rank spell with required spell (prev: %u, first: %u, rank: %d, req: %u).", i->first,i->second.prev,i->second.first,i->second.rank,i->second.req, i_req->second.prev,i_req->second.first,i_req->second.rank,i_req->second.req); } } } // fill next rank cache for(SpellChainMap::const_iterator i = mSpellChains.begin(); i != mSpellChains.end(); ++i) { uint32 spell_id = i->first; SpellChainNode const& node = i->second; if(node.prev) mSpellChainsNext.insert(SpellChainMapNext::value_type(node.prev,spell_id)); if(node.req) mSpellChainsNext.insert(SpellChainMapNext::value_type(node.req,spell_id)); } // check single rank redundant cases (single rank talents/spell abilities not added by default so this can be only custom cases) for(SpellChainMap::const_iterator i = mSpellChains.begin(); i != mSpellChains.end(); ++i) { // skip non-first ranks, and spells with additional reqs if (i->second.rank > 1 || i->second.req) continue; if (mSpellChainsNext.find(i->first) == mSpellChainsNext.end()) { sLog.outErrorDb("Spell %u (prev: %u, first: %u, rank: %d, req: %u) listed in `spell_chain` has single rank data, so redundant.", i->first,i->second.prev,i->second.first,i->second.rank,i->second.req); } } sLog.outString(); sLog.outString( ">> Loaded %u spell chain records (%u from DBC data with %u req field updates, and %u loaded from table)", dbc_count+new_count, dbc_count, req_count, new_count); } void SpellMgr::LoadSpellLearnSkills() { mSpellLearnSkills.clear(); // need for reload case // search auto-learned skills and add its to map also for use in unlearn spells/talents uint32 dbc_count = 0; BarGoLink bar(sSpellStore.GetNumRows()); for (uint32 spell = 0; spell < sSpellStore.GetNumRows(); ++spell) { bar.step(); SpellEntry const* entry = sSpellStore.LookupEntry(spell); if (!entry) continue; for (int i = 0; i < MAX_EFFECT_INDEX; ++i) { if (entry->Effect[i] == SPELL_EFFECT_SKILL) { SpellLearnSkillNode dbc_node; dbc_node.skill = entry->EffectMiscValue[i]; dbc_node.step = entry->CalculateSimpleValue(SpellEffectIndex(i)); if (dbc_node.skill != SKILL_RIDING) dbc_node.value = 1; else dbc_node.value = dbc_node.step * 75; dbc_node.maxvalue = dbc_node.step * 75; mSpellLearnSkills[spell] = dbc_node; ++dbc_count; break; } } } sLog.outString(); sLog.outString(">> Loaded %u Spell Learn Skills from DBC", dbc_count); } void SpellMgr::LoadSpellLearnSpells() { mSpellLearnSpells.clear(); // need for reload case // 0 1 2 QueryResult *result = WorldDatabase.Query("SELECT entry, SpellID, Active FROM spell_learn_spell"); if (!result) { BarGoLink bar(1); bar.step(); sLog.outString(); sLog.outString(">> Loaded 0 spell learn spells"); sLog.outErrorDb("`spell_learn_spell` table is empty!"); return; } uint32 count = 0; BarGoLink bar(result->GetRowCount()); do { bar.step(); Field *fields = result->Fetch(); uint32 spell_id = fields[0].GetUInt32(); SpellLearnSpellNode node; node.spell = fields[1].GetUInt32(); node.active = fields[2].GetBool(); node.autoLearned= false; if (!sSpellStore.LookupEntry(spell_id)) { sLog.outErrorDb("Spell %u listed in `spell_learn_spell` does not exist",spell_id); continue; } if (!sSpellStore.LookupEntry(node.spell)) { sLog.outErrorDb("Spell %u listed in `spell_learn_spell` learning nonexistent spell %u",spell_id,node.spell); continue; } if (GetTalentSpellCost(node.spell)) { sLog.outErrorDb("Spell %u listed in `spell_learn_spell` attempt learning talent spell %u, skipped",spell_id,node.spell); continue; } mSpellLearnSpells.insert(SpellLearnSpellMap::value_type(spell_id,node)); ++count; } while (result->NextRow()); delete result; // search auto-learned spells and add its to map also for use in unlearn spells/talents uint32 dbc_count = 0; for(uint32 spell = 0; spell < sSpellStore.GetNumRows(); ++spell) { SpellEntry const* entry = sSpellStore.LookupEntry(spell); if (!entry) continue; for(int i = 0; i < MAX_EFFECT_INDEX; ++i) { if(entry->Effect[i]==SPELL_EFFECT_LEARN_SPELL) { SpellLearnSpellNode dbc_node; dbc_node.spell = entry->EffectTriggerSpell[i]; dbc_node.active = true; // all dbc based learned spells is active (show in spell book or hide by client itself) // ignore learning nonexistent spells (broken/outdated/or generic learning spell 483 if (!sSpellStore.LookupEntry(dbc_node.spell)) continue; // talent or passive spells or skill-step spells auto-casted and not need dependent learning, // pet teaching spells don't must be dependent learning (casted) // other required explicit dependent learning dbc_node.autoLearned = entry->EffectImplicitTargetA[i]==TARGET_PET || GetTalentSpellCost(spell) > 0 || IsPassiveSpell(entry) || IsSpellHaveEffect(entry,SPELL_EFFECT_SKILL_STEP); SpellLearnSpellMapBounds db_node_bounds = GetSpellLearnSpellMapBounds(spell); bool found = false; for(SpellLearnSpellMap::const_iterator itr = db_node_bounds.first; itr != db_node_bounds.second; ++itr) { if (itr->second.spell == dbc_node.spell) { sLog.outErrorDb("Spell %u auto-learn spell %u in spell.dbc then the record in `spell_learn_spell` is redundant, please fix DB.", spell,dbc_node.spell); found = true; break; } } if (!found) // add new spell-spell pair if not found { mSpellLearnSpells.insert(SpellLearnSpellMap::value_type(spell,dbc_node)); ++dbc_count; } } } } sLog.outString(); sLog.outString( ">> Loaded %u spell learn spells + %u found in DBC", count, dbc_count ); } void SpellMgr::LoadSpellScriptTarget() { mSpellScriptTarget.clear(); // need for reload case uint32 count = 0; QueryResult *result = WorldDatabase.Query("SELECT entry,type,targetEntry FROM spell_script_target"); if (!result) { BarGoLink bar(1); bar.step(); sLog.outString(); sLog.outErrorDb(">> Loaded 0 SpellScriptTarget. DB table `spell_script_target` is empty."); return; } BarGoLink bar(result->GetRowCount()); do { Field *fields = result->Fetch(); bar.step(); uint32 spellId = fields[0].GetUInt32(); uint32 type = fields[1].GetUInt32(); uint32 targetEntry = fields[2].GetUInt32(); SpellEntry const* spellProto = sSpellStore.LookupEntry(spellId); if (!spellProto) { sLog.outErrorDb("Table `spell_script_target`: spellId %u listed for TargetEntry %u does not exist.",spellId,targetEntry); continue; } bool targetfound = false; for (int i = 0; i < MAX_EFFECT_INDEX; ++i) { if( spellProto->EffectImplicitTargetA[i] == TARGET_SCRIPT || spellProto->EffectImplicitTargetB[i] == TARGET_SCRIPT || spellProto->EffectImplicitTargetA[i] == TARGET_SCRIPT_COORDINATES || spellProto->EffectImplicitTargetB[i] == TARGET_SCRIPT_COORDINATES || spellProto->EffectImplicitTargetA[i] == TARGET_FOCUS_OR_SCRIPTED_GAMEOBJECT || spellProto->EffectImplicitTargetB[i] == TARGET_FOCUS_OR_SCRIPTED_GAMEOBJECT || spellProto->EffectImplicitTargetA[i] == TARGET_AREAEFFECT_INSTANT || spellProto->EffectImplicitTargetB[i] == TARGET_AREAEFFECT_INSTANT || spellProto->EffectImplicitTargetA[i] == TARGET_AREAEFFECT_CUSTOM || spellProto->EffectImplicitTargetB[i] == TARGET_AREAEFFECT_CUSTOM || spellProto->EffectImplicitTargetA[i] == TARGET_AREAEFFECT_GO_AROUND_DEST || spellProto->EffectImplicitTargetB[i] == TARGET_AREAEFFECT_GO_AROUND_DEST) { targetfound = true; break; } } if (!targetfound) { sLog.outErrorDb("Table `spell_script_target`: spellId %u listed for TargetEntry %u does not have any implicit target TARGET_SCRIPT(38) or TARGET_SCRIPT_COORDINATES (46) or TARGET_FOCUS_OR_SCRIPTED_GAMEOBJECT (40).", spellId, targetEntry); continue; } if (type >= MAX_SPELL_TARGET_TYPE) { sLog.outErrorDb("Table `spell_script_target`: target type %u for TargetEntry %u is incorrect.",type,targetEntry); continue; } // Checks by target type switch (type) { case SPELL_TARGET_TYPE_GAMEOBJECT: { if (!targetEntry) break; if (!sGOStorage.LookupEntry<GameObjectInfo>(targetEntry)) { sLog.outErrorDb("Table `spell_script_target`: gameobject template entry %u does not exist.",targetEntry); continue; } break; } default: if (!targetEntry) { sLog.outErrorDb("Table `spell_script_target`: target entry == 0 for not GO target type (%u).",type); continue; } if (const CreatureInfo* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(targetEntry)) { if (spellId == 30427 && !cInfo->SkinLootId) { sLog.outErrorDb("Table `spell_script_target` has creature %u as a target of spellid 30427, but this creature has no skinlootid. Gas extraction will not work!", cInfo->Entry); continue; } } else { sLog.outErrorDb("Table `spell_script_target`: creature template entry %u does not exist.",targetEntry); continue; } break; } mSpellScriptTarget.insert(SpellScriptTarget::value_type(spellId,SpellTargetEntry(SpellTargetType(type),targetEntry))); ++count; } while (result->NextRow()); delete result; // Check all spells /* Disabled (lot errors at this moment) for(uint32 i = 1; i < sSpellStore.nCount; ++i) { SpellEntry const * spellInfo = sSpellStore.LookupEntry(i); if(!spellInfo) continue; bool found = false; for(int j = 0; j < MAX_EFFECT_INDEX; ++j) { if( spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT || spellInfo->EffectImplicitTargetA[j] != TARGET_SELF && spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT ) { SpellScriptTarget::const_iterator lower = GetBeginSpellScriptTarget(spellInfo->Id); SpellScriptTarget::const_iterator upper = GetEndSpellScriptTarget(spellInfo->Id); if(lower==upper) { sLog.outErrorDb("Spell (ID: %u) has effect EffectImplicitTargetA/EffectImplicitTargetB = %u (TARGET_SCRIPT), but does not have record in `spell_script_target`",spellInfo->Id,TARGET_SCRIPT); break; // effects of spell } } } } */ sLog.outString(); sLog.outString(">> Loaded %u Spell Script Targets", count); } void SpellMgr::LoadSpellPetAuras() { mSpellPetAuraMap.clear(); // need for reload case uint32 count = 0; // 0 1 2 3 QueryResult *result = WorldDatabase.Query("SELECT spell, effectId, pet, aura FROM spell_pet_auras"); if (!result) { BarGoLink bar(1); bar.step(); sLog.outString(); sLog.outString(">> Loaded %u spell pet auras", count); return; } BarGoLink bar(result->GetRowCount()); do { Field *fields = result->Fetch(); bar.step(); uint32 spell = fields[0].GetUInt32(); SpellEffectIndex eff = SpellEffectIndex(fields[1].GetUInt32()); uint32 pet = fields[2].GetUInt32(); uint32 aura = fields[3].GetUInt32(); if (eff >= MAX_EFFECT_INDEX) { sLog.outErrorDb("Spell %u listed in `spell_pet_auras` with wrong spell effect index (%u)", spell, eff); continue; } SpellPetAuraMap::iterator itr = mSpellPetAuraMap.find((spell<<8) + eff); if(itr != mSpellPetAuraMap.end()) { itr->second.AddAura(pet, aura); } else { SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell); if (!spellInfo) { sLog.outErrorDb("Spell %u listed in `spell_pet_auras` does not exist", spell); continue; } if (spellInfo->Effect[eff] != SPELL_EFFECT_DUMMY && (spellInfo->Effect[eff] != SPELL_EFFECT_APPLY_AURA || spellInfo->EffectApplyAuraName[eff] != SPELL_AURA_DUMMY)) { sLog.outError("Spell %u listed in `spell_pet_auras` does not have dummy aura or dummy effect", spell); continue; } SpellEntry const* spellInfo2 = sSpellStore.LookupEntry(aura); if (!spellInfo2) { sLog.outErrorDb("Aura %u listed in `spell_pet_auras` does not exist", aura); continue; } PetAura pa(pet, aura, spellInfo->EffectImplicitTargetA[eff] == TARGET_PET, spellInfo->CalculateSimpleValue(eff)); mSpellPetAuraMap[(spell<<8) + eff] = pa; } ++count; } while( result->NextRow() ); delete result; sLog.outString(); sLog.outString( ">> Loaded %u spell pet auras", count ); } void SpellMgr::LoadPetLevelupSpellMap() { uint32 count = 0; uint32 family_count = 0; for (uint32 i = 0; i < sCreatureFamilyStore.GetNumRows(); ++i) { CreatureFamilyEntry const *creatureFamily = sCreatureFamilyStore.LookupEntry(i); if(!creatureFamily) // not exist continue; for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j) { SkillLineAbilityEntry const *skillLine = sSkillLineAbilityStore.LookupEntry(j); if( !skillLine ) continue; if (skillLine->skillId!=creatureFamily->skillLine[0] && (!creatureFamily->skillLine[1] || skillLine->skillId!=creatureFamily->skillLine[1])) continue; if(skillLine->learnOnGetSkill != ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL) continue; SpellEntry const *spell = sSpellStore.LookupEntry(skillLine->spellId); if(!spell) // not exist continue; PetLevelupSpellSet& spellSet = mPetLevelupSpellMap[creatureFamily->ID]; if(spellSet.empty()) ++family_count; spellSet.insert(PetLevelupSpellSet::value_type(spell->spellLevel,spell->Id)); count++; } } sLog.outString(); sLog.outString( ">> Loaded %u pet levelup and default spells for %u families", count, family_count ); } bool SpellMgr::LoadPetDefaultSpells_helper(CreatureInfo const* cInfo, PetDefaultSpellsEntry& petDefSpells) { // skip empty list; bool have_spell = false; for(int j = 0; j < MAX_CREATURE_SPELL_DATA_SLOT; ++j) { if(petDefSpells.spellid[j]) { have_spell = true; break; } } if(!have_spell) return false; // remove duplicates with levelupSpells if any if(PetLevelupSpellSet const *levelupSpells = cInfo->family ? GetPetLevelupSpellList(cInfo->family) : NULL) { for(int j = 0; j < MAX_CREATURE_SPELL_DATA_SLOT; ++j) { if(!petDefSpells.spellid[j]) continue; for(PetLevelupSpellSet::const_iterator itr = levelupSpells->begin(); itr != levelupSpells->end(); ++itr) { if (itr->second == petDefSpells.spellid[j]) { petDefSpells.spellid[j] = 0; break; } } } } // skip empty list; have_spell = false; for(int j = 0; j < MAX_CREATURE_SPELL_DATA_SLOT; ++j) { if(petDefSpells.spellid[j]) { have_spell = true; break; } } return have_spell; } void SpellMgr::LoadPetDefaultSpells() { MANGOS_ASSERT(MAX_CREATURE_SPELL_DATA_SLOT==CREATURE_MAX_SPELLS); mPetDefaultSpellsMap.clear(); uint32 countCreature = 0; uint32 countData = 0; for(uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i ) { CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i); if(!cInfo) continue; if(!cInfo->PetSpellDataId) continue; // for creature with PetSpellDataId get default pet spells from dbc CreatureSpellDataEntry const* spellDataEntry = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId); if(!spellDataEntry) continue; int32 petSpellsId = -(int32)cInfo->PetSpellDataId; PetDefaultSpellsEntry petDefSpells; for(int j = 0; j < MAX_CREATURE_SPELL_DATA_SLOT; ++j) petDefSpells.spellid[j] = spellDataEntry->spellId[j]; if(LoadPetDefaultSpells_helper(cInfo, petDefSpells)) { mPetDefaultSpellsMap[petSpellsId] = petDefSpells; ++countData; } } // different summon spells for(uint32 i = 0; i < sSpellStore.GetNumRows(); ++i ) { SpellEntry const* spellEntry = sSpellStore.LookupEntry(i); if(!spellEntry) continue; for(int k = 0; k < MAX_EFFECT_INDEX; ++k) { if(spellEntry->Effect[k]==SPELL_EFFECT_SUMMON || spellEntry->Effect[k]==SPELL_EFFECT_SUMMON_PET) { uint32 creature_id = spellEntry->EffectMiscValue[k]; CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(creature_id); if(!cInfo) continue; // already loaded if(cInfo->PetSpellDataId) continue; // for creature without PetSpellDataId get default pet spells from creature_template int32 petSpellsId = cInfo->Entry; if(mPetDefaultSpellsMap.find(cInfo->Entry) != mPetDefaultSpellsMap.end()) continue; PetDefaultSpellsEntry petDefSpells; for(int j = 0; j < MAX_CREATURE_SPELL_DATA_SLOT; ++j) petDefSpells.spellid[j] = cInfo->spells[j]; if(LoadPetDefaultSpells_helper(cInfo, petDefSpells)) { mPetDefaultSpellsMap[petSpellsId] = petDefSpells; ++countCreature; } } } } sLog.outString(); sLog.outString( ">> Loaded addition spells for %u pet spell data entries and %u summonable creature templates", countData, countCreature ); } /// Some checks for spells, to prevent adding deprecated/broken spells for trainers, spell book, etc bool SpellMgr::IsSpellValid(SpellEntry const* spellInfo, Player* pl, bool msg) { // not exist if(!spellInfo) return false; bool need_check_reagents = false; // check effects for(int i = 0; i < MAX_EFFECT_INDEX; ++i) { switch(spellInfo->Effect[i]) { case 0: continue; // craft spell for crafting nonexistent item (break client recipes list show) case SPELL_EFFECT_CREATE_ITEM: case SPELL_EFFECT_CREATE_ITEM_2: { if (spellInfo->EffectItemType[i] == 0) { // skip auto-loot crafting spells, its not need explicit item info (but have special fake items sometime) if (!IsLootCraftingSpell(spellInfo)) { if(msg) { if(pl) ChatHandler(pl).PSendSysMessage("Craft spell %u not have create item entry.",spellInfo->Id); else sLog.outErrorDb("Craft spell %u not have create item entry.",spellInfo->Id); } return false; } } // also possible IsLootCraftingSpell case but fake item must exist anyway else if (!ObjectMgr::GetItemPrototype( spellInfo->EffectItemType[i] )) { if(msg) { if(pl) ChatHandler(pl).PSendSysMessage("Craft spell %u create item (Entry: %u) but item does not exist in item_template.",spellInfo->Id,spellInfo->EffectItemType[i]); else sLog.outErrorDb("Craft spell %u create item (Entry: %u) but item does not exist in item_template.",spellInfo->Id,spellInfo->EffectItemType[i]); } return false; } need_check_reagents = true; break; } case SPELL_EFFECT_LEARN_SPELL: { SpellEntry const* spellInfo2 = sSpellStore.LookupEntry(spellInfo->EffectTriggerSpell[i]); if( !IsSpellValid(spellInfo2,pl,msg) ) { if(msg) { if(pl) ChatHandler(pl).PSendSysMessage("Spell %u learn to broken spell %u, and then...",spellInfo->Id,spellInfo->EffectTriggerSpell[i]); else sLog.outErrorDb("Spell %u learn to invalid spell %u, and then...",spellInfo->Id,spellInfo->EffectTriggerSpell[i]); } return false; } break; } } } if(need_check_reagents) { for(int j = 0; j < MAX_SPELL_REAGENTS; ++j) { if(spellInfo->Reagent[j] > 0 && !ObjectMgr::GetItemPrototype( spellInfo->Reagent[j] )) { if(msg) { if(pl) ChatHandler(pl).PSendSysMessage("Craft spell %u requires reagent item (Entry: %u) but item does not exist in item_template.",spellInfo->Id,spellInfo->Reagent[j]); else sLog.outErrorDb("Craft spell %u requires reagent item (Entry: %u) but item does not exist in item_template.",spellInfo->Id,spellInfo->Reagent[j]); } return false; } } } return true; } void SpellMgr::LoadSpellAreas() { mSpellAreaMap.clear(); // need for reload case mSpellAreaForQuestMap.clear(); mSpellAreaForActiveQuestMap.clear(); mSpellAreaForQuestEndMap.clear(); mSpellAreaForAuraMap.clear(); uint32 count = 0; // 0 1 2 3 4 5 6 7 8 QueryResult *result = WorldDatabase.Query("SELECT spell, area, quest_start, quest_start_active, quest_end, aura_spell, racemask, gender, autocast FROM spell_area"); if (!result) { BarGoLink bar(1); bar.step(); sLog.outString(); sLog.outString(">> Loaded %u spell area requirements", count); return; } BarGoLink bar(result->GetRowCount()); do { Field *fields = result->Fetch(); bar.step(); uint32 spell = fields[0].GetUInt32(); SpellArea spellArea; spellArea.spellId = spell; spellArea.areaId = fields[1].GetUInt32(); spellArea.questStart = fields[2].GetUInt32(); spellArea.questStartCanActive = fields[3].GetBool(); spellArea.questEnd = fields[4].GetUInt32(); spellArea.auraSpell = fields[5].GetInt32(); spellArea.raceMask = fields[6].GetUInt32(); spellArea.gender = Gender(fields[7].GetUInt8()); spellArea.autocast = fields[8].GetBool(); if (!sSpellStore.LookupEntry(spell)) { sLog.outErrorDb("Spell %u listed in `spell_area` does not exist", spell); continue; } { bool ok = true; SpellAreaMapBounds sa_bounds = GetSpellAreaMapBounds(spellArea.spellId); for (SpellAreaMap::const_iterator itr = sa_bounds.first; itr != sa_bounds.second; ++itr) { if (spellArea.spellId != itr->second.spellId) continue; if (spellArea.areaId != itr->second.areaId) continue; if (spellArea.questStart != itr->second.questStart) continue; if (spellArea.auraSpell != itr->second.auraSpell) continue; if ((spellArea.raceMask & itr->second.raceMask) == 0) continue; if (spellArea.gender != itr->second.gender) continue; // duplicate by requirements ok =false; break; } if (!ok) { sLog.outErrorDb("Spell %u listed in `spell_area` already listed with similar requirements.", spell); continue; } } if (spellArea.areaId && !GetAreaEntryByAreaID(spellArea.areaId)) { sLog.outErrorDb("Spell %u listed in `spell_area` have wrong area (%u) requirement", spell,spellArea.areaId); continue; } if (spellArea.questStart && !sObjectMgr.GetQuestTemplate(spellArea.questStart)) { sLog.outErrorDb("Spell %u listed in `spell_area` have wrong start quest (%u) requirement", spell,spellArea.questStart); continue; } if (spellArea.questEnd) { if (!sObjectMgr.GetQuestTemplate(spellArea.questEnd)) { sLog.outErrorDb("Spell %u listed in `spell_area` have wrong end quest (%u) requirement", spell,spellArea.questEnd); continue; } if (spellArea.questEnd==spellArea.questStart && !spellArea.questStartCanActive) { sLog.outErrorDb("Spell %u listed in `spell_area` have quest (%u) requirement for start and end in same time", spell,spellArea.questEnd); continue; } } if (spellArea.auraSpell) { SpellEntry const* spellInfo = sSpellStore.LookupEntry(abs(spellArea.auraSpell)); if (!spellInfo) { sLog.outErrorDb("Spell %u listed in `spell_area` have wrong aura spell (%u) requirement", spell,abs(spellArea.auraSpell)); continue; } switch (spellInfo->EffectApplyAuraName[EFFECT_INDEX_0]) { case SPELL_AURA_DUMMY: case SPELL_AURA_PHASE: case SPELL_AURA_GHOST: break; default: sLog.outErrorDb("Spell %u listed in `spell_area` have aura spell requirement (%u) without dummy/phase/ghost aura in effect 0", spell,abs(spellArea.auraSpell)); continue; } if (uint32(abs(spellArea.auraSpell))==spellArea.spellId) { sLog.outErrorDb("Spell %u listed in `spell_area` have aura spell (%u) requirement for itself", spell, abs(spellArea.auraSpell)); continue; } // not allow autocast chains by auraSpell field (but allow use as alternative if not present) if (spellArea.autocast && spellArea.auraSpell > 0) { bool chain = false; SpellAreaForAuraMapBounds saBound = GetSpellAreaForAuraMapBounds(spellArea.spellId); for (SpellAreaForAuraMap::const_iterator itr = saBound.first; itr != saBound.second; ++itr) { if (itr->second->autocast && itr->second->auraSpell > 0) { chain = true; break; } } if (chain) { sLog.outErrorDb("Spell %u listed in `spell_area` have aura spell (%u) requirement that itself autocast from aura", spell,spellArea.auraSpell); continue; } SpellAreaMapBounds saBound2 = GetSpellAreaMapBounds(spellArea.auraSpell); for (SpellAreaMap::const_iterator itr2 = saBound2.first; itr2 != saBound2.second; ++itr2) { if (itr2->second.autocast && itr2->second.auraSpell > 0) { chain = true; break; } } if (chain) { sLog.outErrorDb("Spell %u listed in `spell_area` have aura spell (%u) requirement that itself autocast from aura", spell,spellArea.auraSpell); continue; } } } if (spellArea.raceMask && (spellArea.raceMask & RACEMASK_ALL_PLAYABLE)==0) { sLog.outErrorDb("Spell %u listed in `spell_area` have wrong race mask (%u) requirement", spell,spellArea.raceMask); continue; } if (spellArea.gender!=GENDER_NONE && spellArea.gender!=GENDER_FEMALE && spellArea.gender!=GENDER_MALE) { sLog.outErrorDb("Spell %u listed in `spell_area` have wrong gender (%u) requirement", spell,spellArea.gender); continue; } SpellArea const* sa = &mSpellAreaMap.insert(SpellAreaMap::value_type(spell,spellArea))->second; // for search by current zone/subzone at zone/subzone change if (spellArea.areaId) mSpellAreaForAreaMap.insert(SpellAreaForAreaMap::value_type(spellArea.areaId,sa)); // for search at quest start/reward if (spellArea.questStart) { if (spellArea.questStartCanActive) mSpellAreaForActiveQuestMap.insert(SpellAreaForQuestMap::value_type(spellArea.questStart,sa)); else mSpellAreaForQuestMap.insert(SpellAreaForQuestMap::value_type(spellArea.questStart,sa)); } // for search at quest start/reward if (spellArea.questEnd) mSpellAreaForQuestEndMap.insert(SpellAreaForQuestMap::value_type(spellArea.questEnd,sa)); // for search at aura apply if (spellArea.auraSpell) mSpellAreaForAuraMap.insert(SpellAreaForAuraMap::value_type(abs(spellArea.auraSpell),sa)); ++count; } while (result->NextRow()); delete result; sLog.outString(); sLog.outString(">> Loaded %u spell area requirements", count); } SpellCastResult SpellMgr::GetSpellAllowedInLocationError(SpellEntry const *spellInfo, uint32 map_id, uint32 zone_id, uint32 area_id, Player const* player) { // normal case int32 areaGroupId = spellInfo->AreaGroupId; if (areaGroupId > 0) { bool found = false; AreaGroupEntry const* groupEntry = sAreaGroupStore.LookupEntry(areaGroupId); while (groupEntry) { for (uint32 i=0; i<6; ++i) if (groupEntry->AreaId[i] == zone_id || groupEntry->AreaId[i] == area_id) found = true; if (found || !groupEntry->nextGroup) break; // Try search in next group groupEntry = sAreaGroupStore.LookupEntry(groupEntry->nextGroup); } if (!found) return SPELL_FAILED_INCORRECT_AREA; } // continent limitation (virtual continent), ignore for GM if ((spellInfo->AttributesEx4 & SPELL_ATTR_EX4_CAST_ONLY_IN_OUTLAND) && !(player && player->isGameMaster())) { uint32 v_map = GetVirtualMapForMapAndZone(map_id, zone_id); MapEntry const* mapEntry = sMapStore.LookupEntry(v_map); if (!mapEntry || mapEntry->addon < 1 || !mapEntry->IsContinent()) return SPELL_FAILED_INCORRECT_AREA; } // raid instance limitation if (spellInfo->AttributesEx6 & SPELL_ATTR_EX6_NOT_IN_RAID_INSTANCE) { MapEntry const* mapEntry = sMapStore.LookupEntry(map_id); if (!mapEntry || mapEntry->IsRaid()) return SPELL_FAILED_NOT_IN_RAID_INSTANCE; } // DB base check (if non empty then must fit at least single for allow) SpellAreaMapBounds saBounds = GetSpellAreaMapBounds(spellInfo->Id); if (saBounds.first != saBounds.second) { for(SpellAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr) { if(itr->second.IsFitToRequirements(player,zone_id,area_id)) return SPELL_CAST_OK; } return SPELL_FAILED_INCORRECT_AREA; } // bg spell checks // do not allow spells to be cast in arenas // - with SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA flag // - with greater than 10 min CD if ((spellInfo->AttributesEx4 & SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA) || (GetSpellRecoveryTime(spellInfo) > 10 * MINUTE * IN_MILLISECONDS && !(spellInfo->AttributesEx4 & SPELL_ATTR_EX4_USABLE_IN_ARENA))) if (player && player->InArena()) return SPELL_FAILED_NOT_IN_ARENA; // Spell casted only on battleground if ((spellInfo->AttributesEx3 & SPELL_ATTR_EX3_BATTLEGROUND)) if (!player || !player->InBattleGround()) return SPELL_FAILED_ONLY_BATTLEGROUNDS; switch(spellInfo->Id) { // a trinket in alterac valley allows to teleport to the boss case 22564: // recall case 22563: // recall { if (!player) return SPELL_FAILED_REQUIRES_AREA; BattleGround* bg = player->GetBattleGround(); return map_id == 30 && bg && bg->GetStatus() != STATUS_WAIT_JOIN ? SPELL_CAST_OK : SPELL_FAILED_REQUIRES_AREA; } case 23333: // Warsong Flag case 23335: // Silverwing Flag return map_id == 489 && player && player->InBattleGround() ? SPELL_CAST_OK : SPELL_FAILED_REQUIRES_AREA; case 34976: // Netherstorm Flag return map_id == 566 && player && player->InBattleGround() ? SPELL_CAST_OK : SPELL_FAILED_REQUIRES_AREA; case 2584: // Waiting to Resurrect case 42792: // Recently Dropped Flag case 43681: // Inactive { return player && player->InBattleGround() ? SPELL_CAST_OK : SPELL_FAILED_ONLY_BATTLEGROUNDS; } case 22011: // Spirit Heal Channel case 22012: // Spirit Heal case 24171: // Resurrection Impact Visual case 44535: // Spirit Heal (mana) { MapEntry const* mapEntry = sMapStore.LookupEntry(map_id); if (!mapEntry) return SPELL_FAILED_INCORRECT_AREA; return mapEntry->IsBattleGround()? SPELL_CAST_OK : SPELL_FAILED_ONLY_BATTLEGROUNDS; } case 44521: // Preparation { if (!player) return SPELL_FAILED_REQUIRES_AREA; BattleGround* bg = player->GetBattleGround(); return bg && bg->GetStatus()==STATUS_WAIT_JOIN ? SPELL_CAST_OK : SPELL_FAILED_ONLY_BATTLEGROUNDS; } case 32724: // Gold Team (Alliance) case 32725: // Green Team (Alliance) case 35774: // Gold Team (Horde) case 35775: // Green Team (Horde) { return player && player->InArena() ? SPELL_CAST_OK : SPELL_FAILED_ONLY_IN_ARENA; } case 32727: // Arena Preparation { if (!player) return SPELL_FAILED_REQUIRES_AREA; if (!player->InArena()) return SPELL_FAILED_REQUIRES_AREA; BattleGround* bg = player->GetBattleGround(); return bg && bg->GetStatus()==STATUS_WAIT_JOIN ? SPELL_CAST_OK : SPELL_FAILED_ONLY_IN_ARENA; } case 74410: // Arena - Dampening return player && player->InArena() ? SPELL_CAST_OK : SPELL_FAILED_ONLY_IN_ARENA; case 74411: // Battleground - Dampening { if (!player) return SPELL_FAILED_ONLY_BATTLEGROUNDS; BattleGround* bg = player->GetBattleGround(); return bg && !bg->isArena() ? SPELL_CAST_OK : SPELL_FAILED_ONLY_BATTLEGROUNDS; } } return SPELL_CAST_OK; } void SpellMgr::LoadSkillLineAbilityMap() { mSkillLineAbilityMap.clear(); BarGoLink bar(sSkillLineAbilityStore.GetNumRows()); uint32 count = 0; for (uint32 i = 0; i < sSkillLineAbilityStore.GetNumRows(); ++i) { bar.step(); SkillLineAbilityEntry const *SkillInfo = sSkillLineAbilityStore.LookupEntry(i); if(!SkillInfo) continue; mSkillLineAbilityMap.insert(SkillLineAbilityMap::value_type(SkillInfo->spellId,SkillInfo)); ++count; } sLog.outString(); sLog.outString(">> Loaded %u SkillLineAbility MultiMap Data", count); } void SpellMgr::LoadSkillRaceClassInfoMap() { mSkillRaceClassInfoMap.clear(); BarGoLink bar(sSkillRaceClassInfoStore.GetNumRows()); uint32 count = 0; for (uint32 i = 0; i < sSkillRaceClassInfoStore.GetNumRows(); ++i) { bar.step(); SkillRaceClassInfoEntry const *skillRCInfo = sSkillRaceClassInfoStore.LookupEntry(i); if (!skillRCInfo) continue; // not all skills really listed in ability skills list if (!sSkillLineStore.LookupEntry(skillRCInfo->skillId)) continue; mSkillRaceClassInfoMap.insert(SkillRaceClassInfoMap::value_type(skillRCInfo->skillId,skillRCInfo)); ++count; } sLog.outString(); sLog.outString(">> Loaded %u SkillRaceClassInfo MultiMap Data", count); } void SpellMgr::CheckUsedSpells(char const* table) { uint32 countSpells = 0; uint32 countMasks = 0; // 0 1 2 3 4 5 6 7 8 9 10 11 QueryResult *result = WorldDatabase.PQuery("SELECT spellid,SpellFamilyName,SpellFamilyMaskA,SpellFamilyMaskB,SpellIcon,SpellVisual,SpellCategory,EffectType,EffectAura,EffectIdx,Name,Code FROM %s",table); if (!result) { BarGoLink bar(1); bar.step(); sLog.outString(); sLog.outErrorDb("`%s` table is empty!",table); return; } BarGoLink bar(result->GetRowCount()); do { Field *fields = result->Fetch(); bar.step(); uint32 spell = fields[0].GetUInt32(); int32 family = fields[1].GetInt32(); uint64 familyMaskA = fields[2].GetUInt64(); uint32 familyMaskB = fields[3].GetUInt32(); int32 spellIcon = fields[4].GetInt32(); int32 spellVisual = fields[5].GetInt32(); int32 category = fields[6].GetInt32(); int32 effectType = fields[7].GetInt32(); int32 auraType = fields[8].GetInt32(); int32 effectIdx = fields[9].GetInt32(); std::string name = fields[10].GetCppString(); std::string code = fields[11].GetCppString(); // checks of correctness requirements itself if (family < -1 || family > SPELLFAMILY_PET) { sLog.outError("Table '%s' for spell %u have wrong SpellFamily value(%u), skipped.",table,spell,family); continue; } // TODO: spellIcon check need dbc loading if (spellIcon < -1) { sLog.outError("Table '%s' for spell %u have wrong SpellIcon value(%u), skipped.",table,spell,spellIcon); continue; } // TODO: spellVisual check need dbc loading if (spellVisual < -1) { sLog.outError("Table '%s' for spell %u have wrong SpellVisual value(%u), skipped.",table,spell,spellVisual); continue; } // TODO: for spellCategory better check need dbc loading if (category < -1 || (category >=0 && sSpellCategoryStore.find(category) == sSpellCategoryStore.end())) { sLog.outError("Table '%s' for spell %u have wrong SpellCategory value(%u), skipped.",table,spell,category); continue; } if (effectType < -1 || effectType >= TOTAL_SPELL_EFFECTS) { sLog.outError("Table '%s' for spell %u have wrong SpellEffect type value(%u), skipped.",table,spell,effectType); continue; } if (auraType < -1 || auraType >= TOTAL_AURAS) { sLog.outError("Table '%s' for spell %u have wrong SpellAura type value(%u), skipped.",table,spell,auraType); continue; } if (effectIdx < -1 || effectIdx >= 3) { sLog.outError("Table '%s' for spell %u have wrong EffectIdx value(%u), skipped.",table,spell,effectIdx); continue; } // now checks of requirements if(spell) { ++countSpells; SpellEntry const* spellEntry = sSpellStore.LookupEntry(spell); if(!spellEntry) { sLog.outError("Spell %u '%s' not exist but used in %s.",spell,name.c_str(),code.c_str()); continue; } if (family >= 0 && spellEntry->SpellFamilyName != uint32(family)) { sLog.outError("Spell %u '%s' family(%u) <> %u but used in %s.",spell,name.c_str(),spellEntry->SpellFamilyName,family,code.c_str()); continue; } if(familyMaskA != UI64LIT(0xFFFFFFFFFFFFFFFF) || familyMaskB != 0xFFFFFFFF) { if(familyMaskA == UI64LIT(0x0000000000000000) && familyMaskB == 0x00000000) { if (spellEntry->SpellFamilyFlags) { sLog.outError("Spell %u '%s' not fit to (" I64FMT "," I32FMT ") but used in %s.", spell, name.c_str(), familyMaskA, familyMaskB, code.c_str()); continue; } } else { if (!spellEntry->IsFitToFamilyMask(familyMaskA, familyMaskB)) { sLog.outError("Spell %u '%s' not fit to (" I64FMT "," I32FMT ") but used in %s.",spell,name.c_str(),familyMaskA,familyMaskB,code.c_str()); continue; } } } if (spellIcon >= 0 && spellEntry->SpellIconID != uint32(spellIcon)) { sLog.outError("Spell %u '%s' icon(%u) <> %u but used in %s.",spell,name.c_str(),spellEntry->SpellIconID,spellIcon,code.c_str()); continue; } if (spellVisual >= 0 && spellEntry->SpellVisual[0] != uint32(spellVisual)) { sLog.outError("Spell %u '%s' visual(%u) <> %u but used in %s.",spell,name.c_str(),spellEntry->SpellVisual[0],spellVisual,code.c_str()); continue; } if (category >= 0 && spellEntry->Category != uint32(category)) { sLog.outError("Spell %u '%s' category(%u) <> %u but used in %s.",spell,name.c_str(),spellEntry->Category,category,code.c_str()); continue; } if (effectIdx >= EFFECT_INDEX_0) { if (effectType >= 0 && spellEntry->Effect[effectIdx] != uint32(effectType)) { sLog.outError("Spell %u '%s' effect%d <> %u but used in %s.",spell,name.c_str(),effectIdx+1,effectType,code.c_str()); continue; } if (auraType >= 0 && spellEntry->EffectApplyAuraName[effectIdx] != uint32(auraType)) { sLog.outError("Spell %u '%s' aura%d <> %u but used in %s.",spell,name.c_str(),effectIdx+1,auraType,code.c_str()); continue; } } else { if (effectType >= 0 && !IsSpellHaveEffect(spellEntry,SpellEffects(effectType))) { sLog.outError("Spell %u '%s' not have effect %u but used in %s.",spell,name.c_str(),effectType,code.c_str()); continue; } if (auraType >= 0 && !IsSpellHaveAura(spellEntry, AuraType(auraType))) { sLog.outError("Spell %u '%s' not have aura %u but used in %s.",spell,name.c_str(),auraType,code.c_str()); continue; } } } else { ++countMasks; bool found = false; for(uint32 spellId = 1; spellId < sSpellStore.GetNumRows(); ++spellId) { SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellId); if (!spellEntry) continue; if (family >=0 && spellEntry->SpellFamilyName != uint32(family)) continue; if (familyMaskA != UI64LIT(0xFFFFFFFFFFFFFFFF) || familyMaskB != 0xFFFFFFFF) { if(familyMaskA == UI64LIT(0x0000000000000000) && familyMaskB == 0x00000000) { if (spellEntry->SpellFamilyFlags) continue; } else { if (!spellEntry->IsFitToFamilyMask(familyMaskA, familyMaskB)) continue; } } if (spellIcon >= 0 && spellEntry->SpellIconID != uint32(spellIcon)) continue; if (spellVisual >= 0 && spellEntry->SpellVisual[0] != uint32(spellVisual)) continue; if (category >= 0 && spellEntry->Category != uint32(category)) continue; if (effectIdx >= 0) { if (effectType >=0 && spellEntry->Effect[effectIdx] != uint32(effectType)) continue; if (auraType >=0 && spellEntry->EffectApplyAuraName[effectIdx] != uint32(auraType)) continue; } else { if (effectType >=0 && !IsSpellHaveEffect(spellEntry,SpellEffects(effectType))) continue; if (auraType >=0 && !IsSpellHaveAura(spellEntry,AuraType(auraType))) continue; } found = true; break; } if (!found) { if (effectIdx >= 0) sLog.outError("Spells '%s' not found for family %i (" I64FMT "," I32FMT ") icon(%i) visual(%i) category(%i) effect%d(%i) aura%d(%i) but used in %s", name.c_str(),family,familyMaskA,familyMaskB,spellIcon,spellVisual,category,effectIdx+1,effectType,effectIdx+1,auraType,code.c_str()); else sLog.outError("Spells '%s' not found for family %i (" I64FMT "," I32FMT ") icon(%i) visual(%i) category(%i) effect(%i) aura(%i) but used in %s", name.c_str(),family,familyMaskA,familyMaskB,spellIcon,spellVisual,category,effectType,auraType,code.c_str()); continue; } } } while( result->NextRow() ); delete result; sLog.outString(); sLog.outString( ">> Checked %u spells and %u spell masks", countSpells, countMasks ); } DiminishingGroup GetDiminishingReturnsGroupForSpell(SpellEntry const* spellproto, bool triggered) { // Explicit Diminishing Groups switch(spellproto->SpellFamilyName) { case SPELLFAMILY_GENERIC: // some generic arena related spells have by some strange reason MECHANIC_TURN if (spellproto->Mechanic == MECHANIC_TURN) return DIMINISHING_NONE; break; case SPELLFAMILY_MAGE: // Dragon's Breath if (spellproto->SpellIconID == 1548) return DIMINISHING_DISORIENT; break; case SPELLFAMILY_ROGUE: { // Blind if (spellproto->IsFitToFamilyMask(UI64LIT(0x00001000000))) return DIMINISHING_FEAR_CHARM_BLIND; // Cheap Shot else if (spellproto->IsFitToFamilyMask(UI64LIT(0x00000000400))) return DIMINISHING_CHEAPSHOT_POUNCE; // Crippling poison - Limit to 10 seconds in PvP (No SpellFamilyFlags) else if (spellproto->SpellIconID == 163) return DIMINISHING_LIMITONLY; break; } case SPELLFAMILY_HUNTER: { // Freezing Trap & Freezing Arrow & Wyvern Sting if (spellproto->SpellIconID == 180 || spellproto->SpellIconID == 1721) return DIMINISHING_DISORIENT; break; } case SPELLFAMILY_WARLOCK: { // Curses/etc if (spellproto->IsFitToFamilyMask(UI64LIT(0x00080000000))) return DIMINISHING_LIMITONLY; break; } case SPELLFAMILY_PALADIN: { // Judgement of Justice - Limit to 10 seconds in PvP if (spellproto->IsFitToFamilyMask(UI64LIT(0x00000100000))) return DIMINISHING_LIMITONLY; break; } case SPELLFAMILY_DRUID: { // Cyclone if (spellproto->IsFitToFamilyMask(UI64LIT(0x02000000000))) return DIMINISHING_CYCLONE; // Pounce else if (spellproto->IsFitToFamilyMask(UI64LIT(0x00000020000))) return DIMINISHING_CHEAPSHOT_POUNCE; // Faerie Fire else if (spellproto->IsFitToFamilyMask(UI64LIT(0x00000000400))) return DIMINISHING_LIMITONLY; break; } case SPELLFAMILY_WARRIOR: { // Hamstring - limit duration to 10s in PvP if (spellproto->IsFitToFamilyMask(UI64LIT(0x00000000002))) return DIMINISHING_LIMITONLY; break; } case SPELLFAMILY_PRIEST: { // Shackle Undead if (spellproto->SpellIconID == 27) return DIMINISHING_DISORIENT; break; } case SPELLFAMILY_DEATHKNIGHT: { // Hungering Cold (no flags) if (spellproto->SpellIconID == 2797) return DIMINISHING_DISORIENT; break; } default: break; } // Get by mechanic uint32 mechanic = GetAllSpellMechanicMask(spellproto); if (!mechanic) return DIMINISHING_NONE; if (mechanic & ((1<<(MECHANIC_STUN-1))|(1<<(MECHANIC_SHACKLE-1)))) return triggered ? DIMINISHING_TRIGGER_STUN : DIMINISHING_CONTROL_STUN; if (mechanic & ((1<<(MECHANIC_SLEEP-1))|(1<<(MECHANIC_FREEZE-1)))) return DIMINISHING_FREEZE_SLEEP; if (mechanic & ((1<<(MECHANIC_KNOCKOUT-1))|(1<<(MECHANIC_POLYMORPH-1))|(1<<(MECHANIC_SAPPED-1)))) return DIMINISHING_DISORIENT; if (mechanic & (1<<(MECHANIC_ROOT-1))) return triggered ? DIMINISHING_TRIGGER_ROOT : DIMINISHING_CONTROL_ROOT; if (mechanic & ((1<<(MECHANIC_FEAR-1))|(1<<(MECHANIC_CHARM-1))|(1<<(MECHANIC_TURN-1)))) return DIMINISHING_FEAR_CHARM_BLIND; if (mechanic & ((1<<(MECHANIC_SILENCE-1))|(1<<(MECHANIC_INTERRUPT-1)))) return DIMINISHING_SILENCE; if (mechanic & (1<<(MECHANIC_DISARM-1))) return DIMINISHING_DISARM; if (mechanic & (1<<(MECHANIC_BANISH-1))) return DIMINISHING_BANISH; if (mechanic & (1<<(MECHANIC_HORROR-1))) return DIMINISHING_HORROR; return DIMINISHING_NONE; } int32 GetDiminishingReturnsLimitDuration(DiminishingGroup group, SpellEntry const* spellproto) { if(!IsDiminishingReturnsGroupDurationLimited(group)) return 0; // Explicit diminishing duration switch(spellproto->SpellFamilyName) { case SPELLFAMILY_HUNTER: { // Wyvern Sting if (spellproto->SpellFamilyFlags & UI64LIT(0x0000100000000000)) return 6000; break; } case SPELLFAMILY_PALADIN: { // Repentance - limit to 6 seconds in PvP if (spellproto->SpellFamilyFlags & UI64LIT(0x00000000004)) return 6000; break; } case SPELLFAMILY_DRUID: { // Faerie Fire - limit to 40 seconds in PvP (3.1) if (spellproto->SpellFamilyFlags & UI64LIT(0x00000000400)) return 40000; break; } default: break; } return 10000; } bool IsDiminishingReturnsGroupDurationLimited(DiminishingGroup group) { switch(group) { case DIMINISHING_CONTROL_STUN: case DIMINISHING_TRIGGER_STUN: case DIMINISHING_CONTROL_ROOT: case DIMINISHING_TRIGGER_ROOT: case DIMINISHING_FEAR_CHARM_BLIND: case DIMINISHING_DISORIENT: case DIMINISHING_CHEAPSHOT_POUNCE: case DIMINISHING_FREEZE_SLEEP: case DIMINISHING_CYCLONE: case DIMINISHING_BANISH: case DIMINISHING_LIMITONLY: return true; default: return false; } return false; } DiminishingReturnsType GetDiminishingReturnsGroupType(DiminishingGroup group) { switch(group) { case DIMINISHING_CYCLONE: case DIMINISHING_TRIGGER_STUN: case DIMINISHING_CONTROL_STUN: return DRTYPE_ALL; case DIMINISHING_CONTROL_ROOT: case DIMINISHING_TRIGGER_ROOT: case DIMINISHING_FEAR_CHARM_BLIND: case DIMINISHING_DISORIENT: case DIMINISHING_SILENCE: case DIMINISHING_DISARM: case DIMINISHING_HORROR: case DIMINISHING_FREEZE_SLEEP: case DIMINISHING_BANISH: case DIMINISHING_CHEAPSHOT_POUNCE: return DRTYPE_PLAYER; default: break; } return DRTYPE_NONE; } bool SpellArea::IsFitToRequirements(Player const* player, uint32 newZone, uint32 newArea) const { if(gender!=GENDER_NONE) { // not in expected gender if(!player || gender != player->getGender()) return false; } if(raceMask) { // not in expected race if(!player || !(raceMask & player->getRaceMask())) return false; } if(areaId) { // not in expected zone if(newZone!=areaId && newArea!=areaId) return false; } if(questStart) { // not in expected required quest state if(!player || (!questStartCanActive || !player->IsActiveQuest(questStart)) && !player->GetQuestRewardStatus(questStart)) return false; } if(questEnd) { // not in expected forbidden quest state if(!player || player->GetQuestRewardStatus(questEnd)) return false; } if(auraSpell) { // not have expected aura if(!player) return false; if(auraSpell > 0) // have expected aura return player->HasAura(auraSpell, EFFECT_INDEX_0); else // not have expected aura return !player->HasAura(-auraSpell, EFFECT_INDEX_0); } return true; } SpellEntry const* GetSpellEntryByDifficulty(uint32 id, Difficulty difficulty, bool isRaid) { SpellDifficultyEntry const* spellDiff = sSpellDifficultyStore.LookupEntry(id); if (!spellDiff) return NULL; for (Difficulty diff = difficulty; diff >= REGULAR_DIFFICULTY; diff = GetPrevDifficulty(diff, isRaid)) { if (spellDiff->spellId[diff]) return sSpellStore.LookupEntry(spellDiff->spellId[diff]); } return NULL; }
fgenesis/mangos
src/game/SpellMgr.cpp
C++
gpl-2.0
188,760
package mattparks.mods.space.venus.entities; import mattparks.mods.space.venus.items.GCVenusItems; import micdoodle8.mods.galacticraft.api.entity.IEntityBreathable; import net.minecraft.entity.Entity; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.monster.EntityMob; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.projectile.EntitySmallFireball; import net.minecraft.util.DamageSource; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class GCVenusEntityEvolvedBlaze extends EntityMob implements IEntityBreathable { private float heightOffset = 0.5F; private int heightOffsetUpdateTime; private int field_70846_g; public GCVenusEntityEvolvedBlaze(World par1World) { super(par1World); this.isImmuneToFire = true; this.experienceValue = 10; } @Override protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setAttribute(6.0D); } @Override protected void attackEntity(Entity par1Entity, float par2) { if (this.attackTime <= 0 && par2 < 2.0F && par1Entity.boundingBox.maxY > this.boundingBox.minY && par1Entity.boundingBox.minY < this.boundingBox.maxY) { this.attackTime = 20; this.attackEntityAsMob(par1Entity); } else if (par2 < 30.0F) { double d0 = par1Entity.posX - this.posX; double d1 = par1Entity.boundingBox.minY + par1Entity.height / 2.0F - (this.posY + this.height / 2.0F); double d2 = par1Entity.posZ - this.posZ; if (this.attackTime == 0) { ++this.field_70846_g; if (this.field_70846_g == 1) { this.attackTime = 60; this.func_70844_e(true); } else if (this.field_70846_g <= 4) { this.attackTime = 6; } else { this.attackTime = 100; this.field_70846_g = 0; this.func_70844_e(false); } if (this.field_70846_g > 1) { float f1 = MathHelper.sqrt_float(par2) * 0.5F; this.worldObj.playAuxSFXAtEntity((EntityPlayer)null, 1009, (int)this.posX, (int)this.posY, (int)this.posZ, 0); for (int i = 0; i < 1; ++i) { EntitySmallFireball entitysmallfireball = new EntitySmallFireball(this.worldObj, this, d0 + this.rand.nextGaussian() * f1, d1, d2 + this.rand.nextGaussian() * f1); entitysmallfireball.posY = this.posY + this.height / 2.0F + 0.5D; this.worldObj.spawnEntityInWorld(entitysmallfireball); } } } this.rotationYaw = (float)(Math.atan2(d2, d0) * 180.0D / Math.PI) - 90.0F; this.hasAttacked = true; } } @Override public boolean canBreath() { return true; } @Override protected void dropFewItems(boolean par1, int par2) { if (par1) { int j = this.rand.nextInt(2 + par2); for (int k = 0; k < j; ++k) { this.dropItem(GCVenusItems.venusRod.itemID, 1); } } } @Override protected void entityInit() { super.entityInit(); this.dataWatcher.addObject(16, new Byte((byte)0)); } @Override protected void fall(float par1) {} public void func_70844_e(boolean par1) { byte b0 = this.dataWatcher.getWatchableObjectByte(16); if (par1) { b0 = (byte)(b0 | 1); } else { b0 &= -2; } this.dataWatcher.updateObject(16, Byte.valueOf(b0)); } public boolean func_70845_n() { return (this.dataWatcher.getWatchableObjectByte(16) & 1) != 0; } @Override public float getBrightness(float par1) { return 1.0F; } @Override @SideOnly(Side.CLIENT) public int getBrightnessForRender(float par1) { return 15728880; } @Override protected String getDeathSound() { return "mob.blaze.death"; } @Override protected int getDropItemId() { return GCVenusItems.venusRod.itemID; } @Override protected String getHurtSound() { return "mob.blaze.hit"; } @Override protected String getLivingSound() { return "mob.blaze.breathe"; } @Override public boolean isBurning() { return this.func_70845_n(); } @Override protected boolean isValidLightLevel() { return true; } @Override public void onLivingUpdate() { if (!this.worldObj.isRemote) { if (this.isWet()) { this.attackEntityFrom(DamageSource.drown, 1.0F); } --this.heightOffsetUpdateTime; if (this.heightOffsetUpdateTime <= 0) { this.heightOffsetUpdateTime = 100; this.heightOffset = 0.5F + (float)this.rand.nextGaussian() * 3.0F; } if (this.getEntityToAttack() != null && this.getEntityToAttack().posY + this.getEntityToAttack().getEyeHeight() > this.posY + this.getEyeHeight() + this.heightOffset) { this.motionY += (0.30000001192092896D - this.motionY) * 0.30000001192092896D; } } if (this.rand.nextInt(24) == 0) { this.worldObj.playSoundEffect(this.posX + 0.5D, this.posY + 0.5D, this.posZ + 0.5D, "fire.fire", 1.0F + this.rand.nextFloat(), this.rand.nextFloat() * 0.7F + 0.3F); } if (!this.onGround && this.motionY < 0.0D) { this.motionY *= 0.6D; } for (int i = 0; i < 2; ++i) { this.worldObj.spawnParticle("largesmoke", this.posX + (this.rand.nextDouble() - 0.5D) * this.width, this.posY + this.rand.nextDouble() * this.height, this.posZ + (this.rand.nextDouble() - 0.5D) * this.width, 0.0D, 0.0D, 0.0D); } super.onLivingUpdate(); } }
4Space/4-Space-1.6.4
common/mattparks/mods/space/venus/entities/GCVenusEntityEvolvedBlaze.java
Java
gpl-2.0
6,459
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark 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. * * The Benchmark 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 * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest15221") public class BenchmarkTest15221 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = request.getHeader("foo"); String bar = doSomething(param); try { float rand = java.security.SecureRandom.getInstance("SHA1PRNG").nextFloat(); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("Problem executing SecureRandom.nextFloat() - TestCase"); throw new ServletException(e); } response.getWriter().println("Weak Randomness Test java.security.SecureRandom.nextFloat() executed"); } // end doPost private static String doSomething(String param) throws ServletException, IOException { String bar = "safe!"; java.util.HashMap<String,Object> map33682 = new java.util.HashMap<String,Object>(); map33682.put("keyA-33682", "a_Value"); // put some stuff in the collection map33682.put("keyB-33682", param.toString()); // put it in a collection map33682.put("keyC", "another_Value"); // put some stuff in the collection bar = (String)map33682.get("keyB-33682"); // get it back out bar = (String)map33682.get("keyA-33682"); // get safe value back out return bar; } }
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest15221.java
Java
gpl-2.0
2,564
<?php require_once dirname(__FILE__) . '/Reviews.php'; class Sabai_Addon_Directory_Controller_UserReviews extends Sabai_Addon_Directory_Controller_Reviews { protected function _createQuery(Sabai_Context $context, $sort, Sabai_Addon_Entity_Model_Bundle $bundle = null) { return parent::_createQuery($context, $sort, $bundle) ->propertyIs('post_user_id', $context->identity->id); } }
ssxenon01/mm
resources/plugins/sabai-directory/lib/Directory/Controller/UserReviews.php
PHP
gpl-2.0
418
/* * 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 */ /* * ServerMessenger.java * * Created on December 11, 2001, 7:43 PM */ package games.strategy.net; import games.strategy.engine.chat.ChatController; import games.strategy.engine.chat.IChatChannel; import games.strategy.engine.lobby.server.login.LobbyLoginValidator; import games.strategy.engine.lobby.server.userDB.MutedIpController; import games.strategy.engine.lobby.server.userDB.MutedMacController; import games.strategy.engine.lobby.server.userDB.MutedUsernameController; import games.strategy.engine.message.HubInvoke; import games.strategy.engine.message.RemoteMethodCall; import games.strategy.engine.message.RemoteName; import games.strategy.engine.message.SpokeInvoke; import games.strategy.net.nio.NIOSocket; import games.strategy.net.nio.NIOSocketListener; import games.strategy.net.nio.QuarantineConversation; import games.strategy.net.nio.ServerQuarantineConversation; import java.io.IOException; import java.io.Serializable; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.channels.ClosedChannelException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import java.util.logging.Logger; /** * A Messenger that can have many clients connected to it. * * @author Sean Bridges * @version 1.0 */ public class ServerMessenger implements IServerMessenger, NIOSocketListener { private static Logger s_logger = Logger.getLogger(ServerMessenger.class.getName()); private final Selector m_acceptorSelector; private final ServerSocketChannel m_socketChannel; private final Node m_node; private boolean m_shutdown = false; private final NIOSocket m_nioSocket; private final CopyOnWriteArrayList<IMessageListener> m_listeners = new CopyOnWriteArrayList<IMessageListener>(); private final CopyOnWriteArrayList<IMessengerErrorListener> m_errorListeners = new CopyOnWriteArrayList<IMessengerErrorListener>(); private final CopyOnWriteArrayList<IConnectionChangeListener> m_connectionListeners = new CopyOnWriteArrayList<IConnectionChangeListener>(); private boolean m_acceptNewConnection = false; private ILoginValidator m_loginValidator; // all our nodes private final ConcurrentHashMap<INode, SocketChannel> m_nodeToChannel = new ConcurrentHashMap<INode, SocketChannel>(); private final ConcurrentHashMap<SocketChannel, INode> m_channelToNode = new ConcurrentHashMap<SocketChannel, INode>(); // A hack, till I think of something better public ServerMessenger(final String name, final int portNumber, final IObjectStreamFactory streamFactory) throws IOException { m_socketChannel = ServerSocketChannel.open(); m_socketChannel.configureBlocking(false); m_socketChannel.socket().setReuseAddress(true); m_socketChannel.socket().bind(new InetSocketAddress(portNumber), 10); m_nioSocket = new NIOSocket(streamFactory, this, "Server"); m_acceptorSelector = Selector.open(); if (IPFinder.findInetAddress() != null) m_node = new Node(name, IPFinder.findInetAddress(), portNumber); else m_node = new Node(name, InetAddress.getLocalHost(), portNumber); final Thread t = new Thread(new ConnectionHandler(), "Server Messenger Connection Handler"); t.start(); } public void setLoginValidator(final ILoginValidator loginValidator) { m_loginValidator = loginValidator; } public ILoginValidator getLoginValidator() { return m_loginValidator; } /** Creates new ServerMessenger */ public ServerMessenger(final String name, final int portNumber) throws IOException { this(name, portNumber, new DefaultObjectStreamFactory()); } /* * @see IMessenger#addMessageListener(Class, IMessageListener) */ public void addMessageListener(final IMessageListener listener) { m_listeners.add(listener); } /* * @see IMessenger#removeMessageListener(Class, IMessageListener) */ public void removeMessageListener(final IMessageListener listener) { m_listeners.remove(listener); } /** * Get a list of nodes. */ public Set<INode> getNodes() { final Set<INode> rVal = new HashSet<INode>(m_nodeToChannel.keySet()); rVal.add(m_node); return rVal; } public synchronized void shutDown() { if (!m_shutdown) { m_shutdown = true; m_nioSocket.shutDown(); try { m_socketChannel.close(); } catch (final Exception e) { // ignore } if (m_acceptorSelector != null) m_acceptorSelector.wakeup(); } } public synchronized boolean isShutDown() { return m_shutdown; } public boolean isConnected() { return !m_shutdown; } /** * Send a message to the given node. */ public void send(final Serializable msg, final INode to) { if (m_shutdown) return; if (s_logger.isLoggable(Level.FINEST)) { s_logger.log(Level.FINEST, "Sending" + msg + " to:" + to); } final MessageHeader header = new MessageHeader(to, m_node, msg); final SocketChannel socketChannel = m_nodeToChannel.get(to); // the socket was removed if (socketChannel == null) { if (s_logger.isLoggable(Level.FINER)) { s_logger.log(Level.FINER, "no channel for node:" + to + " dropping message:" + msg); } // the socket has not been added yet return; } m_nioSocket.send(socketChannel, header); } /** * Send a message to all nodes. */ public void broadcast(final Serializable msg) { final MessageHeader header = new MessageHeader(m_node, msg); forwardBroadcast(header); } private boolean isLobby() { return m_loginValidator instanceof LobbyLoginValidator; } private boolean isGame() { return !isLobby(); } private final Object m_cachedListLock = new Object(); private final HashMap<String, String> m_cachedMacAddresses = new HashMap<String, String>(); public String GetPlayerMac(final String name) { synchronized (m_cachedListLock) { String mac = m_cachedMacAddresses.get(name); if (mac == null) mac = m_playersThatLeftMacs_Last10.get(name); return mac; } } // We need to cache whether players are muted, because otherwise the database would have to be accessed each time a message was sent, which can be very slow private final List<String> m_liveMutedUsernames = new ArrayList<String>(); public boolean IsUsernameMuted(final String username) { synchronized (m_cachedListLock) { return m_liveMutedUsernames.contains(username); } } public void NotifyUsernameMutingOfPlayer(final String username, final Date muteExpires) { synchronized (m_cachedListLock) { if (!m_liveMutedUsernames.contains(username)) m_liveMutedUsernames.add(username); if (muteExpires != null) ScheduleUsernameUnmuteAt(username, muteExpires.getTime()); } } private final List<String> m_liveMutedIpAddresses = new ArrayList<String>(); public boolean IsIpMuted(final String ip) { synchronized (m_cachedListLock) { return m_liveMutedIpAddresses.contains(ip); } } public void NotifyIPMutingOfPlayer(final String ip, final Date muteExpires) { synchronized (m_cachedListLock) { if (!m_liveMutedIpAddresses.contains(ip)) m_liveMutedIpAddresses.add(ip); if (muteExpires != null) ScheduleIpUnmuteAt(ip, muteExpires.getTime()); } } private final List<String> m_liveMutedMacAddresses = new ArrayList<String>(); public boolean IsMacMuted(final String mac) { synchronized (m_cachedListLock) { return m_liveMutedMacAddresses.contains(mac); } } public void NotifyMacMutingOfPlayer(final String mac, final Date muteExpires) { synchronized (m_cachedListLock) { if (!m_liveMutedMacAddresses.contains(mac)) m_liveMutedMacAddresses.add(mac); if (muteExpires != null) ScheduleMacUnmuteAt(mac, muteExpires.getTime()); } } private void ScheduleUsernameUnmuteAt(final String username, final long checkTime) { final Timer unmuteUsernameTimer = new Timer("Username unmute timer"); unmuteUsernameTimer.schedule(GetUsernameUnmuteTask(username), new Date(checkTime)); } private void ScheduleIpUnmuteAt(final String ip, final long checkTime) { final Timer unmuteIpTimer = new Timer("IP unmute timer"); unmuteIpTimer.schedule(GetIpUnmuteTask(ip), new Date(checkTime)); } private void ScheduleMacUnmuteAt(final String mac, final long checkTime) { final Timer unmuteMacTimer = new Timer("Mac unmute timer"); unmuteMacTimer.schedule(GetMacUnmuteTask(mac), new Date(checkTime)); } public void NotifyPlayerLogin(final String uniquePlayerName, final String ip, final String mac) { synchronized (m_cachedListLock) { m_cachedMacAddresses.put(uniquePlayerName, mac); if (isLobby()) { final String realName = uniquePlayerName.split(" ")[0]; if (!m_liveMutedUsernames.contains(realName)) { final long muteTill = new MutedUsernameController().getUsernameUnmuteTime(realName); if (muteTill != -1 && muteTill <= System.currentTimeMillis()) { m_liveMutedUsernames.add(realName); // Signal the player as muted ScheduleUsernameUnmuteAt(realName, muteTill); } } if (!m_liveMutedIpAddresses.contains(ip)) { final long muteTill = new MutedIpController().getIpUnmuteTime(ip); if (muteTill != -1 && muteTill <= System.currentTimeMillis()) { m_liveMutedIpAddresses.add(ip); // Signal the player as muted ScheduleIpUnmuteAt(ip, muteTill); } } if (!m_liveMutedMacAddresses.contains(mac)) { final long muteTill = new MutedMacController().getMacUnmuteTime(mac); if (muteTill != -1 && muteTill <= System.currentTimeMillis()) { m_liveMutedMacAddresses.add(mac); // Signal the player as muted ScheduleMacUnmuteAt(mac, muteTill); } } } } } private final HashMap<String, String> m_playersThatLeftMacs_Last10 = new HashMap<String, String>(); public HashMap<String, String> GetPlayersThatLeftMacs_Last10() { return m_playersThatLeftMacs_Last10; } private void NotifyPlayerRemoval(final INode node) { synchronized (m_cachedListLock) { m_playersThatLeftMacs_Last10.put(node.getName(), m_cachedMacAddresses.get(node.getName())); if (m_playersThatLeftMacs_Last10.size() > 10) m_playersThatLeftMacs_Last10.remove(m_playersThatLeftMacs_Last10.entrySet().iterator().next().toString()); m_cachedMacAddresses.remove(node.getName()); } } public static final String YOU_HAVE_BEEN_MUTED_LOBBY = "?YOUR LOBBY CHATTING HAS BEEN TEMPORARILY 'MUTED' BY THE ADMINS, TRY AGAIN LATER"; // Special character to stop spoofing by server public static final String YOU_HAVE_BEEN_MUTED_GAME = "?YOUR CHATTING IN THIS GAME HAS BEEN 'MUTED' BY THE HOST"; // Special character to stop spoofing by host public void messageReceived(final MessageHeader msg, final SocketChannel channel) { final INode expectedReceive = m_channelToNode.get(channel); if (!expectedReceive.equals(msg.getFrom())) { throw new IllegalStateException("Expected: " + expectedReceive + " not: " + msg.getFrom()); } if (msg.getMessage() instanceof HubInvoke) // Chat messages are always HubInvoke's { if (isLobby() && ((HubInvoke) msg.getMessage()).call.getRemoteName().equals("_ChatCtrl_LOBBY_CHAT")) { final String realName = msg.getFrom().getName().split(" ")[0]; if (IsUsernameMuted(realName)) { bareBonesSendChatMessage(YOU_HAVE_BEEN_MUTED_LOBBY, msg.getFrom()); return; } else if (IsIpMuted(msg.getFrom().getAddress().getHostAddress())) { bareBonesSendChatMessage(YOU_HAVE_BEEN_MUTED_LOBBY, msg.getFrom()); return; } else if (IsMacMuted(GetPlayerMac(msg.getFrom().getName()))) { bareBonesSendChatMessage(YOU_HAVE_BEEN_MUTED_LOBBY, msg.getFrom()); return; } } else if (isGame() && ((HubInvoke) msg.getMessage()).call.getRemoteName().equals("_ChatCtrlgames.strategy.engine.framework.ui.ServerStartup.CHAT_NAME")) { final String realName = msg.getFrom().getName().split(" ")[0]; if (IsUsernameMuted(realName)) { bareBonesSendChatMessage(YOU_HAVE_BEEN_MUTED_GAME, msg.getFrom()); return; } else if (IsIpMuted(msg.getFrom().getAddress().getHostAddress())) { bareBonesSendChatMessage(YOU_HAVE_BEEN_MUTED_GAME, msg.getFrom()); return; } if (IsMacMuted(GetPlayerMac(msg.getFrom().getName()))) { bareBonesSendChatMessage(YOU_HAVE_BEEN_MUTED_GAME, msg.getFrom()); return; } } } if (msg.getFor() == null) { forwardBroadcast(msg); notifyListeners(msg); } else if (msg.getFor().equals(m_node)) { notifyListeners(msg); } else { forward(msg); } } private void bareBonesSendChatMessage(final String message, final INode to) { final List<Object> args = new ArrayList<Object>(); final Class[] argTypes = new Class[1]; args.add(message); argTypes[0] = args.get(0).getClass(); RemoteName rn; if (isLobby()) rn = new RemoteName(ChatController.getChatChannelName("_LOBBY_CHAT"), IChatChannel.class); else rn = new RemoteName(ChatController.getChatChannelName("games.strategy.engine.framework.ui.ServerStartup.CHAT_NAME"), IChatChannel.class); final RemoteMethodCall call = new RemoteMethodCall(rn.getName(), "chatOccured", args.toArray(), argTypes, rn.getClazz()); final SpokeInvoke spokeInvoke = new SpokeInvoke(null, false, call, getServerNode()); send(spokeInvoke, to); } // The following code is used in hosted lobby games by the host for player mini-banning and mini-muting private final List<String> m_miniBannedUsernames = new ArrayList<String>(); public boolean IsUsernameMiniBanned(final String username) { synchronized (m_cachedListLock) { return m_miniBannedUsernames.contains(username); } } public void NotifyUsernameMiniBanningOfPlayer(final String username, final Date expires) { synchronized (m_cachedListLock) { if (!m_miniBannedUsernames.contains(username)) m_miniBannedUsernames.add(username); if (expires != null) { final Timer unbanUsernameTimer = new Timer("Username unban timer"); unbanUsernameTimer.schedule(new TimerTask() { @Override public void run() { synchronized (m_cachedListLock) { m_miniBannedUsernames.remove(username); } } }, new Date(expires.getTime())); } } } private final List<String> m_miniBannedIpAddresses = new ArrayList<String>(); public boolean IsIpMiniBanned(final String ip) { synchronized (m_cachedListLock) { return m_miniBannedIpAddresses.contains(ip); } } public void NotifyIPMiniBanningOfPlayer(final String ip, final Date expires) { synchronized (m_cachedListLock) { if (!m_miniBannedIpAddresses.contains(ip)) m_miniBannedIpAddresses.add(ip); if (expires != null) { final Timer unbanIpTimer = new Timer("IP unban timer"); unbanIpTimer.schedule(new TimerTask() { @Override public void run() { synchronized (m_cachedListLock) { m_miniBannedIpAddresses.remove(ip); } } }, new Date(expires.getTime())); } } } private final List<String> m_miniBannedMacAddresses = new ArrayList<String>(); public boolean IsMacMiniBanned(final String mac) { synchronized (m_cachedListLock) { return m_miniBannedMacAddresses.contains(mac); } } public void NotifyMacMiniBanningOfPlayer(final String mac, final Date expires) { synchronized (m_cachedListLock) { if (!m_miniBannedMacAddresses.contains(mac)) m_miniBannedMacAddresses.add(mac); if (expires != null) { final Timer unbanMacTimer = new Timer("Mac unban timer"); unbanMacTimer.schedule(new TimerTask() { @Override public void run() { synchronized (m_cachedListLock) { m_miniBannedMacAddresses.remove(mac); } } }, new Date(expires.getTime())); } } } private void forward(final MessageHeader msg) { if (m_shutdown) return; final SocketChannel socketChannel = m_nodeToChannel.get(msg.getFor()); if (socketChannel == null) throw new IllegalStateException("No channel for:" + msg.getFor() + " all channels:" + socketChannel); m_nioSocket.send(socketChannel, msg); } private void forwardBroadcast(final MessageHeader msg) { if (m_shutdown) return; final SocketChannel fromChannel = m_nodeToChannel.get(msg.getFrom()); final List<SocketChannel> nodes = new ArrayList<SocketChannel>(m_nodeToChannel.values()); if (s_logger.isLoggable(Level.FINEST)) { s_logger.log(Level.FINEST, "broadcasting to" + nodes); } for (final SocketChannel channel : nodes) { if (channel != fromChannel) m_nioSocket.send(channel, msg); } } private boolean isNameTaken(final String nodeName) { for (final INode node : getNodes()) { if (node.getName().equalsIgnoreCase(nodeName)) return true; } return false; } public String getUniqueName(String currentName) { if (currentName.length() > 50) { currentName = currentName.substring(0, 50); } if (currentName.length() < 2) { currentName = "aa" + currentName; } synchronized (m_node) { if (isNameTaken(currentName)) { int i = 1; while (true) { final String newName = currentName + " (" + i + ")"; if (!isNameTaken(newName)) { currentName = newName; break; } i++; } } } return currentName; } private void notifyListeners(final MessageHeader msg) { final Iterator<IMessageListener> iter = m_listeners.iterator(); while (iter.hasNext()) { final IMessageListener listener = iter.next(); listener.messageReceived(msg.getMessage(), msg.getFrom()); } } public void addErrorListener(final IMessengerErrorListener listener) { m_errorListeners.add(listener); } public void removeErrorListener(final IMessengerErrorListener listener) { m_errorListeners.remove(listener); } public void addConnectionChangeListener(final IConnectionChangeListener listener) { m_connectionListeners.add(listener); } public void removeConnectionChangeListener(final IConnectionChangeListener listener) { m_connectionListeners.remove(listener); } private void notifyConnectionsChanged(final boolean added, final INode node) { final Iterator<IConnectionChangeListener> iter = m_connectionListeners.iterator(); while (iter.hasNext()) { if (added) { iter.next().connectionAdded(node); } else { iter.next().connectionRemoved(node); } } } public void setAcceptNewConnections(final boolean accept) { m_acceptNewConnection = accept; } public boolean isAcceptNewConnections() { return m_acceptNewConnection; } /** * Get the local node */ public INode getLocalNode() { return m_node; } private class ConnectionHandler implements Runnable { public void run() { try { m_socketChannel.register(m_acceptorSelector, SelectionKey.OP_ACCEPT); } catch (final ClosedChannelException e) { s_logger.log(Level.SEVERE, "socket closed", e); shutDown(); } while (!m_shutdown) { try { m_acceptorSelector.select(); } catch (final IOException e) { s_logger.log(Level.SEVERE, "Could not accept on server", e); shutDown(); } if (m_shutdown) continue; final Set<SelectionKey> keys = m_acceptorSelector.selectedKeys(); final Iterator<SelectionKey> iter = keys.iterator(); while (iter.hasNext()) { final SelectionKey key = iter.next(); iter.remove(); if (key.isAcceptable() && key.isValid()) { final ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); // Accept the connection and make it non-blocking SocketChannel socketChannel = null; try { socketChannel = serverSocketChannel.accept(); if (socketChannel == null) { continue; } socketChannel.configureBlocking(false); socketChannel.socket().setKeepAlive(true); } catch (final IOException e) { s_logger.log(Level.FINE, "Could not accept channel", e); try { if (socketChannel != null) socketChannel.close(); } catch (final IOException e2) { s_logger.log(Level.FINE, "Could not close channel", e2); } continue; } // we are not accepting connections if (!m_acceptNewConnection) { try { socketChannel.close(); } catch (final IOException e) { s_logger.log(Level.FINE, "Could not close channel", e); } continue; } final ServerQuarantineConversation conversation = new ServerQuarantineConversation(m_loginValidator, socketChannel, m_nioSocket, ServerMessenger.this); m_nioSocket.add(socketChannel, conversation); } else if (!key.isValid()) { key.cancel(); } } } } } private TimerTask GetUsernameUnmuteTask(final String username) { return new TimerTask() { @Override public void run() { // lobby has a database we need to check, normal hosted games do not if ((isLobby() && new MutedUsernameController().getUsernameUnmuteTime(username) == -1) || (isGame())) // If the mute has expired { synchronized (m_cachedListLock) { m_liveMutedUsernames.remove(username); // Remove the username from the list of live username's muted } } } }; } private TimerTask GetIpUnmuteTask(final String ip) { return new TimerTask() { @Override public void run() { // lobby has a database we need to check, normal hosted games do not if ((isLobby() && new MutedIpController().getIpUnmuteTime(ip) == -1) || (isGame())) // If the mute has expired { synchronized (m_cachedListLock) { m_liveMutedIpAddresses.remove(ip); // Remove the ip from the list of live ip's muted } } } }; } private TimerTask GetMacUnmuteTask(final String mac) { return new TimerTask() { @Override public void run() { // lobby has a database we need to check, normal hosted games do not if ((isLobby() && new MutedMacController().getMacUnmuteTime(mac) == -1) || (isGame())) // If the mute has expired { synchronized (m_cachedListLock) { m_liveMutedMacAddresses.remove(mac); // Remove the mac from the list of live mac's muted } } } }; } public boolean isServer() { return true; } public void removeConnection(final INode node) { if (node.equals(m_node)) throw new IllegalArgumentException("Cant remove ourself!"); NotifyPlayerRemoval(node); SocketChannel channel = m_nodeToChannel.remove(node); if (channel == null) { channel = m_nodeToChannel.remove(node); } if (channel == null) { s_logger.info("Could not remove connection to node:" + node); return; } m_channelToNode.remove(channel); m_nioSocket.close(channel); notifyConnectionsChanged(false, node); s_logger.info("Connection removed:" + node); } public INode getServerNode() { return m_node; } public void socketError(final SocketChannel channel, final Exception error) { if (channel == null) throw new IllegalArgumentException("Null channel"); // already closed, dont report it again final INode node = m_channelToNode.get(channel); if (node != null) removeConnection(node); } public void socketUnqaurantined(final SocketChannel channel, final QuarantineConversation conversation) { final ServerQuarantineConversation con = (ServerQuarantineConversation) conversation; final INode remote = new Node(con.getRemoteName(), (InetSocketAddress) channel.socket().getRemoteSocketAddress()); if (s_logger.isLoggable(Level.FINER)) { s_logger.log(Level.FINER, "Unquarntined node:" + remote); } m_nodeToChannel.put(remote, channel); m_channelToNode.put(channel, remote); notifyConnectionsChanged(true, remote); s_logger.info("Connection added to:" + remote); } public INode getRemoteNode(final SocketChannel channel) { return m_channelToNode.get(channel); } public InetSocketAddress getRemoteServerSocketAddress() { return m_node.getSocketAddress(); } @Override public String toString() { return "ServerMessenger LocalNode:" + m_node + " ClientNodes:" + m_nodeToChannel.keySet(); } }
tea-dragon/triplea
src/main/java/games/strategy/net/ServerMessenger.java
Java
gpl-2.0
25,312
// This file is part of Agros2D. // // Agros2D 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. // // Agros2D 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 Agros2D. If not, see <http://www.gnu.org/licenses/>. // // hp-FEM group (http://hpfem.org/) // University of Nevada, Reno (UNR) and University of West Bohemia, Pilsen // Email: agros2d@googlegroups.com, home page: http://hpfem.org/agros2d/ #include "localvalueview.h" #include "scene.h" LocalPointValue::LocalPointValue(Point &point) { this->point = point; PointValue val = pointValue(Util::scene()->sceneSolution()->sln(), point); value = val.value; derivative = val.derivative; labelMarker = val.marker; } PointValue LocalPointValue::pointValue(Solution *sln, Point &point) { double tmpValue; Point tmpDerivative; SceneLabelMarker *tmpLabelMarker = NULL; if (sln) { int index = Util::scene()->sceneSolution()->findTriangleInMesh(Util::scene()->sceneSolution()->meshInitial(), point); if (index != -1) { if ((Util::scene()->problemInfo()->analysisType == AnalysisType_Transient) && Util::scene()->sceneSolution()->timeStep() == 0) // const solution at first time step tmpValue = Util::scene()->problemInfo()->initialCondition.number; else tmpValue = sln->get_pt_value(point.x, point.y, H2D_FN_VAL_0); if (Util::scene()->problemInfo()->physicField() != PhysicField_Elasticity) { tmpDerivative.x = sln->get_pt_value(point.x, point.y, H2D_FN_DX_0); tmpDerivative.y = sln->get_pt_value(point.x, point.y, H2D_FN_DY_0); } // find marker Element *element = Util::scene()->sceneSolution()->meshInitial()->get_element_fast(index); tmpLabelMarker = Util::scene()->labels[element->marker]->marker; } } return PointValue(tmpValue, tmpDerivative, tmpLabelMarker); } // ************************************************************************************************************************************* LocalPointValueView::LocalPointValueView(QWidget *parent): QDockWidget(tr("Local Values"), parent) { QSettings settings; setMinimumWidth(280); setObjectName("LocalPointValueView"); createActions(); createMenu(); trvWidget = new QTreeWidget(); trvWidget->setHeaderHidden(false); trvWidget->setContextMenuPolicy(Qt::CustomContextMenu); trvWidget->setMouseTracking(true); trvWidget->setColumnCount(3); trvWidget->setColumnWidth(0, settings.value("LocalPointValueView/TreeViewColumn0", 150).value<int>()); trvWidget->setColumnWidth(1, settings.value("LocalPointValueView/TreeViewColumn1", 80).value<int>()); trvWidget->setIndentation(12); QStringList labels; labels << tr("Label") << tr("Value") << tr("Unit"); trvWidget->setHeaderLabels(labels); connect(trvWidget, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(doContextMenu(const QPoint &))); QPushButton *btnPoint = new QPushButton(); btnPoint->setText(actPoint->text()); btnPoint->setIcon(actPoint->icon()); btnPoint->setMaximumSize(btnPoint->sizeHint()); connect(btnPoint, SIGNAL(clicked()), this, SLOT(doPoint())); // main widget QVBoxLayout *layout = new QVBoxLayout(); layout->addWidget(trvWidget); layout->addWidget(btnPoint); layout->setContentsMargins(0, 0, 0, 7); QWidget *widget = new QWidget(this); widget->setLayout(layout); setWidget(widget); } LocalPointValueView::~LocalPointValueView() { QSettings settings; settings.setValue("LocalPointValueView/TreeViewColumn0", trvWidget->columnWidth(0)); settings.setValue("LocalPointValueView/TreeViewColumn1", trvWidget->columnWidth(1)); } void LocalPointValueView::createActions() { // point actPoint = new QAction(icon("scene-node"), tr("Local point value"), this); connect(actPoint, SIGNAL(triggered()), this, SLOT(doPoint())); // copy value actCopy = new QAction(icon(""), tr("Copy value"), this); connect(actCopy, SIGNAL(triggered()), this, SLOT(doCopyValue())); } void LocalPointValueView::createMenu() { mnuInfo = new QMenu(this); mnuInfo->addAction(actPoint); mnuInfo->addAction(actCopy); } void LocalPointValueView::doPoint() { LocalPointValueDialog localPointValueDialog(point); if (localPointValueDialog.exec() == QDialog::Accepted) { doShowPoint(localPointValueDialog.point()); } } void LocalPointValueView::doContextMenu(const QPoint &pos) { actCopy->setEnabled(false); QTreeWidgetItem *item = trvWidget->itemAt(pos); if (item) if (!item->text(1).isEmpty()) { trvWidget->setCurrentItem(item); actCopy->setEnabled(true); } mnuInfo->exec(QCursor::pos()); } void LocalPointValueView::doShowPoint(const Point &point) { // store point this->point = point; doShowPoint(); } void LocalPointValueView::doCopyValue() { QTreeWidgetItem *item = trvWidget->currentItem(); if (item) if (!item->text(1).isEmpty()) QApplication::clipboard()->setText(item->text(1)); } void LocalPointValueView::doShowPoint() { trvWidget->clear(); // point QTreeWidgetItem *pointNode = new QTreeWidgetItem(trvWidget); pointNode->setText(0, tr("Point")); pointNode->setExpanded(true); addTreeWidgetItemValue(pointNode, Util::scene()->problemInfo()->labelX() + ":", QString("%1").arg(point.x, 0, 'f', 5), tr("m")); addTreeWidgetItemValue(pointNode, Util::scene()->problemInfo()->labelY() + ":", QString("%1").arg(point.y, 0, 'f', 5), tr("m")); trvWidget->insertTopLevelItem(0, pointNode); if (Util::scene()->sceneSolution()->isSolved()) Util::scene()->problemInfo()->hermes()->showLocalValue(trvWidget, Util::scene()->problemInfo()->hermes()->localPointValue(point)); trvWidget->resizeColumnToContents(2); } LocalPointValueDialog::LocalPointValueDialog(Point point, QWidget *parent) : QDialog(parent) { setWindowIcon(icon("scene-node")); setWindowTitle(tr("Local point value")); setModal(true); txtPointX = new SLineEditValue(); txtPointX->setNumber(point.x); txtPointY = new SLineEditValue(); txtPointY->setNumber(point.y); connect(txtPointX, SIGNAL(evaluated(bool)), this, SLOT(evaluated(bool))); connect(txtPointY, SIGNAL(evaluated(bool)), this, SLOT(evaluated(bool))); QFormLayout *layoutPoint = new QFormLayout(); layoutPoint->addRow(Util::scene()->problemInfo()->labelX() + " (m):", txtPointX); layoutPoint->addRow(Util::scene()->problemInfo()->labelY() + " (m):", txtPointY); // dialog buttons buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); QVBoxLayout *layout = new QVBoxLayout(); layout->addLayout(layoutPoint); layout->addStretch(); layout->addWidget(buttonBox); setLayout(layout); setMinimumSize(sizeHint()); setMaximumSize(sizeHint()); } LocalPointValueDialog::~LocalPointValueDialog() { delete txtPointX; delete txtPointY; } Point LocalPointValueDialog::point() { return Point(txtPointX->value().number, txtPointY->value().number); } void LocalPointValueDialog::evaluated(bool isError) { buttonBox->button(QDialogButtonBox::Ok)->setEnabled(!isError); }
panek50/agros2d
src/localvalueview.cpp
C++
gpl-2.0
8,032
#!/usr/bin/env python # Copyright (C) 2007--2016 the X-ray Polarimetry Explorer (XPE) team. # # For the license terms see the file LICENSE, distributed along with this # software. # # 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. import struct import numpy import os import logging as logger # python2/3 compatibility fix try: xrange except NameError: xrange = range # color core fror creen printout, work only on posix class ixpeAnsiColors: HEADER = '\033[95m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' # # Useful constants # XPOL_NUM_COLUMNS = 300 XPOL_NUM_ROWS = 352 XPOL_NUM_PIXELS = XPOL_NUM_COLUMNS*XPOL_NUM_ROWS # # Class for a windowed event # class ixpeEventWindowed: """Basic class representing an event aquired in windowed mode. """ HEADER_MARKER = 65535 HEADER_LENGTH = 20 def __init__(self, xmin, xmax, ymin, ymax, buffer_id, t1, t2, s1, s2, adc_values): """Constructor. """ self.xmin = xmin self.xmax = xmax self.ymin = ymin self.ymax = ymax self.buffer_id = buffer_id self.microseconds = (t1 + t2*65534)*0.8 self.adc_values = adc_values def size(self): """Return the total number of bytes in the event. """ return self.HEADER_LENGTH + 2*self.num_pixels() def num_columns(self): """Return the number of columns. """ return (self.xmax - self.xmin + 1) def num_rows(self): """Return the number of rows. """ return (self.ymax - self.ymin + 1) def num_pixels(self): """Return the total number of pixels in the window. """ return self.num_rows()*self.num_columns() def adc_value(self, col, row): """Return the pulse height for a given pixel in the window. """ return self.adc_values[col, row] def highest_pixel(self): """Return the coordinats of the pixel with the maximum value of ADC counts. """ return numpy.unravel_index(numpy.argmax(self.adc_values), self.adc_values.shape) def highest_adc_value(self): """Return the maximum value of ADC counts for the pixels in the event. """ return self.adc_values.max() def ascii(self, zero_suppression=5, max_threshold=0.75, width=4, color=True): """Return a pretty-printed ASCII representation of the event. """ if os.name != 'posix': color = False _fmt = '%%%dd' % width _max = self.highest_adc_value() text = '' text += ' '*(2*width + 2) for col in xrange(self.num_columns()): text += _fmt % (col + self.xmin) text += '\n' text += ' '*(2*width + 2) for col in xrange(self.num_columns()): text += _fmt % col text += '\n' text += ' '*(2*width + 1) + '+' + '-'*(width*self.num_columns()) + '\n' for row in xrange(self.num_rows()): text += (_fmt % (row + self.ymin)) + ' ' + (_fmt % row) + '|' for col in xrange(self.num_columns()): adc = self.adc_value(col, row) pix = _fmt % adc if color and adc == _max: pix = '%s%s%s' %\ (ixpeAnsiColors.RED, pix, ixpeAnsiColors.ENDC) elif color and adc >= max_threshold*_max: pix = '%s%s%s' %\ (ixpeAnsiColors.YELLOW, pix, ixpeAnsiColors.ENDC) elif color and adc > zero_suppression: pix = '%s%s%s' %\ (ixpeAnsiColors.GREEN, pix, ixpeAnsiColors.ENDC) text += pix text += '\n%s|\n' % (' '*(2*width + 1)) return text def draw_ascii(self, zero_suppression=5): """Print the ASCII representation of the event. """ print(self.ascii(zero_suppression)) def __str__(self): """String representation. """ text = 'buffer %5d, w(%3d, %3d)--(%3d, %3d), %d px, t = %d us' %\ (self.buffer_id, self.xmin, self.ymin, self.xmax, self.ymax, self.num_pixels(), self.microseconds) return text # # Class for a windowed file # class ixpeBinaryFileWindowed: """Binary file acquired in windowed mode. """ def __init__(self, filePath): """Constructor. """ logger.info('Opening input binary file %s...' % filePath) self.__file = open(filePath, 'rb') def seek(self, offset): """ redefine seek """ self.__file.seek(offset) def read(self, n): """ redefine read """ return self.__file.read(n) def close(self): """ redefine """ self.__file.close() def read_word(self): """Read and byte-swap a single 2-bytes binary word from file. Note that struct.unpack returns a tuple even when we read a single number, and here we're returning the first (and only) element of the tuple. """ return struct.unpack('H', self.read(2))[0] def read_words(self, num_words): """Read and byte-swap a fixed number of 2-bytes binary words from file. Args ---- num_words : int The number of words to be read from the input file. """ return struct.unpack('%dH' % num_words, self.read(2*num_words)) def read_adc_word(self): """Read and byte-swap a single 2-bytes binary word from file. Same as read word, but adc value are now signed """ return struct.unpack('h', self.read(2))[0] def read_adc_words(self, num_words): """Read and byte-swap a fixed number of 2-bytes binary words from file. Same as read_words, but adc values are now signed. Args ---- num_words : int The number of words to be read from the input file. """ return struct.unpack('%dh' % num_words, self.read(2*num_words)) def __iter__(self): """Basic iterator implementation. """ return self def next(self): """Read the next event in the file. """ try: header = self.read_word() except Exception: raise StopIteration() if header != ixpeEventWindowed.HEADER_MARKER: msg = 'Event header mismatch at byte %d' % self.tell() msg += ' (expected %s, got %s).' %\ (hex(ixpeEventWindowed.HEADER_MARKER), hex(header)) logger.error(msg) logger.info('Moving ahead to the next event header...') while header != ixpeEventWindowed.HEADER_MARKER: header = self.read_word() logger.info('Got back in synch at byte %d.' % self.tell()) xmin, xmax, ymin, ymax, buf_id, t1, t2, s1, s2 = self.read_words(9) num_columns = (xmax - xmin + 1) num_rows = (ymax - ymin + 1) data = self.read_adc_words(num_rows*num_columns) adc = numpy.array(data).reshape((num_rows, num_columns)).T return ixpeEventWindowed(xmin, xmax, ymin, ymax, buf_id, t1, t2, s1, s2, adc) if __name__ == '__main__': import argparse formatter = argparse.ArgumentDefaultsHelpFormatter parser = argparse.ArgumentParser(formatter_class=formatter) parser.add_argument('infile', type=str, help='the input binary file') parser.add_argument('-n', '--num_events', type=int, default=10, help = 'number of events to be processed') args = parser.parse_args() #test_windowed input_file = ixpeBinaryFileWindowed(args.infile) for i in xrange(args.num_events): event = input_file.next() print (event) event.draw_ascii() try: input("e2g") except NameError: raw_input("e2g")
lucabaldini/xpedaq
scripts/ixpe_evt_lib.py
Python
gpl-2.0
7,540
/** * Copyright (c) 2014 Igor Botian * * 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 * * @author Igor Botian <igor.botian@gmail.com> */ package ru.spbftu.igorbotian.phdapp.common.impl; import ru.spbftu.igorbotian.phdapp.common.*; import java.util.Objects; import java.util.Set; /** * @see ru.spbftu.igorbotian.phdapp.common.impl.AbstractInputDataImpl * @see ru.spbftu.igorbotian.phdapp.common.PointwiseInputData * @see ru.spbftu.igorbotian.phdapp.common.InputDataFactory */ class PointwiseInputDataImpl extends AbstractInputDataImpl implements PointwiseInputData { private final PointwiseTrainingSet trainingSet; public PointwiseInputDataImpl(UnclassifiedData testingSet, PointwiseTrainingSet trainingSet) throws DataException { super(testingSet); this.trainingSet = Objects.requireNonNull(trainingSet); } public Set<? extends PointwiseTrainingObject> trainingSet() { return trainingSet.objects(); } @Override public int hashCode() { return Objects.hash(super.hashCode(), trainingSet); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || !(obj instanceof PointwiseInputDataImpl)) { return false; } PointwiseInputDataImpl other = (PointwiseInputDataImpl) obj; return super.equals(other) && trainingSet.equals(other.trainingSet); } @Override public String toString() { return String.join(";", super.toString(), trainingSet.toString()); } }
igorbotian/phdapp
input/src/main/java/ru/spbftu/igorbotian/phdapp/common/impl/PointwiseInputDataImpl.java
Java
gpl-2.0
2,247
using System.Collections.Generic; using System.IO; using System.Timers; namespace DevWilson { internal class ImageList : List<ImageFileAttributes> { private readonly string filePath; private readonly object syncRoot = new object(); private Timer saveTimer; public ImageList(string filePath) { this.filePath = filePath; } public void Load() { if (File.Exists(filePath)) { lock (syncRoot) { if (saveTimer != null) { saveTimer.Stop(); saveTimer = null; } ImageListToXml.LoadFromXml(filePath, this); } } } public void Save() { lock (syncRoot) { if (saveTimer == null || !saveTimer.Enabled) { saveTimer = new Timer(5000); saveTimer.Elapsed += saveTimer_Elapsed; saveTimer.AutoReset = false; saveTimer.Start(); } } } public List<ImageFileAttributes> Clone() { lock (syncRoot) { return new List<ImageFileAttributes>(this); } } private void saveTimer_Elapsed(object sender, ElapsedEventArgs e) { string folderPath = Path.GetDirectoryName(filePath); if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } lock (syncRoot) { ImageListToXml.SaveAsXml(filePath, this); } } } }
abmv/MetaComic
MetaComics.Client/Code/PDF/PDFImageWorks/ImageList.cs
C#
gpl-2.0
1,807
showWord(["pr.","Lan, anndan. Ti moun yo t ap jwe nan dlo a." ])
georgejhunt/HaitiDictionary.activity
data/words/nan.js
JavaScript
gpl-2.0
64
/*************************************************************************** tag: FMTC Tue Mar 11 21:49:27 CET 2008 DataFlowInterface.cpp DataFlowInterface.cpp - description ------------------- begin : Tue March 11 2008 copyright : (C) 2008 FMTC email : peter.soetens@fmtc.be *************************************************************************** * This library 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. * * * * As a special exception, you may use this file as part of a free * * software library without restriction. Specifically, if other files * * instantiate templates or use macros or inline functions from this * * file, or you compile this file and link it with other files to * * produce an executable, this file does not by itself cause the * * resulting executable to be covered by the GNU General Public * * License. This exception does not however invalidate any other * * reasons why the executable file might be covered by the GNU General * * Public License. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307 USA * * * ***************************************************************************/ #include "DataFlowInterface.hpp" #include "Logger.hpp" #include "Service.hpp" #include "TaskContext.hpp" namespace RTT { using namespace detail; DataFlowInterface::DataFlowInterface(Service* parent /* = 0 */) : mservice(parent) {} DataFlowInterface::~DataFlowInterface() { } TaskContext* DataFlowInterface::getOwner() const { return mservice ? mservice->getOwner() : 0; } PortInterface& DataFlowInterface::addPort(PortInterface& port) { if ( !chkPtr("addPort", "PortInterface", &port) ) return port; this->addLocalPort(port); if (mservice && mservice->hasService( port.getName()) != 0) { log(Warning) <<"'addPort' "<< port.getName() << ": name already in use as Service. Replacing previous service with new one." <<endlog(); mservice->removeService(port.getName()); } if (!mservice) { log(Warning) <<"'addPort' "<< port.getName() << ": DataFlowInterface not given to parent. Not adding Service." <<endlog(); return port; } Service::shared_ptr ms( this->createPortObject( port.getName()) ); if ( ms ) mservice->addService( ms ); // END NOTE. return port; } PortInterface& DataFlowInterface::addLocalPort(PortInterface& port) { for ( Ports::iterator it(mports.begin()); it != mports.end(); ++it) if ( (*it)->getName() == port.getName() ) { log(Warning) <<"'addPort' "<< port.getName() << ": name already in use. Disconnecting and replacing previous port with new one." <<endlog(); removePort( port.getName() ); break; } mports.push_back( &port ); port.setInterface( this ); return port; } InputPortInterface& DataFlowInterface::addEventPort(InputPortInterface& port, SlotFunction callback) { if ( !chkPtr("addEventPort", "PortInterface", &port) ) return port; this->addLocalEventPort(port, callback); if (mservice && mservice->hasService( port.getName()) != 0) { log(Warning) <<"'addPort' "<< port.getName() << ": name already in use as Service. Replacing previous service with new one." <<endlog(); mservice->removeService(port.getName()); } if (!mservice) { log(Warning) <<"'addPort' "<< port.getName() << ": DataFlowInterface not given to parent. Not adding Service." <<endlog(); return port; } Service::shared_ptr ms( this->createPortObject( port.getName()) ); if ( ms ) mservice->addService( ms ); return port; } #ifdef ORO_SIGNALLING_PORTS void DataFlowInterface::setupHandles() { for_each(handles.begin(), handles.end(), boost::bind(&Handle::connect, _1)); } void DataFlowInterface::cleanupHandles() { for_each(handles.begin(), handles.end(), boost::bind(&Handle::disconnect, _1)); } #else void DataFlowInterface::dataOnPort(base::PortInterface* port) { if ( mservice && mservice->getOwner() ) mservice->getOwner()->dataOnPort(port); } #endif InputPortInterface& DataFlowInterface::addLocalEventPort(InputPortInterface& port, SlotFunction callback) { this->addLocalPort(port); if (mservice == 0 || mservice->getOwner() == 0) { log(Error) << "addLocalEventPort "<< port.getName() <<": DataFlowInterface not part of a TaskContext. Will not trigger any TaskContext nor register callback." <<endlog(); return port; } if (callback) mservice->getOwner()->dataOnPortCallback(&port,callback); // the handle will be deleted when the port is removed. port.signalInterface(true); return port; } void DataFlowInterface::removePort(const std::string& name) { for ( Ports::iterator it(mports.begin()); it != mports.end(); ++it) if ( (*it)->getName() == name ) { if (mservice) { mservice->removeService( name ); if (mservice->getOwner()) mservice->getOwner()->dataOnPortRemoved( *it ); } (*it)->disconnect(); // remove all connections and callbacks. mports.erase(it); return; } } DataFlowInterface::Ports DataFlowInterface::getPorts() const { return mports; } DataFlowInterface::PortNames DataFlowInterface::getPortNames() const { std::vector<std::string> res; for ( Ports::const_iterator it(mports.begin()); it != mports.end(); ++it) res.push_back( (*it)->getName() ); return res; } PortInterface* DataFlowInterface::getPort(const std::string& name) const { for ( Ports::const_iterator it(mports.begin()); it != mports.end(); ++it) if ( (*it)->getName() == name ) return *it; return 0; } std::string DataFlowInterface::getPortDescription(const std::string& name) const { for ( Ports::const_iterator it(mports.begin()); it != mports.end(); ++it) if ( (*it)->getName() == name ) return (*it)->getDescription(); return ""; } bool DataFlowInterface::setPortDescription(const std::string& name, const std::string description) { Service::shared_ptr srv = mservice->getService(name); if (srv) { srv->doc(description); return true; } return false; } Service* DataFlowInterface::createPortObject(const std::string& name) { PortInterface* p = this->getPort(name); if ( !p ) return 0; Service* to = p->createPortObject(); if (to) { std::string d = this->getPortDescription(name); if ( !d.empty() ) to->doc( d ); else to->doc("No description set for this Port. Use .doc() to document it."); } return to; } void DataFlowInterface::clear() { // remove TaskObjects: for ( Ports::iterator it(mports.begin()); it != mports.end(); ++it) { if (mservice) mservice->removeService( (*it)->getName() ); } mports.clear(); } bool DataFlowInterface::chkPtr(const std::string & where, const std::string & name, const void *ptr) { if ( ptr == 0) { log(Error) << "You tried to add a null pointer in '"<< where << "' for the object '" << name << "'. Fix your code !"<< endlog(); return false; } return true; } }
jbohren-forks/rtt-smits
rtt/DataFlowInterface.cpp
C++
gpl-2.0
9,316
<?php /* * Removes core controls */ function shoestrap_remove_controls( $wp_customize ){ $wp_customize->remove_control( 'header_textcolor'); } add_action( 'customize_register', 'shoestrap_remove_controls' );
westerniowawireless/wiaw.net
wp-content/themes/shoestrap/lib/customizer/functions/remove-controls.php
PHP
gpl-2.0
213
# -*- coding: utf-8 -*- # # Copyright (C) 2010-2016 Red Hat, Inc. # # Authors: # Thomas Woerner <twoerner@redhat.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import os.path import copy from firewall.core.base import SHORTCUTS, DEFAULT_ZONE_TARGET from firewall.core.prog import runProg from firewall.core.logger import log from firewall.functions import tempFile, readfile, splitArgs, check_mac, portStr, \ check_single_address from firewall import config from firewall.errors import FirewallError, INVALID_PASSTHROUGH, INVALID_RULE, UNKNOWN_ERROR from firewall.core.rich import Rich_Accept, Rich_Reject, Rich_Drop, Rich_Mark, \ Rich_Masquerade, Rich_ForwardPort, Rich_IcmpBlock import string BUILT_IN_CHAINS = { "security": [ "INPUT", "OUTPUT", "FORWARD" ], "raw": [ "PREROUTING", "OUTPUT" ], "mangle": [ "PREROUTING", "POSTROUTING", "INPUT", "OUTPUT", "FORWARD" ], "nat": [ "PREROUTING", "POSTROUTING", "OUTPUT" ], "filter": [ "INPUT", "OUTPUT", "FORWARD" ], } DEFAULT_REJECT_TYPE = { "ipv4": "icmp-host-prohibited", "ipv6": "icmp6-adm-prohibited", } ICMP = { "ipv4": "icmp", "ipv6": "ipv6-icmp", } # ipv ebtables also uses this # def common_reverse_rule(args): """ Inverse valid rule """ replace_args = { # Append "-A": "-D", "--append": "--delete", # Insert "-I": "-D", "--insert": "--delete", # New chain "-N": "-X", "--new-chain": "--delete-chain", } ret_args = args[:] for arg in replace_args: try: idx = ret_args.index(arg) except Exception: continue if arg in [ "-I", "--insert" ]: # With insert rulenum, then remove it if it is a number # Opt at position idx, chain at position idx+1, [rulenum] at # position idx+2 try: int(ret_args[idx+2]) except Exception: pass else: ret_args.pop(idx+2) ret_args[idx] = replace_args[arg] return ret_args def common_reverse_passthrough(args): """ Reverse valid passthough rule """ replace_args = { # Append "-A": "-D", "--append": "--delete", # Insert "-I": "-D", "--insert": "--delete", # New chain "-N": "-X", "--new-chain": "--delete-chain", } ret_args = args[:] for x in replace_args: try: idx = ret_args.index(x) except ValueError: continue if x in [ "-I", "--insert" ]: # With insert rulenum, then remove it if it is a number # Opt at position idx, chain at position idx+1, [rulenum] at # position idx+2 try: int(ret_args[idx+2]) except ValueError: pass else: ret_args.pop(idx+2) ret_args[idx] = replace_args[x] return ret_args raise FirewallError(INVALID_PASSTHROUGH, "no '-A', '-I' or '-N' arg") # ipv ebtables also uses this # def common_check_passthrough(args): """ Check if passthough rule is valid (only add, insert and new chain rules are allowed) """ args = set(args) not_allowed = set(["-C", "--check", # check rule "-D", "--delete", # delete rule "-R", "--replace", # replace rule "-L", "--list", # list rule "-S", "--list-rules", # print rules "-F", "--flush", # flush rules "-Z", "--zero", # zero rules "-X", "--delete-chain", # delete chain "-P", "--policy", # policy "-E", "--rename-chain"]) # rename chain) # intersection of args and not_allowed is not empty, i.e. # something from args is not allowed if len(args & not_allowed) > 0: raise FirewallError(INVALID_PASSTHROUGH, "arg '%s' is not allowed" % list(args & not_allowed)[0]) # args need to contain one of -A, -I, -N needed = set(["-A", "--append", "-I", "--insert", "-N", "--new-chain"]) # empty intersection of args and needed, i.e. # none from args contains any needed command if len(args & needed) == 0: raise FirewallError(INVALID_PASSTHROUGH, "no '-A', '-I' or '-N' arg") class ip4tables(object): ipv = "ipv4" name = "ip4tables" zones_supported = True def __init__(self, fw): self._fw = fw self._command = config.COMMANDS[self.ipv] self._restore_command = config.COMMANDS["%s-restore" % self.ipv] self.wait_option = self._detect_wait_option() self.restore_wait_option = self._detect_restore_wait_option() self.fill_exists() self.available_tables = [] self.rich_rule_priority_counts = {} self.our_chains = {} # chains created by firewalld def fill_exists(self): self.command_exists = os.path.exists(self._command) self.restore_command_exists = os.path.exists(self._restore_command) def __run(self, args): # convert to string list if self.wait_option and self.wait_option not in args: _args = [self.wait_option] + ["%s" % item for item in args] else: _args = ["%s" % item for item in args] log.debug2("%s: %s %s", self.__class__, self._command, " ".join(_args)) (status, ret) = runProg(self._command, _args) if status != 0: raise ValueError("'%s %s' failed: %s" % (self._command, " ".join(_args), ret)) return ret def split_value(self, rules, opts=None): """Split values combined with commas for options in opts""" if opts is None: return rules out_rules = [ ] for rule in rules: processed = False for opt in opts: try: i = rule.index(opt) except ValueError: pass else: if len(rule) > i and "," in rule[i+1]: # For all items in the comma separated list in index # i of the rule, a new rule is created with a single # item from this list processed = True items = rule[i+1].split(",") for item in items: _rule = rule[:] _rule[i+1] = item out_rules.append(_rule) if not processed: out_rules.append(rule) return out_rules def _rule_replace(self, rule, pattern, replacement): try: i = rule.index(pattern) except ValueError: return False else: rule[i:i+1] = replacement return True def is_chain_builtin(self, ipv, table, chain): return table in BUILT_IN_CHAINS and \ chain in BUILT_IN_CHAINS[table] def build_chain_rules(self, add, table, chain): rule = [ "-t", table ] if add: rule.append("-N") else: rule.append("-X") rule.append(chain) return [rule] def build_rule(self, add, table, chain, index, args): rule = [ "-t", table ] if add: rule += [ "-I", chain, str(index) ] else: rule += [ "-D", chain ] rule += args return rule def reverse_rule(self, args): return common_reverse_rule(args) def check_passthrough(self, args): common_check_passthrough(args) def reverse_passthrough(self, args): return common_reverse_passthrough(args) def passthrough_parse_table_chain(self, args): table = "filter" try: i = args.index("-t") except ValueError: pass else: if len(args) >= i+1: table = args[i+1] chain = None for opt in [ "-A", "--append", "-I", "--insert", "-N", "--new-chain" ]: try: i = args.index(opt) except ValueError: pass else: if len(args) >= i+1: chain = args[i+1] return (table, chain) def _set_rule_replace_rich_rule_priority(self, rule, rich_rule_priority_counts): """ Change something like -t filter -I public_IN %%RICH_RULE_PRIORITY%% 123 or -t filter -A public_IN %%RICH_RULE_PRIORITY%% 321 into -t filter -I public_IN 4 or -t filter -I public_IN """ try: i = rule.index("%%RICH_RULE_PRIORITY%%") except ValueError: pass else: rule_add = True insert = False insert_add_index = -1 rule.pop(i) priority = rule.pop(i) if type(priority) != int: raise FirewallError(INVALID_RULE, "rich rule priority must be followed by a number") table = "filter" for opt in [ "-t", "--table" ]: try: j = rule.index(opt) except ValueError: pass else: if len(rule) >= j+1: table = rule[j+1] for opt in [ "-A", "--append", "-I", "--insert", "-D", "--delete" ]: try: insert_add_index = rule.index(opt) except ValueError: pass else: if len(rule) >= insert_add_index+1: chain = rule[insert_add_index+1] if opt in [ "-I", "--insert" ]: insert = True if opt in [ "-D", "--delete" ]: rule_add = False chain = (table, chain) # Add the rule to the priority counts. We don't need to store the # rule, just bump the ref count for the priority value. if not rule_add: if chain not in rich_rule_priority_counts or \ priority not in rich_rule_priority_counts[chain] or \ rich_rule_priority_counts[chain][priority] <= 0: raise FirewallError(UNKNOWN_ERROR, "nonexistent or underflow of rich rule priority count") rich_rule_priority_counts[chain][priority] -= 1 else: if chain not in rich_rule_priority_counts: rich_rule_priority_counts[chain] = {} if priority not in rich_rule_priority_counts[chain]: rich_rule_priority_counts[chain][priority] = 0 # calculate index of new rule index = 1 for p in sorted(rich_rule_priority_counts[chain].keys()): if p == priority and insert: break index += rich_rule_priority_counts[chain][p] if p == priority: break rich_rule_priority_counts[chain][priority] += 1 rule[insert_add_index] = "-I" rule.insert(insert_add_index+2, "%d" % index) def set_rules(self, rules, log_denied): temp_file = tempFile() table_rules = { } rich_rule_priority_counts = copy.deepcopy(self.rich_rule_priority_counts) for _rule in rules: rule = _rule[:] # replace %%REJECT%% self._rule_replace(rule, "%%REJECT%%", \ ["REJECT", "--reject-with", DEFAULT_REJECT_TYPE[self.ipv]]) # replace %%ICMP%% self._rule_replace(rule, "%%ICMP%%", [ICMP[self.ipv]]) # replace %%LOGTYPE%% try: i = rule.index("%%LOGTYPE%%") except ValueError: pass else: if log_denied == "off": continue if log_denied in [ "unicast", "broadcast", "multicast" ]: rule[i:i+1] = [ "-m", "pkttype", "--pkt-type", log_denied ] else: rule.pop(i) self._set_rule_replace_rich_rule_priority(rule, rich_rule_priority_counts) table = "filter" # get table form rule for opt in [ "-t", "--table" ]: try: i = rule.index(opt) except ValueError: pass else: if len(rule) >= i+1: rule.pop(i) table = rule.pop(i) # we can not use joinArgs here, because it would use "'" instead # of '"' for the start and end of the string, this breaks # iptables-restore for i in range(len(rule)): for c in string.whitespace: if c in rule[i] and not (rule[i].startswith('"') and rule[i].endswith('"')): rule[i] = '"%s"' % rule[i] table_rules.setdefault(table, []).append(rule) for table in table_rules: rules = table_rules[table] rules = self.split_value(rules, [ "-s", "--source" ]) rules = self.split_value(rules, [ "-d", "--destination" ]) temp_file.write("*%s\n" % table) for rule in rules: temp_file.write(" ".join(rule) + "\n") temp_file.write("COMMIT\n") temp_file.close() stat = os.stat(temp_file.name) log.debug2("%s: %s %s", self.__class__, self._restore_command, "%s: %d" % (temp_file.name, stat.st_size)) args = [ ] if self.restore_wait_option: args.append(self.restore_wait_option) args.append("-n") (status, ret) = runProg(self._restore_command, args, stdin=temp_file.name) if log.getDebugLogLevel() > 2: lines = readfile(temp_file.name) if lines is not None: i = 1 for line in lines: log.debug3("%8d: %s" % (i, line), nofmt=1, nl=0) if not line.endswith("\n"): log.debug3("", nofmt=1) i += 1 os.unlink(temp_file.name) if status != 0: raise ValueError("'%s %s' failed: %s" % (self._restore_command, " ".join(args), ret)) self.rich_rule_priority_counts = rich_rule_priority_counts return ret def set_rule(self, rule, log_denied): # replace %%REJECT%% self._rule_replace(rule, "%%REJECT%%", \ ["REJECT", "--reject-with", DEFAULT_REJECT_TYPE[self.ipv]]) # replace %%ICMP%% self._rule_replace(rule, "%%ICMP%%", [ICMP[self.ipv]]) # replace %%LOGTYPE%% try: i = rule.index("%%LOGTYPE%%") except ValueError: pass else: if log_denied == "off": return "" if log_denied in [ "unicast", "broadcast", "multicast" ]: rule[i:i+1] = [ "-m", "pkttype", "--pkt-type", log_denied ] else: rule.pop(i) rich_rule_priority_counts = copy.deepcopy(self.rich_rule_priority_counts) self._set_rule_replace_rich_rule_priority(rule, self.rich_rule_priority_counts) output = self.__run(rule) self.rich_rule_priority_counts = rich_rule_priority_counts return output def get_available_tables(self, table=None): ret = [] tables = [ table ] if table else BUILT_IN_CHAINS.keys() for table in tables: if table in self.available_tables: ret.append(table) else: try: self.__run(["-t", table, "-L", "-n"]) self.available_tables.append(table) ret.append(table) except ValueError: log.debug1("%s table '%s' does not exist (or not enough permission to check)." % (self.ipv, table)) return ret def _detect_wait_option(self): wait_option = "" ret = runProg(self._command, ["-w", "-L", "-n"]) # since iptables-1.4.20 if ret[0] == 0: wait_option = "-w" # wait for xtables lock ret = runProg(self._command, ["-w10", "-L", "-n"]) # since iptables > 1.4.21 if ret[0] == 0: wait_option = "-w10" # wait max 10 seconds log.debug2("%s: %s will be using %s option.", self.__class__, self._command, wait_option) return wait_option def _detect_restore_wait_option(self): temp_file = tempFile() temp_file.write("#foo") temp_file.close() wait_option = "" for test_option in ["-w", "--wait=2"]: ret = runProg(self._restore_command, [test_option], stdin=temp_file.name) if ret[0] == 0 and "invalid option" not in ret[1] \ and "unrecognized option" not in ret[1]: wait_option = test_option break log.debug2("%s: %s will be using %s option.", self.__class__, self._restore_command, wait_option) os.unlink(temp_file.name) return wait_option def build_flush_rules(self): self.rich_rule_priority_counts = {} rules = [] for table in BUILT_IN_CHAINS.keys(): # Flush firewall rules: -F # Delete firewall chains: -X # Set counter to zero: -Z for flag in [ "-F", "-X", "-Z" ]: rules.append(["-t", table, flag]) return rules def build_set_policy_rules(self, policy): rules = [] for table in BUILT_IN_CHAINS.keys(): if table == "nat": continue for chain in BUILT_IN_CHAINS[table]: rules.append(["-t", table, "-P", chain, policy]) return rules def supported_icmp_types(self): """Return ICMP types that are supported by the iptables/ip6tables command and kernel""" ret = [ ] output = "" try: output = self.__run(["-p", "icmp" if self.ipv == "ipv4" else "ipv6-icmp", "--help"]) except ValueError as ex: if self.ipv == "ipv4": log.debug1("iptables error: %s" % ex) else: log.debug1("ip6tables error: %s" % ex) lines = output.splitlines() in_types = False for line in lines: #print(line) if in_types: line = line.strip().lower() splits = line.split() for split in splits: if split.startswith("(") and split.endswith(")"): x = split[1:-1] else: x = split if x not in ret: ret.append(x) if self.ipv == "ipv4" and line.startswith("Valid ICMP Types:") or \ self.ipv == "ipv6" and line.startswith("Valid ICMPv6 Types:"): in_types = True return ret def build_default_tables(self): # nothing to do, they always exist return [] def build_default_rules(self, log_denied="off"): default_rules = {} default_rules["security"] = [ ] self.our_chains["security"] = set() for chain in BUILT_IN_CHAINS["security"]: default_rules["security"].append("-N %s_direct" % chain) default_rules["security"].append("-A %s -j %s_direct" % (chain, chain)) self.our_chains["security"].add("%s_direct" % chain) default_rules["raw"] = [ ] self.our_chains["raw"] = set() for chain in BUILT_IN_CHAINS["raw"]: default_rules["raw"].append("-N %s_direct" % chain) default_rules["raw"].append("-A %s -j %s_direct" % (chain, chain)) self.our_chains["raw"].add("%s_direct" % chain) if chain == "PREROUTING": default_rules["raw"].append("-N %s_ZONES_SOURCE" % chain) default_rules["raw"].append("-N %s_ZONES" % chain) default_rules["raw"].append("-A %s -j %s_ZONES_SOURCE" % (chain, chain)) default_rules["raw"].append("-A %s -j %s_ZONES" % (chain, chain)) self.our_chains["raw"].update(set(["%s_ZONES_SOURCE" % chain, "%s_ZONES" % chain])) default_rules["mangle"] = [ ] self.our_chains["mangle"] = set() for chain in BUILT_IN_CHAINS["mangle"]: default_rules["mangle"].append("-N %s_direct" % chain) default_rules["mangle"].append("-A %s -j %s_direct" % (chain, chain)) self.our_chains["mangle"].add("%s_direct" % chain) if chain == "PREROUTING": default_rules["mangle"].append("-N %s_ZONES_SOURCE" % chain) default_rules["mangle"].append("-N %s_ZONES" % chain) default_rules["mangle"].append("-A %s -j %s_ZONES_SOURCE" % (chain, chain)) default_rules["mangle"].append("-A %s -j %s_ZONES" % (chain, chain)) self.our_chains["mangle"].update(set(["%s_ZONES_SOURCE" % chain, "%s_ZONES" % chain])) default_rules["nat"] = [ ] self.our_chains["nat"] = set() for chain in BUILT_IN_CHAINS["nat"]: default_rules["nat"].append("-N %s_direct" % chain) default_rules["nat"].append("-A %s -j %s_direct" % (chain, chain)) self.our_chains["nat"].add("%s_direct" % chain) if chain in [ "PREROUTING", "POSTROUTING" ]: default_rules["nat"].append("-N %s_ZONES_SOURCE" % chain) default_rules["nat"].append("-N %s_ZONES" % chain) default_rules["nat"].append("-A %s -j %s_ZONES_SOURCE" % (chain, chain)) default_rules["nat"].append("-A %s -j %s_ZONES" % (chain, chain)) self.our_chains["nat"].update(set(["%s_ZONES_SOURCE" % chain, "%s_ZONES" % chain])) default_rules["filter"] = [ "-N INPUT_direct", "-N INPUT_ZONES_SOURCE", "-N INPUT_ZONES", "-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT", "-A INPUT -i lo -j ACCEPT", "-A INPUT -j INPUT_direct", "-A INPUT -j INPUT_ZONES_SOURCE", "-A INPUT -j INPUT_ZONES", ] if log_denied != "off": default_rules["filter"].append("-A INPUT -m conntrack --ctstate INVALID %%LOGTYPE%% -j LOG --log-prefix 'STATE_INVALID_DROP: '") default_rules["filter"].append("-A INPUT -m conntrack --ctstate INVALID -j DROP") if log_denied != "off": default_rules["filter"].append("-A INPUT %%LOGTYPE%% -j LOG --log-prefix 'FINAL_REJECT: '") default_rules["filter"].append("-A INPUT -j %%REJECT%%") default_rules["filter"] += [ "-N FORWARD_direct", "-N FORWARD_IN_ZONES_SOURCE", "-N FORWARD_IN_ZONES", "-N FORWARD_OUT_ZONES_SOURCE", "-N FORWARD_OUT_ZONES", "-A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT", "-A FORWARD -i lo -j ACCEPT", "-A FORWARD -j FORWARD_direct", "-A FORWARD -j FORWARD_IN_ZONES_SOURCE", "-A FORWARD -j FORWARD_IN_ZONES", "-A FORWARD -j FORWARD_OUT_ZONES_SOURCE", "-A FORWARD -j FORWARD_OUT_ZONES", ] if log_denied != "off": default_rules["filter"].append("-A FORWARD -m conntrack --ctstate INVALID %%LOGTYPE%% -j LOG --log-prefix 'STATE_INVALID_DROP: '") default_rules["filter"].append("-A FORWARD -m conntrack --ctstate INVALID -j DROP") if log_denied != "off": default_rules["filter"].append("-A FORWARD %%LOGTYPE%% -j LOG --log-prefix 'FINAL_REJECT: '") default_rules["filter"].append("-A FORWARD -j %%REJECT%%") default_rules["filter"] += [ "-N OUTPUT_direct", "-A OUTPUT -o lo -j ACCEPT", "-A OUTPUT -j OUTPUT_direct", ] self.our_chains["filter"] = set(["INPUT_direct", "INPUT_ZONES_SOURCE", "INPUT_ZONES", "FORWARD_direct", "FORWARD_IN_ZONES_SOURCE", "FORWARD_IN_ZONES", "FORWARD_OUT_ZONES_SOURCE", "FORWARD_OUT_ZONES", "OUTPUT_direct"]) final_default_rules = [] for table in default_rules: if table not in self.get_available_tables(): continue for rule in default_rules[table]: final_default_rules.append(["-t", table] + splitArgs(rule)) return final_default_rules def get_zone_table_chains(self, table): if table == "filter": return { "INPUT", "FORWARD_IN", "FORWARD_OUT" } if table == "mangle": if "mangle" in self.get_available_tables() and \ "nat" in self.get_available_tables(): return { "PREROUTING" } if table == "nat": if "nat" in self.get_available_tables(): return { "PREROUTING", "POSTROUTING" } if table == "raw": if "raw" in self.get_available_tables(): return { "PREROUTING" } return {} def build_zone_source_interface_rules(self, enable, zone, zone_target, interface, table, chain, append=False): # handle all zones in the same way here, now # trust and block zone targets are handled now in __chain opt = { "PREROUTING": "-i", "POSTROUTING": "-o", "INPUT": "-i", "FORWARD_IN": "-i", "FORWARD_OUT": "-o", "OUTPUT": "-o", }[chain] target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS[chain], zone=zone) if zone_target == DEFAULT_ZONE_TARGET: action = "-g" else: action = "-j" if enable and not append: rule = [ "-I", "%s_ZONES" % chain, "1" ] elif enable: rule = [ "-A", "%s_ZONES" % chain ] else: rule = [ "-D", "%s_ZONES" % chain ] rule += [ "-t", table, opt, interface, action, target ] return [rule] def build_zone_source_address_rules(self, enable, zone, zone_target, address, table, chain): add_del = { True: "-A", False: "-D" }[enable] opt = { "PREROUTING": "-s", "POSTROUTING": "-d", "INPUT": "-s", "FORWARD_IN": "-s", "FORWARD_OUT": "-d", "OUTPUT": "-d", }[chain] target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS[chain], zone=zone) if zone_target == DEFAULT_ZONE_TARGET: action = "-g" else: action = "-j" if address.startswith("ipset:"): name = address[6:] if opt == "-d": opt = "dst" else: opt = "src" flags = ",".join([opt] * self._fw.ipset.get_dimension(name)) rule = [ add_del, "%s_ZONES_SOURCE" % chain, "-t", table, "-m", "set", "--match-set", name, flags, action, target ] else: if check_mac(address): # outgoing can not be set if opt == "-d": return "" rule = [ add_del, "%s_ZONES_SOURCE" % chain, "-t", table, "-m", "mac", "--mac-source", address.upper(), action, target ] else: rule = [ add_del, "%s_ZONES_SOURCE" % chain, "-t", table, opt, address, action, target ] return [rule] def build_zone_chain_rules(self, zone, table, chain): _zone = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS[chain], zone=zone) self.our_chains[table].update(set([_zone, "%s_log" % _zone, "%s_deny" % _zone, "%s_pre" % _zone, "%s_post" % _zone, "%s_allow" % _zone])) rules = [] rules.append([ "-N", _zone, "-t", table ]) rules.append([ "-N", "%s_pre" % _zone, "-t", table ]) rules.append([ "-N", "%s_log" % _zone, "-t", table ]) rules.append([ "-N", "%s_deny" % _zone, "-t", table ]) rules.append([ "-N", "%s_allow" % _zone, "-t", table ]) rules.append([ "-N", "%s_post" % _zone, "-t", table ]) rules.append([ "-A", _zone, "-t", table, "-j", "%s_pre" % _zone ]) rules.append([ "-A", _zone, "-t", table, "-j", "%s_log" % _zone ]) rules.append([ "-A", _zone, "-t", table, "-j", "%s_deny" % _zone ]) rules.append([ "-A", _zone, "-t", table, "-j", "%s_allow" % _zone ]) rules.append([ "-A", _zone, "-t", table, "-j", "%s_post" % _zone ]) target = self._fw.zone._zones[zone].target if self._fw.get_log_denied() != "off": if table == "filter" and \ chain in [ "INPUT", "FORWARD_IN", "FORWARD_OUT", "OUTPUT" ]: if target in [ "REJECT", "%%REJECT%%" ]: rules.append([ "-A", _zone, "-t", table, "%%LOGTYPE%%", "-j", "LOG", "--log-prefix", "\"%s_REJECT: \"" % _zone ]) if target == "DROP": rules.append([ "-A", _zone, "-t", table, "%%LOGTYPE%%", "-j", "LOG", "--log-prefix", "\"%s_DROP: \"" % _zone ]) # Handle trust, block and drop zones: # Add an additional rule with the zone target (accept, reject # or drop) to the base zone only in the filter table. # Otherwise it is not be possible to have a zone with drop # target, that is allowing traffic that is locally initiated # or that adds additional rules. (RHBZ#1055190) if table == "filter" and \ target in [ "ACCEPT", "REJECT", "%%REJECT%%", "DROP" ] and \ chain in [ "INPUT", "FORWARD_IN", "FORWARD_OUT", "OUTPUT" ]: rules.append([ "-A", _zone, "-t", table, "-j", target ]) return rules def _rule_limit(self, limit): if limit: return [ "-m", "limit", "--limit", limit.value ] return [] def _rich_rule_chain_suffix(self, rich_rule): if type(rich_rule.element) in [Rich_Masquerade, Rich_ForwardPort, Rich_IcmpBlock]: # These are special and don't have an explicit action pass elif rich_rule.action: if type(rich_rule.action) not in [Rich_Accept, Rich_Reject, Rich_Drop, Rich_Mark]: raise FirewallError(INVALID_RULE, "Unknown action %s" % type(rich_rule.action)) else: raise FirewallError(INVALID_RULE, "No rule action specified.") if rich_rule.priority == 0: if type(rich_rule.element) in [Rich_Masquerade, Rich_ForwardPort] or \ type(rich_rule.action) in [Rich_Accept, Rich_Mark]: return "allow" elif type(rich_rule.element) in [Rich_IcmpBlock] or \ type(rich_rule.action) in [Rich_Reject, Rich_Drop]: return "deny" elif rich_rule.priority < 0: return "pre" else: return "post" def _rich_rule_chain_suffix_from_log(self, rich_rule): if not rich_rule.log and not rich_rule.audit: raise FirewallError(INVALID_RULE, "Not log or audit") if rich_rule.priority == 0: return "log" elif rich_rule.priority < 0: return "pre" else: return "post" def _rich_rule_priority_fragment(self, rich_rule): if rich_rule.priority == 0: return [] return ["%%RICH_RULE_PRIORITY%%", rich_rule.priority] def _rich_rule_log(self, rich_rule, enable, table, target, rule_fragment): if not rich_rule.log: return [] add_del = { True: "-A", False: "-D" }[enable] chain_suffix = self._rich_rule_chain_suffix_from_log(rich_rule) rule = ["-t", table, add_del, "%s_%s" % (target, chain_suffix)] rule += self._rich_rule_priority_fragment(rich_rule) rule += rule_fragment + [ "-j", "LOG" ] if rich_rule.log.prefix: rule += [ "--log-prefix", "'%s'" % rich_rule.log.prefix ] if rich_rule.log.level: rule += [ "--log-level", "%s" % rich_rule.log.level ] rule += self._rule_limit(rich_rule.log.limit) return rule def _rich_rule_audit(self, rich_rule, enable, table, target, rule_fragment): if not rich_rule.audit: return [] add_del = { True: "-A", False: "-D" }[enable] chain_suffix = self._rich_rule_chain_suffix_from_log(rich_rule) rule = ["-t", table, add_del, "%s_%s" % (target, chain_suffix)] rule += self._rich_rule_priority_fragment(rich_rule) rule += rule_fragment if type(rich_rule.action) == Rich_Accept: _type = "accept" elif type(rich_rule.action) == Rich_Reject: _type = "reject" elif type(rich_rule.action) == Rich_Drop: _type = "drop" else: _type = "unknown" rule += [ "-j", "AUDIT", "--type", _type ] rule += self._rule_limit(rich_rule.audit.limit) return rule def _rich_rule_action(self, zone, rich_rule, enable, table, target, rule_fragment): if not rich_rule.action: return [] add_del = { True: "-A", False: "-D" }[enable] chain_suffix = self._rich_rule_chain_suffix(rich_rule) chain = "%s_%s" % (target, chain_suffix) if type(rich_rule.action) == Rich_Accept: rule_action = [ "-j", "ACCEPT" ] elif type(rich_rule.action) == Rich_Reject: rule_action = [ "-j", "REJECT" ] if rich_rule.action.type: rule_action += [ "--reject-with", rich_rule.action.type ] elif type(rich_rule.action) == Rich_Drop: rule_action = [ "-j", "DROP" ] elif type(rich_rule.action) == Rich_Mark: target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["PREROUTING"], zone=zone) table = "mangle" chain = "%s_%s" % (target, chain_suffix) rule_action = [ "-j", "MARK", "--set-xmark", rich_rule.action.set ] else: raise FirewallError(INVALID_RULE, "Unknown action %s" % type(rich_rule.action)) rule = ["-t", table, add_del, chain] rule += self._rich_rule_priority_fragment(rich_rule) rule += rule_fragment + rule_action rule += self._rule_limit(rich_rule.action.limit) return rule def _rich_rule_destination_fragment(self, rich_dest): if not rich_dest: return [] rule_fragment = [] if rich_dest.invert: rule_fragment.append("!") rule_fragment += [ "-d", rich_dest.addr ] return rule_fragment def _rich_rule_source_fragment(self, rich_source): if not rich_source: return [] rule_fragment = [] if rich_source.addr: if rich_source.invert: rule_fragment.append("!") rule_fragment += [ "-s", rich_source.addr ] elif hasattr(rich_source, "mac") and rich_source.mac: rule_fragment += [ "-m", "mac" ] if rich_source.invert: rule_fragment.append("!") rule_fragment += [ "--mac-source", rich_source.mac ] elif hasattr(rich_source, "ipset") and rich_source.ipset: rule_fragment += [ "-m", "set" ] if rich_source.invert: rule_fragment.append("!") flags = self._fw.zone._ipset_match_flags(rich_source.ipset, "src") rule_fragment += [ "--match-set", rich_source.ipset, flags ] return rule_fragment def build_zone_ports_rules(self, enable, zone, proto, port, destination=None, rich_rule=None): add_del = { True: "-A", False: "-D" }[enable] table = "filter" target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["INPUT"], zone=zone) rule_fragment = [ "-p", proto ] if port: rule_fragment += [ "--dport", "%s" % portStr(port) ] if destination: rule_fragment += [ "-d", destination ] if rich_rule: rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination) rule_fragment += self._rich_rule_source_fragment(rich_rule.source) if not rich_rule or rich_rule.action != Rich_Mark: rule_fragment += [ "-m", "conntrack", "--ctstate", "NEW,UNTRACKED" ] rules = [] if rich_rule: rules.append(self._rich_rule_log(rich_rule, enable, table, target, rule_fragment)) rules.append(self._rich_rule_audit(rich_rule, enable, table, target, rule_fragment)) rules.append(self._rich_rule_action(zone, rich_rule, enable, table, target, rule_fragment)) else: rules.append([add_del, "%s_allow" % (target), "-t", table] + rule_fragment + [ "-j", "ACCEPT" ]) return rules def build_zone_protocol_rules(self, enable, zone, protocol, destination=None, rich_rule=None): add_del = { True: "-A", False: "-D" }[enable] table = "filter" target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["INPUT"], zone=zone) rule_fragment = [ "-p", protocol ] if destination: rule_fragment += [ "-d", destination ] if rich_rule: rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination) rule_fragment += self._rich_rule_source_fragment(rich_rule.source) if not rich_rule or rich_rule.action != Rich_Mark: rule_fragment += [ "-m", "conntrack", "--ctstate", "NEW,UNTRACKED" ] rules = [] if rich_rule: rules.append(self._rich_rule_log(rich_rule, enable, table, target, rule_fragment)) rules.append(self._rich_rule_audit(rich_rule, enable, table, target, rule_fragment)) rules.append(self._rich_rule_action(zone, rich_rule, enable, table, target, rule_fragment)) else: rules.append([add_del, "%s_allow" % (target), "-t", table] + rule_fragment + [ "-j", "ACCEPT" ]) return rules def build_zone_source_ports_rules(self, enable, zone, proto, port, destination=None, rich_rule=None): add_del = { True: "-A", False: "-D" }[enable] table = "filter" target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["INPUT"], zone=zone) rule_fragment = [ "-p", proto ] if port: rule_fragment += [ "--sport", "%s" % portStr(port) ] if destination: rule_fragment += [ "-d", destination ] if rich_rule: rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination) rule_fragment += self._rich_rule_source_fragment(rich_rule.source) if not rich_rule or rich_rule.action != Rich_Mark: rule_fragment += [ "-m", "conntrack", "--ctstate", "NEW,UNTRACKED" ] rules = [] if rich_rule: rules.append(self._rich_rule_log(rich_rule, enable, table, target, rule_fragment)) rules.append(self._rich_rule_audit(rich_rule, enable, table, target, rule_fragment)) rules.append(self._rich_rule_action(zone, rich_rule, enable, table, target, rule_fragment)) else: rules.append([add_del, "%s_allow" % (target), "-t", table] + rule_fragment + [ "-j", "ACCEPT" ]) return rules def build_zone_helper_ports_rules(self, enable, zone, proto, port, destination, helper_name): add_del = { True: "-A", False: "-D" }[enable] target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["PREROUTING"], zone=zone) rule = [ add_del, "%s_allow" % (target), "-t", "raw", "-p", proto ] if port: rule += [ "--dport", "%s" % portStr(port) ] if destination: rule += [ "-d", destination ] rule += [ "-j", "CT", "--helper", helper_name ] return [rule] def build_zone_masquerade_rules(self, enable, zone, rich_rule=None): add_del = { True: "-A", False: "-D" }[enable] target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["POSTROUTING"], zone=zone) rule_fragment = [] if rich_rule: chain_suffix = self._rich_rule_chain_suffix(rich_rule) rule_fragment += self._rich_rule_priority_fragment(rich_rule) rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination) rule_fragment += self._rich_rule_source_fragment(rich_rule.source) else: chain_suffix = "allow" rules = [] rules.append(["-t", "nat", add_del, "%s_%s" % (target, chain_suffix)] + rule_fragment + [ "!", "-o", "lo", "-j", "MASQUERADE" ]) # FORWARD_OUT target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["FORWARD_OUT"], zone=zone) rule_fragment = [] if rich_rule: chain_suffix = self._rich_rule_chain_suffix(rich_rule) rule_fragment += self._rich_rule_priority_fragment(rich_rule) rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination) rule_fragment += self._rich_rule_source_fragment(rich_rule.source) else: chain_suffix = "allow" rules.append(["-t", "filter", add_del, "%s_%s" % (target, chain_suffix)] + rule_fragment + ["-m", "conntrack", "--ctstate", "NEW,UNTRACKED", "-j", "ACCEPT" ]) return rules def build_zone_forward_port_rules(self, enable, zone, filter_chain, port, protocol, toport, toaddr, mark_id, rich_rule=None): add_del = { True: "-A", False: "-D" }[enable] mark_str = "0x%x" % mark_id mark = [ "-m", "mark", "--mark", mark_str ] to = "" if toaddr: if check_single_address("ipv6", toaddr): to += "[%s]" % toaddr else: to += toaddr if toport and toport != "": to += ":%s" % portStr(toport, "-") target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["PREROUTING"], zone=zone) rule_fragment = [ "-p", protocol, "--dport", portStr(port) ] rich_rule_priority_fragment = [] if rich_rule: chain_suffix = self._rich_rule_chain_suffix(rich_rule) rich_rule_priority_fragment = self._rich_rule_priority_fragment(rich_rule) rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination) rule_fragment += self._rich_rule_source_fragment(rich_rule.source) else: chain_suffix = "allow" rules = [] if rich_rule: rules.append(self._rich_rule_log(rich_rule, enable, "mangle", target, rule_fragment)) rules.append(["-t", "mangle", add_del, "%s_%s" % (target, chain_suffix)] + rich_rule_priority_fragment + rule_fragment + [ "-j", "MARK", "--set-mark", mark_str ]) # local and remote rules.append(["-t", "nat", add_del, "%s_%s" % (target, chain_suffix)] + rich_rule_priority_fragment + ["-p", protocol ] + mark + [ "-j", "DNAT", "--to-destination", to ]) target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS[filter_chain], zone=zone) rules.append(["-t", "filter", add_del, "%s_%s" % (target, chain_suffix)] + rich_rule_priority_fragment + ["-m", "conntrack", "--ctstate", "NEW,UNTRACKED" ] + mark + [ "-j", "ACCEPT" ]) return rules def build_zone_icmp_block_rules(self, enable, zone, ict, rich_rule=None): table = "filter" add_del = { True: "-A", False: "-D" }[enable] if self.ipv == "ipv4": proto = [ "-p", "icmp" ] match = [ "-m", "icmp", "--icmp-type", ict.name ] else: proto = [ "-p", "ipv6-icmp" ] match = [ "-m", "icmp6", "--icmpv6-type", ict.name ] rules = [] for chain in ["INPUT", "FORWARD_IN"]: target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS[chain], zone=zone) if self._fw.zone.query_icmp_block_inversion(zone): final_chain = "%s_allow" % target final_target = "ACCEPT" else: final_chain = "%s_deny" % target final_target = "%%REJECT%%" rule_fragment = [] if rich_rule: rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination) rule_fragment += self._rich_rule_source_fragment(rich_rule.source) rule_fragment += proto + match if rich_rule: rules.append(self._rich_rule_log(rich_rule, enable, table, target, rule_fragment)) rules.append(self._rich_rule_audit(rich_rule, enable, table, target, rule_fragment)) if rich_rule.action: rules.append(self._rich_rule_action(zone, rich_rule, enable, table, target, rule_fragment)) else: chain_suffix = self._rich_rule_chain_suffix(rich_rule) rules.append(["-t", table, add_del, "%s_%s" % (target, chain_suffix)] + self._rich_rule_priority_fragment(rich_rule) + rule_fragment + [ "-j", "%%REJECT%%" ]) else: if self._fw.get_log_denied() != "off" and final_target != "ACCEPT": rules.append([ add_del, final_chain, "-t", table ] + rule_fragment + [ "%%LOGTYPE%%", "-j", "LOG", "--log-prefix", "\"%s_ICMP_BLOCK: \"" % zone ]) rules.append([ add_del, final_chain, "-t", table ] + rule_fragment + [ "-j", final_target ]) return rules def build_zone_icmp_block_inversion_rules(self, enable, zone): table = "filter" rules = [] for chain in [ "INPUT", "FORWARD_IN" ]: rule_idx = 6 _zone = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS[chain], zone=zone) if self._fw.zone.query_icmp_block_inversion(zone): ibi_target = "%%REJECT%%" if self._fw.get_log_denied() != "off": if enable: rule = [ "-I", _zone, str(rule_idx) ] else: rule = [ "-D", _zone ] rule = rule + [ "-t", table, "-p", "%%ICMP%%", "%%LOGTYPE%%", "-j", "LOG", "--log-prefix", "\"%s_ICMP_BLOCK: \"" % _zone ] rules.append(rule) rule_idx += 1 else: ibi_target = "ACCEPT" if enable: rule = [ "-I", _zone, str(rule_idx) ] else: rule = [ "-D", _zone ] rule = rule + [ "-t", table, "-p", "%%ICMP%%", "-j", ibi_target ] rules.append(rule) return rules def build_zone_rich_source_destination_rules(self, enable, zone, rich_rule): table = "filter" target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["INPUT"], zone=zone) rule_fragment = [] rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination) rule_fragment += self._rich_rule_source_fragment(rich_rule.source) rules = [] rules.append(self._rich_rule_log(rich_rule, enable, table, target, rule_fragment)) rules.append(self._rich_rule_audit(rich_rule, enable, table, target, rule_fragment)) rules.append(self._rich_rule_action(zone, rich_rule, enable, table, target, rule_fragment)) return rules def is_ipv_supported(self, ipv): return ipv == self.ipv class ip6tables(ip4tables): ipv = "ipv6" name = "ip6tables" def build_rpfilter_rules(self, log_denied=False): rules = [] rules.append([ "-I", "PREROUTING", "-t", "raw", "-m", "rpfilter", "--invert", "-j", "DROP" ]) if log_denied != "off": rules.append([ "-I", "PREROUTING", "-t", "raw", "-m", "rpfilter", "--invert", "-j", "LOG", "--log-prefix", "rpfilter_DROP: " ]) rules.append([ "-I", "PREROUTING", "-t", "raw", "-p", "ipv6-icmp", "--icmpv6-type=neighbour-solicitation", "-j", "ACCEPT" ]) # RHBZ#1575431, kernel bug in 4.16-4.17 rules.append([ "-I", "PREROUTING", "-t", "raw", "-p", "ipv6-icmp", "--icmpv6-type=router-advertisement", "-j", "ACCEPT" ]) # RHBZ#1058505 return rules def build_rfc3964_ipv4_rules(self): daddr_list = [ "::0.0.0.0/96", # IPv4 compatible "::ffff:0.0.0.0/96", # IPv4 mapped "2002:0000::/24", # 0.0.0.0/8 (the system has no address assigned yet) "2002:0a00::/24", # 10.0.0.0/8 (private) "2002:7f00::/24", # 127.0.0.0/8 (loopback) "2002:ac10::/28", # 172.16.0.0/12 (private) "2002:c0a8::/32", # 192.168.0.0/16 (private) "2002:a9fe::/32", # 169.254.0.0/16 (IANA Assigned DHCP link-local) "2002:e000::/19", # 224.0.0.0/4 (multicast), 240.0.0.0/4 (reserved and broadcast) ] chain_name = "RFC3964_IPv4" self.our_chains["filter"].add(chain_name) rules = [] rules.append(["-t", "filter", "-N", chain_name]) for daddr in daddr_list: rules.append(["-t", "filter", "-I", chain_name, "-d", daddr, "-j", "REJECT", "--reject-with", "addr-unreach"]) if self._fw._log_denied in ["unicast", "all"]: rules.append(["-t", "filter", "-I", chain_name, "-d", daddr, "-j", "LOG", "--log-prefix", "\"RFC3964_IPv4_REJECT: \""]) # Inject into FORWARD and OUTPUT chains rules.append(["-t", "filter", "-I", "OUTPUT", "3", "-j", chain_name]) rules.append(["-t", "filter", "-I", "FORWARD", "4", "-j", chain_name]) return rules
hos7ein/firewalld
src/firewall/core/ipXtables.py
Python
gpl-2.0
53,449
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2009, 2013 Zuza Software Foundation # # This file is part of Pootle. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see <http://www.gnu.org/licenses/>. import json import time from translate.storage import factory, statsdb from pootle.tests import PootleTestCase from pootle_store.models import Store, Unit class UnitTests(PootleTestCase): def setUp(self): super(UnitTests, self).setUp() self.store = Store.objects.get(pootle_path="/af/tutorial/pootle.po") def _update_translation(self, item, newvalues): unit = self.store.getitem(item) time.sleep(1) if 'target' in newvalues: unit.target = newvalues['target'] if 'fuzzy' in newvalues: unit.markfuzzy(newvalues['fuzzy']) if 'translator_comment' in newvalues: unit.translator_comment = newvalues['translator_comment'] unit.save() self.store.sync(update_translation=True) return self.store.getitem(item) def test_getorig(self): for dbunit in self.store.units.iterator(): storeunit = dbunit.getorig() self.assertEqual(dbunit.getid(), storeunit.getid()) def test_convert(self): for dbunit in self.store.units.iterator(): if dbunit.hasplural() and not dbunit.istranslated(): # skip untranslated plural units, they will always look different continue storeunit = dbunit.getorig() newunit = dbunit.convert(self.store.file.store.UnitClass) self.assertEqual(str(newunit), str(storeunit)) def test_update_target(self): dbunit = self._update_translation(0, {'target': u'samaka'}) storeunit = dbunit.getorig() self.assertEqual(dbunit.target, u'samaka') self.assertEqual(dbunit.target, storeunit.target) pofile = factory.getobject(self.store.file.path) self.assertEqual(dbunit.target, pofile.units[dbunit.index].target) def test_empty_plural_target(self): """test we don't delete empty plural targets""" dbunit = self._update_translation(2, {'target': [u'samaka']}) storeunit = dbunit.getorig() self.assertEqual(len(storeunit.target.strings), 2) dbunit = self._update_translation(2, {'target': u''}) self.assertEqual(len(storeunit.target.strings), 2) def test_update_plural_target(self): dbunit = self._update_translation(2, {'target': [u'samaka', u'samak']}) storeunit = dbunit.getorig() self.assertEqual(dbunit.target.strings, [u'samaka', u'samak']) self.assertEqual(dbunit.target.strings, storeunit.target.strings) pofile = factory.getobject(self.store.file.path) self.assertEqual(dbunit.target.strings, pofile.units[dbunit.index].target.strings) self.assertEqual(dbunit.target, u'samaka') self.assertEqual(dbunit.target, storeunit.target) self.assertEqual(dbunit.target, pofile.units[dbunit.index].target) def test_update_plural_target_dict(self): dbunit = self._update_translation(2, {'target': {0: u'samaka', 1: u'samak'}}) storeunit = dbunit.getorig() self.assertEqual(dbunit.target.strings, [u'samaka', u'samak']) self.assertEqual(dbunit.target.strings, storeunit.target.strings) pofile = factory.getobject(self.store.file.path) self.assertEqual(dbunit.target.strings, pofile.units[dbunit.index].target.strings) self.assertEqual(dbunit.target, u'samaka') self.assertEqual(dbunit.target, storeunit.target) self.assertEqual(dbunit.target, pofile.units[dbunit.index].target) def test_update_fuzzy(self): dbunit = self._update_translation(0, {'target': u'samaka', 'fuzzy': True}) storeunit = dbunit.getorig() self.assertTrue(dbunit.isfuzzy()) self.assertEqual(dbunit.isfuzzy(), storeunit.isfuzzy()) pofile = factory.getobject(self.store.file.path) self.assertEqual(dbunit.isfuzzy(), pofile.units[dbunit.index].isfuzzy()) time.sleep(1) dbunit = self._update_translation(0, {'fuzzy': False}) storeunit = dbunit.getorig() self.assertFalse(dbunit.isfuzzy()) self.assertEqual(dbunit.isfuzzy(), storeunit.isfuzzy()) pofile = factory.getobject(self.store.file.path) self.assertEqual(dbunit.isfuzzy(), pofile.units[dbunit.index].isfuzzy()) def test_update_comment(self): dbunit = self._update_translation(0, {'translator_comment': u'7amada'}) storeunit = dbunit.getorig() self.assertEqual(dbunit.getnotes(origin="translator"), u'7amada') self.assertEqual(dbunit.getnotes(origin="translator"), storeunit.getnotes(origin="translator")) pofile = factory.getobject(self.store.file.path) self.assertEqual(dbunit.getnotes(origin="translator"), pofile.units[dbunit.index].getnotes(origin="translator")) class SuggestionTests(PootleTestCase): def setUp(self): super(SuggestionTests, self).setUp() self.store = Store.objects.get(pootle_path="/af/tutorial/pootle.po") def test_hash(self): unit = self.store.getitem(0) suggestion = unit.add_suggestion("gras") first_hash = suggestion.target_hash suggestion.translator_comment = "my nice comment" second_hash = suggestion.target_hash assert first_hash != second_hash suggestion.target = "gras++" assert first_hash != second_hash != suggestion.target_hash class StoreTests(PootleTestCase): def setUp(self): super(StoreTests, self).setUp() self.store = Store.objects.get(pootle_path="/af/tutorial/pootle.po") def test_quickstats(self): statscache = statsdb.StatsCache() dbstats = self.store.getquickstats() filestats = statscache.filetotals(self.store.file.path) self.assertEqual(dbstats['total'], filestats['total']) self.assertEqual(dbstats['totalsourcewords'], filestats['totalsourcewords']) self.assertEqual(dbstats['untranslated'], filestats['untranslated']) self.assertEqual(dbstats['untranslatedsourcewords'], filestats['untranslatedsourcewords']) self.assertEqual(dbstats['fuzzy'], filestats['fuzzy']) self.assertEqual(dbstats['fuzzysourcewords'], filestats['fuzzysourcewords']) self.assertEqual(dbstats['translated'], filestats['translated']) self.assertEqual(dbstats['translatedsourcewords'], filestats['translatedsourcewords']) self.assertEqual(dbstats['translatedtargetwords'], filestats['translatedtargetwords']) class XHRTestAnonymous(PootleTestCase): """ Base class for testing the XHR views. """ def setUp(self): # FIXME: We should test on a bigger dataset (with a fixture maybe) super(XHRTestAnonymous, self).setUp() self.store = Store.objects.get(pootle_path="/af/tutorial/pootle.po") self.unit = self.store.units[0] self.uid = self.unit.id self.bad_uid = 69696969 self.path = self.store.pootle_path self.bad_path = "/foo/bar/baz.po" self.post_data = {'id': self.uid, 'index': 1, 'path': self.path, 'pootle_path': self.path, 'store': self.path, 'source_f_0': 'fish', 'target_f_0': 'arraina'} # # Tests for the get_view_units() view. # def test_get_view_units_response_ok(self): """AJAX request, should return HTTP 200.""" r = self.client.get("%(pootle_path)s/view" %\ {'pootle_path': self.path}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) def test_get_view_units_bad_store(self): """Checks for store correctness when passing an invalid path.""" r = self.client.get("%(pootle_path)s/view" %\ {'pootle_path': self.bad_path}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 404) # # Tests for the get_more_context() view. # def test_get_more_context_response_ok(self): """AJAX request, should return HTTP 200.""" r = self.client.get("/unit/context/%s" % self.uid, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) def test_get_more_context_bad_unit(self): """Checks for store correctness when passing an invalid uid.""" r = self.client.get("/unit/context/%s" % self.bad_uid, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 404) def test_get_more_context_bad_store_unit(self): """Checks for store/unit correctness when passing an invalid path/uid.""" r = self.client.get("/unit/context/%s" % self.bad_uid, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 404) # # Tests for the get_edit_unit() view. # def test_get_edit_unit_response_ok(self): """AJAX request, should return HTTP 200.""" r = self.client.get("/unit/edit/%s" % self.uid, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) def test_get_edit_unit_bad_unit(self): """Checks for unit correctness when passing an invalid uid.""" r = self.client.get("/unit/edit/%s" % self.bad_uid, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 404) def test_get_edit_unit_bad_store_unit(self): """Checks for store/unit correctness when passing an invalid path/uid.""" r = self.client.get("/unit/edit/%s" % self.bad_uid, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 404) def test_get_edit_unit_good_response(self): """Checks for returned data correctness.""" r = self.client.get("/unit/edit/%s" % self.uid, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) self.assertTemplateUsed(r, 'unit/edit.html') # # Tests for the get_failing_checks() view. # def test_get_failing_checks_response_ok(self): """AJAX request, should return HTTP 200.""" r = self.client.get("%(pootle_path)s/checks/" %\ {'pootle_path': self.path}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) def test_get_failing_checks_bad_store(self): """Checks for store correctness when passing an invalid path.""" r = self.client.get("%(pootle_path)s/checks/" %\ {'pootle_path': self.bad_path}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 404) # # Tests for the process_submit() view. # def test_process_submit_response_ok(self): """AJAX request, should return HTTP 200.""" for m in ("submission", "suggestion"): r = self.client.post("/unit/process/%(uid)s/%(method)s" %\ {'uid': self.uid, 'method': m}, self.post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) def test_process_submit_bad_unit(self): """Checks for unit correctness when passing an invalid uid.""" for m in ("submission", "suggestion"): r = self.client.post("/unit/process/%(uid)s/%(method)s" %\ {'uid': self.bad_uid, 'method': m}, self.post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) j = json.loads(r.content) self.assertTrue('captcha' in j.keys()) def test_process_submit_bad_store_unit(self): """Checks for store/unit correctness when passing an invalid path/uid.""" for m in ("submission", "suggestion"): r = self.client.post("/unit/process/%(uid)s/%(method)s" %\ {'uid': self.bad_uid, 'method': m}, self.post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) j = json.loads(r.content) self.assertTrue('captcha' in j.keys()) def test_process_submit_bad_form(self): """Checks for form correctness when bad POST data is passed.""" form_data = self.post_data del(form_data['index']) for m in ("submission", "suggestion"): r = self.client.post("/unit/process/%(uid)s/%(method)s" %\ {'uid': self.uid, 'method': m}, form_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) j = json.loads(r.content) self.assertTrue('captcha' in j.keys()) def test_process_submit_good_response(self): """Checks for returned data correctness.""" for m in ("submission", "suggestion"): r = self.client.post("/unit/process/%(uid)s/%(method)s" %\ {'uid': self.uid, 'method': m}, self.post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) j = json.loads(r.content) self.assertTrue('captcha' in j.keys()) class XHRTestNobody(XHRTestAnonymous): """ Tests the XHR views as a non-privileged user. """ username = 'nonpriv' password = 'nonpriv' def setUp(self): super(XHRTestNobody, self).setUp() self.client.login(username=self.username, password=self.password) def test_process_submit_bad_unit(self): """Checks for unit correctness when passing an invalid uid.""" for m in ("submission", "suggestion"): r = self.client.post("/unit/process/%(uid)s/%(method)s" %\ {'uid': self.bad_uid, 'method': m}, self.post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 404) def test_process_submit_bad_store_unit(self): """Checks for store/unit correctness when passing an invalid path/uid.""" for m in ("submission", "suggestion"): r = self.client.post("/unit/process/%(uid)s/%(method)s" %\ {'uid': self.bad_uid, 'method': m}, self.post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 404) def test_process_submit_bad_form(self): """Checks for form correctness when bad POST data is passed.""" form_data = self.post_data del(form_data['index']) for m in ("submission", "suggestion"): r = self.client.post("/unit/process/%(uid)s/%(method)s" %\ {'uid': self.uid, 'method': m}, form_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 400) def test_process_submit_good_response(self): """Checks for returned data correctness.""" r = self.client.post("/unit/process/%(uid)s/%(method)s" %\ {'uid': self.uid, 'method': "suggestion"}, self.post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) unit = Unit.objects.get(id=self.uid) sugg = unit.get_suggestions()[0] self.assertEqual(sugg.target, self.post_data['target_f_0']) r = self.client.post("/unit/process/%(uid)s/%(method)s" %\ {'uid': self.uid, 'method': "submission"}, self.post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) unit = Unit.objects.get(id=self.uid) self.assertEqual(unit.target, self.post_data['target_f_0']) class XHRTestAdmin(XHRTestNobody): """ Tests the XHR views as admin user. """ username = 'admin' password = 'admin'
arky/pootle-dev
pootle/apps/pootle_store/tests.py
Python
gpl-2.0
17,327
<?php /*------------------------------------------------------------------------ # com_localise - Localise # ------------------------------------------------------------------------ # author Mohammad Hasani Eghtedar <m.h.eghtedar@gmail.com> # copyright Copyright (C) 2010 http://joomlacode.org/gf/project/com_localise/. All Rights Reserved. # @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL # Websites: http://joomlacode.org/gf/project/com_localise/ # Technical Support: Forum - http://joomlacode.org/gf/project/com_localise/forum/ -------------------------------------------------------------------------*/ // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ); $document = & JFactory::getDocument(); $document->setTitle(JText::_('COM_LOCALISE_LOCALISE') . " - " . JText::_('COM_LOCALISE_PACKAGE'));
bcnu/aptopnews
administrator/components/com_localise/views/package/tmpl/default_document.php
PHP
gpl-2.0
834
/** * @copyright 2009-2019 Vanilla Forums Inc. * @license GPL-2.0-only */ import classNames from "classnames"; import React from "react"; import { useSection, withSection } from "@library/layout/LayoutContext"; import { ILayoutContainer } from "@library/layout/components/interface.layoutContainer"; export function Panel(props: ILayoutContainer) { const Tag = (props.tag as "div") || "div"; return ( <Tag className={classNames(useSection().classes.panel, props.className)} aria-hidden={props.ariaHidden} ref={props.innerRef} > {props.children} </Tag> ); } export default withSection(Panel);
vanilla/vanilla
library/src/scripts/layout/components/Panel.tsx
TypeScript
gpl-2.0
682
<?php namespace estoque\Http\Controllers; use Illuminate\Http\Request; use estoque\Http\Requests; use estoque\Http\Controllers\Controller; class HomeController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // return view('home'); } }
Thiago-Cardoso/treinamento-Laravel5.1
app/Http/Controllers/HomeController.php
PHP
gpl-2.0
456
import processing.core.*; import processing.data.*; import processing.event.*; import processing.opengl.*; import java.util.Map; import java.util.Iterator; import SimpleOpenNI.*; import java.util.Random; import java.net.*; import java.util.Arrays; import java.util.HashMap; import java.util.ArrayList; import java.io.File; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; public class masterB extends PApplet { SimpleOpenNI context; OPC opc; float dx, dy; int test = 0; int numSketches = 4; int numPixels = 60; //per ring float angleOfFirst = PI; //For Spinning Pixels int[] spinHue; int backgroundBright = 0; int backgroundSat = 0; int backgroundSpinHue = 0; int numSpinners = 30; int spinCounter = 0; int spinSat = 100; int shapeCounter[]; int randomPixel[]; int speed = 1; int numInThreshold1 = 0; int numInThreshold2 = 0; int numInThreshold3 = 0; PVector[] spinCircle = new PVector[numSpinners]; shapeClass[][] spinningDots; PVector[] spinDot = new PVector[numSpinners]; // //For fading circles boolean personOnLeft = false; boolean personOnRight = false; boolean leftChanged = false; boolean rightChanged = false; int numFaders = 30; shapeClass[][] fadingDots; PVector[] fadeCircle = new PVector[numFaders]; PVector[] fadeDot = new PVector[numFaders]; int[] fadeHue = new int[numFaders]; int[] fadeSat = new int[numFaders]; int[] faderBrightnesses = new int[numFaders]; boolean[] increaseBrightnesses = new boolean[numFaders]; int initIncBright = 0; int[] oldHue = new int[numFaders]; int faderBrightness = 1; boolean increaseBrightness = true; // //For depthThreshold PImage display; PImage flipped; int depthHue = 0; int depthSat = 100; int depthBri = 100; int backgroundHue = 50;// int hue = 0; int brightness = 0; boolean backwards = false; int numShapes = 1; int counter = 0; boolean firstPass = true; Random randomGenerator = new Random(); char direction; PVector circle = new PVector(); PVector circle2 = new PVector(); shapeClass[] dots; shapeClass[] dots2; shapeClass[][][] dotsArray = new shapeClass[8][8][numPixels]; int pixelCounter = 0; PVector dot = new PVector(); PVector dot2 = new PVector(); float radius; PVector blank; public void setup() { context = new SimpleOpenNI(0, this); context.enableDepth(); blank = new PVector(); blank.x = 0; blank.y = 0; //Use height for width and height to draw square window size(240, 240); // Connect to the local instance of fcserver opc = new OPC(this, "127.0.0.1", 7891); // Map an 8x8 grid of rings of LEDs to the center of the window int numPixelsPerRing = numPixels; opc.ledRingGrid(width, height, numPixelsPerRing); colorMode(HSB, 100); background(0, 0, 0); ///Fading initialization fadingDots = new shapeClass[numFaders][numPixels]; for (int i=0; i<numFaders; i++) { fadeCircle[i] = new PVector(); fadeCircle[i].x = width/16 + (width/8 * (int)random(8)); fadeCircle[i].y = height/16 + (height/8 * (int)random(8)); fadeDot[i] = new PVector(); fadeHue[i] = (int)random(100); oldHue[i] = fadeHue[i]; fadeSat[i] = 100; faderBrightnesses[i] = (int)random(100); initIncBright = (int)random(1); if (initIncBright == 1) increaseBrightnesses[i] = true; else increaseBrightnesses[i] = false; for (int j=0; j<numPixels; j++) fadingDots[i][j] = new shapeClass(color(0, 0, 0), blank); } /// ////Spinner initialization spinHue = new int[numSpinners]; shapeCounter = new int[numSpinners]; randomPixel = new int[numSpinners]; spinningDots = new shapeClass[numSpinners][numPixels]; for (int i=0; i<numSpinners; i++) { spinCircle[i] = new PVector(); spinCircle[i].x = width/16 + (width/8 * (int)random(8)); spinCircle[i].y = height/16 + (height/8 * (int)random(8)); spinDot[i] = new PVector(); randomPixel[i] = (int)random(numPixels); spinHue[i] = (int)random(100); for (int j=0; j<numPixels; j++) { spinningDots[i][j] = new shapeClass(color(0, 0, 0), blank); } } //// opc.setStatusLed(false); radius = ((width + height) / 2) / 20; } float noiseScale=0.02f; public float fractalNoise(float x, float y, float z) { float r = 0; float amp = 1.0f; for (int octave = 0; octave < 4; octave++) { r += noise(x, y, z) * amp; amp /= 2; x *= 2; y *= 2; z *= 2; } return r; } public void draw() { if (hour() >= 5 && hour() < 23) { //Fading Circles if (minute() % 15 >= 10) // if(test == 1) { background(0, 0, 0); context.update(); for (int x = 0; x < context.depthWidth (); x++) { for (int y = 0; y < context.depthHeight (); y++) { // mirroring image int offset = x + y * context.depthWidth(); int[] depthValues = context.depthMap(); int rawDepth = depthValues[offset]; //only get the pixel corresponding to a certain depth int depthmin=0; int depthmax=3000; if (rawDepth < depthmax && rawDepth > depthmin) { if ((x % 640) < 320) personOnLeft = true; if ((x % 640) > 320) personOnRight = true; } } } for (int i=0; i<numFaders; i++) { if (faderBrightnesses[i] >= 100) increaseBrightnesses[i] = false; else if (faderBrightnesses[i] <= 0) increaseBrightnesses[i] = true; if (increaseBrightnesses[i] == true) faderBrightnesses[i]+=5; else if (increaseBrightnesses[i] == false) faderBrightnesses[i]-=5; } for (int i=0; i<numFaders; i++) { for (int j=0; j<numPixels; j++) { float a = angleOfFirst + j * 2 * PI / numPixels; fadeDot[i].x = (int)(fadeCircle[i].x - radius * cos(a) + 0.5f); fadeDot[i].y = (int)(fadeCircle[i].y - radius * sin(a) + 0.5f); if (personOnLeft == true) { if (fadeCircle[i].x < width/2) { fadeHue[i] = (int)random(100); leftChanged = true; } } if (personOnLeft == false && leftChanged == true) { fadeHue[i] = oldHue[i]; if (i == numFaders) leftChanged = false; } if (personOnRight == true) { if (fadeCircle[i].x > width/2) { fadeHue[i] = (int)random(100); rightChanged = true; } } if (personOnRight == false && rightChanged == true && leftChanged == false) { fadeHue[i] = oldHue[i]; if (i == numFaders) rightChanged = false; } fadingDots[i][j] = new shapeClass(color(fadeHue[i], fadeSat[i], faderBrightnesses[i]), fadeDot[i]); fadingDots[i][j].display(); } } for (int i=0; i<numFaders; i++) { if (faderBrightnesses[i] == 0) { fadeCircle[i].x = width/16 + (width/8 * (int)random(8)); fadeCircle[i].y = height/16 + (height/8 * (int)random(8)); fadeHue[i] = (int)random(100); oldHue[i] = fadeHue[i]; fadeSat[i] = 100; for (int k=0; k<numFaders; k++) { if (k != i) { while ( (fadeCircle[i].x == fadeCircle[k].x) && (fadeCircle[i].y == fadeCircle[k].y)) { fadeCircle[i].x = width/16 + (width/8 * (int)random(8)); fadeCircle[i].y = height/16 + (height/8 * (int)random(8)); } } } } } personOnLeft = false; personOnRight = false; } //Clouds if (minute() % 15 <= 5) { // if(test == 1) { long now = millis(); float speed = 0.002f; float angle = sin(now * 0.001f); float z = now * 0.00008f; float hue = now * 0.01f; float scale = 0.005f; int brightnessScale = 100; context.update(); for (int x = 0; x < context.depthHeight (); x++) { for (int y = 0; y < context.depthHeight (); y++) { // mirroring image int offset = context.depthWidth()-x-1+y*context.depthWidth(); int[] depthValues = context.depthMap(); int rawDepth = depthValues[offset]; int pix = x + y * context.depthWidth(); //only get the pixel corresponding to a certain depth int depthmin1 = 0; int depthmax1 = 2000; if (rawDepth < depthmax1 && rawDepth > depthmin1) speed = 0.005f; int depthmin2=2000; int depthmax2=3000; if (rawDepth < depthmax2 && rawDepth > depthmin2) speed = 0.004f; int depthmin3 = 3000; int depthmax3 = 3500; if (rawDepth < depthmax3 && rawDepth > depthmin3) speed = 0.003f; } } dx += cos(angle) * speed; dy += sin(angle) * speed; loadPixels(); for (int x=0; x < width; x++) { for (int y=0; y < height; y++) { float n = fractalNoise(dx + x*scale, dy + y*scale, z) - 0.75f; float m = fractalNoise(dx + x*scale, dy + y*scale, z + 10.0f) - 0.75f; int c = color( (hue + 80.0f * m) % 100.0f, 100 - 100 * constrain(pow(3.0f * n, 3.5f), 0, 0.9f), brightnessScale * constrain(pow(3.0f * n, 1.5f), 0, 0.9f) ); pixels[x + width*y] = c; } } updatePixels(); } //Xtion Depth Threshold if ((minute() % 15) >= 5 && (minute() % 15) < 10) // if(test == 0) { context.update(); display = context.depthImage(); display.loadPixels(); flipped = createImage(display.width, display.height, HSB); flipped.loadPixels(); //loop to select a depthzone for (int x = 0; x < context.depthWidth (); x++) { for (int y = 0; y < context.depthHeight (); y++) { // mirroring image int offset = context.depthWidth()-x-1+y*context.depthWidth(); int[] depthValues = context.depthMap(); int rawDepth = depthValues[offset]; int pix = x + y * context.depthWidth(); //only get the pixel corresponding to a certain depth int depthmin=0; int depthmax=3530; if (rawDepth < depthmax && rawDepth > depthmin) { display.pixels[pix] = color(depthHue, depthSat, depthBri); /* hue+=10; bri+=1; if(hue>=100) { hue=0; } if(bri>=100) bri=50; */ } else display.pixels[pix] = color(backgroundHue, 50, 50); } } for(int x = 0; x < context.depthWidth(); x++) { for(int y = 0; y < context.depthHeight(); y++) { int pix = x + y * context.depthWidth(); int pixInv = (context.depthWidth() - x - 1) + (context.depthHeight() - y - 1) * context.depthWidth(); flipped.pixels[pixInv] = display.pixels[pix]; } } image(flipped, 0, 0, width*1.333333333f, height); depthHue++; if (depthHue==100) depthHue=0; backgroundHue++; if (backgroundHue==100) backgroundHue=0; } /* //Spinning Dots if ((minute() % 20 >= 15) && (minute() % 20 < 20)) if(test == 0) { background(backgroundSpinHue, backgroundSat, backgroundBright); context.update(); display = context.depthImage(); display.loadPixels(); for (int x = 0; x < context.depthHeight (); x++) { for (int y = 0; y < context.depthHeight (); y++) { // mirroring image int offset = context.depthWidth()-x-1+y*context.depthWidth(); int[] depthValues = context.depthMap(); int rawDepth = depthValues[offset]; int pix = x + y * context.depthWidth(); //only get the pixel corresponding to a certain depth int depthmin2=2000; int depthmax2=3000; if (rawDepth < depthmax2 && rawDepth > depthmin2) { // display.pixels[pix] = color(depthHue%100, depthSat, depthBri); numInThreshold2++; } else display.pixels[pix] = color(0); int depthmin1 = 0; int depthmax1 = 2000; if (rawDepth < depthmax1 && rawDepth > depthmin1) numInThreshold1++; int depthmin3 = 3000; int depthmax3 = 3500; if (rawDepth < depthmax3 && rawDepth > depthmin3) numInThreshold3++; } } // display.updatePixels(); // image(display, 0, 0, width*1.333333, height); depthHue++; if (numInThreshold1 < 10000 && numInThreshold2 < 10000 && numInThreshold3 < 35000) speed=1; if (numInThreshold3 > 35000 && numInThreshold3 > numInThreshold2 && numInThreshold3 > numInThreshold1) speed=2; if (numInThreshold2 > 10000 && numInThreshold2 > numInThreshold1 && numInThreshold2 > numInThreshold3) speed=3; if (numInThreshold1 > 10000 && numInThreshold1 > numInThreshold2 && numInThreshold1 > numInThreshold2) speed=4; //assign idividual dot positions from circle center point position for (int i=0; i<numSpinners; i++) { shapeCounter[i]++; float a = angleOfFirst + ((spinCounter + randomPixel[i]) % numPixels) * 2 * PI / numPixels * speed; spinDot[i].x = (int)(spinCircle[i].x - radius * cos(a) + 0.5); spinDot[i].y = (int)(spinCircle[i].y - radius * sin(a) + 0.5); } //create the dots from positions for (int i=0; i<numSpinners; i++) spinningDots[i][spinCounter%numPixels] = new shapeClass(color(spinHue[i], spinSat, 100), spinDot[i]); //display all dots for (int i=0; i<numSpinners; i++) { for (int j=0; j<numPixels; j++) spinningDots[i][j].display(); } if (spinCounter%5==0) { for (int i=0; i<numSpinners; i++) { spinHue[i]++; if (spinHue[i] == 100) spinHue[i] = 0; } } spinCounter++; if (spinCounter == numPixels*4) spinCounter = 0; for (int i=0; i<numSpinners; i++) { if (shapeCounter[i]%5 == (int)random(5) && spinCounter%numPixels == 0) { spinCircle[i].x = width/16 + (width/8 * (int)random(8)); spinCircle[i].y = height/16 + (height/8 * (int)random(8)); randomPixel[i] = (int)random(numPixels); //check to make sure dots aren't on top of each other for (int k=0; k<numSpinners; k++) { if (k != i) { while ( (spinCircle[i].x == spinCircle[k].x) && (spinCircle[i].y == spinCircle[k].y)) { spinCircle[i].x = width/16 + (width/8 * (int)random(8)); spinCircle[i].y = height/16 + (height/8 * (int)random(8)); } } } for (int j=0; j<numPixels; j++) { float a = angleOfFirst + j * 2 * PI / numPixels; spinDot[i].x = (int)(spinCircle[i].x - radius * cos(a) + 0.5); spinDot[i].y = (int)(spinCircle[i].y - radius * sin(a) + 0.5); } } } numInThreshold1 = 0; numInThreshold2 = 0; numInThreshold3 = 0; } */ } else background(0, 0, 0); } class shapeClass { int colour; PVector pos; shapeClass(int colour, PVector pos) { this.colour = colour; this.pos = pos; } public void display() { smooth(); fill(colour); strokeWeight(0); ellipseMode(CENTER); // ellipse(pos.x - 40, pos.y - 40, 50, 50); // println("shape.x: " + pos.x); // println("shape.y: " + pos.y); ellipse(pos.x, pos.y, 3, 3); } } /* * Simple Open Pixel Control client for Processing, * designed to sample each LED's color from some point on the canvas. * * Micah Elizabeth Scott, 2013 * This file is released into the public domain. */ public class OPC { Socket socket; OutputStream output; String host; int port; int[] pixelLocations; byte[] packetData; byte firmwareConfig; String colorCorrection; boolean enableShowLocations; OPC(PApplet parent, String host, int port) { this.host = host; this.port = port; this.enableShowLocations = true; parent.registerDraw(this); } // Set the location of a single LED public void led(int index, int x, int y) { // For convenience, automatically grow the pixelLocations array. We do want this to be an array, // instead of a HashMap, to keep draw() as fast as it can be. if (pixelLocations == null) { pixelLocations = new int[index + 1]; } else if (index >= pixelLocations.length) { pixelLocations = Arrays.copyOf(pixelLocations, index + 1); } pixelLocations[index] = x + width * y; } // Set the locations of a ring of LEDs. The center of the ring is at (x, y), // with "radius" pixels between the center and each LED. The first LED is at // the indicated angle, in radians, measured clockwise from +X. public void ledRing(int index, int count, float x, float y, float radius, float angle, boolean inverted) { float pi = PI; if(inverted == true) pi *= -1; for (int i = 0; i < count; i++) { float a = angle + i * 2 * pi / count; led(index + i, (int)(x - radius * cos(a) + 0.5f), (int)(y - radius * sin(a) + 0.5f)); } } //Draws an 8x8 grid of pixel rings. //Grid is drawn column by column, starting at the bottom left, //and is relative to screen size. public void ledRingGrid(int screenWidth, int screenHeight, int numPixels) { int xPosition = screenWidth / 16; int index = 0; float radius = ((screenWidth + screenHeight) / 2) / 20; float angleOfFirstPixel = PI; boolean inverted = false; if(numPixels == 16) inverted = true; for(int x = 0; x < 8; x++) { int yPosition = screenHeight - (screenHeight / 16); for(int y = 0; y < 8; y++) { ledRing(index, numPixels, xPosition, yPosition, radius, angleOfFirstPixel, inverted); yPosition -= screenHeight / 8; index += numPixels; } xPosition += screenHeight / 8; } } // Should the pixel sampling locations be visible? This helps with debugging. // Showing locations is enabled by default. You might need to disable it if our drawing // is interfering with your processing sketch, or if you'd simply like the screen to be // less cluttered. public void showLocations(boolean enabled) { enableShowLocations = enabled; } // Enable or disable dithering. Dithering avoids the "stair-stepping" artifact and increases color // resolution by quickly jittering between adjacent 8-bit brightness levels about 400 times a second. // Dithering is on by default. public void setDithering(boolean enabled) { if (enabled) firmwareConfig &= ~0x01; else firmwareConfig |= 0x01; sendFirmwareConfigPacket(); } // Enable or disable frame interpolation. Interpolation automatically blends between consecutive frames // in hardware, and it does so with 16-bit per channel resolution. Combined with dithering, this helps make // fades very smooth. Interpolation is on by default. public void setInterpolation(boolean enabled) { if (enabled) firmwareConfig &= ~0x02; else firmwareConfig |= 0x02; sendFirmwareConfigPacket(); } // Put the Fadecandy onboard LED under automatic control. It blinks any time the firmware processes a packet. // This is the default configuration for the LED. public void statusLedAuto() { firmwareConfig &= 0x0C; sendFirmwareConfigPacket(); } // Manually turn the Fadecandy onboard LED on or off. This disables automatic LED control. public void setStatusLed(boolean on) { firmwareConfig |= 0x04; // Manual LED control if (on) firmwareConfig |= 0x08; else firmwareConfig &= ~0x08; sendFirmwareConfigPacket(); } // Set the color correction parameters public void setColorCorrection(float gamma, float red, float green, float blue) { colorCorrection = "{ \"gamma\": " + gamma + ", \"whitepoint\": [" + red + "," + green + "," + blue + "]}"; sendColorCorrectionPacket(); } // Set custom color correction parameters from a string public void setColorCorrection(String s) { colorCorrection = s; sendColorCorrectionPacket(); } // Send a packet with the current firmware configuration settings public void sendFirmwareConfigPacket() { if (output == null) { // We'll do this when we reconnect return; } byte[] packet = new byte[9]; packet[0] = 0; // Channel (reserved) packet[1] = (byte)0xFF; // Command (System Exclusive) packet[2] = 0; // Length high byte packet[3] = 5; // Length low byte packet[4] = 0x00; // System ID high byte packet[5] = 0x01; // System ID low byte packet[6] = 0x00; // Command ID high byte packet[7] = 0x02; // Command ID low byte packet[8] = firmwareConfig; try { output.write(packet); } catch (Exception e) { dispose(); } } // Send a packet with the current color correction settings public void sendColorCorrectionPacket() { if (colorCorrection == null) { // No color correction defined return; } if (output == null) { // We'll do this when we reconnect return; } byte[] content = colorCorrection.getBytes(); int packetLen = content.length + 4; byte[] header = new byte[8]; header[0] = 0; // Channel (reserved) header[1] = (byte)0xFF; // Command (System Exclusive) header[2] = (byte)(packetLen >> 8); header[3] = (byte)(packetLen & 0xFF); header[4] = 0x00; // System ID high byte header[5] = 0x01; // System ID low byte header[6] = 0x00; // Command ID high byte header[7] = 0x01; // Command ID low byte try { output.write(header); output.write(content); } catch (Exception e) { dispose(); } } // Automatically called at the end of each draw(). // This handles the automatic Pixel to LED mapping. // If you aren't using that mapping, this function has no effect. // In that case, you can call setPixelCount(), setPixel(), and writePixels() // separately. public void draw() { if (pixelLocations == null) { // No pixels defined yet return; } if (output == null) { // Try to (re)connect connect(); } if (output == null) { return; } int numPixels = pixelLocations.length; int ledAddress = 4; setPixelCount(numPixels); loadPixels(); for (int i = 0; i < numPixels; i++) { int pixelLocation = pixelLocations[i]; int pixel = pixels[pixelLocation]; packetData[ledAddress] = (byte)(pixel >> 16); packetData[ledAddress + 1] = (byte)(pixel >> 8); packetData[ledAddress + 2] = (byte)pixel; ledAddress += 3; if (enableShowLocations) { pixels[pixelLocation] = 0xFFFFFF ^ pixel; } } writePixels(); if (enableShowLocations) { updatePixels(); } } // Change the number of pixels in our output packet. // This is normally not needed; the output packet is automatically sized // by draw() and by setPixel(). public void setPixelCount(int numPixels) { int numBytes = 3 * numPixels; int packetLen = 4 + numBytes; if (packetData == null || packetData.length != packetLen) { // Set up our packet buffer packetData = new byte[packetLen]; packetData[0] = 0; // Channel packetData[1] = 0; // Command (Set pixel colors) packetData[2] = (byte)(numBytes >> 8); packetData[3] = (byte)(numBytes & 0xFF); } } // Directly manipulate a pixel in the output buffer. This isn't needed // for pixels that are mapped to the screen. public void setPixel(int number, int c) { int offset = 4 + number * 3; if (packetData == null || packetData.length < offset + 3) { setPixelCount(number + 1); } packetData[offset] = (byte) (c >> 16); packetData[offset + 1] = (byte) (c >> 8); packetData[offset + 2] = (byte) c; } // Read a pixel from the output buffer. If the pixel was mapped to the display, // this returns the value we captured on the previous frame. public int getPixel(int number) { int offset = 4 + number * 3; if (packetData == null || packetData.length < offset + 3) { return 0; } return (packetData[offset] << 16) | (packetData[offset + 1] << 8) | packetData[offset + 2]; } // Transmit our current buffer of pixel values to the OPC server. This is handled // automatically in draw() if any pixels are mapped to the screen, but if you haven't // mapped any pixels to the screen you'll want to call this directly. public void writePixels() { if (packetData == null || packetData.length == 0) { // No pixel buffer return; } if (output == null) { // Try to (re)connect connect(); } if (output == null) { return; } try { output.write(packetData); } catch (Exception e) { dispose(); } } public void dispose() { // Destroy the socket. Called internally when we've disconnected. if (output != null) { println("Disconnected from OPC server"); } socket = null; output = null; } public void connect() { // Try to connect to the OPC server. This normally happens automatically in draw() try { socket = new Socket(host, port); socket.setTcpNoDelay(true); output = socket.getOutputStream(); println("Connected to OPC server"); } catch (ConnectException e) { dispose(); } catch (IOException e) { dispose(); } sendColorCorrectionPacket(); sendFirmwareConfigPacket(); } } static public void main(String[] passedArgs) { String[] appletArgs = new String[] { "masterB" }; if (passedArgs != null) { PApplet.main(concat(appletArgs, passedArgs)); } else { PApplet.main(appletArgs); } } }
Signal-to-Noise-Media-Labs/open_windows
sketches/masterB/application.linux64/source/masterB.java
Java
gpl-2.0
26,791
<?php /** * @package HikaShop for Joomla! * @version 4.4.0 * @author hikashop.com * @copyright (C) 2010-2020 HIKARI SOFTWARE. All rights reserved. * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ defined('_JEXEC') or die('Restricted access'); ?> <table class="admintable" width="100%"> <tr> <td class="key"> <?php echo JText::_( 'HIKA_NAME' ); ?> </td> <td> <?php $systemOrderStatuses = array('created', 'confirmed', 'cancelled', 'refunded', 'shipped'); if(!empty($this->element->category_id) && in_array($this->element->category_name, $systemOrderStatuses) && !@$this->translation && @$this->element->category_type=='status'){ ?> <input id="category_name" type="hidden" size="80" name="<?php echo $this->category_name_input; ?>" value="<?php echo $this->escape(@$this->element->category_name); ?>" /><?php echo $this->escape(@$this->element->category_name); ?> <?php }else{ ?> <input id="category_name" type="text" size="80" name="<?php echo $this->category_name_input; ?>" value="<?php echo $this->escape(@$this->element->category_name); ?>" /> <?php } if(isset($this->category_name_published)){ $publishedid = 'published-'.$this->category_name_id; ?> <span id="<?php echo $publishedid; ?>" class="spanloading"><?php echo $this->toggle->toggle($publishedid,(int) $this->category_name_published,'translation') ?></span> <?php } ?> </td> </tr> <tr> <td class="key"> <?php echo JText::_( 'CATEGORY_DESCRIPTION' ); ?> </td> <td width="100%"></td> </tr> <tr> <td colspan="2" width="100%"> <?php if(isset($this->category_description_published)){ $publishedid = 'published-'.$this->category_description_id; ?> <span id="<?php echo $publishedid; ?>" class="spanloading"><?php echo $this->toggle->toggle($publishedid,(int) $this->category_description_published,'translation') ?></span> <br/> <?php } $this->editor->height = 150; $this->editor->content = @$this->element->category_description; echo $this->editor->display(); ?> </td> </tr> <?php if(empty($this->element->category_type) || in_array($this->element->category_type,array('product','manufacturer'))){ ?> <tr> <td class="key"> <?php echo JText::_( 'CATEGORY_META_DESCRIPTION' ); ?> </td> <td> <textarea id="category_meta_description" cols="46" rows="2" name="<?php echo $this->category_meta_description_input; ?>"><?php echo $this->escape(@$this->element->category_meta_description); ?></textarea> <?php if(isset($this->category_meta_description_published)){ $publishedid = 'published-'.$this->category_meta_description_id; ?> <span id="<?php echo $publishedid; ?>" class="spanloading"><?php echo $this->toggle->toggle($publishedid,(int) $this->category_meta_description_published,'translation') ?></span> <?php } ?> </td> </tr> <tr> <td class="key"> <?php echo JText::_( 'CATEGORY_KEYWORDS' ); ?> </td> <td> <textarea id="category_keywords" cols="46" rows="1" name="<?php echo $this->category_keywords_input; ?>"><?php echo $this->escape(@$this->element->category_keywords); ?></textarea> <?php if(isset($this->category_keywords_published)){ $publishedid = 'published-'.$this->category_keywords_id; ?> <span id="<?php echo $publishedid; ?>" class="spanloading"><?php echo $this->toggle->toggle($publishedid,(int) $this->category_keywords_published,'translation') ?></span> <?php } ?> </td> </tr> <tr> <td class="key"> <?php echo JText::_( 'PAGE_TITLE' ); ?> </td> <td> <textarea id="category_page_title" cols="46" rows="2" name="<?php echo $this->category_page_title_input; ?>"><?php if(!isset($this->element->category_page_title)) $this->element->category_page_title=''; echo $this->escape(@$this->element->category_page_title); ?></textarea> <?php if(isset($this->category_page_title_published)){ $publishedid = 'published-'.$this->category_page_title_id; ?> <span id="<?php echo $publishedid; ?>" class="spanloading"><?php echo $this->toggle->toggle($publishedid,(int) $this->category_page_title_published,'translation') ?></span> <?php } ?> </td> </tr> <tr> <td class="key"> <?php echo JText::_( 'HIKA_ALIAS' ); ?> </td> <td> <textarea id="category_alias" cols="46" rows="2" name="<?php echo $this->category_alias_input; ?>"><?php if(!isset($this->element->category_alias))$this->element->category_alias=''; echo $this->escape(@$this->element->category_alias); ?></textarea> <?php if(isset($this->category_alias_published)){ $publishedid = 'published-'.$this->category_alias_id; ?> <span id="<?php echo $publishedid; ?>" class="spanloading"><?php echo $this->toggle->toggle($publishedid,(int) $this->category_alias_published,'translation') ?></span> <?php } ?> </td> </tr> <tr> <td class="key"> <?php echo JText::_( 'PRODUCT_CANONICAL' ); ?> </td> <td> <input type="text" id="category_canonical" name="<?php echo $this->category_canonical_input; ?>" value="<?php if(!isset($this->element->category_alias))$this->element->category_alias=''; echo $this->escape(@$this->element->category_canonical); ?>"/> <?php if(isset($this->category_canonical_published)){ $publishedid = 'published-'.$this->category_canonical_id; ?> <span id="<?php echo $publishedid; ?>" class="spanloading"><?php echo $this->toggle->toggle($publishedid,(int) $this->category_canonical_published,'translation') ?></span> <?php } ?> </td> </tr> <?php } ?> </table>
emundus/v6
administrator/components/com_hikashop/views/category/tmpl/normal.php
PHP
gpl-2.0
6,147
<?PHP require_once "nxheader.inc.php"; // Get the Google Maps API-Key $apikey = $cds->content->get("Google-API-Key"); // Create the Maps-API. The apikey is passed as parameter. $maps = $cds->plugins->getApi("Google Maps API", $apikey); $cds->layout->addToHeader($maps->printGoogleJS()); require_once $cds->path."inc/header.php"; $headline = $cds->content->get("Headline"); $body = $cds->content->get("Body"); if ($headline != "") { echo '<h1>'.$headline.'</h1>'; br(); } if ($body !="") { echo $cds->content->get("Body"); br(); } br(); if ($sma != 1) { // add a point to the map $maps->addAddress($cds->content->get("Address"), $cds->content->get("Address Description")); // setup width and height and zoom factor (0-17) $maps->setWidth(600); $maps->setHeight(450); $maps->zoomLevel = 2; // setup controls $maps->showControl = $cds->content->get("ShowControls"); // draw the map. $maps->showMap(); } else { echo "Address: ".$cds->content->get("Address"); br(); echo "Address Description: ".$cds->content->get("Address Description"); } require_once $cds->path."inc/footer.php"; require_once "nxfooter.inc.php"; ?>
sweih/nxr
wwwdev/map.php
PHP
gpl-2.0
1,192
<?php /** * @package Joomla * @subpackage com_morfeoshow * @copyright Copyright (C) Vamba & Matthew Thomson. All rights reserved. * @license GNU/GPL. * @author Vamba (.joomlaitalia.com) & Matthew Thomson (ignitejoomlaextensions.com) * @based on com_morfeoshow * @author Matthew Thomson (ignitejoomlaextensions.com) * Joomla! and com_morfeoshow are free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed they include or * are derivative of works licensed under the GNU General Public License or * other free or open source software licenses. */ defined( '_JEXEC' ) or die( 'Restricted access' ); ?> <form action="index.php" method="post" name="adminForm" id="adminForm"> <fieldset class="adminform"> <legend><?php echo JText::_( 'Edit images description' ); ?></legend> <table class="admintable" cellpadding="5" cellspacing="0" border="0" "> <tr> <td> &nbsp; </td> <td> <img src="../images/morfeoshow/<?php echo $row->folder . '/thumbs/' . $img_row->filename; ?>" /> </td> </tr> <tr> <td width="100" align="right" class="key"> <?php echo JText::_( 'Title' ); ?> </td> <td> <input class="text_area" type="text" name="title" id="title" size="40" value="<?php echo htmlspecialchars($img_row->title, ENT_QUOTES, 'UTF-8'); ?>" /> </td> </tr> <tr> <td width="100" align="right" class="key"> <?php echo JText::_( 'Date' ); ?> </td> <td><?php echo JHTML::_('calendar', $img_row->imgdate, 'imgdate', 'imgdate', '%Y-%m-%d ', array('class'=>'inputbox', 'size'=>'25', 'maxlength'=>'19')); ?></td> </tr> <td width="100" align="right" class="key"> <?php echo JText::_( 'Description' ); ?> </td> <td> <?php echo $editor->display( 'html', $img_row->html ,'100%', '150', '40', '5', array('pagebreak', 'readmore', 'image') );?> </td> </tr> <tr> <td width="100" align="right" class="key"> <?php echo JText::_( 'Creator' ); ?> </td> <td> <input class="text_area" type="text" name="creator" id="creator" size="40" value="<?php echo $img_row->creator ?>" /> </td> </tr> <tr> <td width="100" align="right" class="key"> <?php echo JText::_( 'Web Site Link' ); ?> </td> <td> <input class="text_area" type="text" name="link" id="link" size="80" value="<?php echo $img_row->link ?>" /> </td> </tr> </table> </fieldset> <input type="hidden" name="folder" value="<?php echo $row->folder; ?>" /> <input type="hidden" name="task" value="" /> <input type="hidden" name="option" value="<?php echo $option ?>" /> <input type="hidden" name="cid" value="<?php echo $id ?>" /> <input type="hidden" name="id" value="<?php echo $img_row->id; ?>" /> </form>
jcorrego/graduarte
administrator/components/com_morfeoshow/view/editphoto.php
PHP
gpl-2.0
2,901
<?php /* ** ZABBIX ** Copyright (C) 2000-2005 SIA Zabbix ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. **/ ?> <?php class CTriggersInfo extends CTable { /* var $style; var $show_header; var $nodeid;*/ function CTriggersInfo($style = STYLE_HORISONTAL) { $this->style = null; parent::CTable(NULL,"triggers_info"); $this->SetOrientation($style); $this->show_header = true; $this->nodeid = get_current_nodeid(); } function SetOrientation($value) { if($value != STYLE_HORISONTAL && $value != STYLE_VERTICAL) return $this->error("Incorrect value for SetOrientation [$value]"); $this->style = $value; } function SetNodeid($nodeid) { $this->nodeid = (int)$nodeid; } function HideHeader() { $this->show_header = false; } function BodyToString() { global $USER_DETAILS; $this->CleanItems(); $ok = $uncn = $info = $warn = $avg = $high = $dis = 0; $db_priority = DBselect("select t.priority,t.value,count(*) as cnt from triggers t,hosts h,hosts_groups hg,items i,functions f". " where t.status=".TRIGGER_STATUS_ENABLED." and f.itemid=i.itemid ". " and h.hostid=i.hostid and h.status=".HOST_STATUS_MONITORED." and t.triggerid=f.triggerid ". " and i.status=".ITEM_STATUS_ACTIVE. ' and hg.hostid=h.hostid and hg.groupid in ('.get_accessible_groups_by_user($USER_DETAILS,PERM_READ_ONLY, null, null, $this->nodeid).') '. " group by priority,t.value"); while($row=DBfetch($db_priority)) { switch($row["value"]) { case TRIGGER_VALUE_TRUE: switch($row["priority"]) { case 1: $info += $row["cnt"]; break; case 2: $warn += $row["cnt"]; break; case 3: $avg += $row["cnt"]; break; case 4: $high += $row["cnt"]; break; case 5: $dis += $row["cnt"]; break; default: $uncn += $row["cnt"]; break; } break; case TRIGGER_VALUE_FALSE: $ok += $row["cnt"]; break; default: $uncn += $row["cnt"]; break; } } if($this->show_header) { $header = new CCol(S_TRIGGERS_INFO,"header"); if($this->style == STYLE_HORISONTAL) $header->SetColspan(7); $this->AddRow($header); } $trok = new CCol($ok.SPACE.S_OK, "normal"); $uncn = new CCol($uncn.SPACE.S_NOT_CLASSIFIED,"unknown"); $info = new CCol($info.SPACE.S_INFORMATION, "information"); $warn = new CCol($warn.SPACE.S_WARNING, "warning"); $avg = new CCol($avg.SPACE.S_AVERAGE, "average"); $high = new CCol($high.SPACE.S_HIGH, "high"); $dis = new CCol($dis.SPACE.S_DISASTER, "disaster"); if($this->style == STYLE_HORISONTAL) { $this->AddRow(array($trok, $uncn, $info, $warn, $avg, $high, $dis)); } else { $this->AddRow($trok); $this->AddRow($uncn); $this->AddRow($info); $this->AddRow($warn); $this->AddRow($avg); $this->AddRow($high); $this->AddRow($dis); } return parent::BodyToString(); } } ?>
Shmuma/z
frontends/php/include/classes/ctriggerinfo.mod.php
PHP
gpl-2.0
3,613
import java.util.*; import java.util.regex.*; import java.text.*; import java.math.*; import java.awt.geom.*; public class SimpleWordGame { public int points(String[] player, String[] dictionary) { Set<String> wrds = new HashSet<String>(); Set<String> dict = new HashSet<String>(); for(int i = 0; i < player.length; i++) wrds.add(player[i]); for(int i = 0; i < dictionary.length; i++) dict.add(dictionary[i]); int ans = 0; Iterator<String> iterator = wrds.iterator(); while(iterator.hasNext()) { String ele = iterator.next(); if(dict.contains(ele)) ans += ele.length() * ele.length(); } return ans; } public static void main(String[] args) { long time; int answer; boolean errors = false; int desiredAnswer; time = System.currentTimeMillis(); answer = new SimpleWordGame().points(new String[]{ "apple", "orange", "strawberry" }, new String[]{ "strawberry", "orange", "grapefruit", "watermelon" }); System.out.println("Time: " + (System.currentTimeMillis()-time)/1000.0 + " seconds"); desiredAnswer = 136; System.out.println("Your answer:"); System.out.println("\t" + answer); System.out.println("Desired answer:"); System.out.println("\t" + desiredAnswer); if (answer != desiredAnswer) { errors = true; System.out.println("DOESN'T MATCH!!!!"); } else System.out.println("Match :-)"); System.out.println(); time = System.currentTimeMillis(); answer = new SimpleWordGame().points(new String[]{ "apple" }, new String[]{ "strawberry", "orange", "grapefruit", "watermelon" }); System.out.println("Time: " + (System.currentTimeMillis()-time)/1000.0 + " seconds"); desiredAnswer = 0; System.out.println("Your answer:"); System.out.println("\t" + answer); System.out.println("Desired answer:"); System.out.println("\t" + desiredAnswer); if (answer != desiredAnswer) { errors = true; System.out.println("DOESN'T MATCH!!!!"); } else System.out.println("Match :-)"); System.out.println(); time = System.currentTimeMillis(); answer = new SimpleWordGame().points(new String[]{ "orange", "orange" }, new String[]{ "strawberry", "orange", "grapefruit", "watermelon" }); System.out.println("Time: " + (System.currentTimeMillis()-time)/1000.0 + " seconds"); desiredAnswer = 36; System.out.println("Your answer:"); System.out.println("\t" + answer); System.out.println("Desired answer:"); System.out.println("\t" + desiredAnswer); if (answer != desiredAnswer) { errors = true; System.out.println("DOESN'T MATCH!!!!"); } else System.out.println("Match :-)"); System.out.println(); time = System.currentTimeMillis(); answer = new SimpleWordGame().points(new String[]{ "lidi", "o", "lidi", "gnbewjzb", "kten", "ebnelff", "gptsvqx", "rkauxq", "rkauxq", "kfkcdn"}, new String[]{ "nava", "wk", "kfkcdn", "lidi", "gptsvqx", "ebnelff", "hgsppdezet", "ulf", "rkauxq", "wcicx"}); System.out.println("Time: " + (System.currentTimeMillis()-time)/1000.0 + " seconds"); desiredAnswer = 186; System.out.println("Your answer:"); System.out.println("\t" + answer); System.out.println("Desired answer:"); System.out.println("\t" + desiredAnswer); if (answer != desiredAnswer) { errors = true; System.out.println("DOESN'T MATCH!!!!"); } else System.out.println("Match :-)"); System.out.println(); if (errors) System.out.println("Some of the test cases had errors :-("); else System.out.println("You're a stud (at least on the test data)! :-D "); } } //Powered by [KawigiEdit] 2.0!
venkatesh551/TopCoder
older/SimpleWordGame.java
Java
gpl-2.0
3,588
<?php //-------------------------------------------------------------------- //- File : contact/mailing_lists.php //- Project : FVWM Home Page //- Programmer : Uwe Pross //-------------------------------------------------------------------- if(!isset($rel_path)) $rel_path = "./.."; //-------------------------------------------------------------------- // load some global definitions //-------------------------------------------------------------------- if(!isset($navigation_check)) include_once($rel_path.'/definitions.inc'); //-------------------------------------------------------------------- // Site definitions //-------------------------------------------------------------------- $title = "FVWM - Mailing Lists"; $heading = "FVWM - Mailing Lists"; $link_name = "Mailing Lists"; $link_picture = "pictures/icons/contact_mailing_list"; $parent_site = "top"; $child_sites = array(); $requested_file = basename(my_get_global("PHP_SELF", "SERVER")); $this_site = "mailing_lists"; //-------------------------------------------------------------------- // check if we should stop here //-------------------------------------------------------------------- if(isset($navigation_check)) return; //-------------------------------------------------------------------- // load the layout file //-------------------------------------------------------------------- if(!isset($site_has_been_loaded)) { $site_has_been_loaded = "true"; include_once(sec_filename("$layout_file")); exit(); } decoration_window_start("Mailing lists"); ?> <p> PLEASE ASK QUESTIONS RELATED TO XMMS ON THE XMMS MAILING LIST. See <a href="http://xmms.org/">http://xmms.org/</a>. </p> <h4>The mailing list addresses are:</h4> <ul> <li><a href="mailto:fvwm@fvwm.org">fvwm@fvwm.org</a> (Discussion and questions list)</li> <li><a href="mailto:fvwm-announce@fvwm.org">fvwm-announce@fvwm.org</a> (Announcement only list)</li> <li><a href="mailto:fvwm-workers@fvwm.org">fvwm-workers@fvwm.org</a> (Beta testers and contributors list)</li> </ul> <p> Please help us managing incoming mail by following a few rules when you write to any of the fvwm related mailing list: <ul> <li> When quoting previous mails in a discussion, please put your replies below the quoted portions of the text.</li> <li> Quote all relevant parts of the original mail in a reply. <li> Type about 66 to 72 characters per line.</li> <li> Insert line breaks manually, even if your email program does it for you.</li> <li> Always specify the fvwm version you use when asking questions or reporting problems.</li> </ul> </p> <p> They are maintained by Jason Tibbitts, and are Majordomo based mailing lists. To subscribe to a list, send "<code>subscribe</code>" in the body of a message to the appropriate <code>*-request</code> address. </p> <p> To unsubscribe from the list, send "<code>unsubscribe</code>" in the body of a message to the appropriate <code>*-request</code> address. </p> <h4>*-request addresses are:</h4> <p> <ul> <li> <a href="mailto:fvwm-request@fvwm.org">fvwm-request@fvwm.org</a></li> <li> <a href="mailto:fvwm-announce-request@fvwm.org">fvwm-announce-request@fvwm.org</a></li> <li> <a href="mailto:fvwm-workers-request@fvwm.org">fvwm-workers-request@fvwm.org</a></li> </ul> </p> <p> <strong>Subscription requests sent to the list will be ignored!</strong><br> Please follow the above instructions for subscribing properly. </p> <p> To report problems with any of the mailing lists, send mail to <a href="mailto:fvwm-owner@fvwm.org">fvwm-owner@fvwm.org</a>. </p> <p> Also the mailing lists are archived: <a href="http://www.mail-archive.com/fvwm@lists.math.uh.edu/">fvwm</a>, <a href="http://www.mail-archive.com/fvwm-workers@lists.math.uh.edu/">fvwm-workers</a>. </p> <p> <form method="GET" action="http://www.mail-archive.com/search"> <b>Search the fvwm mail archive: </b> <input type="text" value="" name="q" size="30"> <input type="hidden" name="num" value="100"> <input type="hidden" name="l" value="fvwm@lists.math.uh.edu"> <input type="submit" name="btnG" value="Search Archives"> </form> <p> <form method="GET" action="http://www.mail-archive.com/search"> <b>Search the fvwm workers mail archive: </b> <input type="text" value="" name="q" size="30"> <input type="hidden" name="num" value="100"> <input type="hidden" name="l" value="fvwm-workers@lists.math.uh.edu"> <input type="submit" name="btnG" value="Search Archives"> </form> <h4>IRC Channels</h4> <p> Several IRC channels are also available to discuss fvwm related topics or to get help. They are not official in a sense that the fvwm developers maintain them, but there is a chance to meet some of the developers there: </p> <ul> <li> #fvwm on freenode</li> <li> +fvwm.de on IRCnet (German channel)</li> </ul> <?php decoration_window_end(); ?>
ThomasAdam/fvwm-web
contact/index.php
PHP
gpl-2.0
5,170
/* $Id: tstMvWnd.cpp 44529 2013-02-04 15:54:15Z vboxsync $ */ /* * Copyright (C) 2010-2011 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #include <windows.h> #define Assert(_m) do {} while (0) #define vboxVDbgPrint(_m) do {} while (0) static LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { if(uMsg == WM_DESTROY) { PostQuitMessage(0); return 0; } // switch(uMsg) // { // case WM_CLOSE: // vboxVDbgPrint((__FUNCTION__": got WM_CLOSE for hwnd(0x%x)", hwnd)); // return 0; // case WM_DESTROY: // vboxVDbgPrint((__FUNCTION__": got WM_DESTROY for hwnd(0x%x)", hwnd)); // return 0; // case WM_NCHITTEST: // vboxVDbgPrint((__FUNCTION__": got WM_NCHITTEST for hwnd(0x%x)\n", hwnd)); // return HTNOWHERE; // } return DefWindowProc(hwnd, uMsg, wParam, lParam); } #define VBOXDISPWND_NAME L"tstMvWnd" HRESULT tstMvWndCreate(DWORD w, DWORD h, HWND *phWnd) { HRESULT hr = S_OK; HINSTANCE hInstance = (HINSTANCE)GetModuleHandle(NULL); /* Register the Window Class. */ WNDCLASS wc; if (!GetClassInfo(hInstance, VBOXDISPWND_NAME, &wc)) { wc.style = CS_OWNDC; wc.lpfnWndProc = WindowProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = NULL; wc.hCursor = NULL; wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = VBOXDISPWND_NAME; if (!RegisterClass(&wc)) { DWORD winErr = GetLastError(); vboxVDbgPrint((__FUNCTION__": RegisterClass failed, winErr(%d)\n", winErr)); hr = E_FAIL; } } if (hr == S_OK) { HWND hWnd = CreateWindowEx (0 /*WS_EX_CLIENTEDGE*/, VBOXDISPWND_NAME, VBOXDISPWND_NAME, WS_OVERLAPPEDWINDOW, 0, 0, w, h, GetDesktopWindow() /* hWndParent */, NULL /* hMenu */, hInstance, NULL /* lpParam */); Assert(hWnd); if (hWnd) { *phWnd = hWnd; } else { DWORD winErr = GetLastError(); vboxVDbgPrint((__FUNCTION__": CreateWindowEx failed, winErr(%d)\n", winErr)); hr = E_FAIL; } } return hr; } static int g_Width = 400; static int g_Height = 300; static DWORD WINAPI tstMvWndThread(void *pvUser) { HWND hWnd = (HWND)pvUser; RECT Rect; BOOL bRc = GetWindowRect(hWnd, &Rect); Assert(bRc); if (bRc) { bRc = SetWindowPos(hWnd, HWND_TOPMOST, 0, /* int X */ 0, /* int Y */ g_Width, //Rect.left - Rect.right, g_Height, //Rect.bottom - Rect.top, SWP_SHOWWINDOW); Assert(bRc); if (bRc) { int dX = 10, dY = 10; int xMin = 5, xMax = 300; int yMin = 5, yMax = 300; int x = dX, y = dY; do { bRc = SetWindowPos(hWnd, HWND_TOPMOST, x, /* int X */ y, /* int Y */ g_Width, //Rect.left - Rect.right, g_Height, //Rect.bottom - Rect.top, SWP_SHOWWINDOW); x += dX; if (x > xMax) x = xMin; y += dY; if (y > yMax) y = yMin; Sleep(5); } while(1); } } return 0; } int main(int argc, char **argv, char **envp) { HWND hWnd; HRESULT hr = tstMvWndCreate(200, 200, &hWnd); Assert(hr == S_OK); if (hr == S_OK) { HANDLE hThread = CreateThread( NULL /* LPSECURITY_ATTRIBUTES lpThreadAttributes */, 0 /* SIZE_T dwStackSize */, tstMvWndThread, hWnd, 0 /* DWORD dwCreationFlags */, NULL /* pThreadId */); Assert(hThread); if (hThread) { MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } } DestroyWindow (hWnd); } return 0; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // NOREF(hInstance); NOREF(hPrevInstance); NOREF(lpCmdLine); NOREF(nCmdShow); return main(__argc, __argv, environ); }
carmark/vbox
src/VBox/Additions/WINNT/Graphics/Video/disp/wddm/dbg/tstMvWnd.cpp
C++
gpl-2.0
5,327
<?php /** * Logique des tâches * * PHP versions 5 * * LODEL - Logiciel d'Edition ELectronique. * * Home page: http://www.lodel.org * E-Mail: lodel@lodel.org * * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * @package lodel/logic * @author Ghislain Picard * @author Jean Lamy * @author Pierre-Alain Mignot * @copyright 2001-2002, Ghislain Picard, Marin Dacos * @copyright 2003, Ghislain Picard, Marin Dacos, Luc Santeramo, Nicolas Nutten, Anne Gentil-Beccot * @copyright 2004, Ghislain Picard, Marin Dacos, Luc Santeramo, Anne Gentil-Beccot, Bruno Cénou * @copyright 2005, Ghislain Picard, Marin Dacos, Luc Santeramo, Gautier Poupeau, Jean Lamy, Bruno Cénou * @copyright 2006, Marin Dacos, Luc Santeramo, Bruno Cénou, Jean Lamy, Mikaël Cixous, Sophie Malafosse * @copyright 2007, Marin Dacos, Bruno Cénou, Sophie Malafosse, Pierre-Alain Mignot * @copyright 2008, Marin Dacos, Bruno Cénou, Pierre-Alain Mignot, Inès Secondat de Montesquieu, Jean-François Rivière * @copyright 2009, Marin Dacos, Bruno Cénou, Pierre-Alain Mignot, Inès Secondat de Montesquieu, Jean-François Rivière * @licence http://www.gnu.org/copyleft/gpl.html * @since Fichier ajouté depuis la version 0.8 * @version CVS:$Id$ */ /** * Classe de logique des tâches * * @package lodel/logic * @author Ghislain Picard * @author Jean Lamy * @copyright 2001-2002, Ghislain Picard, Marin Dacos * @copyright 2003, Ghislain Picard, Marin Dacos, Luc Santeramo, Nicolas Nutten, Anne Gentil-Beccot * @copyright 2004, Ghislain Picard, Marin Dacos, Luc Santeramo, Anne Gentil-Beccot, Bruno Cénou * @copyright 2005, Ghislain Picard, Marin Dacos, Luc Santeramo, Gautier Poupeau, Jean Lamy, Bruno Cénou * @copyright 2006, Marin Dacos, Luc Santeramo, Bruno Cénou, Jean Lamy, Mikaël Cixous, Sophie Malafosse * @copyright 2007, Marin Dacos, Bruno Cénou, Sophie Malafosse, Pierre-Alain Mignot * @copyright 2008, Marin Dacos, Bruno Cénou, Pierre-Alain Mignot, Inès Secondat de Montesquieu, Jean-François Rivière * @copyright 2009, Marin Dacos, Bruno Cénou, Pierre-Alain Mignot, Inès Secondat de Montesquieu, Jean-François Rivière * @licence http://www.gnu.org/copyleft/gpl.html * @since Classe ajouté depuis la version 0.8 * @see logic.php */ class TasksLogic extends Logic { /** * generic equivalent assoc array */ public $g_name; /** Constructor */ public function __construct() { parent::__construct("tasks"); } /** * Affichage d'un objet * * @param array &$context le contexte passé par référence * @param array &$error le tableau des erreurs éventuelles passé par référence */ public function viewAction(&$context,&$error) { trigger_error("TasksLogic::viewAction", E_USER_ERROR); } /** * Changement du rang d'un objet * * @param array &$context le contexte passé par référence * @param array &$error le tableau des erreurs éventuelles passé par référence */ public function changeRankAction(&$context, &$error, $groupfields = "", $status = "status>0") { trigger_error("TasksLogic::changeRankAction", E_USER_ERROR); } /** * add/edit Action */ public function editAction(&$context,&$error, $clean=false) { trigger_error("TasksLogic::editAction", E_USER_ERROR); } /*---------------------------------------------------------------*/ //! Private or protected from this point /** * @private */ /** * Indique si un objet est protégé en suppression * * Cette méthode indique si un objet, identifié par son identifiant numérique et * éventuellement son status, ne peut pas être supprimé. Dans le cas où un objet ne serait * pas supprimable un message est retourné indiquant la cause. Sinon la méthode renvoit le * booleen false. * * @param integer $id identifiant de l'objet * @param integer $status status de l'objet * @return false si l'objet n'est pas protégé en suppression, un message sinon */ public function isdeletelocked($id,$status=0) { $id = (int)$id; // basic check. Should be more advanced because of the potential conflict between // adminlodel adn othe rusers $vo=$this->_getMainTableDAO()->find("id='".$id."' AND user='".C::get('id', 'lodeluser')."'","id"); return $vo->id ? false : true ; } // begin{publicfields} automatic generation // /** * Retourne la liste des champs publics * @access private */ protected function _publicfields() { return array(); } // end{publicfields} automatic generation // // begin{uniquefields} automatic generation // // end{uniquefields} automatic generation // } // class
charlycoste/lodel-old
lodel/scripts/logic/class.tasks.php
PHP
gpl-2.0
5,266
<?php namespace PaLogic\Bundle\UserBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class PaLogicUserBundle extends Bundle { public function getParent() { return 'FOSUserBundle'; // Name of parent bundle } }
71m024/palogic
src/PaLogic/Bundle/UserBundle/PaLogicUserBundle.php
PHP
gpl-2.0
238
/* * Copyright (C) 2006, 2008 Thomas Zander <zander@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "GroupShape.h" #include <KoShapeFactory.h> #include <KoCreateShapesTool.h> #include <QDomElement> GroupShape::GroupShape(KoShapeFactory *shapeFactory) : IconShape(shapeFactory->icon()) { m_shapeFactory = shapeFactory; } void GroupShape::visit(KoCreateShapesTool *tool) { tool->setShapeId(m_shapeFactory->id()); tool->setShapeProperties(0); } QString GroupShape::toolTip() { return m_shapeFactory->toolTip(); } QString GroupShape::groupId() const { return m_shapeFactory->id(); } void GroupShape::save(QDomElement &root) { Q_UNUSED(root); }
JeremiasE/KFormula
plugins/dockers/shapeselector/GroupShape.cpp
C++
gpl-2.0
1,427
<?php //====================================================== // Copyright (C) 2006 Claudio Redaelli, All Rights Reserved // // This file is part of the Unit Command Climate // Assessment and Survey System (UCCASS) // // UCCASS is free software; you can redistribute it and/or // modify it under the terms of the Affero General Public License as // published by Affero, Inc.; either version 1 of the License, or // (at your option) any later version. // // http://www.affero.org/oagpl.html // // UCCASS 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 // Affero General Public License for more details. //====================================================== include('classes/main.class.php'); include('classes/special_results.class.php'); include('classes/spss_results.class.php'); $survey = new UCCASS_SPSS_Results(@$_REQUEST['sid'], @$_REQUEST['sep'], @$_REQUEST['del'], @$_REQUEST['altdel'], @$_REQUEST['text'], @$_REQUEST['altcr'], @$_REQUEST['order']); echo $survey->getData(); ?>
nishad/uccass
results_spss.php
PHP
gpl-2.0
1,125
import data from './data.json'; import * as F2 from '../../../../src/index'; // 兼容之前的pinch和pan import '../../../../src/interaction/index'; import Pan from '../../../../src/interaction/pan'; import Pinch from '../../../../src/interaction/pinch'; const canvas = document.createElement('canvas'); canvas.width = 500; canvas.height = 500; document.body.appendChild(canvas); const chart = new F2.Chart({ el: canvas, pixelRatio: window.devicePixelRatio }); chart.source(data, { reportDate: { type: 'timeCat', tickCount: 3, range: [ 0, 1 ], mask: 'YYYY-MM-DD' }, rate: { tickCount: 5 } }); chart.line() .position('reportDate*rate') .color('name'); describe('Interaction', () => { it('contructor compatible', () => { expect(F2.Chart._Interactions.pan).toBe(Pan); expect(F2.Chart._Interactions.pinch).toBe(Pinch); }); it('instance compatible', () => { chart.interaction('pan'); chart.interaction('pinch'); chart.render(); expect(chart._interactions.pan).toBeInstanceOf(Pan); expect(chart._interactions.pinch).toBeInstanceOf(Pinch); }); });
antvis/g2-mobile
test/unit/interaction/new/compatible-spec.js
JavaScript
gpl-2.0
1,124
#-*- coding: utf-8 -*- from openerp.osv import fields, osv class partner_add_contact(osv.osv_memory): _name = "partner.add.contact" _columns = { "name": fields.char("Nom", size=128, required=True), "partner_id": fields.many2one("res.partner", u"Partenaire associé"), "firstname": fields.char("Prénom", size=128, required=True), "phone": fields.char(u"Numéro de téléphone", size=30), "mobile": fields.char(u"Téléphone portable"), "email": fields.char("Email", size=128), "position": fields.char(u"Fonction dans l'entreprise", size=128), 'civilite': fields.selection([('mr', 'Monsieur'),('mme', 'Madame'),('mlle','Mademoiselle')], u'Civilité'), } def set_contact(self, cr, uid, ids, context=None): obj = self.browse(cr, uid, ids[0], context=context) vals = { "name": obj.name, "partner_id": obj.partner_id.id, "firstname": obj.firstname, "phone": obj.phone, "mobile": obj.mobile, "email": obj.email, "position": obj.position, "civilite": obj.civilite } return self.pool.get('magellanes.contact').create(cr, uid, vals, context)
ATSTI/administra
open_corretora/brokerage/wizard/partner_add_contact.py
Python
gpl-2.0
1,249
/* $Id$ */ /* * This file is part of OpenTTD. * OpenTTD 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. * OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>. */ /** @file sound.cpp Handling of playing sounds. */ #include "stdafx.h" #include "landscape.h" #include "mixer.h" #include "newgrf_sound.h" #include "fios.h" #include "window_gui.h" #include "vehicle_base.h" /* The type of set we're replacing */ #define SET_TYPE "sounds" #include "base_media_func.h" static SoundEntry _original_sounds[ORIGINAL_SAMPLE_COUNT]; static void OpenBankFile(const char *filename) { memset(_original_sounds, 0, sizeof(_original_sounds)); /* If there is no sound file (nosound set), don't load anything */ if (filename == NULL) return; FioOpenFile(SOUND_SLOT, filename); size_t pos = FioGetPos(); uint count = FioReadDword(); /* The new format has the highest bit always set */ bool new_format = HasBit(count, 31); ClrBit(count, 31); count /= 8; /* Simple check for the correct number of original sounds. */ if (count != ORIGINAL_SAMPLE_COUNT) { /* Corrupt sample data? Just leave the allocated memory as those tell * there is no sound to play (size = 0 due to calloc). Not allocating * the memory disables valid NewGRFs that replace sounds. */ DEBUG(misc, 6, "Incorrect number of sounds in '%s', ignoring.", filename); return; } FioSeekTo(pos, SEEK_SET); for (uint i = 0; i != ORIGINAL_SAMPLE_COUNT; i++) { _original_sounds[i].file_slot = SOUND_SLOT; _original_sounds[i].file_offset = GB(FioReadDword(), 0, 31) + pos; _original_sounds[i].file_size = FioReadDword(); } for (uint i = 0; i != ORIGINAL_SAMPLE_COUNT; i++) { SoundEntry *sound = &_original_sounds[i]; char name[255]; FioSeekTo(sound->file_offset, SEEK_SET); /* Check for special case, see else case */ FioReadBlock(name, FioReadByte()); // Read the name of the sound if (new_format || strcmp(name, "Corrupt sound") != 0) { FioSeekTo(12, SEEK_CUR); // Skip past RIFF header /* Read riff tags */ for (;;) { uint32 tag = FioReadDword(); uint32 size = FioReadDword(); if (tag == ' tmf') { FioReadWord(); // wFormatTag sound->channels = FioReadWord(); // wChannels sound->rate = FioReadDword(); // samples per second if (!new_format) sound->rate = 11025; // seems like all old samples should be played at this rate. FioReadDword(); // avg bytes per second FioReadWord(); // alignment sound->bits_per_sample = FioReadByte(); // bits per sample FioSeekTo(size - (2 + 2 + 4 + 4 + 2 + 1), SEEK_CUR); } else if (tag == 'atad') { sound->file_size = size; sound->file_slot = SOUND_SLOT; sound->file_offset = FioGetPos(); break; } else { sound->file_size = 0; break; } } } else { /* * Special case for the jackhammer sound * (name in sample.cat is "Corrupt sound") * It's no RIFF file, but raw PCM data */ sound->channels = 1; sound->rate = 11025; sound->bits_per_sample = 8; sound->file_slot = SOUND_SLOT; sound->file_offset = FioGetPos(); } } } static bool SetBankSource(MixerChannel *mc, const SoundEntry *sound) { assert(sound != NULL); if (sound->file_size == 0) return false; int8 *mem = MallocT<int8>(sound->file_size + 2); /* Add two extra bytes so rate conversion can read these * without reading out of its input buffer. */ mem[sound->file_size ] = 0; mem[sound->file_size + 1] = 0; FioSeekToFile(sound->file_slot, sound->file_offset); FioReadBlock(mem, sound->file_size); /* 16-bit PCM WAV files should be signed by default */ if (sound->bits_per_sample == 8) { for (uint i = 0; i != sound->file_size; i++) { mem[i] += -128; // Convert unsigned sound data to signed } } #if TTD_ENDIAN == TTD_BIG_ENDIAN if (sound->bits_per_sample == 16) { uint num_samples = sound->file_size / 2; int16 *samples = (int16 *)mem; for (uint i = 0; i < num_samples; i++) { samples[i] = BSWAP16(samples[i]); } } #endif assert(sound->bits_per_sample == 8 || sound->bits_per_sample == 16); assert(sound->channels == 1); assert(sound->file_size != 0 && sound->rate != 0); MxSetChannelRawSrc(mc, mem, sound->file_size, sound->rate, sound->bits_per_sample == 16); return true; } void InitializeSound() { DEBUG(misc, 1, "Loading sound effects..."); OpenBankFile(BaseSounds::GetUsedSet()->files->filename); } /* Low level sound player */ static void StartSound(SoundID sound_id, float pan, uint volume) { if (volume == 0) return; const SoundEntry *sound = GetSound(sound_id); if (sound == NULL) return; /* Empty sound? */ if (sound->rate == 0) return; MixerChannel *mc = MxAllocateChannel(); if (mc == NULL) return; if (!SetBankSource(mc, sound)) return; /* Apply the sound effect's own volume. */ volume = sound->volume * volume; MxSetChannelVolume(mc, volume, pan); MxActivateChannel(mc); } static const byte _vol_factor_by_zoom[] = {255, 190, 134, 87}; assert_compile(lengthof(_vol_factor_by_zoom) == ZOOM_LVL_COUNT); static const byte _sound_base_vol[] = { 128, 90, 128, 128, 128, 128, 128, 128, 128, 90, 90, 128, 128, 128, 128, 128, 128, 128, 128, 80, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 90, 90, 90, 128, 90, 128, 128, 90, 128, 128, 128, 90, 128, 128, 128, 128, 128, 128, 90, 128, 128, 128, 128, 90, 128, 128, 128, 128, 128, 128, 128, 128, 90, 90, 90, 128, 128, 128, 90, }; static const byte _sound_idx[] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 0, 1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, }; void SndCopyToPool() { for (uint i = 0; i < ORIGINAL_SAMPLE_COUNT; i++) { SoundEntry *sound = AllocateSound(); *sound = _original_sounds[_sound_idx[i]]; sound->volume = _sound_base_vol[i]; sound->priority = 0; } } /** * Decide 'where' (between left and right speaker) to play the sound effect. * @param sound Sound effect to play * @param left Left edge of virtual coordinates where the sound is produced * @param right Right edge of virtual coordinates where the sound is produced * @param top Top edge of virtual coordinates where the sound is produced * @param bottom Bottom edge of virtual coordinates where the sound is produced */ static void SndPlayScreenCoordFx(SoundID sound, int left, int right, int top, int bottom) { if (_settings_client.music.effect_vol == 0) return; const Window *w; FOR_ALL_WINDOWS_FROM_BACK(w) { const ViewPort *vp = w->viewport; if (vp != NULL && left < vp->virtual_left + vp->virtual_width && right > vp->virtual_left && top < vp->virtual_top + vp->virtual_height && bottom > vp->virtual_top) { int screen_x = (left + right) / 2 - vp->virtual_left; int width = (vp->virtual_width == 0 ? 1 : vp->virtual_width); float panning = (float)screen_x / width; StartSound( sound, panning, (_settings_client.music.effect_vol * _vol_factor_by_zoom[vp->zoom - ZOOM_LVL_BEGIN]) / 256 ); return; } } } void SndPlayTileFx(SoundID sound, TileIndex tile) { /* emits sound from center of the tile */ int x = min(MapMaxX() - 1, TileX(tile)) * TILE_SIZE + TILE_SIZE / 2; int y = min(MapMaxY() - 1, TileY(tile)) * TILE_SIZE - TILE_SIZE / 2; uint z = (y < 0 ? 0 : GetSlopeZ(x, y)); Point pt = RemapCoords(x, y, z); y += 2 * TILE_SIZE; Point pt2 = RemapCoords(x, y, GetSlopeZ(x, y)); SndPlayScreenCoordFx(sound, pt.x, pt2.x, pt.y, pt2.y); } void SndPlayVehicleFx(SoundID sound, const Vehicle *v) { SndPlayScreenCoordFx(sound, v->coord.left, v->coord.right, v->coord.top, v->coord.bottom ); } void SndPlayFx(SoundID sound) { StartSound(sound, 0.5, _settings_client.music.effect_vol); } INSTANTIATE_BASE_MEDIA_METHODS(BaseMedia<SoundsSet>, SoundsSet) /** Names corresponding to the sound set's files */ static const char * const _sound_file_names[] = { "samples" }; template <class T, size_t Tnum_files, Subdirectory Tsubdir> /* static */ const char * const *BaseSet<T, Tnum_files, Tsubdir>::file_names = _sound_file_names; template <class Tbase_set> /* static */ const char *BaseMedia<Tbase_set>::GetExtension() { return ".obs"; // OpenTTD Base Sounds } template <class Tbase_set> /* static */ bool BaseMedia<Tbase_set>::DetermineBestSet() { if (BaseMedia<Tbase_set>::used_set != NULL) return true; const Tbase_set *best = NULL; for (const Tbase_set *c = BaseMedia<Tbase_set>::available_sets; c != NULL; c = c->next) { /* Skip unuseable sets */ if (c->GetNumMissing() != 0) continue; if (best == NULL || (best->fallback && !c->fallback) || best->valid_files < c->valid_files || (best->valid_files == c->valid_files && (best->shortname == c->shortname && best->version < c->version))) { best = c; } } BaseMedia<Tbase_set>::used_set = best; return BaseMedia<Tbase_set>::used_set != NULL; }
koreapyj/openttd-yacd
src/sound.cpp
C++
gpl-2.0
9,517
/* This file is part of Cyclos (www.cyclos.org). A project of the Social Trade Organisation (www.socialtrade.org). Cyclos 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. Cyclos 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 Cyclos; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package nl.strohalm.cyclos.controls.members.references; import java.util.Calendar; import java.util.Collection; import java.util.Map; import javax.servlet.http.HttpServletRequest; import nl.strohalm.cyclos.annotations.Inject; import nl.strohalm.cyclos.controls.ActionContext; import nl.strohalm.cyclos.controls.BaseQueryAction; import nl.strohalm.cyclos.entities.accounts.AccountType; import nl.strohalm.cyclos.entities.accounts.transactions.Payment; import nl.strohalm.cyclos.entities.accounts.transactions.TransferType; import nl.strohalm.cyclos.entities.members.Element; import nl.strohalm.cyclos.entities.members.Member; import nl.strohalm.cyclos.entities.members.Reference; import nl.strohalm.cyclos.entities.members.Reference.Level; import nl.strohalm.cyclos.entities.members.Reference.Nature; import nl.strohalm.cyclos.entities.members.ReferenceQuery; import nl.strohalm.cyclos.entities.members.TransactionFeedback; import nl.strohalm.cyclos.entities.settings.LocalSettings; import nl.strohalm.cyclos.services.elements.ReferenceService; import nl.strohalm.cyclos.entities.utils.Period; import nl.strohalm.cyclos.utils.RelationshipHelper; import nl.strohalm.cyclos.utils.RequestHelper; import nl.strohalm.cyclos.entities.utils.TimePeriod; import nl.strohalm.cyclos.utils.binding.BeanBinder; import nl.strohalm.cyclos.utils.binding.DataBinder; import nl.strohalm.cyclos.utils.binding.DataBinderHelper; import nl.strohalm.cyclos.utils.conversion.CoercionHelper; import nl.strohalm.cyclos.utils.query.QueryParameters; import nl.strohalm.cyclos.utils.validation.ValidationException; /** * Action used to view a member's references and edit the reference to that member * @author luis */ public class MemberReferencesAction extends BaseQueryAction { /** * Represents the direction we're searching * @author luis */ public static enum Direction { RECEIVED, GIVEN } private DataBinder<ReferenceQuery> dataBinder; private ReferenceService referenceService; @Inject public void setReferenceService(final ReferenceService referenceService) { this.referenceService = referenceService; } @SuppressWarnings("unchecked") @Override protected void executeQuery(final ActionContext context, final QueryParameters queryParameters) { final HttpServletRequest request = context.getRequest(); final MemberReferencesForm form = context.getForm(); final Direction direction = CoercionHelper.coerce(Direction.class, form.getDirection()); final Member member = (Member) request.getAttribute("member"); final ReferenceQuery query = (ReferenceQuery) queryParameters; if (member != null) { form.setMemberId(member.getId()); } // Retrieve both summaries for all time and last 30 days final Map<Level, Integer> allTime = referenceService.countReferencesByLevel(query.getNature(), member, direction == Direction.RECEIVED); request.setAttribute("summaryAllTime", allTime); final Period period30 = new TimePeriod(30, TimePeriod.Field.DAYS).periodEndingAt(Calendar.getInstance()); final Map<Level, Integer> last30Days = referenceService.countReferencesHistoryByLevel(query.getNature(), member, period30, direction == Direction.RECEIVED); request.setAttribute("summaryLast30Days", last30Days); // Calculate the score int totalAllTime = 0; int total30Days = 0; int scoreAllTime = 0; int score30Days = 0; final Collection<Level> levels = (Collection<Level>) request.getAttribute("levels"); int nonNeutralCountAllTime = 0; int positiveCountAllTime = 0; int nonNeutralCount30Days = 0; int positiveCount30Days = 0; for (final Level level : levels) { final int value = level.getValue(); final int allTimeCount = CoercionHelper.coerce(Integer.TYPE, allTime.get(level)); final int last30DaysCount = CoercionHelper.coerce(Integer.TYPE, last30Days.get(level)); // Calculate the total totalAllTime += allTimeCount; total30Days += last30DaysCount; // Calculate the score (sum of count * value) scoreAllTime += allTimeCount * value; score30Days += last30DaysCount * value; // Calculate the data for positive percentage if (value != 0) { nonNeutralCountAllTime += allTimeCount; nonNeutralCount30Days += last30DaysCount; if (value > 0) { positiveCountAllTime += allTimeCount; positiveCount30Days += last30DaysCount; } } } // Calculate the positive percentage final int percentAllTime = nonNeutralCountAllTime == 0 ? 0 : Math.round((float) positiveCountAllTime / nonNeutralCountAllTime * 100F); final int percentLast30Days = nonNeutralCount30Days == 0 ? 0 : Math.round((float) positiveCount30Days / nonNeutralCount30Days * 100F); // Store calculated data on request request.setAttribute("totalAllTime", totalAllTime); request.setAttribute("total30Days", total30Days); request.setAttribute("scoreAllTime", scoreAllTime); request.setAttribute("score30Days", score30Days); request.setAttribute("percentAllTime", percentAllTime); request.setAttribute("percent30Days", percentLast30Days); // Get the references list request.setAttribute("references", referenceService.search(query)); } @Override protected QueryParameters prepareForm(final ActionContext context) { final MemberReferencesForm form = context.getForm(); final HttpServletRequest request = context.getRequest(); final ReferenceQuery query = getDataBinder().readFromString(form.getQuery()); query.setNature(CoercionHelper.coerce(Nature.class, form.getNature())); if (query.getNature() == null) { query.setNature(Nature.GENERAL); } // Find out the member Member member; try { member = (Member) (form.getMemberId() <= 0L ? context.getAccountOwner() : elementService.load(form.getMemberId(), Element.Relationships.GROUP)); } catch (final Exception e) { throw new ValidationException(); } final boolean myReferences = member.equals(context.getAccountOwner()); // Retrieve the direction we're looking at Direction direction = CoercionHelper.coerce(Direction.class, form.getDirection()); if (direction == null) { direction = Direction.RECEIVED; form.setDirection(direction.name()); } final boolean isGiven = direction == Direction.GIVEN; if (isGiven) { query.setFrom(member); } else { query.setTo(member); } final boolean isGeneral = query.getNature() == Reference.Nature.GENERAL; if (!isGeneral) { query.fetch(RelationshipHelper.nested(TransactionFeedback.Relationships.TRANSFER, Payment.Relationships.TYPE, TransferType.Relationships.FROM, AccountType.Relationships.CURRENCY)); } // When it's a member (or operator) viewing of other member's received general references, he can set his own too final boolean canSetReference = isGeneral && referenceService.canGiveGeneralReference(member); // Check whether the logged user can manage references on the list final boolean canManage = isGeneral && (myReferences && isGiven || !myReferences) && referenceService.canManageGeneralReference(member); // Bind the form and store the request attributes final LocalSettings localSettings = settingsService.getLocalSettings(); getDataBinder().writeAsString(form.getQuery(), query); request.setAttribute("member", member); request.setAttribute("canManage", canManage); request.setAttribute("myReferences", myReferences); request.setAttribute("isGiven", isGiven); request.setAttribute("isGeneral", isGeneral); request.setAttribute("levels", localSettings.getReferenceLevelList()); request.setAttribute("canSetReference", canSetReference); RequestHelper.storeEnum(request, Direction.class, "directions"); if (!isGeneral) { final boolean showAmount = context.isAdmin() || context.getAccountOwner().equals(member); request.setAttribute("showAmount", showAmount); } return query; } @Override protected boolean willExecuteQuery(final ActionContext context, final QueryParameters queryParameters) throws Exception { return true; } private DataBinder<ReferenceQuery> getDataBinder() { if (dataBinder == null) { final BeanBinder<ReferenceQuery> binder = BeanBinder.instance(ReferenceQuery.class); binder.registerBinder("pageParameters", DataBinderHelper.pageBinder()); dataBinder = binder; } return dataBinder; } }
mateli/OpenCyclos
src/main/java/nl/strohalm/cyclos/controls/members/references/MemberReferencesAction.java
Java
gpl-2.0
9,953
using System; using System.Collections.Generic; namespace LeetCode { public partial class Solution { public int LengthOfLongestSubstring(string s) { //TODO 以下算法虽然思路是对的,但是写法有问题,无法通过长字符串的测试,不应该递归 #region Bad performance // IList<char> dic=new List<char>(); // for (var i = 0; i < s.Length; i++) // { // char c = s [i]; // if (dic.Contains (c)) // { // var sub = s.Substring (s.IndexOf (c) + 1); // // return Math.Max (i, LengthOfLongestSubstring (sub)); // } // dic.Add (c); // // } // return s.Length; #endregion //IList<char> dic=new List<char>(); const int ARRAY_LEN=255; int[] dic=new int[ARRAY_LEN]; for (var i = 0; i < ARRAY_LEN; i++) { dic [i] = -1; } int start = 0; int max = 0; for (var i = 0; i < s.Length; i++) { var c = s [i]; if (dic[c]>=start)//也就是说dic里面不是-1,已经被赋值过,而且这个值在start位置之后出现,判断为重复 { int len = i - start; max = Math.Max (max, len); start = dic [c] + 1; } dic [c] = i; } max = Math.Max (max, s.Length - start); return max; } } }
studyzy/Leetcode
CSharp/LeetCode/LongestSubstringWithoutRepeatingCharacters.cs
C#
gpl-2.0
1,226
/**************************************************************************** The Sire build utility 'sire'. Copyright (C) 1999, 2000, 2002, 2003 David W Orchard (davido@errol.org.uk) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***************************************************************************** File : machine.cpp Class : None Desc : A description AMENDMENTS EDIT 001 21-Nov-97 davido Check the root directory as well. EDIT 002 13-Jan-99 davido Support SuSe Linux file positions. EDIT 003 14-Aug-99 davido Support Linux Fortran 77 EDIT 004 19-May-00 davido Take out the platform specific dependency. EDIT 005 15-Nov-02 davido Remove support for infrequently used options EDIT 006 10-Jan-03 davido Remove getPython, getMachine() and getPlatform(). Now redundant. *****************************************************************************/ /************* INCLUDE ******************************************************/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "sys.h" #include "env.h" #include "machine.h" #include "build_v.h" /************* FUNCTIONS ****************************************************/ static char const *findName(char **list) { static char buff1[256]; static char buff2[256]; int len1; int len2; for (char **p = list; (NULL != *p); p++) { strcpy(buff1, (char*)Tenv::appExpand(*p)); strcpy(buff2, (char*)Tenv::appGet("ROOTDIR")); // 004 strcat(buff2, buff1); len1 = strlen(buff1); len2 = strlen(buff2); for (char const * const *q = getExeList(); (NULL != *q); q++) { strcpy(buff1 +len1, *q); strcpy(buff2 +len2, *q); if (!access(buff1, X_OK)) // Check the given path return (buff1); if (!access(buff2, X_OK)) // Check against the file system root return (buff2); } } return (*list); } char const *getCCP() { // C++ Compiler static char *list[] = { "/bin/CC", "/bin/ccp", "/usr/bin/CC", "/usr/bin/ccp", "/usr/ucb/CC", "/usr/ucb/ccp", "/usr/lang/CC", "/usr/lang/ccp", "/opt/SUNWspro/bin/CC", "/opt/SUNWspro/bin/ccp", "${RELEASE}/SC1.0/CC", "${RELEASE}/SC1.0/ccp", "/usr/local/bin/gcc", "${Init}/bin/cl", "/usr/bin/g++", // 002 NULL }; return(findName(list)); } char const *getCPP() { // C Preprocessor static char *list[] = { "/bin/cpp", "/usr/bin/cpp", "/usr/ucb/cpp", "/usr/lang/cpp", "/opt/SUNWspro/bin/cpp", "${RELEASE}/SC1.0/cpp", NULL }; return(findName(list)); } char const *getCC() { // C Compiler static char *list[] = { "/bin/cc", "/usr/ucb/cc", "/usr/bin/cc", "/usr/lang/cc", "/opt/SUNWspro/bin/cc", "${RELEASE}/SC1.0/cc", "${Init}/bin/cl", "/usr/bin/gcc", // 002 NULL }; return(findName(list)); } char const *getJava() { // C Compiler static char *list[] = { "/usr/bin/javac", "javac", NULL }; return(findName(list)); } char const *getSH() { // C Compiler static char *list[] = { "/bin/sh", NULL }; return(findName(list)); } char const *getCSH() { // C Compiler static char *list[] = { "/bin/csh", NULL }; return(findName(list)); } char const *getTmpDir() { const char *path = "/tmp"; // UNIX - default #if defined (INTEL_NT) || defined (INTEL_9X) if (NULL != (path = Tenv::appGet("TMP"))) { if (access((char*)path, F_OK) || !isDir(path)) { // Does not exist path = NULL; } } if ((NULL == path) && (NULL != (path = Tenv::appGet("TEMP")))) { if (access((char*)path, F_OK) || !isDir(path)) { // Does not exist path = NULL; } } if (NULL == path) { // PC - default char buff[512]; sprintf(buff, "%s/tmp", Tenv::appGet("ROOTDIR")); path = buff; } #endif return(path); } /************* END OF FILE **************************************************/
LaMaisonOrchard/Sire
sire/machine.cpp
C++
gpl-2.0
4,814
require 'rails_helper' RSpec.shared_context 'some assigned reviews and some unassigned reviews' do let!(:user) { create(:user) } let!(:review_assigned1) { create(:review, by_user: user.login) } let!(:review_assigned2) { create(:review, by_user: user.login) } let!(:review_unassigned1) { create(:review, by_user: user.login) } let!(:review_unassigned2) { create(:review, by_user: user.login) } let!(:history_element1) do create(:history_element_review_assigned, op_object_id: review_assigned1.id, user_id: user.id) end let!(:history_element2) do create(:history_element_review_assigned, op_object_id: review_assigned2.id, user_id: user.id) end let!(:history_element3) do create(:history_element_review_accepted, op_object_id: review_assigned2.id, user_id: user.id) end let!(:history_element4) do create(:history_element_review_accepted, op_object_id: review_unassigned1.id, user_id: user.id) end end RSpec.describe Review do let(:project) { create(:project_with_package, name: 'Apache', package_name: 'apache2') } let(:package) { project.packages.first } let(:user) { create(:user, login: 'King') } let(:group) { create(:group, title: 'Staff') } it { is_expected.to belong_to(:bs_request).touch(true) } describe 'validations' do it 'is not allowed to specify by_user and any other reviewable' do [:by_group, :by_project, :by_package].each do |reviewable| review = Review.create(:by_user => user.login, reviewable => 'not-existent-reviewable') expect(review.errors.messages[:base]). to eq(['it is not allowed to have more than one reviewer entity: by_user, by_group, by_project, by_package']) end end it 'is not allowed to specify by_group and any other reviewable' do [:by_project, :by_package].each do |reviewable| review = Review.create(:by_group => group.title, reviewable => 'not-existent-reviewable') expect(review.errors.messages[:base]). to eq(['it is not allowed to have more than one reviewer entity: by_user, by_group, by_project, by_package']) end end end describe '.assigned' do include_context 'some assigned reviews and some unassigned reviews' subject { Review.assigned } it { is_expected.to match_array([review_assigned1, review_assigned2]) } end describe '.unassigned' do include_context 'some assigned reviews and some unassigned reviews' subject { Review.unassigned } it { is_expected.to match_array([review_unassigned1, review_unassigned2]) } end describe '.set_associations' do context 'with valid attributes' do it 'sets user association when by_user object exists' do review = create(:review, by_user: user.login) expect(review.user).to eq(user) expect(review.by_user).to eq(user.login) end it 'sets group association when by_group object exists' do review = create(:review, by_group: group.title) expect(review.group).to eq(group) expect(review.by_group).to eq(group.title) end it 'sets project association when by_project object exists' do review = create(:review, by_project: project.name) expect(review.project).to eq(project) expect(review.by_project).to eq(project.name) end it 'sets package and project associations when by_package and by_project object exists' do review = create(:review, by_project: project.name, by_package: package.name) expect(review.package).to eq(package) expect(review.by_package).to eq(package.name) expect(review.project).to eq(project) expect(review.by_project).to eq(project.name) end end context 'with invalid attributes' do let!(:nobody) { create(:user_nobody) } it 'does not set user association when by_user object does not exist' do review = Review.new(by_user: 'not-existent') expect(review.user).to eq(nil) expect(review.valid?).to eq(false) end it 'does not set user association when by_user object is _nobody_' do review = Review.new(by_user: nobody) expect(review.user).to eq(nil) expect(review.valid?).to eq(false) expect(review.errors.messages[:base]). to eq(["Couldn't find user #{nobody.login}"]) end it 'does not set group association when by_group object does not exist' do review = Review.new(by_group: 'not-existent') expect(review.group).to eq(nil) expect(review.valid?).to eq(false) end it 'does not set project association when by_project object does not exist' do review = Review.new(by_project: 'not-existent') expect(review.project).to eq(nil) expect(review.valid?).to eq(false) end it 'does not set project and package associations when by_project and by_package object does not exist' do review = Review.new(by_project: 'not-existent', by_package: 'not-existent') expect(review.package).to eq(nil) expect(review.valid?).to eq(false) end it 'does not set package association when by_project parameter is missing' do review = Review.new(by_package: package.name) expect(review.package).to eq(nil) expect(review.valid?).to eq(false) end end end describe '#accepted_at' do let!(:user) { create(:user) } let(:review_state) { :accepted } let!(:review) do create( :review, by_user: user.login, state: review_state ) end let!(:history_element_review_accepted) do create( :history_element_review_accepted, review: review, user: user, created_at: Faker::Time.forward(1) ) end context 'with a review assigned to and assigned to state = accepted' do let!(:review2) do create( :review, by_user: user.login, review_id: review.id, state: :accepted ) end let!(:history_element_review_accepted2) do create( :history_element_review_accepted, review: review2, user: user, created_at: Faker::Time.forward(2) ) end subject { review.accepted_at } it { is_expected.to eq(history_element_review_accepted2.created_at) } end context 'with a review assigned to and assigned to state != accepted' do let!(:review2) do create( :review, by_user: user.login, review_id: review.id, updated_at: Faker::Time.forward(2), state: :new ) end subject { review.accepted_at } it { is_expected.to eq(nil) } end context 'with no reviewed assigned to and state = accepted' do subject { review.accepted_at } it { is_expected.to eq(history_element_review_accepted.created_at) } end context 'with no reviewed assigned to and state != accepted' do let(:review_state) { :new } subject { review.accepted_at } it { is_expected.to eq(nil) } end end describe '#declined_at' do let!(:user) { create(:user) } let(:review_state) { :declined } let!(:review) do create( :review, by_user: user.login, state: review_state ) end let!(:history_element_review_declined) do create( :history_element_review_declined, review: review, user: user, created_at: Faker::Time.forward(1) ) end context 'with a review assigned to and assigned to state = declined' do let!(:review2) do create( :review, by_user: user.login, review_id: review.id, state: :declined ) end let!(:history_element_review_declined2) do create( :history_element_review_declined, review: review2, user: user, created_at: Faker::Time.forward(2) ) end subject { review.declined_at } it { is_expected.to eq(history_element_review_declined2.created_at) } end context 'with a review assigned to and assigned to state != declined' do let!(:review2) do create( :review, by_user: user.login, review_id: review.id, updated_at: Faker::Time.forward(2), state: :new ) end subject { review.declined_at } it { is_expected.to eq(nil) } end context 'with no reviewed assigned to and state = declined' do subject { review.declined_at } it { is_expected.to eq(history_element_review_declined.created_at) } end context 'with no reviewed assigned to and state != declined' do let(:review_state) { :new } subject { review.declined_at } it { is_expected.to eq(nil) } end end describe '#validate_not_self_assigned' do let!(:user) { create(:user) } let!(:review) { create(:review, by_user: user.login) } context 'assigned to itself' do before { review.review_id = review.id } subject! { review.valid? } it { expect(review.errors[:review_id].count).to eq(1) } end context 'assigned to a different review' do let!(:review2) { create(:review, by_user: user.login) } before { review.review_id = review2.id } subject! { review.valid? } it { expect(review.errors[:review_id].count).to eq(0) } end end describe '#validate_non_symmetric_assignment' do let!(:user) { create(:user) } let!(:review) { create(:review, by_user: user.login) } let!(:review2) { create(:review, by_user: user.login, review_id: review.id) } context 'review1 is assigned to review2 which is already assigned to review1' do before { review.review_id = review2.id } subject! { review.valid? } it { expect(review.errors[:review_id].count).to eq(1) } end context 'review1 is assigned to review3' do let!(:review3) { create(:review, by_user: user.login) } before { review.review_id = review3.id } subject! { review.valid? } it { expect(review.errors[:review_id].count).to eq(0) } end end describe '#update_caches' do RSpec.shared_examples "the subject's cache is reset when it's review changes" do before do Timecop.travel(1.minute) @cache_key = subject.cache_key review.state = :accepted review.save subject.reload end it { expect(subject.cache_key).not_to eq(@cache_key) } end context 'by_user' do let!(:review) { create(:user_review) } subject { review.user } it_should_behave_like "the subject's cache is reset when it's review changes" end context 'by_group' do let(:groups_user) { create(:groups_user) } let(:group) { groups_user.group } let(:user) { groups_user.user } let!(:review) { create(:review, by_group: group) } it_should_behave_like "the subject's cache is reset when it's review changes" do subject { user } end it_should_behave_like "the subject's cache is reset when it's review changes" do subject { group } end end context 'by_package with a direct relationship' do let(:relationship_package_user) { create(:relationship_package_user) } let(:package) { relationship_package_user.package } let!(:review) { create(:review, by_package: package, by_project: package.project) } subject { relationship_package_user.user } it_should_behave_like "the subject's cache is reset when it's review changes" end context 'by_package with a group relationship' do let(:relationship_package_group) { create(:relationship_package_group) } let(:package) { relationship_package_group.package } let(:group) { relationship_package_group.group } let(:groups_user) { create(:groups_user, group: group) } let!(:user) { groups_user.user } let!(:review) { create(:review, by_package: package, by_project: package.project) } it_should_behave_like "the subject's cache is reset when it's review changes" do subject { user } end it_should_behave_like "the subject's cache is reset when it's review changes" do subject { group } end end context 'by_project with a direct relationship' do let(:relationship_project_user) { create(:relationship_project_user) } let(:project) { relationship_project_user.project } let!(:review) { create(:review, by_project: project) } subject { relationship_project_user.user } it_should_behave_like "the subject's cache is reset when it's review changes" end context 'by_project with a group relationship' do let(:relationship_project_group) { create(:relationship_project_group) } let(:project) { relationship_project_group.project } let(:group) { relationship_project_group.group } let(:groups_user) { create(:groups_user, group: group) } let!(:user) { groups_user.user } let!(:review) { create(:review, by_project: project) } it_should_behave_like "the subject's cache is reset when it's review changes" do subject { user } end it_should_behave_like "the subject's cache is reset when it's review changes" do subject { group } end end end describe '#reviewable_by?' do let(:other_user) { create(:user, login: 'bob') } let(:other_group) { create(:group, title: 'my_group') } let(:other_project) { create(:project_with_package, name: 'doc:things', package_name: 'less') } let(:other_package) { other_project.packages.first } let(:other_package_with_same_name) { create(:package, name: package.name) } let(:review_by_user) { create(:review, by_user: user.login) } let(:review_by_group) { create(:review, by_group: group.title) } let(:review_by_project) { create(:review, by_project: project.name) } let(:review_by_package) { create(:review, by_project: project.name, by_package: package.name) } it 'returns true if review configuration matches provided hash' do expect(review_by_user.reviewable_by?(by_user: user.login)).to be(true) expect(review_by_group.reviewable_by?(by_group: group.title)).to be(true) expect(review_by_project.reviewable_by?(by_project: project.name)).to be(true) expect(review_by_package.reviewable_by?(by_package: package.name, by_project: package.project.name)).to be(true) end it 'returns false if review configuration does not match provided hash' do expect(review_by_user.reviewable_by?(by_user: other_user.login)).to be_falsy expect(review_by_group.reviewable_by?(by_group: other_group.title)).to be_falsy expect(review_by_project.reviewable_by?(by_project: other_project.name)).to be_falsy expect(review_by_package.reviewable_by?(by_package: other_package.name, by_project: other_package.project.name)).to be_falsy expect(review_by_package.reviewable_by?(by_package: other_package_with_same_name.name, by_project: other_package_with_same_name.project.name)).to be_falsy end end describe '.new_from_xml_hash' do let(:request_xml) do "<request> <review state='accepted' by_user='#{user}'/> </request>" end let(:request_hash) { Xmlhash.parse(request_xml) } let(:review_hash) { request_hash['review'] } subject { Review.new_from_xml_hash(review_hash) } it 'initalizes the review in state :new' do expect(subject.state).to eq(:new) end end end
Ana06/open-build-service
src/api/spec/models/review_spec.rb
Ruby
gpl-2.0
15,667
#include "\z\ifa3_comp_ace\addons\cannon\script_component.hpp"
bux/IFA3_ACE_COMPAT
addons/cannon/functions/script_component.hpp
C++
gpl-2.0
62
using System; using Server; using Server.Items; namespace Server.Items { public abstract class BaseSpear : BaseMeleeWeapon { public override int DefHitSound{ get{ return 0x23C; } } public override int DefMissSound{ get{ return 0x238; } } public override SkillName DefSkill{ get{ return SkillName.Fencing; } } public override WeaponType DefType{ get{ return WeaponType.Piercing; } } public override WeaponAnimation DefAnimation{ get{ return WeaponAnimation.Pierce2H; } } public BaseSpear( int itemID ) : base( itemID ) { } public BaseSpear( Serial serial ) : base( serial ) { } 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(); } public override void OnHit( Mobile attacker, Mobile defender ) { base.OnHit( attacker, defender ); if ( !Core.AOS && Layer == Layer.TwoHanded && (attacker.Skills[SkillName.Anatomy].Value / 400.0) >= Utility.RandomDouble() ) { defender.SendMessage( "You receive a paralyzing blow!" ); // Is this not localized? defender.Freeze( TimeSpan.FromSeconds( 2.0 ) ); attacker.SendMessage( "You deliver a paralyzing blow!" ); // Is this not localized? attacker.PlaySound( 0x11C ); } if ( !Core.AOS && Poison != null && PoisonCharges > 0 ) { --PoisonCharges; if ( Utility.RandomDouble() >= 0.5 ) // 50% chance to poison defender.ApplyPoison( attacker, Poison ); } } } }
brodock/sunuo
scripts/legacy/Items/Weapons/SpearsAndForks/BaseSpear.cs
C#
gpl-2.0
1,599
package it.giacomos.android.wwwsapp.locationUtils; public class Constants { public static final long LOCATION_UPDATE_INTERVAL = 25000L; public static final long LOCATION_FASTEST_UPDATE_INTERVAL = 20000L; public static final long LOCATION_UPDATES_GPS_MIN_TIME = 12000l; public static final float LOCATION_UPDATES_NETWORK_MIN_DIST = 80f; public static final float LOCATION_UPDATES_GPS_MIN_DIST = 20f; // public static final long LOCATION_UPDATES_PASSIVE_MIN_TIME = 5000l; // public static final float LOCATION_UPDATES_PASSIVE_MIN_DIST = 10f; public static final int LOCATION_COMPARER_INTERVAL = 1000 * 60; public static final int LOCATION_COMPARER_ACCURACY = 200; }
delleceste/wwwsapp
src/it/giacomos/android/wwwsapp/locationUtils/Constants.java
Java
gpl-2.0
688
<?php require_once("include/bittorrent.php"); dbconn(); $langid = 0 + $_GET['sitelanguage']; if ($langid) { $lang_folder = validlang($langid); if(get_langfolder_cookie() != $lang_folder) { set_langfolder_cookie($lang_folder); header("Location: " . $_SERVER['PHP_SELF']); } } require_once(get_langfile_path("", false, $CURLANGDIR)); failedloginscheck (); cur_user_check () ; stdhead($lang_login['head_login']); $s = "<select name=\"sitelanguage\" onchange='submit()'>\n"; $langs = langlist("site_lang"); foreach ($langs as $row) { if ($row["site_lang_folder"] == get_langfolder_cookie()) $se = "selected=\"selected\""; else $se = ""; $s .= "<option value=\"". $row["id"] ."\" ". $se. ">" . htmlspecialchars($row["lang_name"]) . "</option>\n"; } $s .= "\n</select>"; ?> <?php unset($returnto); if (!empty($_GET["returnto"])) { $returnto = $_GET["returnto"]; if (!$_GET["nowarn"]) { print("<h1>" . $lang_login['h1_not_logged_in']. "</h1>\n"); print("<p><b>" . $lang_login['p_error']. "</b> " . $lang_login['p_after_logged_in']. "</p>\n"); } } ?> <iframe id="loginframe" name="loginframe" style="display:none;height:1px;width:1px;"></iframe> <form name="formlogin" method="post" target="loginframe"> <p><?php echo $lang_login['p_need_cookies_enables']?><br /> [<b><?php echo $maxloginattempts;?></b>] <?php echo $lang_login['p_fail_ban']?></p> <p><?php echo $lang_login['p_you_have']?> <b><?php echo remaining ();?></b> <?php echo $lang_login['p_remaining_tries']?></p> <p><font color=blue><b>注意:</b></font>登录前请确认您的帐号在西北望BBS已经激活!并注意帐号大小写!</p> <table border="0" cellpadding="5"> <tr><td class="rowhead"><?php echo $lang_login['rowhead_username']?></td><td class="rowfollow" align="left"><input type="text" name="username" style="width: 180px; border: 1px solid gray" /></td></tr> <tr><td class="rowhead"><?php echo $lang_login['rowhead_password']?></td><td class="rowfollow" align="left"><input type="password" name="password" style="width: 180px; border: 1px solid gray"/></td></tr> <tr><td class="toolbox" colspan="2" align="right"><input type="submit" value="<?php echo $lang_login['button_login']?>" class="btn" onClick="LoginbyBBS()" > <input type="reset" value="<?php echo $lang_login['button_reset']?>" class="btn" /></td></tr> </table> <?php if (isset($returnto)) print("<input type=\"hidden\" name=\"returnto\" value=\"" . htmlspecialchars($returnto) . "\" />\n"); ?> </form> <p><?php echo $lang_login['p_no_account_signup']?></p> <?php if ($smtptype != 'none'){ ?> <p><?php echo $lang_login['p_forget_pass_recover']?></p> <p><?php echo $lang_login['p_tishi']?></p> <?php } if ($showhelpbox_main != 'no'){?> <table width="700" class="main" border="0" cellspacing="0" cellpadding="0"><tr><td class="embedded"> <h2><?php echo $lang_login['text_helpbox'] ?><font class="small"> - <?php echo $lang_login['text_helpbox_note'] ?><font id= "waittime" color="red"></font></h2> <?php print("<table width='100%' border='1' cellspacing='0' cellpadding='1'><tr><td class=\"text\">\n"); print("<iframe src='" . get_protocol_prefix() . $BASEURL . "/shoutbox.php?type=helpbox' width='650' height='180' frameborder='0' name='sbox' marginwidth='0' marginheight='0'></iframe><br /><br />\n"); print("<form action='" . get_protocol_prefix() . $BASEURL . "/shoutbox.php' id='helpbox' method='get' target='sbox' name='shbox'>\n"); print($lang_login['text_message']."<input type='text' id=\"hbtext\" name='shbox_text' autocomplete='off' style='width: 500px; border: 1px solid gray' ><input type='submit' id='hbsubmit' class='btn' name='shout' value=\"".$lang_login['sumbit_shout']."\" /><input type='reset' class='btn' value=".$lang_login['submit_clear']." /> <input type='hidden' name='sent' value='yes'><input type='hidden' name='type' value='helpbox' />\n"); print("<div id=sbword style=\"display: none\">".$lang_login['sumbit_shout']."</div>"); print(smile_row("shbox","shbox_text")); print("</td></tr></table></form></td></tr></table>"); } stdfoot();
lzuhzy/xbwpt
xbwpt/login.php
PHP
gpl-2.0
4,030
<?php /******************************************************************** PhPeace - Portal Management System Copyright notice (C) 2003-2019 Francesco Iannuzzelli <francesco@phpeace.org> All rights reserved This script is part of PhPeace. PhPeace 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. PhPeace 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. The GNU General Public License (GPL) is available at http://www.gnu.org/copyleft/gpl.html. A copy can be found in the file COPYING distributed with these scripts. This copyright notice MUST APPEAR in all copies of the script! ********************************************************************/ if (!defined('SERVER_ROOT')) define('SERVER_ROOT',$_SERVER['DOCUMENT_ROOT']); include_once(SERVER_ROOT."/include/header.php"); $phpeace = new Phpeace; $title[] = array('licence',''); echo $hh->ShowTitle($title); ?> <pre> <strong><a href="http://www.phpeace.org" target="_blank" title="PhPeace website - Link to external site - Opens in new browser window">PhPeace</a> - Portal Management System</strong> Copyright (C) 2003-2018 Francesco Iannuzzelli &lt;<a href="mailto:francesco@phpeace.org">francesco@phpeace.org</a>&gt; All rights reserved PhPeace 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. PhPeace 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. The GNU General Public License (GPL) is available at <a href="http://www.gnu.org/copyleft/gpl.html" target="_blank" title="GNU/GPL website - Link to external site - Opens in new browser window">http://www.gnu.org/copyleft/gpl.html</a>. For your convenience a copy is reported below. <hr> GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS </pre> <?php include_once(SERVER_ROOT."/include/footer.php"); ?>
fra967/phpeace
admin/gate/licence.php
PHP
gpl-2.0
17,635
using System; using MonoDevelop.Projects; using System.Xml; using MonoDevelop.Core.Assemblies; namespace MonoDevelop.MonoGame { public static class MonoGameBuildAction { public static readonly string Shader; public static bool IsMonoGameBuildAction(string action){ return action == Shader; } static MonoGameBuildAction(){ Shader = "MonoGameShader"; } } public static class MonoGameProject : DotNetAssemblyProject { public MonoGameProject () { Init (); } public MonoGameProject (string languageName) : base (languageName) { Init (); } public MonoGameProject(string languageName, ProjectCreateInformation info, XmlElement projectOptions) :base(languageName, info, projectOptions) { Init (); } private void Init(){ } public override SolutionItemConfiguration CreateConfiguration(string name) { var conf = new MonoGameProjectConfiguration (name); conf.CopyFrom (base.CreateConfiguration (name)); return conf; } public override bool SupportsFormat (FileFormat format) { return format.Id == "MSBuild10"; } public override TargetFrameworkMoniker GetDefaultTargetFrameworkForFormat (FileFormat format) { return new TargetFrameworkMoniker("4.0"); } public override bool SupportsFramework (MonoDevelop.Core.Assemblies.TargetFramework framework) { if (framework.Id != (MonoDevelop.Core.Assemblies.TargetFrameworkMoniker.NET_4_0)) return false; else return base.SupportsFramework (framework); } protected override System.Collections.Generic.IList<string> GetCommonBuildActions () { var actions = new System.Collections.Generic.List<string> (base.GetCommonBuildActions ()); actions.Add (MonoGameBuildAction.Shader); return actions; } public override string GetDefaultBuildAction (string fileName) { if (System.IO.Path.GetExtension (fileName) == ".fx") { return MonoGameBuildAction.Shader; } return base.GetDefaultBuildAction (fileName); } protected override void PopulateSupportFileList (FileCopySet list, ConfigurationSelector configuration) { base.PopulateSupportFileList (list, configuration); foreach(var projectReference in References){ if (projectReference != null && projectReference.Package.Name == "monogame") { if (projectReference.ReferenceType == ReferenceType.Gac) { foreach (var assem in projectReference.Package.Assemblies) { list.Add (assem.Location); var cfg = (MonoGameProjectConfiguration)configuration.GetConfiguration (this); if (cfg.DebugMode) { var mdbFile = TargetRuntime.GetAssemblyDebugInfoFile (assem.Location); if (System.IO.File.Equals(mdbFile)){ list.Add(mdbFile); } } } } break; } } } } public class MonoGameBuildExtension : ProjectServiceExtension{ protected override BuildResult Build (MonoDevelop.Core.IProgressMonitor monitor, IBuildTarget item, ConfigurationSelector configuration) { try { return base.Build(monitor, item, configuration); } finally { } } protected override BuildResult Compile (MonoDevelop.Core.IProgressMonitor monitor, SolutionEntityItem item, BuildData buildData) { try { var proj = item as MonoGameProject; if (proj == null){ return base.Compile (monitor, item, buildData); } var results = new System.Collections.Generic.List<BuildResult>(); foreach (var file in proj.Files) { if (MonoGameBuildAction.IsMonoGameBuildAction(file.BuildAction)){ buildData.Items.Add(file); var buildresults = MonoGameContentProcessor.Compile(file, monitor,buildData); results.Add(buildresults); } } return base.Compile(monitor, item, buildData).Append(results); } finally { } } } public class MonoGameProjectBinding : IProjectBinding{ public Project CreateProject(ProjectCreateInformation info, System.Xml.XmlElement projectOptions){ string lang = projectOptions.GetAttribute ("language"); return new MonoGameProject (lang, info, projectOptions); } public Project CreateSingleFileproject(string sourceFile){ throw new InvalidOperationException (); } public Project CanCreateSingleFileProject(string sourceFile){ return false; } public string Name{ get{return "MonoGame"; } } } public class MonoGameProjectConfiguration : DotNetProjectConfiguration{ public MonoGameProjectConfiguration () : base (){ } public MonoGameProjectConfiguration (string name): base(name){ } public override void CopyFrom (ItemConfiguration configuration) { base.CopyFrom (configuration); } } public class MonoGameContentProcessor { public static BuildResult Compile( ProjectFile file, MonoDevelop.Core.IProgressMonitor monitor, BuildData buildData){ switch (file.BuildAction) { case "MonoGameShader": { var results = new BuildResult (); monitor.Log.WriteLine ("Compiling Shader"); monitor.Log.WriteLine ("Shader : " + buildData.Configuration.OutputDirectory); monitor.Log.WriteLine ("Shader : " + file.FilePath); monitor.Log.WriteLine ("Shader : " + file.ToString ()); return results; } default: return new BuildResult (); } } } }
stebyrne04/Monogame_templates
Properties/MonoGameProject.cs
C#
gpl-2.0
5,230
package com.example.review; public class SwitchStringStatement { public static void main(String args[]){ String color = "Blue"; String shirt = " Shirt"; switch (color){ case "Blue": shirt = "Blue" + shirt; break; case "Red": shirt = "Red" + shirt; break; default: shirt = "White" + shirt; } System.out.println("Shirt type: " + shirt); } }
amzaso/Java_servef
02-Review/examples/ReviewExamples/src/com/example/review/SwitchStringStatement.java
Java
gpl-2.0
536
<?php // Form override fo theme settings function saa_basic_form_system_theme_settings_alter(&$form, $form_state) { $form['options_settings'] = array( '#type' => 'fieldset', '#title' => t('Theme Specific Settings'), '#collapsible' => FALSE, '#collapsed' => FALSE ); $form['options_settings']['saa_basic_tabs'] = array( '#type' => 'checkbox', '#title' => t('Use the ZEN tabs'), '#description' => t('Check this if you wish to replace the default tabs by the ZEN tabs'), '#default_value' => theme_get_setting('saa_basic_tabs'), ); $form['options_settings']['saa_basic_breadcrumb'] = array( '#type' => 'fieldset', '#title' => t('Breadcrumb settings'), '#attributes' => array('id' => 'basic-breadcrumb'), ); $form['options_settings']['saa_basic_breadcrumb']['saa_basic_breadcrumb'] = array( '#type' => 'select', '#title' => t('Display breadcrumb'), '#default_value' => theme_get_setting('saa_basic_breadcrumb'), '#options' => array( 'yes' => t('Yes'), 'admin' => t('Only in admin section'), 'no' => t('No'), ), ); $form['options_settings']['saa_basic_breadcrumb']['saa_basic_breadcrumb_separator'] = array( '#type' => 'textfield', '#title' => t('Breadcrumb separator'), '#description' => t('Text only. Don’t forget to include spaces.'), '#default_value' => theme_get_setting('saa_basic_breadcrumb_separator'), '#size' => 5, '#maxlength' => 10, '#prefix' => '<div id="div-basic-breadcrumb-collapse">', // jquery hook to show/hide optional widgets ); $form['options_settings']['saa_basic_breadcrumb']['saa_basic_breadcrumb_home'] = array( '#type' => 'checkbox', '#title' => t('Show home page link in breadcrumb'), '#default_value' => theme_get_setting('saa_basic_breadcrumb_home'), ); $form['options_settings']['saa_basic_breadcrumb']['saa_basic_breadcrumb_trailing'] = array( '#type' => 'checkbox', '#title' => t('Append a separator to the end of the breadcrumb'), '#default_value' => theme_get_setting('saa_basic_breadcrumb_trailing'), '#description' => t('Useful when the breadcrumb is placed just before the title.'), ); $form['options_settings']['saa_basic_breadcrumb']['saa_basic_breadcrumb_title'] = array( '#type' => 'checkbox', '#title' => t('Append the content title to the end of the breadcrumb'), '#default_value' => theme_get_setting('saa_basic_breadcrumb_title'), '#description' => t('Useful when the breadcrumb is not placed just before the title.'), '#suffix' => '</div>', // #div-basic-breadcrumb-collapse" ); //IE specific settings. $form['options_settings']['saa_basic_ie'] = array( '#type' => 'fieldset', '#title' => t('Internet Explorer Stylesheets'), '#attributes' => array('id' => 'basic-ie'), ); $form['options_settings']['saa_basic_ie']['saa_basic_ie_enabled'] = array( '#type' => 'checkbox', '#title' => t('Enable Internet Explorer stylesheets in theme'), '#default_value' => theme_get_setting('saa_basic_ie_enabled'), '#description' => t('If you check this box you can choose which IE stylesheets in theme get rendered on display.'), ); $form['options_settings']['saa_basic_ie']['saa_basic_ie_enabled_css'] = array( '#type' => 'fieldset', '#title' => t('Check which IE versions you want to enable additional .css stylesheets for.'), '#states' => array( 'visible' => array( ':input[name="saa_basic_ie_enabled"]' => array('checked' => TRUE), ), ), ); $form['options_settings']['saa_basic_ie']['saa_basic_ie_enabled_css']['saa_basic_ie_enabled_versions'] = array( '#type' => 'checkboxes', '#options' => array( 'ie8' => t('Internet Explorer 8'), 'ie9' => t('Internet Explorer 9'), 'ie10' => t('Internet Explorer 10'), ), '#default_value' => theme_get_setting('saa_basic_ie_enabled_versions'), ); $form['options_settings']['clear_registry'] = array( '#type' => 'checkbox', '#title' => t('Rebuild theme registry on every page.'), '#description' =>t('During theme development, it can be very useful to continuously <a href="!link">rebuild the theme registry</a>. WARNING: this is a huge performance penalty and must be turned off on production websites.', array('!link' => 'http://drupal.org/node/173880#theme-registry')), '#default_value' => theme_get_setting('clear_registry'), ); }
saaphx-dev/saa
sites/all/themes/saa-basic/theme-settings.php
PHP
gpl-2.0
4,665
<? /************************************************************************************************** * Archivo: StoreConsultaDetalleUbicacion.php * ------------------------------------------------------------------------------------------------ * Version: 1.0 * Descripcion: * Modificaciones: * - * * Nota: Registrar en este encabezado todas las modificaciones hechas al archivo. **************************************************************************************************/ require_once ('template.php'); require_once ('Sysgran/Core/Red/Encoder.php'); require_once ('Sysgran/Core/Listados/FiltroNumerico.php'); require_once ('Sysgran/Core/Php/StoreCustom.php'); class StoreConsultaDetalleUbicacion extends StoreCustom { function StoreConsultaDetalleUbicacion ($paginado = false) { parent::__construct ($paginado); $this->AgregarFiltro (new FiltroNumerico ('ubicacion', 'ubic')); $this->AgregarFiltro (new FiltroNumerico ('producto', 'prod')); $this->AgregarFiltro (new FiltroNumerico ('almacen', 'alm')); } function ArmarQuery () { $fubic = $this->GetFiltro ('ubicacion'); $fprod = $this->GetFiltro ('producto'); $falm = $this->GetFiltro ('almacen'); $where = ''; if ($fubic->EsActivo ()) { $where .= " AND d.iUbicacionAlmacenId = " . $fubic->GetValor (); } if ($fprod->EsActivo ()) { $where .= " AND p.iProductoId = " . $fprod->GetValor (); } if ($falm->EsActivo ()) { $where .= " AND u.iAlmacenId = " . $falm->GetValor (); } $query = "SELECT d.iDetalleUbicacionAlmacenId, d.iNroDeDetalle, d.fCantidad, um.cCodigo AS cod_um, p.cCodigo AS cod_producto, d.iNroDeDetalle FROM DetalleUbicacionAlmacen d JOIN UbicacionAlmacen u ON u.iUbicacionAlmacenId = d.iUbicacionAlmacenId JOIN Producto p ON p.iProductoId = d.iProductoId JOIN UnidadDeMedida um ON um.iUnidadDeMedidaId = p.iUnidadDeMedidaStockId WHERE u.bActivo = " . DB::ToBoolean (true) . " AND d.fCantidad > 0 $where ORDER BY u.cCodigo, d.iDetalleubicacionAlmacenId ASC"; return $query; } function CargarItem ($rs) { $ret['id'] = $rs->Fields ('iDetalleUbicacionAlmacenId'); $ret['nroDeDetalle'] = $rs->Fields ('iNroDeDetalle'); $ret['codigoProducto'] = $rs->Fields ('cod_producto'); $ret['cantidad'] = $rs->Fields ('fCantidad'); $ret['codigoUnidadDeMedida'] = $rs->Fields ('cod_um'); return $ret; } }
marcelinoar/FrameworkWeb
src/base/servidor/Sysgran/Aplicacion/Modulos/Produccion/Store/StoreConsultaDetalleUbicacion.php
PHP
gpl-2.0
2,477
<?php /** * Module: Intro Text * * @author SpyroSol * @category BuilderModules * @package Spyropress */ class Spyropress_Module_Intro_Text extends SpyropressBuilderModule { public function __construct() { global $spyropress; // Widget variable settings $this->cssclass = ''; $this->description = __( 'A lightweight component for introduction text.', 'spyropress' ); $this->idbase = 'spyropress_intro_text'; $this->name = __( 'Introduction Text', 'spyropress' ); $this->templates['centered'] = array( 'label' => 'Text Centered', 'class' => 'twelve columns offset-by-two' ); $this->templates['style2'] = array( 'label' => 'Text Centered 2', 'class' => 'fourteen columns marginTop offset-by-one' ); // Fields $this->fields = array( array( 'label' => __( 'Styles', 'spyropress' ), 'id' => 'template', 'type' => 'select', 'options' => $this->get_option_templates() ), array( 'label' => __('Content', 'spyropress' ), 'id' => 'content', 'type' => 'editor' ) ); $this->create_widget(); } function widget( $args, $instance ) { // extracting info extract($args); extract( spyropress_clean_array( $instance ) ); // get view to render include $this->get_view(); } } spyropress_builder_register_module( 'Spyropress_Module_Intro_Text' ); ?>
jamesshannonwd/meesha
wp-content/themes/cutting-edge/framework/builder/modules/intro-text/intro-text.php
PHP
gpl-2.0
1,765
<?php $vortex_like_dislike = get_option("vortex_like_dislike"); function vortex_system_add_dislike_class_buddypress($id){ $vortex_like_dislike = get_option("vortex_like_dislike"); if(is_user_logged_in()){ $current_user_id = get_current_user_id(); $user_key = 'vortex_system_user_'.$current_user_id; }elseif(!is_user_logged_in() && $vortex_like_dislike['v-switch-anon']){ $user_ip = sanitize_text_field($_SERVER['REMOTE_ADDR']); $user_key = 'vortex_system_user_'.$user_ip; }; if(is_user_logged_in() || (!is_user_logged_in() && $vortex_like_dislike['v-switch-anon'])){ if(!get_post_meta($id,$user_key,true) == ''){ $current_user = get_post_meta($id,$user_key,true); $current_user_disliked = $current_user['disliked']; } if($current_user_disliked == 'nodisliked'){ return 'vortex-p-dislike-active'; }elseif(vortex_ra_read_cookie('dislikepost',$id) == 'found' && $current_user_disliked !== 'disliked'){ return 'vortex-p-dislike-active'; } } } function vortex_system_get_total_dislikes_buddypress($id){ $dislikes = get_post_meta($id,'vortex_system_dislikes',true); if(empty($dislikes)){ return 0; }elseif(!$dislikes == ''){ return $dislikes = get_post_meta($id,'vortex_system_dislikes',true); } } function vortex_system_dislike_counter_buddypress($id){ $vortex_like_dislike = get_option("vortex_like_dislike"); if ($vortex_like_dislike['v_custom_text_post_keep'] && vortex_system_add_dislike_class_buddypress($id) == 'vortex-p-dislike-active'){ if(!$vortex_like_dislike['v-switch-anon-counter'] || is_user_logged_in()){ return '<span class="vortex-p-dislike-counter '.$id. '">'.$vortex_like_dislike['v_custom_text_post_dislike'].'</span>'; } }elseif(!$vortex_like_dislike['v-switch-anon-counter'] || is_user_logged_in()){ return '<span class="vortex-p-dislike-counter '.$id. '">'. vortex_system_get_total_dislikes_buddypress($id).'</span>'; } } function vortex_system_render_dislike_button_buddypress($id){ /*dev use the same as below return '<div class="vortex-container-dislike"> <input type="hidden" value="'.get_the_ID().'" ></input> <div class="vortex-p-dislike '.get_the_ID().' '. vortex_system_add_dislike_class() .' '.vortex_system_get_dislike_icon().'"> '.vortex_system_dislike_counter().' </div> </div>'; */ return '<div class="vortex-container-dislike"><input type="hidden" value="'.$id.'" ></input><div class="vortex-p-dislike '.$id.' '. vortex_system_add_dislike_class_buddypress($id) .' '.vortex_system_get_dislike_icon().'">'.vortex_system_dislike_counter_buddypress($id).'</div></div>'; } function vortex_system_add_like_class_buddypress($id){ $vortex_like_dislike = get_option("vortex_like_dislike"); if(is_user_logged_in()){ $current_user_id = get_current_user_id(); $user_key = 'vortex_system_user_'.$current_user_id; }elseif(!is_user_logged_in() && $vortex_like_dislike['v-switch-anon']){ $user_ip = sanitize_text_field($_SERVER['REMOTE_ADDR']); $user_key = 'vortex_system_user_'.$user_ip; }; if(is_user_logged_in() || (!is_user_logged_in() && $vortex_like_dislike['v-switch-anon'])){ if(!get_post_meta($id,$user_key,true) == ''){ $current_user = get_post_meta($id,$user_key,true); $current_user_liked = $current_user['liked']; } if($current_user_liked == 'noliked'){ return 'vortex-p-like-active'; }elseif(vortex_ra_read_cookie('likepost',$id) == 'found' && $current_user_liked !== 'liked'){ return 'vortex-p-like-active'; } } } function vortex_system_get_total_likes_buddypress($id){ $likes = get_post_meta($id,'vortex_system_likes',true); if(empty($likes)){ return 0; }elseif(!$likes == ''){ return $dislikes = get_post_meta($id,'vortex_system_likes',true); } } function vortex_system_like_counter_buddypress($id){ $vortex_like_dislike = get_option("vortex_like_dislike"); if ($vortex_like_dislike['v_custom_text_post_keep'] && vortex_system_add_like_class_buddypress($id) == 'vortex-p-like-active'){ if(!$vortex_like_dislike['v-switch-anon-counter'] || is_user_logged_in()){ return '<span class="vortex-p-like-counter '. $id.'">'.$vortex_like_dislike['v_custom_text_post_like'].'</span>'; } }elseif(!$vortex_like_dislike['v-switch-anon-counter'] || is_user_logged_in()){ return '<span class="vortex-p-like-counter '. $id.'">'.vortex_system_get_total_likes_buddypress($id).'</span>'; } } function vortex_buddypress_render($id){ $vortex_like_dislike = get_option("vortex_like_dislike"); if(!$vortex_like_dislike['v-switch-dislike']){ /* this is for dev the same as below $buttons = ' <div class="vortex-container-vote '.vortex_button_align().'"> <div class="vortex-container-like"> <input type="hidden" value="'.get_the_ID().'" ></input> <div class="vortex-p-like '.get_the_ID().' '.vortex_system_add_like_class().' '.vortex_system_get_like_icon().'"> '.vortex_system_like_counter().' </div> </div> '.vortex_system_render_dislike_button().' </div> ';*/ //leave it inline, bbPress adds p tags for unkown reasons $buttons = '<div class="vortex-container-vote '.vortex_button_align().'"><div class="vortex-container-like"><input type="hidden" value="'.$id.'" ></input><div class="vortex-p-like '.$id.' '.vortex_system_add_like_class_buddypress($id).' '.vortex_system_get_like_icon().'">'.vortex_system_like_counter_buddypress($id).'</div></div>'.vortex_system_render_dislike_button_buddypress($id).'</div>'; return $buttons; }else { /* this is for dev the same as below $buttons = ' <div class="vortex-container-vote '.vortex_button_align().'"> <div class="vortex-container-like"> <input type="hidden" value="'.get_the_ID().'" ></input> <div class="vortex-p-like '.get_the_ID().' '.vortex_system_add_like_class().' '.vortex_system_get_like_icon().'"> '.vortex_system_like_counter().' </div> </div> </div> '; */ $buttons = '<div class="vortex-container-vote '.vortex_button_align().'"><div class="vortex-container-like"><input type="hidden" value="'.$id.'" ></input><div class="vortex-p-like '.$id.' '.vortex_system_add_like_class_buddypress($id).' '.vortex_system_get_like_icon().'">'.vortex_system_like_counter_buddypress($id).'</div></div></div>'; return $buttons; } } function vortex_buddypress_after($content){ return $content.vortex_buddypress_render(bp_get_activity_id()); } function vortex_buddypress_before($content){ return vortex_buddypress_render(bp_get_activity_id()).$content; } $vortex_like_dislike = get_option("vortex_like_dislike"); if($vortex_like_dislike['v_button_visibility'][1] && $vortex_like_dislike['v_button_visibility'][2] ){ add_filter('bp_get_activity_content_body','vortex_buddypress_after'); add_filter('bp_get_activity_content_body','vortex_buddypress_before'); }elseif($vortex_like_dislike['v_button_visibility'][1]){ add_filter('bp_get_activity_content_body','vortex_buddypress_before'); }elseif($vortex_like_dislike['v_button_visibility'][2]){ add_filter('bp_get_activity_content_body','vortex_buddypress_after'); }
jackhutson03/Exashare
wp-content/plugins/rating-system/buddypress.php
PHP
gpl-2.0
7,404
/* * java-gnome, a UI library for writing GTK and GNOME programs from Java! * * Copyright © 2006-2011 Operational Dynamics Consulting, Pty Ltd and Others * * The code in this file, and the program it is a part of, is made available * to you by its authors as open source software: you can redistribute it * and/or modify it under the terms of the GNU General Public License version * 2 ("GPL") as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GPL for more details. * * You should have received a copy of the GPL along with this program. If not, * see http://www.gnu.org/licenses/. The authors of this program may be * contacted through http://java-gnome.sourceforge.net/. * * Linking this library statically or dynamically with other modules is making * a combined work based on this library. Thus, the terms and conditions of * the GPL cover the whole combination. As a special exception (the * "Claspath Exception"), the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent modules, * and to copy and distribute the resulting executable under terms of your * choice, provided that you also meet, for each linked independent module, * the terms and conditions of the license of that module. An independent * module is a module which is not derived from or based on this library. If * you modify this library, you may extend the Classpath Exception to your * version of the library, but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. */ package org.gnome.atk; /* * THIS FILE IS GENERATED CODE! * * To modify its contents or behaviour, either update the generation program, * change the information in the source defs file, or implement an override for * this class. */ import org.gnome.atk.Plumbing; final class AtkLayer extends Plumbing { private AtkLayer() {} static final int INVALID = 0; static final int BACKGROUND = 1; static final int CANVAS = 2; static final int WIDGET = 3; static final int MDI = 4; static final int POPUP = 5; static final int OVERLAY = 6; }
cyberpython/java-gnome
generated/bindings/org/gnome/atk/AtkLayer.java
Java
gpl-2.0
2,440
class AddRegisteredByToCredittypes < ActiveRecord::Migration def self.up if column_exists? :credittypes, :moduser_id rename_column :credittypes, :moduser_id, :registered_by_id else add_column :credittypes, :registered_by_id, :integer end add_column :credittypes, :modified_by_id, :integer end def self.down rename_column :credittypes, :registered_by_id, :moduser_id remove_column :credittypes, :modified_by_id end end
ifunam/salva
db/migrate/20101117233353_add_registered_by_to_credittypes.rb
Ruby
gpl-2.0
465